/
dashboard.py
1082 lines (858 loc) · 42.8 KB
/
dashboard.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
from logging import error
from pandas._config.config import reset_option
import streamlit as st
import pandas as pd
import plotly
import matplotlib.pyplot as plt
import bt
import plotly.express as px
from tabulate import tabulate
from functions import alloc_table, balance_table, line_chart, monthly_returns_table, optomize_table, plot_pie, display_stats_combined, results_to_df, highlight_cols, scatter_plot, short_stats_table, stats_table, sum_table, monthly_table
st.set_page_config(layout="wide") #makes page wider
@st.cache
def get_data_f(dontchange):
s_data = bt.get('spy,efa,iwm,vwo,ibb,agg,hyg,gld,slv,tsla,aapl,msft,qqq', start = '2017-01-01')
cry_data = bt.get('btc-usd,eth-usd', start = '2017-01-01')
data_cache = cry_data.join(s_data, how='outer')
data_cache = data_cache.dropna()
return data_cache
dontchange = 0
data = get_data_f(dontchange)
# st.markdown(
# """
# <style>
# .main {
# background-color: #478f7c;
# }
# </style>
# """,
# unsafe_allow_html=True
# )
word = "Dashboard"
#st.title(word)
class WeighSpecified(bt.Algo):
def __init__(self, **weights):
super(WeighSpecified, self).__init__()
self.weights = weights
def __call__(self, target):
# added copy to make sure these are not overwritten
target.temp["weights"] = self.weights.copy()
return True
st.sidebar.write("Options")
option = st.sidebar.selectbox("Select an Option", ('Portfolio Optimizer','Flexible Dashboard', 'BTC Portfolio Dashboard'))
start_date = '2017-01-01'
if ( option == 'Chart'):
#Beta Columns and Containers
col1_s, col2_s = st.sidebar.beta_columns(2)
col1, col2 = st.beta_columns((2, 1))
col1_header = col1.beta_container()
col2_header = col2.beta_container()
col1_graph = col1.beta_container()
col2_graph = col2.beta_container()
col1_second = col1.beta_container()
col2_second = col2.beta_container()
#Sidebar Inputs
stock_choice_1 = col1_s.selectbox( "Ticker 1", ('spy', 'efa', 'iwm', 'vwo', 'ibb', 'agg', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'btc-usd', 'eth-usd')) #get ticker
percent_1 = col2_s.text_input( "% Allocation", value = 55, max_chars= 3, ) # get percent
stock_choice_1 = stock_choice_1.lower() #bt likes lower case
data_1 = bt.get(stock_choice_1, start = start_date) # get the data
stock_choice_2 = col1_s.selectbox( "Ticker 2", ('agg', 'spy', 'efa', 'iwm', 'vwo', 'ibb', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'btc-usd', 'eth-usd'))
percent_2 = col2_s.text_input( "% Allocation", value = 40, max_chars= 3)
stock_choice_2 = stock_choice_2.lower()
data_2 = bt.get(stock_choice_2, start = start_date)
stock_choice_3 = col1_s.selectbox( "Ticker 3", ('btc-usd', 'spy', 'efa', 'iwm', 'vwo', 'ibb', 'agg', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'eth-usd'))
percent_3 = col2_s.text_input( "% Allocation", value = 5, max_chars= 3)
stock_choice_3 = stock_choice_3.lower()
data_3 = bt.get(stock_choice_3, start = start_date)
#allows us to combine the datasets to account for the difference in reg vs. Crypto
data = data_1.join(data_2, how='outer')
data = data.join(data_3, how= 'outer')
data = data.dropna()
#need the '-' in cryptos to get the data, but bt needs it gone to work
stock_choice_1 = stock_choice_1.replace('-', '')
stock_choice_2 = stock_choice_2.replace('-', '')
stock_choice_3 = stock_choice_3.replace('-', '')
#Buttons
rebalances = col1_graph.selectbox("Rebalancing Timeline", ('Daily', 'Monthly', 'Yearly', 'None'))
#creating Strategy and Backtest
stock_list = stock_choice_1 +',' + stock_choice_2 + ',' + stock_choice_3 #list of tickers to get data for
stock_list_plt = [stock_choice_1, stock_choice_2, stock_choice_3]
percent_list = [percent_1, percent_2, percent_3]
stock_dic = {stock_choice_1: float(percent_1)/100, stock_choice_2: float(percent_2)/100, stock_choice_3: float(percent_3)/100} #dictonary for strat
stock_dic_control = {'spy': float(60)/100, 'agg': float(40)/100, stock_choice_3: float(0)/100}
stock_dic_spy = {'spy': float(100)/100, 'agg': float(0)/100, stock_choice_3: float(0)/100}
stock_dic_agg = {'spy': float(0)/100, 'agg': float(100)/100, stock_choice_3: float(0)/100}
strategy_ = bt.Strategy('Your Strategy Monthly',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
strategy_spy = bt.Strategy('SPY',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_spy),
bt.algos.Rebalance()]) #Creating strategy
strategy_agg = bt.Strategy('AGG',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_agg),
bt.algos.Rebalance()]) #Creating strategy
if (rebalances == 'Daily'):
strategy_ = bt.Strategy('Your Strategy Daily',
[bt.algos.RunDaily(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Daily',
[bt.algos.RunDaily(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
elif (rebalances == 'Monthly'):
strategy_ = bt.Strategy('Your Strategy Monthly',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Monthly',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
elif (rebalances == 'Yearly'):
strategy_ = bt.Strategy('Your Strategy Yearly',
[bt.algos.RunYearly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Yearly',
[bt.algos.RunYearly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
elif (rebalances == 'None'):
strategy_ = bt.Strategy('Your Strategy None',
[bt.algos.RunOnce(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 None',
[bt.algos.RunOnce(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
test_control = bt.Backtest(strategy_control, data)
results_control = bt.run(test_control)
test_spy = bt.Backtest(strategy_spy, data)
results_spy = bt.run(test_spy)
test_agg = bt.Backtest(strategy_agg, data)
results_agg = bt.run(test_agg)
test = bt.Backtest(strategy_, data)
results = bt.run(test)
#Line Chart
ser = results._get_series(None).rebase() #gets all the daily balances as a series
ser2 = results_control._get_series(None).rebase()
result_final = pd.concat([ser, ser2], axis=1) #makes dataframe for both series
col1_header.header("Returns Graph")
col1_graph.line_chart(result_final)
#Pie Chart
if (rebalances == 'None'): #pie chart is wrong since no rebalances
key = results._get_backtest(0) #Chunk of code is how to get the weights, straight from doc
filter = None
if filter is not None:
data = results.backtests[key].security_weights[filter]
else:
data = results.backtests[key].security_weights
for i in range(len(percent_list)): #puts all the right values into the percent list
percent_list[i] = str(round(data[stock_list_plt[i]].iloc[-1]*100))
fig = plot_pie(stock_list_plt, percent_list)
col2_header.header("Pie Chart")
col2_header.pyplot(fig)
#Display Results
results_list = [results, results_control, results_spy, results_agg] #list of results objects
results_df = results_to_df(results_list) #list of the results but now in dataframe
stats = display_stats_combined(results_list)
if (col2_second.button("Display Stats")):#button logic
if(col2_second.button("Hide Stats")):
do_nothing = 0 #literally do nothing
col2_second.dataframe(stats)
col1_second.write(results.display_lookback_returns()) # displays the shortened stats
#Display the Monthly Returns
mon_table = monthly_returns_table(results_list)
st.dataframe(mon_table)
#Scatter of Risk vs Return
fig = scatter_plot(results_df) #scatter function in functions
col2_second.plotly_chart(fig)
#Allocation Table
rebalance_list = [3, 4, 5]
fig = alloc_table(stock_list_plt, percent_list, rebalance_list)
col2.plotly_chart(fig)
elif ( option == 'BTC Portfolio Dashboard'):
#Beta Columns
col1_s, col2_s = st.sidebar.beta_columns(2)
col1, col2 = st.beta_columns((1, 2))
col3, col4, col5 = st.beta_columns((1,1,3))
col1_top = col1.beta_container()
col1_middle = col1.beta_container()
col1_bot = col1.beta_container()
col2t =col2.beta_container()
col2b =col2.beta_container()
table = st.beta_container()
#Creating Strategy and Backtest
slider_input = col1_middle.slider('Percent of BTC-USD in Portfolio', min_value= 0, max_value= 10, value= 5 )
#hardcoding in the values since we dont have user input
stock_choice_1 = 'spy'
stock_choice_2 = 'agg'
stock_choice_3 = 'btc-usd'
stock_list_plt = [stock_choice_1, stock_choice_2, stock_choice_3]
percent_1 = 60-slider_input
percent_2 = 40
percent_3 = slider_input
percent_list = [percent_1, percent_2, percent_3]
#get data seperatly because crypto and reg data dont work together
# data_1 = bt.get(stock_choice_1, start = start_date)
# data_2 = bt.get(stock_choice_2, start = start_date)
# data_3 = bt.get(stock_choice_3, start = start_date)
#Allows for crypto and stock to be in a dataframe
# data = data_1.join(data_2, how='outer')
# data = data.join(data_3, how= 'outer')
# data = data.dropna()
stock_choice_3 = stock_choice_3.replace('-', '') #get data with btc-usd but then bt likes btcusd
stock_dic = {stock_choice_1: float(percent_1)/100, stock_choice_2: float(percent_2)/100, stock_choice_3: float(percent_3)/100} #dictonary for strat
stock_dic_control = {stock_choice_1: float(60)/100, stock_choice_2: float(40)/100, stock_choice_3: float(0)/100} #60-40
stock_dic_spy = {'spy': float(100)/100, 'agg': float(0)/100, stock_choice_3: float(0)/100} #all spy
stock_dic_agg = {'spy': float(0)/100, 'agg': float(100)/100, stock_choice_3: float(0)/100} #all agg
strategy_ = bt.Strategy('Your Strategy',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Portfolio',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
strategy_spy = bt.Strategy('SPY',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_spy),
bt.algos.Rebalance()]) #Creating strategy
strategy_agg = bt.Strategy('AGG',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_agg),
bt.algos.Rebalance()]) #Creating strategy
test_control = bt.Backtest(strategy_control, data)
results_control = bt.run(test_control)
test_spy = bt.Backtest(strategy_spy, data)
results_spy = bt.run(test_spy)
test_agg = bt.Backtest(strategy_agg, data)
results_agg = bt.run(test_agg)
test = bt.Backtest(strategy_, data)
results = bt.run(test)
results_list = [results, results_control, results_spy, results_agg]
results_df = results_to_df(results_list) #list of the results but now in dataframe
#Line Chart
fig = line_chart(results_list)
col1.header("Returns Graph")
col2.plotly_chart(fig)
col5.write("- Click on the legend entries to choose which datasets to display")
#Pie Chart
fig = plot_pie(stock_list_plt, percent_list)
col1_top.header("Pie Chart")
col1_top.pyplot(fig)
#Display Results
# results_list = [results, results_control, results_spy, results_agg] #list of results objects
# results_df = results_to_df(results_list) #list of the results but now in dataframe
# stats = display_stats_combined(results_list)
# if (col2_second.button("Display Stats")):
# if(col2_second.button("Hide Stats")):
# yo = 1
# col2_second.dataframe(stats)
# col1_second.write(results.display_lookback_returns())
#Display the Monthly Returns
mon_table = monthly_returns_table(results_list)
#st.dataframe(mon_table.style.apply(highlight_cols, axis = None))
#Scatter of Risk vs Return
fig = scatter_plot(results_df) #scatter function in functions
fig.update_layout(width = 750, height = 500)
col2t.plotly_chart(fig, width = 750, height =500)
#Allocation Table
rebalance_list = [3, 4, 5]
fig = alloc_table(stock_list_plt, percent_list, rebalance_list)
fig.update_layout(width = 400, height = 130)
#col1.plotly_chart(fig, width = 400, height = 130)
#Balance Table
fig = balance_table(results, results_control)
fig.update_layout(width = 380, height = 75)
col1.plotly_chart(fig, width = 380, height = 75)
#Short Stats Table
fig = short_stats_table(results_list)
fig.update_layout(width = 380, height = 300)
col1.header("Return Statistics")
col1.plotly_chart(fig, width = 380, height = 300)
#Monthly Table
#my_expander = st.beta_expander("Show Monthly Returns")
fig = monthly_table(results_list)
fig.update_layout(width = 1100, height = 2000)
st.plotly_chart(fig, width = 1100, height = 2000)
#Stats Table
stats_expander = col1.beta_expander("Click to Show Strategy Statistics")
fig = stats_table(results_list)
fig.update_layout(width = 380)
stats_expander.plotly_chart(fig, width = 380)
if ( option == 'Flexible Dashboard'):
#Beta Columns and Containers
col1_s, col2_s = st.sidebar.beta_columns(2)
col1, col2 = st.beta_columns((1, 2))
col3, col4, col5 = st.beta_columns((1,1,3))
col1_top = col1.beta_container()
col1_middle = col1.beta_container()
col1_bot = col1.beta_container()
col2t =col2.beta_container()
col2b =col2.beta_container()
col1_header = col1.beta_container()
col2_header = col2.beta_container()
col1_graph = col1.beta_container()
col2_graph = col2.beta_container()
col1_second = col1.beta_container()
col2_second = col2.beta_container()
table = st.beta_container()
#Sidebar Inputs
stock_choice_1 = col1_s.selectbox( "Ticker 1", ('spy', 'efa', 'iwm', 'vwo', 'ibb', 'agg', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'btc-usd', 'eth-usd')) #get ticker
percent_1 = col2_s.text_input( "% Allocation", value = 55, max_chars= 3, ) # get percent
stock_choice_1 = stock_choice_1.lower() #bt likes lower case
#data_1 = bt.get(stock_choice_1, start = start_date) # get the data
stock_choice_2 = col1_s.selectbox( "Ticker 2", ('agg', 'spy', 'efa', 'iwm', 'vwo', 'ibb', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'btc-usd', 'eth-usd'))
percent_2 = col2_s.text_input( "% Allocation", value = 40, max_chars= 3)
stock_choice_2 = stock_choice_2.lower()
#data_2 = bt.get(stock_choice_2, start = start_date)
stock_choice_3 = col1_s.selectbox( "Ticker 3", ('btc-usd', 'spy', 'efa', 'iwm', 'vwo', 'ibb', 'agg', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'eth-usd'))
percent_3 = col2_s.text_input( "% Allocation", value = 5, max_chars= 3)
stock_choice_3 = stock_choice_3.lower()
#data_3 = bt.get(stock_choice_3, start = start_date)
if(float(percent_1)+float(percent_2)+float(percent_3) != 100):
st.sidebar.error("Allocation Must Equal 100")
#allows us to combine the datasets to account for the difference in reg vs. Crypto
# data = data_1.join(data_2, how='outer')
# data = data.join(data_3, how= 'outer')
# data = data.dropna()
#data_con = bt.get('spy,agg,gme', start = start_date)
#need the '-' in cryptos to get the data, but bt needs it gone to work
stock_choice_1 = stock_choice_1.replace('-', '')
stock_choice_2 = stock_choice_2.replace('-', '')
stock_choice_3 = stock_choice_3.replace('-', '')
#Buttons
#rebalances = col1_graph.selectbox("Rebalancing Timeline", ('Daily', 'Monthly', 'Yearly', 'None'))
rebalances = 'Monthly'
#creating Strategy and Backtest
stock_list = stock_choice_1 +',' + stock_choice_2 + ',' + stock_choice_3 #list of tickers to get data for
stock_list_plt = [stock_choice_1, stock_choice_2, stock_choice_3]
percent_list = [percent_1, percent_2, percent_3]
stock_dic = {stock_choice_1: float(percent_1)/100, stock_choice_2: float(percent_2)/100, stock_choice_3: float(percent_3)/100} #dictonary for strat
stock_dic_control = {'spy': float(60)/100, 'agg': float(40)/100, stock_choice_3: float(0)/100}
stock_dic_spy = {'spy': float(100)/100, 'agg': float(0)/100, stock_choice_3: float(0)/100}
stock_dic_agg = {'spy': float(0)/100, 'agg': float(100)/100, stock_choice_3: float(0)/100}
strategy_ = bt.Strategy('Your Strategy',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Portfolio',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
strategy_spy = bt.Strategy('SPY',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_spy),
bt.algos.Rebalance()]) #Creating strategy
strategy_agg = bt.Strategy('AGG',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_agg),
bt.algos.Rebalance()]) #Creating strategy
strategy_daily = bt.Strategy('Daily',
[bt.algos.RunDaily(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_monthly = bt.Strategy('Monthly',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_yearly = bt.Strategy('Yearly',
[bt.algos.RunYearly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_none = bt.Strategy('No Rebalances',
[bt.algos.RunOnce(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
#old rebalances
if (rebalances == 'Daily'):
strategy_daily = bt.Strategy('Your Strategy Daily',
[bt.algos.RunDaily(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Daily',
[bt.algos.RunDaily(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
elif (rebalances == 'Monthly'):
strategy_monthly = bt.Strategy('Monthly',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Portfolio',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
elif (rebalances == 'Yearly'):
strategy_yearly = bt.Strategy('Your Strategy Yearly',
[bt.algos.RunYearly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 Yearly',
[bt.algos.RunYearly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
elif (rebalances == 'None'):
strategy_none = bt.Strategy('Your Strategy None',
[bt.algos.RunOnce(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_control = bt.Strategy('60-40 None',
[bt.algos.RunOnce(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_control),
bt.algos.Rebalance()]) #Creating strategy
#results
test_control = bt.Backtest(strategy_control, data)
results_control = bt.run(test_control)
test_spy = bt.Backtest(strategy_spy, data)
results_spy = bt.run(test_spy)
test_agg = bt.Backtest(strategy_agg, data)
results_agg = bt.run(test_agg)
test = bt.Backtest(strategy_, data)
results = bt.run(test)
#Rebalance Strategies
test_d = bt.Backtest(strategy_daily, data)
results_daily = bt.run(test_d)
test_m = bt.Backtest(strategy_monthly, data)
results_monthly = bt.run(test_m)
test_y = bt.Backtest(strategy_yearly, data)
results_yearly = bt.run(test_y)
test_n = bt.Backtest(strategy_none, data)
results_none = bt.run(test_n)
results_list = [results, results_control, results_spy, results_agg] #list of results objects
results_list_reb = [results_daily, results_monthly, results_yearly, results_none]
#Line Chart
fig = line_chart(results_list)
fig.update_layout(width = 700)
fig2 = line_chart(results_list_reb)
fig2.update_layout(width = 700)
figure = fig
box = col2b.checkbox('Compare Rebalancing Options for Your Strategy')
if box:
figure = fig2
col2b.plotly_chart(figure)
col5.write("- Click on the legend entries to choose which datasets to display")
#Pie Chart
if (rebalances == 'None'): #pie chart is wrong since no rebalances
key = results._get_backtest(0) #Chunk of code is how to get the weights, straight from doc
filter = None
if filter is not None:
data = results.backtests[key].security_weights[filter]
else:
data = results.backtests[key].security_weights
for i in range(len(percent_list)): #puts all the right values into the percent list
percent_list[i] = str(round(data[stock_list_plt[i]].iloc[-1]*100))
fig = plot_pie(stock_list_plt, percent_list)
fig.set_facecolor('#fafafa')
col1_top.header("PORTFOLIO ALLOCATION")
col1_top.pyplot(fig)
#Display Results
results_df = results_to_df(results_list) #list of the results but now in dataframe
stats = display_stats_combined(results_list)
# if (col2_second.button("Display Stats")):#button logic
# if(col2_second.button("Hide Stats")):
# do_nothing = 0 #literally do nothing
#col2_second.dataframe(stats)
#col1_second.write(results.display_lookback_returns()) # displays the shortened stats
#Display the Monthly Returns
mon_table = monthly_returns_table(results_list)
#st.dataframe(mon_table.style.apply(highlight_cols, axis = None))
#Scatter of Risk vs Return
fig = scatter_plot(results_df) #scatter function in functions
fig.update_layout(width = 750, height = 500)
col2t.plotly_chart(fig, width = 750, height =500)
#Allocation Table
rebalance_list = [3, 4, 5]
fig = alloc_table(stock_list_plt, percent_list, rebalance_list)
fig.update_layout(width = 400, height = 130)
#col1.plotly_chart(fig, width = 400, height = 130)
#Balance Table
fig = balance_table(results, results_control)
fig.update_layout(width = 400, height = 75)
col1.plotly_chart(fig, width = 400, height = 75)
#Short Stats Table
fig = short_stats_table(results_list)
fig.update_layout(width = 380, height = 300)
col1.header("Return Statistics")
col1.plotly_chart(fig, width = 380, height = 300)
#Monthly Table
#my_expander = st.beta_expander("Show Monthly Returns")
fig = monthly_table(results_list)
fig.update_layout(width = 1100, height = 800)
st.plotly_chart(fig, width = 1100, height = 800)
#Stats Table
stats_expander = col1.beta_expander("Click to Show Strategy Statistics")
fig = stats_table(results_list)
fig.update_layout(width = 380)
stats_expander.plotly_chart(fig, width = 380)
elif (option == 'Portfolio Optimizer'):
#Beta Columns
col1_s, col2_s = st.sidebar.beta_columns(2)
col1, col2 = st.beta_columns((1, 2))
#Get data
stock_symbols = st.sidebar.text_input("Enter the Stock Tickers Spaced", value = "spy iwm eem efa gld agg hyg" )
crypto_symbols = st.sidebar.text_input("Enter Crypto Tickers Spaced", value= 'btc-usd')
stock_symbols = stock_symbols.replace(' ', ',')
crypto_symbols = crypto_symbols.replace(' ', ',')
data_type = st.sidebar.selectbox("Select the Data Frequency", ('Daily Data', 'Monthly Data', 'Quarterly Data', 'Yearly Data'))
# symbols = 'spy,iwm,eem,efa,gld,agg,hyg'
# crypto_symbols = 'btc-usd,eth-usd'
stock_data = bt.get(stock_symbols, start='1993-01-01')
crypto_data = bt.get(crypto_symbols, start='2016-01-01')
#Merge into dataframe
data_ = crypto_data.join(stock_data, how='outer')
data_ = data_.dropna()
#Daily optimal
if (data_type == "Daily Data"):
#gets daily optimal data
returns = data_.to_log_returns().dropna()
daily_opt = returns.calc_mean_var_weights().as_format(".2%")
#table
fig = optomize_table(daily_opt)
col1.header("Daily Data")
fig.update_layout(width = 300, height = 450)
col1.plotly_chart(fig, width = 300, height = 450)
#preparing data for charts
stock_dic = daily_opt.to_dict()
for key in stock_dic: #makes percents numbers
stock_dic[key] = float(stock_dic[key].replace('%', ''))
stock_dic[key] = stock_dic[key]/100
stock_list = list(stock_dic.keys()) #convert the dictionary into lists for plotting
percent_list = list(stock_dic.values())
temp = []
temp_stock = []
for i in range(len(percent_list)): #Takes out values of 0
if (percent_list[i] != 0):
temp.append(percent_list[i])
temp_stock.append(stock_list[i])
stock_list = temp_stock
percent_list= temp
strategy_color = '#A90BFE'
P6040_color = '#FF7052'
spy_color = '#66F3EC'
agg_color = '#67F9AF'
stock_dic_spy = {'spy': float(100)/100, 'agg': float(0)/100, 'gme': float(0)/100} #all spy
stock_dic_agg = {'spy': float(0)/100, 'agg': float(100)/100, 'gme': float(0)/100} #all agg
strategy_op = bt.Strategy('Your Portolio Optomized',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_port = bt.Strategy('Your Portolio Equal',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighEqually(),
bt.algos.Rebalance()]) #Creating strategy
strategy_spy = bt.Strategy('SPY',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_spy),
bt.algos.Rebalance()]) #Creating strategy
strategy_agg = bt.Strategy('AGG',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_agg),
bt.algos.Rebalance()]) #Creating strategy
test_op = bt.Backtest(strategy_op, data_)
results_op = bt.run(test_op)
test_port = bt.Backtest(strategy_port, data_)
results_port = bt.run(test_port)
test_spy = bt.Backtest(strategy_spy, data)
results_spy = bt.run(test_spy)
test_agg = bt.Backtest(strategy_agg, data)
results_agg = bt.run(test_agg)
#pie chart
results_list = [results_op, results_port]
pie_colors = [strategy_color, P6040_color, spy_color, agg_color, '#7496F3', '#B7FA59', 'brown', '#EE4444', 'gold']
fig = plot_pie(stock_list, percent_list, pie_colors)
#fig.set_size_inches(18.5, 18.5, forward=True) #how to change dimensions since pie is in matplotlib
#col1.header("Optomized Portfolio")
col1.pyplot(fig)
#line chart
fig = line_chart(results_list)
fig.update_layout(width = 750, height = 400)
col2.header("Daily Performance")
col2.plotly_chart(fig, width = 750, height = 400)
#Scatter PLot
results_list.append(results_spy)
results_list.append(results_agg)
results_df = results_to_df(results_list)
fig = scatter_plot(results_df) #scatter function in functions
fig.update_layout(width = 750, height = 500)
col2.plotly_chart(fig, width = 750, height =500)
#Monthly optimal
if (data_type == "Monthly Data"):
#gets daily optimal data
returns = data_.asfreq("M",method='ffill').to_log_returns().dropna()
mon_opt = returns.calc_mean_var_weights().as_format(".2%")
#table
fig = optomize_table(mon_opt)
col1.header("Monthly Data")
fig.update_layout(width = 300, height = 450)
col1.plotly_chart(fig, width = 300, height = 450)
#preparing data for charts
stock_dic = mon_opt.to_dict()
for key in stock_dic: #makes percents numbers
stock_dic[key] = float(stock_dic[key].replace('%', ''))
stock_dic[key] = stock_dic[key]/100
stock_list = list(stock_dic.keys()) #convert the dictionary into lists for plotting
percent_list = list(stock_dic.values())
temp = []
temp_stock = []
for i in range(len(percent_list)): #Takes out values of 0
if (percent_list[i] != 0):
temp.append(percent_list[i])
temp_stock.append(stock_list[i])
stock_list = temp_stock
percent_list= temp
strategy_color = '#A90BFE'
P6040_color = '#FF7052'
spy_color = '#66F3EC'
agg_color = '#67F9AF'
stock_dic_spy = {'spy': float(100)/100, 'agg': float(0)/100, 'gme': float(0)/100} #all spy
stock_dic_agg = {'spy': float(0)/100, 'agg': float(100)/100, 'gme': float(0)/100} #all agg
strategy_op = bt.Strategy('Your Portolio Optomized',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_port = bt.Strategy('Your Portolio Equal',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighEqually(),
bt.algos.Rebalance()]) #Creating strategy
strategy_spy = bt.Strategy('SPY',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_spy),
bt.algos.Rebalance()]) #Creating strategy
strategy_agg = bt.Strategy('AGG',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_agg),
bt.algos.Rebalance()]) #Creating strategy
test_op = bt.Backtest(strategy_op, data_)
results_op = bt.run(test_op)
test_port = bt.Backtest(strategy_port, data_)
results_port = bt.run(test_port)
test_spy = bt.Backtest(strategy_spy, data)
results_spy = bt.run(test_spy)
test_agg = bt.Backtest(strategy_agg, data)
results_agg = bt.run(test_agg)
#pie chart
results_list = [results_op, results_port]
pie_colors = [strategy_color, P6040_color, spy_color, agg_color, '#7496F3', '#B7FA59', 'brown', '#EE4444', 'gold']
fig = plot_pie(stock_list, percent_list, pie_colors)
#fig.set_size_inches(18.5, 18.5, forward=True) #how to change dimensions since pie is in matplotlib
#col1.header("Optomized Portfolio")
col1.pyplot(fig)
#line chart
fig = line_chart(results_list)
fig.update_layout(width = 750, height = 400)
col2.header("Daily Performance")
col2.plotly_chart(fig, width = 750, height = 400)
#Scatter PLot
results_list.append(results_spy)
results_list.append(results_agg)
results_df = results_to_df(results_list)
fig = scatter_plot(results_df) #scatter function in functions
fig.update_layout(width = 750, height = 500)
col2.plotly_chart(fig, width = 750, height =500)
#Quarterly Optimal
if (data_type == "Quarterly Data"):
#gets quarterly optimal data
quarterly_rets = data_.asfreq("Q",method='ffill').to_log_returns().dropna()
quart_opt = quarterly_rets.calc_mean_var_weights().as_format(".2%")
#table
fig = optomize_table(quart_opt)
col1.header("Quarterly Data")
fig.update_layout(width = 300, height = 450)
col1.plotly_chart(fig, width = 300, height = 450)
#preparing data for charts
stock_dic = quart_opt.to_dict()
for key in stock_dic: #makes percents numbers
stock_dic[key] = float(stock_dic[key].replace('%', ''))
stock_dic[key] = stock_dic[key]/100
stock_list = list(stock_dic.keys()) #convert the dictionary into lists for plotting
percent_list = list(stock_dic.values())
temp = []
temp_stock = []
for i in range(len(percent_list)): #Takes out values of 0
if (percent_list[i] != 0):
temp.append(percent_list[i])
temp_stock.append(stock_list[i])
stock_list = temp_stock
percent_list= temp
strategy_color = '#A90BFE'
P6040_color = '#FF7052'
spy_color = '#66F3EC'
agg_color = '#67F9AF'
stock_dic_spy = {'spy': float(100)/100, 'agg': float(0)/100, 'gme': float(0)/100} #all spy
stock_dic_agg = {'spy': float(0)/100, 'agg': float(100)/100, 'gme': float(0)/100} #all agg
strategy_op = bt.Strategy('Your Portolio Optomized',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic),
bt.algos.Rebalance()]) #Creating strategy
strategy_port = bt.Strategy('Your Portolio Equal',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighEqually(),
bt.algos.Rebalance()]) #Creating strategy
strategy_spy = bt.Strategy('SPY',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_spy),
bt.algos.Rebalance()]) #Creating strategy
strategy_agg = bt.Strategy('AGG',
[bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(**stock_dic_agg),
bt.algos.Rebalance()]) #Creating strategy
test_op = bt.Backtest(strategy_op, data_)
results_op = bt.run(test_op)
test_port = bt.Backtest(strategy_port, data_)
results_port = bt.run(test_port)
test_spy = bt.Backtest(strategy_spy, data)
results_spy = bt.run(test_spy)
test_agg = bt.Backtest(strategy_agg, data)
results_agg = bt.run(test_agg)
#pie chart
results_list = [results_op, results_port]
pie_colors = [strategy_color, P6040_color, spy_color, agg_color, '#7496F3', '#B7FA59', 'brown', '#EE4444', 'gold']
fig = plot_pie(stock_list, percent_list, pie_colors)
#fig.set_size_inches(18.5, 18.5, forward=True) #how to change dimensions since pie is in matplotlib
#col1.header("Optomized Portfolio")
col1.pyplot(fig)
#line chart
fig = line_chart(results_list)
fig.update_layout(width = 750, height = 400)
col2.header("Daily Performance")
col2.plotly_chart(fig, width = 750, height = 400)
#Scatter PLot
results_list.append(results_spy)
results_list.append(results_agg)
results_df = results_to_df(results_list)
fig = scatter_plot(results_df) #scatter function in functions
fig.update_layout(width = 750, height = 500)
col2.plotly_chart(fig, width = 750, height =500)
#Yearly Optimal
if (data_type == "Yearly Data"):
#gets Yearly optimal data
year_rets = data_.asfreq("Y",method='ffill').to_log_returns().dropna()
year_opt = year_rets.calc_mean_var_weights().as_format(".2%")
#table
fig = optomize_table(year_opt)
col1.header("Yearly Data")
fig.update_layout(width = 300, height = 450)
col1.plotly_chart(fig, width = 300, height = 450)
#preparing data for charts
stock_dic = year_opt.to_dict()