-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsua(old).py
1410 lines (1155 loc) · 41.1 KB
/
sua(old).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 numpy as np
import pandas as pd
import datetime as dt
import quantstats as qs
from IPython.display import display
import matplotlib.pyplot as plt
import copy
import yfinance as yf
from fpdf import FPDF
import warnings
#import filterwarnings
# Using Python library with performance and risk statistics commonly used in quantitative finance.
from empyrical import (
cagr,
cum_returns,
stability_of_timeseries,
max_drawdown,
sortino_ratio,
alpha_beta,
tail_ratio,
)
# PyPortfolioOpt is a library that implements portfolio optimization methods, including classical mean-variance optimization techniques and Black-Litterman allocation, as well as more recent developments in the field like shrinkage and Hierarchical Risk Parity.
from pypfopt import (
EfficientFrontier,
risk_models,
expected_returns,
HRPOpt,
objective_functions,
black_litterman,
BlackLittermanModel,
)
# Importing prediction models, metrics and logging
from prophet import Prophet
from darts.models import *
from darts import TimeSeries
from darts.utils.missing_values import fill_missing_values
from darts.metrics import mape, mase
import logging
warnings.filterwarnings("ignore")
TODAY = dt.date.today()
BENCHMARK = ["SPY"]
DAYS_IN_YEAR = 365
rebalance_periods = {
"daily": DAYS_IN_YEAR / 365,
"weekly": DAYS_IN_YEAR / 52,
"monthly": DAYS_IN_YEAR / 12,
"month": DAYS_IN_YEAR / 12,
"m": DAYS_IN_YEAR / 12,
"quarterly": DAYS_IN_YEAR / 4,
"quarter": DAYS_IN_YEAR / 4,
"q": DAYS_IN_YEAR / 4,
"6m": DAYS_IN_YEAR / 2,
"2q": DAYS_IN_YEAR / 2,
"1y": DAYS_IN_YEAR,
"year": DAYS_IN_YEAR,
"y": DAYS_IN_YEAR,
"2y": DAYS_IN_YEAR * 2,
}
class Start:
def __init__(
self,
start_date,
portfolio,
weights=None,
rebalance=None,
benchmark=None,
end_date=TODAY,
optimizer=None,
max_vol=0.15,
diversification=1,
# confidences=None,
# view=None,
min_weights=None,
max_weights=None,
risk_manager=None,
data=None,
):
if benchmark is None:
benchmark = BENCHMARK
self.start_date = start_date
self.end_date = end_date
self.portfolio = portfolio
self.weights = weights
self.benchmark = benchmark
self.optimizer = optimizer
self.rebalance = rebalance
self.max_vol = max_vol
self.diversification = diversification
self.max_weights = max_weights
self.min_weights = min_weights
self.risk_manager = risk_manager
self.data = data
optimizers = {
"EF": efficient_frontier,
"MEANVAR": mean_var,
"HRP": hrp,
"MINVAR": min_var,
}
if self.optimizer is None and self.weights is None:
self.weights = [1.0 / len(self.portfolio)] * len(self.portfolio)
elif self.optimizer in optimizers.keys():
if self.optimizer == "MEANVAR":
self.weights = optimizers.get(self.optimizer)(
self, vol_max=max_vol, perf=False)
else:
self.weights = optimizers.get(self.optimizer)(self, perf=False)
if self.rebalance is not None:
self.rebalance = make_rebalance(
self.start_date,
self.end_date,
self.optimizer,
self.portfolio,
self.rebalance,
self.weights,
self.max_vol,
self.diversification,
self.min_weights,
self.max_weights,
)
def get_returns(stocks, wts, start_date, end_date=TODAY):
if len(stocks) > 1:
assets = yf.download(stocks, start=start_date,
end=end_date, progress=False)["Adj Close"]
assets = assets.filter(stocks)
ret_data = assets.pct_change()[1:]
returns = (ret_data * wts).sum(axis=1)
return returns
else:
df = yf.download(stocks, start=start_date,
end=end_date, progress=False)["Adj Close"]
df = pd.DataFrame(df)
returns = df.pct_change()
return returns
def get_returns_from_data(data, wts):
ret_data = data.pct_change()[1:]
returns = (ret_data * wts).sum(axis=1)
return returns
def calculate_information_ratio(returns, benchmark_returns, days=252) -> float:
return_difference = returns - benchmark_returns
volatility = return_difference.std() * np.sqrt(days)
information_ratio_result = return_difference.mean() / volatility
return information_ratio_result
def graph_allocation(my_portfolio):
fig1, ax1 = plt.subplots()
ax1.pie(
my_portfolio.weights,
labels=my_portfolio.portfolio,
autopct="%1.1f%%",
shadow=False,
)
# Equal aspect ratio ensures that pie is drawn as a circle.
ax1.axis("equal")
plt.title("Portfolio's allocation")
plt.show()
def sua(my_portfolio, rf=0.0, sigma_value=1, confidence_value=0.95):
try:
# we want to get the dataframe with the dates and weights
rebalance_schedule = my_portfolio.rebalance
columns = []
for date in rebalance_schedule.columns:
date = date[0:10]
columns.append(date)
rebalance_schedule.columns = columns
# then want to make a list of the dates and start with our first date
dates = [my_portfolio.start_date]
# then our rebalancing dates into that list
dates = dates + rebalance_schedule.columns.to_list()
datess = []
for date in dates:
date = date[0:10]
datess.append(date)
dates = datess
# this will hold returns
returns = pd.Series()
# then we want to be able to call the dates like tuples
for i in range(len(dates) - 1):
# get our weights
weights = rebalance_schedule[str(dates[i + 1])]
# then we want to get the returns
add_returns = get_returns(
my_portfolio.portfolio,
weights,
start_date=dates[i],
end_date=dates[i + 1],
)
# then append those returns
returns = returns.append(add_returns)
except AttributeError:
try:
returns = get_returns_from_data(
my_portfolio.data, my_portfolio.weights)
except AttributeError:
returns = get_returns(
my_portfolio.portfolio,
my_portfolio.weights,
start_date=my_portfolio.start_date,
end_date=my_portfolio.end_date,
)
creturns = (returns + 1).cumprod()
# risk manager
try:
if list(my_portfolio.risk_manager.keys())[0] == "Stop Loss":
values = []
for r in creturns:
if r <= 1 + my_portfolio.risk_manager["Stop Loss"]:
values.append(r)
else:
pass
try:
date = creturns[creturns == values[0]].index[0]
date = str(date.to_pydatetime())
my_portfolio.end_date = date[0:10]
returns = returns[: my_portfolio.end_date]
except Exception as e:
pass
if list(my_portfolio.risk_manager.keys())[0] == "Take Profit":
values = []
for r in creturns:
if r >= 1 + my_portfolio.risk_manager["Take Profit"]:
values.append(r)
else:
pass
try:
date = creturns[creturns == values[0]].index[0]
date = str(date.to_pydatetime())
my_portfolio.end_date = date[0:10]
returns = returns[: my_portfolio.end_date]
except Exception as e:
pass
if list(my_portfolio.risk_manager.keys())[0] == "Max Drawdown":
drawdown = qs.stats.to_drawdown_series(returns)
values = []
for r in drawdown:
if r <= my_portfolio.risk_manager["Max Drawdown"]:
values.append(r)
else:
pass
try:
date = drawdown[drawdown == values[0]].index[0]
date = str(date.to_pydatetime())
my_portfolio.end_date = date[0:10]
returns = returns[: my_portfolio.end_date]
except Exception as e:
pass
except Exception as e:
pass
print("Start date: " + str(my_portfolio.start_date))
print("End date: " + str(my_portfolio.end_date))
benchmark = get_returns(
my_portfolio.benchmark,
wts=[1],
start_date=my_portfolio.start_date,
end_date=my_portfolio.end_date,
)
benchmark = benchmark.dropna()
CAGR = cagr(returns, period='daily', annualization=None)
# CAGR = round(CAGR, 2)
# CAGR = CAGR.tolist()
CAGR = str(round(CAGR * 100, 2)) + "%"
CUM = cum_returns(returns, starting_value=0, out=None) * 100
CUM = CUM.iloc[-1]
CUM = CUM.tolist()
CUM = str(round(CUM, 2)) + "%"
VOL = qs.stats.volatility(returns, annualize=True)
VOL = VOL.tolist()
VOL = str(round(VOL * 100, 2)) + " %"
SR = qs.stats.sharpe(returns, rf=rf)
SR = np.round(SR, decimals=2)
SR = str(SR)
sua.SR = SR
CR = qs.stats.calmar(returns)
CR = CR.tolist()
CR = str(round(CR, 2))
sua.CR = CR
STABILITY = stability_of_timeseries(returns)
STABILITY = round(STABILITY, 2)
STABILITY = str(STABILITY)
MD = max_drawdown(returns, out=None)
MD = str(round(MD * 100, 2)) + " %"
"""OR = omega_ratio(returns, risk_free=0.0, required_return=0.0)
OR = round(OR,2)
OR = str(OR)
print(OR)"""
SOR = sortino_ratio(returns, required_return=0, period='daily')
SOR = round(SOR, 2)
SOR = str(SOR)
SK = qs.stats.skew(returns)
SK = round(SK, 2)
SK = SK.tolist()
SK = str(SK)
KU = qs.stats.kurtosis(returns)
KU = round(KU, 2)
KU = KU.tolist()
KU = str(KU)
TA = tail_ratio(returns)
TA = round(TA, 2)
TA = str(TA)
CSR = qs.stats.common_sense_ratio(returns)
CSR = round(CSR, 2)
CSR = CSR.tolist()
CSR = str(CSR)
VAR = qs.stats.value_at_risk(
returns, sigma=sigma_value, confidence=confidence_value
)
VAR = np.round(VAR, decimals=2)
VAR = str(VAR * 100) + " %"
alpha, beta = alpha_beta(returns, benchmark, risk_free=rf)
AL = round(alpha, 2)
BTA = round(beta, 2)
def condition(x):
return x > 0
win = sum(condition(x) for x in returns)
total = len(returns)
win_ratio = win / total
win_ratio = win_ratio * 100
win_ratio = round(win_ratio, 2)
IR = calculate_information_ratio(returns, benchmark.iloc[:, 0])
IR = round(IR, 2)
data = {
"": [
"Annual return",
"Cumulative return",
"Annual volatility",
"Winning day ratio",
"Sharpe ratio",
"Calmar ratio",
"Information ratio",
"Stability",
"Max Drawdown",
"Sortino ratio",
"Skew",
"Kurtosis",
"Tail Ratio",
"Common sense ratio",
"Daily value at risk",
"Alpha",
"Beta",
],
"Backtest": [
CAGR,
CUM,
VOL,
f"{win_ratio}%",
SR,
CR,
IR,
STABILITY,
MD,
SOR,
SK,
KU,
TA,
CSR,
VAR,
AL,
BTA,
],
}
# Create DataFrame
df = pd.DataFrame(data)
df.set_index("", inplace=True)
df.style.set_properties(
**{"background-color": "white", "color": "black", "border-color": "black"}
)
display(df)
sua.df = data
y = []
for x in returns:
y.append(x)
arr = np.array(y)
# arr
# returns.index
my_color = np.where(arr >= 0, "blue", "grey")
plt.figure(figsize=(30, 8))
plt.vlines(x=returns.index, ymin=0, ymax=arr, color=my_color, alpha=0.4)
plt.title("Returns")
sua.returns = returns
sua.creturns = creturns
sua.benchmark = benchmark
sua.CAGR = CAGR
sua.CUM = CUM
sua.VOL = VOL
sua.SR = SR
sua.win_ratio = win_ratio
sua.CR = CR
sua.IR = IR
sua.STABILITY = STABILITY
sua.MD = MD
sua.SOR = SOR
sua.SK = SK
sua.KU = KU
sua.TA = TA
sua.CSR = CSR
sua.VAR = VAR
sua.AL = AL
sua.BTA = BTA
try:
sua.orderbook = make_rebalance.output
except Exception as e:
OrderBook = pd.DataFrame(
{
"Assets": my_portfolio.portfolio,
"Allocation": my_portfolio.weights,
}
)
sua.orderbook = OrderBook.T
wts = copy.deepcopy(my_portfolio.weights)
indices = [i for i, x in enumerate(wts) if x == 0.0]
while 0.0 in wts:
wts.remove(0.0)
for i in sorted(indices, reverse=True):
del my_portfolio.portfolio[i]
return (
qs.plots.returns(returns, benchmark, cumulative=True),
qs.plots.yearly_returns(returns, benchmark),
qs.plots.monthly_heatmap(returns),
qs.plots.drawdown(returns),
qs.plots.drawdowns_periods(returns),
qs.plots.rolling_volatility(returns),
qs.plots.rolling_sharpe(returns),
qs.plots.rolling_beta(returns, benchmark),
graph_opt(my_portfolio.portfolio, wts, pie_size=7, font_size=14),
)
def flatten(subject) -> list:
muster = []
for item in subject:
if isinstance(item, (list, tuple, set)):
muster.extend(flatten(item))
else:
muster.append(item)
return muster
def graph_opt(my_portfolio, my_weights, pie_size, font_size):
fig1, ax1 = plt.subplots()
fig1.set_size_inches(pie_size, pie_size)
cs = [
"#ff9999",
"#66b3ff",
"#99ff99",
"#ffcc99",
"#f6c9ff",
"#a6fff6",
"#fffeb8",
"#ffe1d4",
"#cccdff",
"#fad6ff",
]
ax1.pie(my_weights, labels=my_portfolio,
autopct="%1.1f%%", shadow=False, colors=cs)
# Equal aspect ratio ensures that pie is drawn as a circle.
ax1.axis("equal")
plt.rcParams["font.size"] = font_size
plt.show()
def equal_weighting(my_portfolio) -> list:
return [1.0 / len(my_portfolio.portfolio)] * len(my_portfolio.portfolio)
def efficient_frontier(my_portfolio, perf=True) -> list:
# changed to take in desired timeline, the problem is that it would use all historical data
ohlc = yf.download(
my_portfolio.portfolio,
start=my_portfolio.start_date,
end=my_portfolio.end_date,
progress=False,
)
prices = ohlc["Adj Close"].dropna(how="all")
df = prices.filter(my_portfolio.portfolio)
# sometimes we will pick a date range where company isn't public we can't set price to 0 so it has to go to 1
df = df.fillna(1)
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)
# optimize for max sharpe ratio
ef = EfficientFrontier(mu, S)
if my_portfolio.min_weights is not None:
ef.add_constraint(lambda x: x >= my_portfolio.min_weights)
if my_portfolio.max_weights is not None:
ef.add_constraint(lambda x: x <= my_portfolio.max_weights)
weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
wts = cleaned_weights.items()
result = []
for val in wts:
a, b = map(list, zip(*[val]))
result.append(b)
if perf is True:
pred = ef.portfolio_performance(verbose=True)
return flatten(result)
def hrp(my_portfolio, perf=True) -> list:
# changed to take in desired timeline, the problem is that it would use all historical data
ohlc = yf.download(
my_portfolio.portfolio,
start=my_portfolio.start_date,
end=my_portfolio.end_date,
progress=False,
)
prices = ohlc["Adj Close"].dropna(how="all")
prices = prices.filter(my_portfolio.portfolio)
# sometimes we will pick a date range where company isn't public we can't set price to 0 so it has to go to 1
prices = prices.fillna(1)
rets = expected_returns.returns_from_prices(prices)
hrp = HRPOpt(rets)
hrp.optimize()
weights = hrp.clean_weights()
wts = weights.items()
result = []
for val in wts:
a, b = map(list, zip(*[val]))
result.append(b)
if perf is True:
hrp.portfolio_performance(verbose=True)
return flatten(result)
def mean_var(my_portfolio, vol_max=0.15, perf=True) -> list:
# changed to take in desired timeline, the problem is that it would use all historical data
ohlc = yf.download(
my_portfolio.portfolio,
start=my_portfolio.start_date,
end=my_portfolio.end_date,
progress=False,
)
prices = ohlc["Adj Close"].dropna(how="all")
prices = prices.filter(my_portfolio.portfolio)
# sometimes we will pick a date range where company isn't public we can't set price to 0 so it has to go to 1
prices = prices.fillna(1)
mu = expected_returns.capm_return(prices)
S = risk_models.CovarianceShrinkage(prices).ledoit_wolf()
ef = EfficientFrontier(mu, S)
ef.add_objective(objective_functions.L2_reg,
gamma=my_portfolio.diversification)
if my_portfolio.min_weights is not None:
ef.add_constraint(lambda x: x >= my_portfolio.min_weights)
if my_portfolio.max_weights is not None:
ef.add_constraint(lambda x: x <= my_portfolio.max_weights)
ef.efficient_risk(vol_max)
weights = ef.clean_weights()
wts = weights.items()
result = []
for val in wts:
a, b = map(list, zip(*[val]))
result.append(b)
if perf is True:
ef.portfolio_performance(verbose=True)
return flatten(result)
def min_var(my_portfolio, perf=True) -> list:
ohlc = yf.download(
my_portfolio.portfolio,
start=my_portfolio.start_date,
end=my_portfolio.end_date,
progress=False,
)
prices = ohlc["Adj Close"].dropna(how="all")
prices = prices.filter(my_portfolio.portfolio)
mu = expected_returns.capm_return(prices)
S = risk_models.CovarianceShrinkage(prices).ledoit_wolf()
ef = EfficientFrontier(mu, S)
ef.add_objective(objective_functions.L2_reg,
gamma=my_portfolio.diversification)
if my_portfolio.min_weights is not None:
ef.add_constraint(lambda x: x >= my_portfolio.min_weights)
if my_portfolio.max_weights is not None:
ef.add_constraint(lambda x: x <= my_portfolio.max_weights)
ef.min_volatility()
weights = ef.clean_weights()
wts = weights.items()
result = []
for val in wts:
a, b = map(list, zip(*[val]))
result.append(b)
if perf is True:
ef.portfolio_performance(verbose=True)
return flatten(result)
def optimize_portfolio(my_portfolio, vol_max=25, pie_size=5, font_size=14):
returns1 = get_returns(
my_portfolio.portfolio,
equal_weighting(my_portfolio),
start_date=my_portfolio.start_date,
end_date=my_portfolio.end_date,
)
creturns1 = (returns1 + 1).cumprod()
port = copy.deepcopy(my_portfolio.portfolio)
wts = [1.0 / len(my_portfolio.portfolio)] * len(my_portfolio.portfolio)
optimizers = {
"EF": efficient_frontier,
"MEANVAR": mean_var,
"HRP": hrp,
"MINVAR": min_var,
}
if my_portfolio.optimizer in optimizers.keys():
if my_portfolio.optimizer == "MEANVAR":
wts = optimizers.get(my_portfolio.optimizer)(
my_portfolio, my_portfolio.max_vol)
else:
wts = optimizers.get(my_portfolio.optimizer)(my_portfolio)
else:
opt = my_portfolio.optimizer
my_portfolio.weights = opt()
print(wts)
print("\n")
indices = [i for i, x in enumerate(wts) if x == 0.0]
while 0.0 in wts:
wts.remove(0.0)
for i in sorted(indices, reverse=True):
del port[i]
graph_opt(port, wts, pie_size, font_size)
print("\n")
returns2 = get_returns(
port, wts, start_date=my_portfolio.start_date, end_date=my_portfolio.end_date
)
creturns2 = (returns2 + 1).cumprod()
plt.rcParams["font.size"] = 13
plt.figure(figsize=(30, 10))
plt.xlabel("Portfolio vs Benchmark")
ax1 = creturns1.plot(color="blue", label="Without optimization")
ax2 = creturns2.plot(color="red", label="With optimization")
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
plt.legend(l1 + l2, loc=2)
plt.show()
def check_schedule(rebalance) -> bool:
valid_schedule = False
if rebalance.lower() in rebalance_periods.keys():
valid_schedule = True
return valid_schedule
def valid_range(start_date, end_date, rebalance) -> tuple:
# make the start date to a datetime
start_date = dt.datetime.strptime(start_date, "%Y-%m-%d")
# have to make end date a datetime because strptime is not supported for date
end_date = dt.datetime(end_date.year, end_date.month, end_date.day)
# gets the number of days
days = (end_date - start_date).days
# checking that date range covers rebalance period
if rebalance in rebalance_periods.keys() and days <= (int(rebalance_periods[rebalance])):
raise KeyError("Date Range does not encompass rebalancing interval")
# we will needs these dates later on so we'll return them back
return start_date, end_date
def get_date_range(start_date, end_date, rebalance) -> list:
# this will keep track of the rebalancing dates and we want to start on the first date
rebalance_dates = [start_date]
input_date = start_date
if rebalance in rebalance_periods.keys():
# run for an arbitrarily large number we'll resolve this by breaking when we break the equality
for i in range(1000):
# increment the date based on the selected period
input_date = input_date + \
dt.timedelta(days=rebalance_periods.get(rebalance))
if input_date <= end_date:
# append the new date if it is earlier or equal to the final date
rebalance_dates.append(input_date)
else:
# break when the next rebalance date is later than our end date
break
# then we want to return those dates
return rebalance_dates
def make_rebalance(
start_date,
end_date,
optimize,
portfolio_input,
rebalance,
allocation,
vol_max,
div,
min,
max,
) -> pd.DataFrame:
sdate = str(start_date)[:10]
if rebalance[0] != sdate:
# makes sure that the value passed through for rebalancing is a valid one
valid_schedule = check_schedule(rebalance)
if valid_schedule is False:
raise KeyError("Not an accepted rebalancing schedule")
# this checks to make sure that the date range given works for the rebalancing
start_date, end_date = valid_range(start_date, end_date, rebalance)
# this function will get us the specific dates
if rebalance[0] != sdate:
dates = get_date_range(start_date, end_date, rebalance)
else:
dates = rebalance
# we are going to make columns with the end date and the weights
columns = ["end_date"] + portfolio_input
# then make a dataframe with the index being the tickers
output_df = pd.DataFrame(index=portfolio_input)
for i in range(len(dates) - 1):
try:
portfolio = Start(
start_date=dates[0],
end_date=dates[i + 1],
portfolio=portfolio_input,
weights=allocation,
optimizer="{}".format(optimize),
max_vol=vol_max,
diversification=div,
min_weights=min,
max_weights=max,
)
except TypeError:
portfolio = Start(
start_date=dates[0],
end_date=dates[i + 1],
portfolio=portfolio_input,
weights=allocation,
optimizer=optimize,
max_vol=vol_max,
diversification=div,
min_weights=min,
max_weights=max,
)
output_df["{}".format(dates[i + 1])] = portfolio.weights
# we have to run it one more time to get what the optimization is for up to today's date
try:
portfolio = Start(
start_date=dates[0],
portfolio=portfolio_input,
weights=allocation,
optimizer="{}".format(optimize),
max_vol=vol_max,
diversification=div,
min_weights=min,
max_weights=max,
)
except TypeError:
portfolio = Start(
start_date=dates[0],
portfolio=portfolio_input,
weights=allocation,
optimizer=optimize,
max_vol=vol_max,
diversification=div,
min_weights=min,
max_weights=max,
)
output_df["{}".format(TODAY)] = portfolio.weights
make_rebalance.output = output_df
return output_df
def get_report(my_portfolio, rf=0.0, sigma_value=1, confidence_value=0.95, filename: str = "report.pdf"):
try:
# we want to get the dataframe with the dates and weights
rebalance_schedule = my_portfolio.rebalance
columns = []
for date in rebalance_schedule.columns:
date = date[0:10]
columns.append(date)
rebalance_schedule.columns = columns
# then want to make a list of the dates and start with our first date
dates = [my_portfolio.start_date]
# then our rebalancing dates into that list
dates = dates + rebalance_schedule.columns.to_list()
datess = []
for date in dates:
date = date[0:10]
datess.append(date)
dates = datess
# this will hold returns
returns = pd.Series()
# then we want to be able to call the dates like tuples
for i in range(len(dates) - 1):
# get our weights
weights = rebalance_schedule[str(dates[i + 1])]
# then we want to get the returns
add_returns = get_returns(
my_portfolio.portfolio,
weights,
start_date=dates[i],
end_date=dates[i + 1],
)
# then append those returns
returns = returns.append(add_returns)
except AttributeError:
try:
returns = get_returns_from_data(
my_portfolio.data, my_portfolio.weights)
except AttributeError:
returns = get_returns(
my_portfolio.portfolio,
my_portfolio.weights,
start_date=my_portfolio.start_date,
end_date=my_portfolio.end_date,
)
creturns = (returns + 1).cumprod()
# risk manager
try:
if list(my_portfolio.risk_manager.keys())[0] == "Stop Loss":
values = []
for r in creturns:
if r <= 1 + my_portfolio.risk_manager["Stop Loss"]:
values.append(r)
else:
pass
try:
date = creturns[creturns == values[0]].index[0]
date = str(date.to_pydatetime())
my_portfolio.end_date = date[0:10]
returns = returns[: my_portfolio.end_date]
except Exception as e:
pass
if list(my_portfolio.risk_manager.keys())[0] == "Take Profit":
values = []
for r in creturns:
if r >= 1 + my_portfolio.risk_manager["Take Profit"]:
values.append(r)
else:
pass
try:
date = creturns[creturns == values[0]].index[0]
date = str(date.to_pydatetime())
my_portfolio.end_date = date[0:10]
returns = returns[: my_portfolio.end_date]
except Exception as e:
pass
if list(my_portfolio.risk_manager.keys())[0] == "Max Drawdown":
drawdown = qs.stats.to_drawdown_series(returns)
values = []
for r in drawdown:
if r <= my_portfolio.risk_manager["Max Drawdown"]:
values.append(r)