import pandas as pd import numpy as np import matplotlib.pyplot as plt def f(z): c = 0.1 n = 2 return c * abs(z)**n * (np.cos(n * np.angle(z)) + 1j * np.sin(n * np.angle(z))) def buy_signal(data): if f(data['Close'].iloc[-1]) > 0: return True else: return False def sell_signal(data): if f(data['Close'].iloc[-1]) < 0: return True else: return False def trade(data): bought = False for i in range(len(data)): if buy_signal(data.iloc[i:i+1]): if not bought: bought = True data.loc[i, 'Action'] = 'Buy' elif sell_signal(data.iloc[i:i+1]): if bought: bought = False data.loc[i, 'Action'] = 'Sell' def backtest(data): trade(data) data['Return'] = data['Close'].pct_change() data['Strategy Return'] = data['Action'].shift(1) * data['Return'] strategy_return = data['Strategy Return'].sum() print(f"Strategy Return: {strategy_return}") # Load data data = pd.read_csv('data.csv', index_col='Date', parse_dates=True) # Backtest strategy backtest(data) # Plot results plt.plot(data['Close']) plt.plot(data['Strategy Return'] + data['Close']) plt.show()