-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathallocators.py
199 lines (153 loc) · 6.93 KB
/
allocators.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
import pandas as pd
import numpy as np
from pypfopt import EfficientFrontier
from pypfopt import risk_models
from pypfopt import expected_returns
from pypfopt.risk_models import CovarianceShrinkage
from pypfopt import objective_functions
import cvxpy as cp
from portfoliolab.clustering.hrp import HierarchicalRiskParity
from sklearn.decomposition import PCA
import tensorflow as tf
import tensorflow.keras as tfk
class CapitalAllocatorEqual:
def __init__(self):
pass
def fit(self, window_fit):
self.window_fit = window_fit
self.n_assets_window = window_fit.shape[-1]
def get_weights(self):
optimal_weights = np.ones(self.n_assets_window) / self.n_assets_window
return pd.DataFrame({
'ticker': self.window_fit.columns,
'weight': optimal_weights
})
class CapitalAllocatorGMV:
def __init__(self, shrinkage = False):
self.shrinkage = shrinkage
def fit(self, window_fit):
self.window_fit = window_fit
self.mu = expected_returns.mean_historical_return(self.window_fit, returns_data=True)
self.S = risk_models.sample_cov(self.window_fit, returns_data=True)
if self.shrinkage:
self.S = CovarianceShrinkage(self.window_fit, returns_data=True).ledoit_wolf()
def get_weights(self):
# Optimize for maximal Sharpe ratio
ef = EfficientFrontier(self.mu, self.S)
optimal_weights = ef.min_volatility()
optimal_weights = pd.DataFrame([dict(optimal_weights)]).T.values.flatten()
return pd.DataFrame({
'ticker': self.window_fit.columns,
'weight': optimal_weights
})
class CapitalAllocatorEF:
def __init__(self, shrinkage = False):
self.shrinkage = shrinkage
def fit(self, window_fit):
self.window_fit = window_fit
self.mu = expected_returns.mean_historical_return(self.window_fit, returns_data=True)
self.S = risk_models.sample_cov(self.window_fit, returns_data=True)
if self.shrinkage:
self.S = CovarianceShrinkage(self.window_fit, returns_data=True).ledoit_wolf()
def get_weights(self):
# Optimize for maximal Sharpe ratio
ef = EfficientFrontier(self.mu, self.S)
optimal_weights = ef.max_sharpe()
optimal_weights = pd.DataFrame([dict(optimal_weights)]).T.values.flatten()
return pd.DataFrame({
'ticker': self.window_fit.columns,
'weight': optimal_weights
})
class CapitalAllocatorCustom:
def __init__(self, shrinkage = False, shorting = False):
self.shrinkage = shrinkage
self.shorting = shorting
def fit(self, window_fit):
self.window_fit = window_fit
self.mu = expected_returns.mean_historical_return(self.window_fit, returns_data=True)
self.S = risk_models.sample_cov(self.window_fit, returns_data=True)
if self.shrinkage:
self.S = CovarianceShrinkage(self.window_fit, returns_data=True).ledoit_wolf()
def get_weights(self):
def decorrelate(weights, corr_matrix):
return np.sqrt(np.dot(weights.T, np.dot(corr_matrix, weights)))
def deviation_risk_parity(w, cov_matrix):
diff = w * np.dot(cov_matrix, w) - (w * np.dot(cov_matrix, w)).reshape(-1, 1)
return (diff ** 2).sum().sum()
# Optimize for maximal Sharpe ratio
if self.shorting:
ef = EfficientFrontier(self.mu, self.S, weight_bounds=(-1, 1))
else:
ef = EfficientFrontier(self.mu, self.S)
ef.add_objective(objective_functions.L2_reg, gamma=10)
# ef.nonconvex_objective(decorrelate, self.window_fit.corr())
ef.nonconvex_objective(deviation_risk_parity, self.S)
optimal_weights = ef.clean_weights()
optimal_weights = pd.DataFrame([dict(optimal_weights)]).T.values.flatten()
return pd.DataFrame({
'ticker': self.window_fit.columns,
'weight': optimal_weights
})
class CapitalAllocatorHRP:
def __init__(self, shrinkage = True):
self.shrinkage = shrinkage
def fit(self, window_fit):
self.window_fit = window_fit
self.S = risk_models.sample_cov(self.window_fit, returns_data=True)
if self.shrinkage:
self.S = CovarianceShrinkage(self.window_fit, returns_data=True).ledoit_wolf()
def get_weights(self):
self.hrp = HierarchicalRiskParity()
self.hrp.allocate(covariance_matrix=self.S, linkage='ward')
optimal_weights = self.hrp.weights[self.window_fit.columns].T.values.flatten()
return pd.DataFrame({
'ticker': self.window_fit.columns,
'weight': optimal_weights
})
class CapitalAllocatorPCA:
def __init__(self, shrinkage = True, C = 10):
self.shrinkage = shrinkage
self.C = C
def fit(self, window_fit):
self.window_fit = window_fit
self.S = risk_models.sample_cov(self.window_fit, returns_data=True)
if self.shrinkage:
self.S = CovarianceShrinkage(self.window_fit, returns_data=True).ledoit_wolf()
def get_weights(self, compontent):
self.pca = PCA(self.C)
returns_train_pca = self.pca.fit_transform(self.S)
pcs = self.pca.components_
w = pcs[compontent, :]
optimal_weights = w / sum(np.abs(w))
return pd.DataFrame({
'ticker': self.window_fit.columns,
'weight': optimal_weights
})
class CapitalAllocatorAE:
def __init__(self, C = 100):
self.C = C
def fit(self, window_fit):
self.window_fit = window_fit
def get_weights(self):
# connect all layers
input_img = tfk.Input(shape=(self.window_fit.shape[1], ))
encoded = tfk.layers.Dense(self.C * 2, activation='relu')(input_img)
encoded = tfk.layers.Dense(self.C, activation='relu', kernel_regularizer=tfk.regularizers.l2(1e-3))(encoded)
decoded = tfk.layers.Dense(self.C * 2, activation= 'relu')(encoded)
decoded = tfk.layers.Dense(self.window_fit.shape[1], activation = 'linear')(decoded)
# construct and compile AE model
self.autoencoder = tfk.Model(input_img, decoded)
self.autoencoder.compile(optimizer='adam', loss='mse')
history = self.autoencoder.fit(self.window_fit, self.window_fit, epochs=100, batch_size=64, verbose=False)
reconstruct = self.autoencoder.predict(self.window_fit)
communal_information = []
for i in range(0, len(self.window_fit.columns)):
diff = np.linalg.norm((self.window_fit.iloc[:,i] - reconstruct[:,i])) # 2 norm difference
communal_information.append(float(diff))
communal_information = np.array(communal_information)
weights_ae = (1 / communal_information)
weights_ae = np.array(weights_ae) / sum(np.abs(weights_ae))
return pd.DataFrame({
'ticker': self.window_fit.columns,
'weight': weights_ae
})