/
backtest1.py
243 lines (225 loc) · 10.5 KB
/
backtest1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import yahoo_finance_api2 as yf
from yahoo_finance_api2 import share
import requests
import pandas as pd
import datetime as dt
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from plotly.graph_objects import Scatter
from dash.dependencies import Input, Output
from yahoo_finance_api2 import exceptions
import concurrent.futures
import multiprocessing as mp
import numpy as np
from backtesting import Strategy
from backtesting import Backtest
from backtesting.lib import crossover
def get_ticker_dict():
"""returns dict of ticker prepared for dropdown"""
url = 'https://en.wikipedia.org/wiki/FTSE_100_Index#cite_note-13'
html = requests.get(url).content
df_list = pd.read_html(html)[3]
tickerdict = [{'label':x['Company'],'value':x['EPIC']} for idx,x in df_list.iterrows()]
return tickerdict
def get_ticker_data(ticker):
"""takes ticker code such as 'AZN' and returns a dataframe of
OCHLV"""
my_share = share.Share(ticker)
try:
data = my_share.get_historical(share.PERIOD_TYPE_DAY,
100,
share.FREQUENCY_TYPE_MINUTE,
30)
if data is not None:
res = list(zip(data['timestamp'],data['open']))
res = [(dt.datetime.fromtimestamp(x[0]/1000),x[1]) for x in res]
df = pd.DataFrame.from_dict({
'value':[x[1] for x in res],
'time':[x[0] for x in res]
})
return df
else:
print('No Data from YahooFinance')
return None
except exceptions.YahooFinanceError:
pass
def get_ticker_data_1(ticker):
"""takes ticker code such as 'AZN' and returns a dataframe of
OCHLV"""
my_share = share.Share(ticker)
try:
data = my_share.get_historical(share.PERIOD_TYPE_DAY,
100,
share.FREQUENCY_TYPE_MINUTE,
30)
if data is not None:
res = list(zip(data['timestamp'],data['open'],data['high'],data['low'],data['close']))
res = [(dt.datetime.fromtimestamp(x[0]/1000),x[1]) for x in res]
df = pd.DataFrame(res,columns=['time','open','high','low','close'])
print(df.columns)
return df
else:
print('No Data from YahooFinance')
return None
except exceptions.YahooFinanceError:
pass
def get_ticker_data_2(ticker):
"""takes ticker code such as 'AZN' and returns a dataframe of
OCHLV"""
my_share = share.Share(ticker)
try:
data = my_share.get_historical(share.PERIOD_TYPE_DAY,
100,
share.FREQUENCY_TYPE_MINUTE,
30)
if data is not None:
df = pd.DataFrame.from_dict(data)
df['timestamp'] = [dt.datetime.fromtimestamp(x/1000) for x in df['timestamp']]
df = df.set_index('timestamp')
df.columns = ['Open','High','Low','Close','Volume']
return df
else:
print('No Data from YahooFinance')
return None
except exceptions.YahooFinanceError:
pass
def SMA(values, n):
"""
Return simple moving average of `values`, at
each step taking into account `n` previous values.
"""
return pd.Series(values).rolling(n).mean()
class SmaCross(Strategy):
"""Define the two MA lags as *class variables*
for later optimization"""
n1 = 10
n2 = 20
def init(self):
self.sma1 = self.I(SMA, self.data.Close, self.n1)
self.sma2 = self.I(SMA, self.data.Close, self.n2)
def next(self):
if crossover(self.sma1, self.sma2):
self.position.close()
self.buy()
elif crossover(self.sma2, self.sma1):
self.position.close()
self.sell()
if __name__=="__main__":
# Next thing is to build an optimiser which makes the best decision of which polynomial form works best for
# this model i.e. Chebyshev, Laguerre, Legendre etc - need to get this working tomorrow.
mp.set_start_method('fork') # My thing
tickerdict = get_ticker_dict()
with concurrent.futures.ThreadPoolExecutor() as exec:
results = {x['value']:exec.submit(get_ticker_data_2,x['value']) for x in tickerdict}
results = {k:v.result() for k,v in results.items()}
results = {k:v.dropna() for k,v in results.items() if v is not None}
def make_good_ticker_dict(tickerdict,results):
res = [x for x in tickerdict if x['value'] in results.keys()]
return res
good_ticker_dict = make_good_ticker_dict(tickerdict,results)
degree_options = [{'label':x,'value':x} for x in range(1,10)]
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children=[
html.H1(children='Test Yahoo Finance Fetcher',
style={'textAlign':'center'}),
html.Div(className='row',children=[
html.Div(className='four columns', children=[
html.Label(['Select Stock'],style={'text-align':'center'}),
dcc.Dropdown(
id='ticker_dropdown',
options=good_ticker_dict,
value='AZN'),
]),
html.Div(className='four columns', children=[
html.Label(['Select Degree'],style={'text-align':'center'}),
dcc.Dropdown(
id='degrees',
options=degree_options,
value=4),
]),
],style=dict(display='flex')),
html.Div([
html.Div([
dcc.Graph(id='my_fig')],
className='six columns'),
html.Div([
dcc.Graph(id='my_fig2')],
className='six columns'),
],className='row'),
html.Div([
html.Div([
dcc.Graph(id='my_fig3')],
className='six columns'),
html.Div([
dcc.Graph(id='my_fig4')],
className='six columns'),
],className='row'),
html.Div([html.H3(['SMA Cross'])]),
dcc.Graph(id='my_fig5'),
html.H5('Line Fit Co-Efficients'),
html.P(id='coefs'),
html.H5('SMA Cross Optimal'),
html.P(id='smac')
])
@app.callback(
[Output(component_id='my_fig', component_property='figure'),
Output(component_id='my_fig2', component_property='figure'),
Output(component_id='my_fig3', component_property='figure'),
Output(component_id='my_fig4', component_property='figure'),
Output(component_id='my_fig5', component_property='figure'),
Output(component_id='coefs',component_property='children'),
Output(component_id='smac',component_property='children')],
[Input(component_id='ticker_dropdown', component_property='value'),
Input(component_id='degrees',component_property='value')]
)
def update_line_chart(ticker,degree):
good_data = results[ticker]
try:
good_data['time'] = good_data.index
start = good_data['time'][0]
time = np.array([pd.Timedelta(x-start).total_seconds() for x in good_data['time']])
fig1 = px.scatter(good_data,x='time',y='Open',template='simple_white',title='Time Series')
fig1.update_traces(marker={'size': 4})
bt = Backtest(results[ticker], SmaCross, cash=10_000, commission=.002)
stats = bt.optimize(n1=range(5, 50, 5),
n2=range(10, 200, 5),
maximize='Equity Final [$]',
constraint=lambda param: param.n1 < param.n2)
eq_curve = stats._equity_curve
eq_curve['time'] = eq_curve.index
fig5 = px.line(eq_curve,x='time',y='Equity',template='simple_white')
smac = str(stats._strategy)
fig1.add_trace(Scatter(x=good_data['time'],y=SMA(good_data['Open'],stats._strategy.n1),name='Short MA'))
fig1.add_trace(Scatter(x=good_data['time'],y=SMA(good_data['Open'],stats._strategy.n2),name='Long MA'))
print(np.nan_to_num(np.array(SMA(good_data['Open'],stats._strategy.n1))))
coefs = np.polyfit(time,np.nan_to_num(np.array(SMA(good_data['Open'],stats._strategy.n1))),degree)
print(coefs)
print(np.polyval(time,coefs))
coef_df = pd.DataFrame.from_dict({'time':time,
'coeffs':np.polyval(coefs,time),
'original_t':good_data['time']})
fig2 = px.line(coef_df,x='original_t',y='coeffs', template='simple_white',title='Polynomial Fit')
der1 = np.polyder(coefs,1)
print('der1: ',der1)
der1_df = pd.DataFrame.from_dict({'time':time,
'der1':np.polyval(der1,time),
'original_t':good_data['time']})
fig3 = px.line(der1_df,x='original_t',y='der1',template='simple_white',title='First Derivative')
der2 = np.polyder(coefs,2)
print('der2: ',der2)
der2_df = pd.DataFrame.from_dict({'time':time,
'der2':np.polyval(der2,time),
'original_t':good_data['time']})
fig4 = px.line(der2_df,x='original_t',y='der2',template='simple_white',title='Second Derivative')
coefs = np.polyfit(time,np.array(good_data['Open']),degree)
print('coefs: ',coefs)
coef_df = pd.DataFrame.from_dict({'time':time,
'coeffs':np.polyval(coefs,time),
'original_t':good_data['time']})
except exceptions.YahooFinanceError:
fig1,fig2,fig3,fig4,fig5 = 'No Ticker Available'
return fig1, fig2, fig3, fig4, fig5, coefs, smac
app.run_server(debug=True)