-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbacktestView.py
1244 lines (1042 loc) · 40 KB
/
backtestView.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
warnings.filterwarnings('ignore')
import os
import tempfile
import zipfile
import uuid
# Customized Bullet chart
import datetime as dt
# import pandas_datareader.data as web
import plotly.express as px
from dash import html, dcc, dash_table
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import plotly.express as px
from plotly.tools import mpl_to_plotly
import dash.dependencies
import pyfolio as pf
import matplotlib.pyplot as plt
plt.switch_backend('Agg')
import empyrical
import quantstats as qs
from quantstats import stats
from pandas_datareader import data as web
from plotly.subplots import make_subplots
# Raw Package
import numpy as np
import pandas as pd
# from pandas_datareader import data as pdr
# Market Data
import yfinance as yf
import yahoo_fin.stock_info as si
#Graphing/Visualization
import plotly.graph_objs as go
from re import S
import re
# from turtle import onclick
import redis
import flask
import backend as ob
import configuration as oc
PRIMARY = '#FFFFFF'
SECONDARY = '#FFFFFF'
ACCENT = '#98C1D9'
DARK_ACCENT = '#474747'
SIDEBAR = '#F7F7F7'
# global yf_data
# yf_data = pd.DataFrame()
df_dict = {}
debug_mode = False # set False to deploy
root_directory = os.getcwd()
stylesheets = ['tabs.css']
jss = ['script.js']
static_route = '/Static/'
# level_marks = ['Debug', 'Info', 'Warning', 'Error']
level_marks = {0: 'Debug', 1: 'Info', 2: 'Warning', 3: 'Error'}
num_marks = 4
# left_column = html.Div([
# html.Div(html.H5('Data Download'), className='grey block2 mb-10'),
# html.Div([
# html.Div('Symbols:', className='four columns'),
# dcc.Dropdown(
# id='symbols',
# options=[{'label': name, 'value': name} for name in pd.read_csv('Static/sp500_companies.csv')['Symbol'].to_list()],
# #options=['AAPL', 'TSLA', 'MSFT', 'AMZN'], #Replace this with list
# multi=True,
# className='eight columns u-pull-right')
# ], className='row mb-10'),
# html.Button('Download', id='download-btn', n_clicks=0, style={'width': '60%', 'margin-left': 0, 'margin-right': '2%'}),
# html.Br(),
# dbc.Row([
# html.Div(html.Hr(style={'borderWidth': "0.3vh", "width": "100%", "color": "#FEC700"}))
# ]),
# html.Div(html.H5('Generate Algorithm Code'), className='black-block2 mb-10'),
# html.Div([
# html.Div('Algos:', className='four columns'),
# dcc.Dropdown(id='module', options=[], className='eight columns u-pull-right')
# # dcc.Dropdown(
# # id='module',
# # options=[{'label': name, 'value': name} for name in oc.cfg['backtest']['modules'].split(',')],
# # className='eight columns u-pull-right')
# ], className='row mb-10'),
# html.Div([
# html.Div('Strategy Name:', className='four columns'),
# #dcc.Dropdown(id='strategy', options=[], className='eight columns u-pull-right')
# dcc.Input(id='filename', className='eight columns u-pull-right', value = "MyStrategy")
# ], className='row mb-10'),
# html.Div([
# html.Div('Capital:', className='four columns'),
# #dcc.Dropdown(id='strategy', options=[], className='eight columns u-pull-right')
# dcc.Input(id='cash', className='eight columns u-pull-right', value = 10000)
# ], className='row mb-10'),
# html.Button('Generate Code', id='save-btn', n_clicks=0, style={'width': '60%', 'margin-left': 0, 'margin-right': '2%'}),
# html.Br(),
# dbc.Row([
# html.Div(html.Hr(style={'borderWidth': "0.3vh", "width": "100%", "color": "#FEC700"}))
# ]),
# html.Div(html.H5('Run Backtest'), className='black-block2 mb-10'),
# html.Div([
# html.Div('Backtest:', className='four columns'),
# dcc.Dropdown(id='strategy', options=[], className='eight columns u-pull-right')
# # dcc.Dropdown(
# # id='module',
# # options=[{'label': name, 'value': name} for name in oc.cfg['backtest']['modules'].split(',')],
# # className='eight columns u-pull-right')
# ], className='row mb-10'),
# html.Button('Run Backtest', id='backtest-btn', n_clicks=0, style={'width': '60%', 'margin-left': 0, 'margin-right': '0%'}),
# html.Div(
# dash_table.DataTable(
# row_selectable=ob.cash_param(),
# # optional - sets the order of columns
# columns=[{"name": i, "id": i} for i in['Parameter', 'Value']],
# editable=True,
# id='params-table'
# ), className='row mb-10'),
# html.Div([
# html.Div('Notes:'),
# html.Textarea(id='notes-area', style={'width': '100%'})
# ], className='row', style={'vertical-align': 'bottom'}),
# ], className="three columns gray-block", style={'position': 'absolute'})
page = html.Div([
dbc.Card(
dbc.CardBody([
html.Br(),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader('Download Data', style={'color': DARK_ACCENT}),
dbc.CardBody([
# select stocks for backtest + download option
html.Div([
dcc.Dropdown(
id='symbols',
options=[{'label': name, 'value': name} for name in pd.read_csv('Static/sp500_companies.csv')['Symbol'].to_list()],
#options=['AAPL', 'TSLA', 'MSFT', 'AMZN'], #Replace this with list
multi=True)
]),
html.Br(),
html.Button('Download', id='download-btn', className='eight columns u-pull-right', n_clicks=0, style={'font-size': '15px', 'font-weight': '5', 'color': PRIMARY, 'background-color': ACCENT, "border-color":ACCENT, 'border-radius': 5}),
]),
], color=PRIMARY, style={'border-radius': 10}),
html.Br(),
dbc.Card([
dbc.CardHeader('Generate Algorithm Code', style={'color': DARK_ACCENT}),
dbc.CardBody([
# Generate code
html.Div([
html.Div('Algos:', className='four columns'),
dcc.Dropdown(id='module', options=[], className='eight columns u-pull-right')
# dcc.Dropdown(
# id='module',
# options=[{'label': name, 'value': name} for name in oc.cfg['backtest']['modules'].split(',')],
# className='eight columns u-pull-right')
], className='row mb-10'),
html.Br(),
html.Div([
html.Div('Strategy Name:', className='four columns'),
#dcc.Dropdown(id='strategy', options=[], className='eight columns u-pull-right')
dcc.Input(id='filename', className='eight columns u-pull-right', value = "MyStrategy", style={'margin-left': '10px', 'width': '210px', 'font-size': '15px', 'font-weight': '5', 'border-radius': 5})
], className='row mb-10'),
html.Br(),
html.Div([
html.Div('Capital:', className='four columns'),
#dcc.Dropdown(id='strategy', options=[], className='eight columns u-pull-right')
dcc.Input(id='cash', className='eight columns u-pull-right', value = 10000, style={'margin-left': '10px', 'width': '210px', 'font-size': '15px', 'font-weight': '5', 'border-radius': 5})
], className='row mb-10'),
html.Br(),
html.Button('Generate Code', id='save-btn', n_clicks=0, className='eight columns u-pull-right', style={'font-size': '15px', 'font-weight': '5', 'color': PRIMARY, 'background-color': ACCENT, "border-color":ACCENT, 'border-radius': 5}),
]),
], color=PRIMARY, style={'border-radius': 10}),
html.Br(),
dbc.Card([
dbc.CardHeader('Run Backtest', style={'color': DARK_ACCENT}),
dbc.CardBody([
# Run backtest
html.Div([
dcc.Dropdown(id='strategy', options=[])
# dcc.Dropdown(
# id='module',
# options=[{'label': name, 'value': name} for name in oc.cfg['backtest']['modules'].split(',')],
# className='eight columns u-pull-right')
]),
html.Br(),
html.Button('Run Backtest', id='backtest-btn', className='eight columns u-pull-right', n_clicks=0, style={'font-size': '15px', 'font-weight': '5', 'color': PRIMARY, 'background-color': ACCENT, "border-color":ACCENT, 'border-radius': 5}),
html.Div(id='intermediate-value', style={'display': 'none'}),
html.Div(id='intermediate-params', style={'display': 'none'}),
html.Div(id='code-generated', style={'display': 'none'}),
html.Div(id='code-generated2', style={'display': 'none'}),
# dcc.Download(id="download-data-csv"),
html.Div(id='intermediate-status', style={'display': 'none'}),
html.Div(id='level-log', contentEditable='True', style={'display': 'none'}),
dcc.Input(id='log-uid', type='text', style={'display': 'none'})
])
], color = PRIMARY, style ={'border-radius': 10}),
], width=2),
dbc.Col([
html.Div([
dbc.Card(
dbc.CardBody([
dbc.Tabs(
[
dbc.Tab(dcc.Graph(id='charts',config={
'displayModeBar': False}), label='Backtest', className='nav-pills'),
# dbc.Tab(cumulative_returns_plot, label='Cumulative Returns', className='nav-pills'),
# dbc.Tab(annual_monthly_returns_plot, label='Annual and Monthly Returns', className='nav-pills'),
# dbc.Tab(rolling_sharpe_plot, label='Rolling Sharpe', className='nav-pills'),
# dbc.Tab(drawdown_periods_plot, label='unfinished', className='nav-pills'),
# dbc.Tab(drawdown_underwater_plot, label='Drawdown Underwater', className='nav-pills'),
# dbc.Tab(quantiles_plot, label='Scatter'),
],
id='tabs',
# active_tab='tab-1',
),
]), color = SECONDARY, style ={'border-radius': 10}
),
]),
], width=7),
dbc.Col([
html.Div([
dbc.Card(
dbc.CardBody([
# html.Div(html.H5('Status'), className='black-block2 mb-10'),
# html.Div([
# #html.Button('Download', id='download-btn', n_clicks=0, style={'width': '30%', 'margin-left': 0, 'margin-right': '2%'}),
# #html.Button('AutoCode', id='save-btn', n_clicks=0, style={'width': '30%', 'margin-left': 0, 'margin-right': '2%'}),
# #html.Button('Backtest', id='backtest-btn', n_clicks=0, style={'width': '34%', 'margin-left': 0, 'margin-right': '0%'}),
# ]),
# html.Div(id='status-area', style={
# 'margin-top': '10px',
# 'padding-left': '10px',
# 'border': '1px solid black',
# 'line-height': '40px',
# 'min-height': '40px',
# }),
html.Div(id='stat-block')
]), color = SECONDARY, style ={'border-radius': 10}
)
])
], width=3)
]),
])
)
], id='graph-container', style={'margin-bottom':'30rem'}
# style={'position': 'absolute', 'top': '0px', 'bottom': '0px', 'left': '0px', 'right': '0px'})
)
# , className='offset-by-three six columns gray-block', style={'position': 'absolute', 'top': 0, 'bottom': '9.2em'})
# right_column = html.Div([
# html.Div(
# html.Div([
# html.Div([
# html.Div(html.H5('Status'), className='black-block2 mb-10'),
# html.Div([
# #html.Button('Download', id='download-btn', n_clicks=0, style={'width': '30%', 'margin-left': 0, 'margin-right': '2%'}),
# #html.Button('AutoCode', id='save-btn', n_clicks=0, style={'width': '30%', 'margin-left': 0, 'margin-right': '2%'}),
# #html.Button('Backtest', id='backtest-btn', n_clicks=0, style={'width': '34%', 'margin-left': 0, 'margin-right': '0%'}),
# ]),
# html.Div(id='status-area', style={
# 'margin-top': '10px',
# 'padding-left': '10px',
# 'border': '1px solid black',
# 'line-height': '40px',
# 'min-height': '40px',
# })
# ], className='gray-block mb-10'),
# html.Div(id='stat-block', className='block',
# style={'position': 'absolute', 'top': '155px', 'left': '75.75%', 'right': 0}),
# ], className='twelve columns'), className='row'),
# ], className='offset-by-nine three columns')
# bottom = html.Div([
# html.Div([
# html.Div('Logs:', className='one columns'),
# html.Div('Level:', className='one columns'),
# html.Div([
# dcc.RangeSlider(
# id='level-slider',
# marks=level_marks,
# min=0,
# max=num_marks-1,
# step=1,
# value=[0, num_marks-1],
# )
# ], className='five columns', style={'margin-top': '-0.5em', 'margin-left': '-1em', })
# ], className='row mb-10'),
# html.Iframe(id='log-frame', style={
# 'width': '100%',
# 'background-color': 'white',
# 'border': '1px solid black',
# 'min-height': '20em',
# 'margin-bottom': '-1em'
# }, className='row'),
# ], className='gray-block')
def make_layout():
return page
# return html.Div([
# html.Div(
# [
# html.Div([
# html.Div([
# left_column, center, right_column
# ], className='row', style={'position': 'absolute', 'bottom': '18em', 'top': '7em', 'right': '1em', 'width': '99%'}),
# # html.Div(
# # bottom
# # , className='row', style={'position': 'absolute', 'bottom': '0.5em', 'right': '1em', 'width': '99%'})
# ]),
# html.Div(id='intermediate-value', style={'display': 'none'}),
# html.Div(id='intermediate-params', style={'display': 'none'}),
# html.Div(id='code-generated', style={'display': 'none'}),
# html.Div(id='code-generated2', style={'display': 'none'}),
# # dcc.Download(id="download-data-csv"),
# html.Div(id='intermediate-status', style={'display': 'none'}),
# html.Div(id='level-log', contentEditable='True', style={'display': 'none'}),
# dcc.Input(id='log-uid', type='text', style={'display': 'none'})
# ], style={'height': '90vh', 'width': '90vw'}
# ),
# ])
# if symbol is None:
# symbol = 'AAPL'
# # app.equity_df.append(yf.download(tickers='AAPL',period='1d',interval='1m', group_by='ticker', auto_adjust = False, prepost = False, threads = True, proxy = None))
# full_report, top_stats, cumulative_returns_plot, annual_monthly_returns_plot, rolling_sharpe_plot, drawdown_periods_plot, drawdown_underwater_plot = key_metrics(symbol)
# kurtosis, profit_ratio, expected_return, exposure, tail_ratio, value_at_risk, payoff_ratio, skew, win_rate, outlier_loss_ratio = top_stats
# headline_stats_df = pd.DataFrame.from_dict({'kurtosis': [kurtosis], 'profit_ratio': [profit_ratio], 'expected_return': [expected_return],
# 'exposure':[exposure], 'tail_ratio':[tail_ratio], 'value_at_risk':[value_at_risk], 'payoff_ratio':[payoff_ratio],
# 'skew':[skew], 'win_rate':[win_rate], 'outlier_loss_ratio':[outlier_loss_ratio]})
# df_dict['Top Stats'] = headline_stats_df
# return html.Div([
# dbc.Card(
# dbc.CardBody([
# dbc.Row([
# dbc.Col([
# drawText('Kurtosis', kurtosis)
# ]),
# dbc.Col([
# drawText('Profit Ratio', profit_ratio)
# ]),
# dbc.Col([
# drawText('Exposure', exposure)
# ]),
# dbc.Col([
# drawText('Tail Ratio', tail_ratio)
# ]),
# dbc.Col([
# drawText('Value at Risk', value_at_risk)
# ]),
# dbc.Col([
# drawText('Payoff Ratio', payoff_ratio)
# ]),
# dbc.Col([
# drawText('Skew', skew)
# ]),
# dbc.Col([
# drawText('Win Rate', win_rate)
# ]),
# # dbc.Col([
# # drawText('Outlier loss Ratio', outlier_loss_ratio)
# # ]),
# ]),
# html.Br(),
# dbc.Row([
# # dbc.Col([
# # eps_trend(symbol),
# # eps_revisions(symbol)
# # ], width=3),
# dbc.Col([
# dbc.Tabs(
# [
# dbc.Tab(cumulative_returns_plot, label='Cumulative Returns', className='nav-pills'),
# dbc.Tab(annual_monthly_returns_plot, label='Annual and Monthly Returns', className='nav-pills'),
# dbc.Tab(rolling_sharpe_plot, label='Rolling Sharpe', className='nav-pills'),
# dbc.Tab(drawdown_periods_plot, label='unfinished', className='nav-pills'),
# dbc.Tab(drawdown_underwater_plot, label='Drawdown Underwater', className='nav-pills'),
# # dbc.Tab(quantiles_plot, label='Scatter'),
# ],
# id='tabs',
# # active_tab='tab-1',
# ),
# ], width=9),
# dbc.Col([
# full_report
# ], width=3),
# ], align='center'),
# html.Br(),
# ]), color = PRIMARY, style ={'border-radius': 10} # all cell border
# )
# ], style={'margin-bottom':'30rem'}
# )
PRIMARY = '#FFFFFF'
SECONDARY = '#FFFFFF'
ACCENT = '#EF5700'
DARK_ACCENT = '#474747'
SIDEBAR = '#F7F7F7'
# PRIMARY = '#15202b'
# SECONDARY = '#192734'
# ACCENT = '#FFFFFF'
# SIDEBAR = '#F4511E'
#F4511E
DATATABLE_STYLE = {
'color': 'white',
'backgroundColor': PRIMARY,
}
DATATABLE_HEADER = {
'backgroundColor': SIDEBAR,
'color': 'white',
'fontWeight': 'bold',
}
TABS_STYLES = {
'height': '44px'
}
TAB_STYLE = {
'padding': '15px',
'fontWeight': 'bold',
'color': DARK_ACCENT,
'backgroundColor': SECONDARY,
'borderRadius': '10px',
'margin-left': '6px',
}
TAB_SELECTED_STYLE = {
'borderTop': '1px solid #d6d6d6',
'borderBottom': '1px solid #d6d6d6',
'backgroundColor': ACCENT,
'color': PRIMARY,
'padding': '15px',
'borderRadius': '10px',
'margin-left': '6px',
}
# helper function for closing temporary files
def close_tmp_file(tf):
try:
os.unlink(tf.name)
tf.close()
except:
pass
# # add csv to download folder
# def add_csv_to_folder(df, name):
# filepath = Path('/finailab_dash/Static/download_folder/' + name + '.csv')
# filepath.parent.mkdir(parents=True, exist_ok=True)
# df.to_csv(filepath)
# Text field
def drawText(title, text):
return html.Div([
dbc.Card([
dbc.CardHeader(title, style={'color': DARK_ACCENT}),
dbc.CardBody([
html.Div([
# html.Header(title, style={'color': 'white', 'fontSize': 15, 'text-decoration': 'underline', 'textAlign': 'left'}),
# html.Br(),
html.Div(str(round(text, 2)), style={'color': DARK_ACCENT, 'textAlign': 'center'}),
# str(round(text, 2))
], style={'color': DARK_ACCENT})
])
], color=PRIMARY, style={'height': 100, 'border-radius': 10}), # , 'backgroundColor':'#FFFFFF', 'border':'1px solid'
])
def beautify_plotly(fig):
return html.Div([
dbc.Card(
dbc.CardBody([
dcc.Graph(
figure=fig,
config={
'displayModeBar': False
}
)
]), color = SECONDARY, style ={'border-radius': 10}
),
])
key_metrics_df = pd.DataFrame()
def key_metrics(symbol):
def get_max_drawdown_underwater_f(underwater):
'''
Determines peak, valley, and recovery dates given an 'underwater'
DataFrame.
An underwater DataFrame is a DataFrame that has precomputed
rolling drawdown.
Parameters
----------
underwater : pd.Series
Underwater returns (rolling drawdown) of a strategy.
Returns
-------
peak : datetime
The maximum drawdown's peak.
valley : datetime
The maximum drawdown's valley.
recovery : datetime
The maximum drawdown's recovery.
'''
#valley = np.argmin(underwater) # end of the period
valley = underwater.index[np.argmin(underwater)] # end of the period
# Find first 0
peak = underwater[:valley][underwater[:valley] == 0].index[-1]
# Find last 0
try:
recovery = underwater[valley:][underwater[valley:] == 0].index[0]
except IndexError:
recovery = np.nan # drawdown not recovered
return peak, valley, recovery
def get_symbol_returns_from_yahoo_f(symbol, start=None, end=None):
'''
Wrapper for pandas.io.data.get_data_yahoo().
Retrieves prices for symbol from yahoo and computes returns
based on adjusted closing prices.
Parameters
----------
symbol : str
Symbol name to load, e.g. 'SPY'
start : pandas.Timestamp compatible, optional
Start date of time period to retrieve
end : pandas.Timestamp compatible, optional
End date of time period to retrieve
Returns
-------
pandas.DataFrame
Returns of symbol in requested period.
'''
try:
px = web.get_data_yahoo(symbol, start=start, end=end)
px['date'] = px.index.to_list()
#px['date'] = px['date'].apply(lambda x: pd.Timestamp(x))
#px['date'] = pd.to_datetime(px['date'])
#px['date'] = pd.to_datetime(px['date'], unit='s')
px.set_index('date', drop=False, inplace=True)
#px.index.rename('date',inplace=True)
rets = px[['Adj Close']].pct_change().dropna()
rets.rename(columns={'Adj Close': 'adjclose'},inplace=True)
except Exception as e:
warnings.warn(
'Yahoo Finance read failed: {}, falling back to Google'.format(e),
UserWarning)
px = web.get_data_google(symbol, start=start, end=end)
rets = px[['Close']].pct_change().dropna()
# rets.index = rets.index.tz_localize('UTC')
rets.columns = [symbol]
return rets
empyrical.utils.get_symbol_returns_from_yahoo = get_symbol_returns_from_yahoo_f
pf.timeseries.get_max_drawdown_underwater = get_max_drawdown_underwater_f
# return pf.create_returns_tear_sheet(stock_rets)
stock_rets = pf.utils.get_symbol_rets(symbol)
# sharpe_ratio = empyrical.sharpe_ratio(stock_rets)
# max_drawdown = empyrical.max_drawdown(stock_rets)
def full_report():
qs.extend_pandas()
df = pd.DataFrame(stock_rets)
df.reset_index(inplace=True)
# df['date'] = df['date'].apply(pd.to_datetime)
# report = qs.reports.metrics(stock_rets, mode='full')
qs.reports.html(stock_rets, output='./assets/full-report.html')
return html.Div([
dbc.Card(
dbc.CardBody(
# html.Iframe(
# src="~/finailab-dash/quantstats-tearsheet.html",
# # style={"height": "1067px", "width": "100%"},
# )
"Coming Soon"
), color = SECONDARY, style ={'border-radius': 10}
),
])
def top_stats():
return [
stats.kurtosis(stock_rets),
stats.profit_ratio(stock_rets),
stats.expected_return(stock_rets),
stats.exposure(stock_rets),
stats.tail_ratio(stock_rets),
stats.value_at_risk(stock_rets),
stats.payoff_ratio(stock_rets),
stats.skew(stock_rets),
stats.win_rate(stock_rets),
stats.outlier_loss_ratio(stock_rets)
]
def cumulative_returns_plot():
# extract data from pyfolio func
plt = pf.plotting.plot_returns(stock_rets)
xy_data = plt.get_lines()[0].get_data()
# create plotly fig
df = pd.DataFrame(xy_data).T
# add_csv_to_folder(df, "cumulative_returns_plot")
df_dict['Cumulative Returns'] = df
fig = px.line(df, x=0, y=1)
fig.update_layout(
title= 'Rolling Sharpe Ratio',
yaxis_title='Returns',
xaxis_title='Date',
# template='plotly_dark',
plot_bgcolor= SECONDARY,
paper_bgcolor= SECONDARY,
font=dict(color=DARK_ACCENT)
)
return beautify_plotly(fig)
def annual_monthly_returns_plot():
fig = make_subplots(rows=1, cols=3)
df = pd.DataFrame(stock_rets)
df['month'] = pd.DatetimeIndex(df.index).month
df['year'] = pd.DatetimeIndex(df.index).year
df[symbol] = df[symbol] * 100
# add_csv_to_folder(df, "annual_monthly_returns_plot")
df_dict['Annual/monthly Returns'] = df
fig1 = px.histogram(df, x=symbol)
fig2 = px.bar(df, x=symbol, y='year', orientation='h')
fig3 = go.Figure(data=go.Heatmap(
z=df[symbol],
x=df['month'],
y=df['year'],
colorscale='YlGn'))
fig = make_subplots(rows=1, cols=3)
for d in fig1.data:
fig.add_trace((go.Scatter(x=d['x'], y=d['y'], name = d['name'])), row=1, col=1)
for d in fig2.data:
fig.add_trace((go.Bar(x=d['x'], y=d['y'], name = d['name'], orientation='h')), row=1, col=2)
for d in fig3.data:
fig.add_trace((go.Heatmap(z=df[symbol], x=df['month'], y=df['year'], colorscale='YlGn')), row=1, col=3)
fig.update_layout(
# template='plotly_dark',
font=dict(color=DARK_ACCENT),
plot_bgcolor= SECONDARY,
paper_bgcolor= SECONDARY,
)
return beautify_plotly(fig)
# def quantiles_plot():
# fig = pf.plot_return_quantiles(stock_rets)
# return (fig)
def rolling_sharpe_plot():
fig = pf.plot_rolling_sharpe(stock_rets)
xy_data = fig.get_lines()[0].get_data()
# create plotly fig
df = pd.DataFrame(xy_data).T
# add_csv_to_folder(df, "rolling_sharpe_plot")
df_dict['Rolling Sharpe'] = df
fig = px.line(df, x=0, y=1)
fig.update_layout(
title= 'Rolling Sharpe Ratio',
yaxis_title='Sharpe Ratio',
xaxis_title='Year',
# template='plotly_dark',
font=dict(color=DARK_ACCENT),
plot_bgcolor= SECONDARY,
paper_bgcolor= SECONDARY,
)
return beautify_plotly(fig)
# NOT FINISHED
def drawdown_periods_plot():
fig = pf.plot_drawdown_periods(stock_rets)
xy_data = fig.get_lines()[0].get_data()
# create plotly fig
df = pd.DataFrame(xy_data).T
# add_csv_to_folder(df, "drawdown_periods_plot")
df_dict['drawdown_periods_plot'] = df
fig = px.line(df, x=0, y=1)
fig.update_layout(
title= 'Top 10 Drawdown Periods',
yaxis_title='Cumulative Returns',
xaxis_title='Year',
# template='plotly_dark',
font=dict(color=DARK_ACCENT),
plot_bgcolor= SECONDARY,
paper_bgcolor= SECONDARY,
)
return beautify_plotly(fig)
def drawdown_underwater_plot():
fig = pf.plot_drawdown_underwater(stock_rets)
xy_data = fig.get_lines()[0].get_data()
# create plotly fig
df = pd.DataFrame(xy_data).T
# add_csv_to_folder(df, "drawdown_underwater_plot")
df_dict['Drawdown Underwater'] = df
fig = px.area(df, x=0, y=1)
fig.update_layout(
title= 'Underwater Plot',
yaxis_title='Drawdown',
xaxis_title='Year',
# template='plotly_dark',
font=dict(color=DARK_ACCENT),
plot_bgcolor= SECONDARY,
paper_bgcolor= SECONDARY,
)
return beautify_plotly(fig)
return full_report(), top_stats(), cumulative_returns_plot(), annual_monthly_returns_plot(), rolling_sharpe_plot(), drawdown_periods_plot(), drawdown_underwater_plot()
def balance_sheet(symbol):
ticker = symbol
data = yf.Ticker(ticker)
df = pd.DataFrame(data.balance_sheet).T
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def eps_trend(symbol):
ticker = symbol
df = si.get_analysts_info(ticker)['EPS Trend'].assign(hack='').set_index('hack')
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def growth_estimates(symbol):
ticker = symbol
df = si.get_analysts_info(ticker)['Growth Estimates'].assign(hack='').set_index('hack')
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def earnings_estimate(symbol):
ticker = symbol
df = si.get_analysts_info(ticker)['Earnings Estimate'].assign(hack='').set_index('hack')
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def revenue_estimate(symbol):
ticker = symbol
df = si.get_analysts_info(ticker)['Revenue Estimate'].assign(hack='').set_index('hack')
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def earnings_history(symbol):
ticker = symbol
df = si.get_analysts_info(ticker)['Earnings History'].assign(hack='').set_index('hack')
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def eps_revisions(symbol):
ticker = symbol
df = si.get_analysts_info(ticker)['EPS Revisions'].assign(hack='').set_index('hack')
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def income_statement(symbol):
ticker = symbol
data = yf.Ticker(ticker)
df = pd.DataFrame(data.financials).T
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER, style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
def cash_flows(symbol):
ticker = symbol
data = yf.Ticker(ticker)
df = pd.DataFrame(data.cashflow).T
return html.Div([
dbc.Card(
dbc.CardBody([dash_table.DataTable(df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns],
style_data=DATATABLE_STYLE, style_header=DATATABLE_HEADER,style_table={'overflowX': 'auto'})
]), color = SECONDARY
),
])
# @app.callback(Output('financials', 'children'), Input('financials-tabs', 'value'), Input('selected-symbol', 'value')
# )
# def render_financials(tab, symbol):
# if symbol is None:
# symbol = 'AAPL'
# if tab == 'balance-sheet':
# return balance_sheet(symbol)
# elif tab == 'income-statement':
# return income_statement(symbol)
# elif tab == 'cash-flows':
# return cash_flows(symbol)
def register_callbacks(app):
@app.server.route('{}<file>'.format(static_route))
def serve_file(file):
if file not in stylesheets and file not in jss:
raise Exception('"{}" is excluded from the allowed static css files'.format(file))
static_directory = os.path.join(root_directory, 'Static')
return flask.send_from_directory(static_directory, file)
@app.callback(Output('module', 'options'), [Input('symbols', 'value')])
def update_algo_list(symbols):
all_files = os.listdir("SampleStrategies")
algo_files = list(filter(lambda f: f.endswith('.py'), all_files))
algo_avlb = [s.rsplit( ".", 1 )[ 0 ] for s in algo_files]
#print(algo_avlb)
return algo_avlb
# @app.callback(Output('strategy', 'options'), [Input('module', 'value')])
# def update_strategy_list(module_name):
# data = ob.test_list(module_name)
# return [{'label': name, 'value': name} for name in data]
@app.callback(Output('strategy', 'options'), [Input('symbols', 'value')])
def update_strategy_list(symbols):
print("strat called")
all_files = os.listdir("MyStrategies")
backtest_files = list(filter(lambda f: f.endswith('.py'), all_files))
backtest_avlb = [s.rsplit( ".", 1 )[ 0 ] for s in backtest_files]
#print(backtest_avlb)
return backtest_avlb
# I think this callback is not needed. No html tag with id = 'params-table' is there
# Commenting out it for now.
# @app.callback(Output('params-table', 'columns'), [Input('module', 'value'), Input('strategy', 'value'), Input('symbols', 'value')])
# def update_params_list(module_name, strategy_name, symbol):
# return ob.params_list(module_name, strategy_name, symbol)
@app.callback(Output('strategy', 'value'), [Input('strategy', 'options')])
def update_strategy_value(options):
if len(options):
#print(options)
return options[0]
return ''
# @app.callback(Output('status-area', 'children'),
# [
# Input('backtest-btn', 'n_clicks'),
# Input('intermediate-params', 'children'),
# Input('intermediate-value', 'children')
# ])
# def update_status_area(n_clicks, packed_params, result):
# if result:
# return 'Done!'
# if n_clicks == 0:
# return ''
# module, strategy, symbol = None, None, None
# try:
# params = json.loads(packed_params)
# if 'module_i' in params:
# module = params['module_i']
# if 'strategy_i' in params:
# strategy = None if params['strategy_i'] == '' else params['strategy_i']
# if 'symbols_i' in params:
# symbol = params['symbols_i']
# except:
# pass
# to_provide = []
# if module is None:
# to_provide.append('module')
# if strategy is None:
# to_provide.append('strategy')
# if symbol is None:
# to_provide.append('symbol')
# if len(to_provide):
# return 'Please provide a value for: {}!'.format(', '.join(to_provide))