df = pd.read_csv('APPLE.csv',index_col=0)
df = df[['Adj_Open','Adj_High', 'Adj_Low', 'Adj_Close']]
df =df.rename(columns={'Adj_Open': 'Open', 'Adj_High': 'High', 'Adj_Low':'Low', 'Adj_Close':'Close'})
df.index = pd.to_datetime(df.index)
df = df.dropna()
df['SAR']=ta.SAR(df.High.values, df.Low.values, acceleration = 0.02, maximum = 0.2)
df['fastk'], df['fastd'] = ta.STOCHF(df.High.values, df.Low.values, df.Close.values ,fastk_period=5, fastd_period=3)
df['slowk'], df['slowd'] = ta.STOCH(df.High.values, df.Low.values, df.Close.values ,fastk_period=5, slowk_period=3, slowd_period=3)
df['Signal'] = np.nan
df.loc[(df.SAR< df.Close) & (df.fastd>df.slowd) & (df.fastk>df.slowk),'Signal'] =1
df.loc[(df.SAR> df.Close) & (df.fastd<df.slowd) & (df.fastk<df.slowk),'Signal'] =-1
df = df.fillna(method='ffill')
df['Stock_Return'] = df.Close.pct_change()
df['strategy_return'] = (df.Stock_Return * df.Signal.shift(1))
df = df.dropna()
(df.strategy_returns+1).cumprod().plot()
plt.show()
In the second last line, three operations are taking place. First, we added 1 to the strategy returns. +1 is added to the strategy returns to denote the principal amount. Next, we took the cumulative product of the strategy returns and finally plotted them.
Date | Strategy Returns | Strategy Returns +1 | cumprod (Strategy Returns +1) |
01-06-2020 | -0.0067 | 0.9933 | 0.9933 |
02-06-2020 | 0.0097 | 1.0097 | 1.00293501 |
03-06-2020 | 0.0234 | 1.0234 | 1.026403689 |
04-06-2020 | -0.0019 | 0.9981 | 1.024453522 |
05-06-2020 | -0.0371 | 0.9629 | 0.986446297 |