Hi All,
I am presenting simple boiler point code that can quickly be applied to test technical indicator strategies using Python. The code:
1. downloads daily stock data from google,
2. calculates the short and long moving averages
3. generates the trading signals
4. calculates the daily returns
5. runs the moving average strategy and calculates the cumulative return
6. plots cumulative return of our simple strategy
Here is the code ... enjoy trying it out and extend it as required:
import numpy as npdata = datar.get_data_google('AAPL', date_start, date_end)
import pandas_datareader as datar
import datetime
import matplotlib.pyplot as plt
date_start = datetime.datetime(2017,1,1)
date_end = datetime.datetime(2017,6,30)
short_ma = 5long_ma = 20
data['short_ma'] = data['Close'].rolling(short_ma).mean()
data['long_ma'] = data['Close'].rolling(long_ma).mean()
data['masig'] = data['short_ma'] - data['long_ma']
data=data.dropna(subset=['masig'])
data['signal'] = np.where(data['masig'] > 0, 1, 0)
data['signal'] = np.where(data['masig'] < 0, -1, data['signal'])
print(data['signal'].value_counts())
data['returns'] = np.log(data['Close']) - np.log(data['Close']).shift(1)
data['strategy'] = data['returns'] * data['signal'].shift(1)
data['strategy'].cumsum().plot(title='Cumulative Return')
plt.show()