-
Notifications
You must be signed in to change notification settings - Fork 0
/
portfolio.py
382 lines (286 loc) · 10.1 KB
/
portfolio.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
"""
The module contains various classes for the construction of portfolio.
"""
import numpy as np
import pandas as pd
import risk_kit as erk
from scipy.optimize import minimize
class MeanVarPortfolio(object):
"""
Portfolio model based on the modern portfolio theory.
The model helps to run a backtest on the mean variance
portfolio strategy and plots the efficient frontier.
Three major mean-variance strategies are implemented:
- Maximum Sharpe Ratio Portfolio
- Equally Weighted Portfolio
- Global Minimum Variance Portfolio
...
Parameters
----------
er: pd.Series
A series of expected returns for different assets
cov: Matrx
The covariance matrix for different assets
"""
def __init__(self, er, covmat):
self.er = er
self.cov = covmat
@property
def er(self):
"""
Get the expected returns
"""
return self._er
@er.setter
def er(self, er):
self._er = er
@property
def cov(self):
"""
Get the covariance matrix.
"""
return self._cov
@cov.setter
def cov(self, covmat):
self._cov = covmat
def minimize_vol(
self, target_return,
):
"""
Returns the optimal weights that achieve the target return
given a set of expected returns and a covariance matrix
Parameters
----------
target_return (float): The targetted return of the portfolio
Returns
-------
pd.Series: The optimal weight assignment that minimizes the
volatility for the given set of expected returns.
"""
# Number of assets
n = self.er.shape[0]
# Random guess to start with.
init_guess = np.repeat(1 / n, n)
# Bounds of the weights
bounds = ((0.0, 1.0),) * n
# Constriant for sum of weights to be equal to 1
weights_sum_to_1 = {
"type": "eq",
"fun": lambda weights: np.sum(weights) - 1,
}
# Constraint that total return should be equal to target return
return_is_target = {
"type": "eq",
"args": (self.er,),
"fun": lambda weights, er: target_return
- erk.portfolio_return(weights, self.er,),
}
weights = minimize(
erk.portfolio_vol,
init_guess,
args=(self.cov,),
method="SLSQP",
options={"disp": False},
constraints=(weights_sum_to_1, return_is_target,),
bounds=bounds,
)
return weights.x
def get_cml(self, riskfree_rate=0.0):
"""
Returns the parameters of the capital market line.
Parameters:
----------
riskfree_rate (float): The riskfree_rate of the market
Returns:
-------
tuple - Returns a tuple of (slope, y_intercept) of the CML.
The y_intercept would be equal to the riskfree_rate.
"""
wt_msr = self.msr(riskfree_rate=riskfree_rate)
ret, vol = self.get_point(wt_msr)
slope = (ret - riskfree_rate) / vol
y_intercept = riskfree_rate
return (slope, y_intercept)
def max_return_cml(self, vol, riskfree_rate=0.0):
"""
The maximum return earned by the captial market line model
for the given volatility.
Parameters:
----------
vol (float): The volatility corresponding to which the maximum return
has to be evaluated.
riskfree_rate (float): The risk free rate of the market
Returns:
-------
float: The return of capital market line corresponding to the given volatility.
"""
slope, intercept = self.get_cml(riskfree_rate)
sigma = 0.05
exp_ret = slope * sigma + intercept
return exp_ret
def get_ef_weights(self, n_points):
"""
Returns a set of optimal weights for n_points equally spaced
target returns from minimum expected return to
maximum expected return.
The weights are a set of weights on the efficient frontier.
Parameters
----------
n_points (int): The number of equally spaced weights to be
considered
Returns
-------
[pd.Series]: The list of n_points equally spaced weights.
"""
target_rs = np.linspace(self.er.min(), self.er.max(), n_points,)
weights = [self.minimize_vol(target_return) for target_return in target_rs]
return weights
def msr(self, riskfree_rate=0.0, use_er=True):
"""
Returns the weights corresponding to the maximum sharpe ratio
portfolio.
Parameters
----------
riskfree_rate (float): The risk free rate of return. Defaults to 0.0.
use_er (bool): Uses the expected return attribute if set to true.
Assumes equal expected returns and gives weights
for global minimum variance if set False.
Defaults to True.
Returns
-------
pd.Series: The optimal weight assignment that minimizes the
volatility for the given set of expected returns.
"""
# Number of stocks
n = self.er.shape[0]
# Uses equally weighted expected returns if use_er is set to False
rets = self.er if use_er else np.repeat(1, n)
# Inital guess of weights
init_guess = np.repeat(1 / n, n)
# Bounds of the weights
bounds = ((0.0, 1.0),) * n
# Constraint for the sum of weights to be equal to 1
weights_sum_to_1 = {
"type": "eq",
"fun": lambda weights: np.sum(weights) - 1,
}
def neg_sharpe(
weights, riskfree_rate, er, cov,
):
"""
Returns the negative of the sharpe ratio
of the given portfolio
"""
r = erk.portfolio_return(weights, er)
vol = erk.portfolio_vol(weights, cov)
return -(r - riskfree_rate) / vol
weights = minimize(
neg_sharpe,
init_guess,
args=(riskfree_rate, rets, self.cov,),
method="SLSQP",
options={"disp": False},
constraints=(weights_sum_to_1,),
bounds=bounds,
)
return weights.x
def ew(self):
"""
Returns the weights corresponding to an equally weighted portfolio.
Returns
-------
pd.Series: The weights for an equally weighted portfolio.
"""
n = self.er.shape[0]
wt = np.repeat(1 / n, n)
return wt
def gmv(self):
"""
Returns the weights corresponding to the global minimum
variance portfolio. The weights only depends on covariance matrix.
Returns
-------
pd.Series: The optimal weight assignment corresponding to the
global minimum variance portfolio.
"""
# Number of assets
n = self.er.shape[0]
# Risk free rate would not be used, so we can take it 0
return self.msr(0.0, use_er=False)
def get_point(self, weights):
"""
Returns the return and risk in terms of volatility
for the given assignemt of weights
Parameters
----------
weights (pd.Series): The weights assigned to different asset in the portfolio.
Returns
-------
(float, float): A tuple representing the return and colatility respectively.
"""
ret = erk.portfolio_return(weights, self.er)
vol = erk.portfolio_vol(weights, self.cov)
return (ret, vol)
def plot_ef(
self,
n_points,
style=".-",
show_cml=False,
riskfree_rate=0.0,
show_ew=False,
show_gmv=False,
):
"""
Plots the efficient frontier for the given expected returns
and covariance matrix.
Parameters
----------
n_points (int): The number of equally spaced weights to be
considered
style (matplotlib.style): The style to be used for plotting
the efficient frontier. Defaults to '.-'.
show_cml (bool): Plots the capital market line if set true.
Defauts to False.
risk_free_rate (float): Risk free rate to be used for plotting
the capital market line. Defualts to 0.0
show_ew (bool): Plots the equally weghted portfolio point
Defauts to False.
show_gmv (bool): Plots the global minimum variance portfolio
Defauts to False.
Returns
-------
matplotlib.plot: The plot of the efficient frontier.
"""
weights = self.get_ef_weights(n_points)
rets = [erk.portfolio_return(w, self.er,) for w in weights]
vols = [erk.portfolio_vol(w, self.cov,) for w in weights]
ef = pd.DataFrame({"Returns": rets, "Volatility": vols,})
ax = ef.plot.line(x="Volatility", y="Returns", style=style)
ax.set_xlim(left=0)
if show_cml:
wt_msr = self.msr(riskfree_rate)
ret_msr, vol_msr = self.get_point(wt_msr)
cml_x = [0, vol_msr]
cml_y = [riskfree_rate, ret_msr]
ax.plot(
cml_x,
cml_y,
color="green",
marker="o",
linestyle="dashed",
linewidth=2,
markersize=10,
)
if show_ew:
wt_ew = self.ew()
ret_ew, vol_ew = self.get_point(wt_ew)
ax.plot(
vol_ew, ret_ew, color="goldenrod", marker="o", markersize=10,
)
if show_gmv:
wt_gmv = self.gmv()
ret_gmv, vol_gmv = self.get_point(wt_gmv)
ax.plot(
vol_gmv, ret_gmv, color="midnightblue", marker="o", markersize=10,
)
return ax