-
Notifications
You must be signed in to change notification settings - Fork 213
/
best_markowitz.py
48 lines (34 loc) · 1.22 KB
/
best_markowitz.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
import numpy as np
import pandas as pd
from .. import tools
from .crp import CRP
class BestMarkowitz(CRP):
"""Optimal Markowitz portfolio constructed in hindsight.
Reference:
https://en.wikipedia.org/wiki/Modern_portfolio_theory
"""
PRICE_TYPE = "ratio"
REPLACE_MISSING = False
def __init__(self, global_sharpe=None, sharpe=None, **kwargs):
self.global_sharpe = global_sharpe
self.sharpe = sharpe
self.opt_markowitz_kwargs = kwargs
def weights(self, X):
"""Find optimal markowitz weights."""
# update frequency
freq = tools.freq(X.index)
R = X - 1
# calculate mean and covariance matrix and annualize them
sigma = R.cov() * freq
if self.sharpe:
mu = pd.Series(np.sqrt(np.diag(sigma)), X.columns) * pd.Series(
self.sharpe
).reindex(X.columns)
elif self.global_sharpe:
mu = pd.Series(np.sqrt(np.diag(sigma)) * self.global_sharpe, X.columns)
else:
mu = R.mean() * freq
self.b = tools.opt_markowitz(mu, sigma, **self.opt_markowitz_kwargs)
return super().weights(R)
if __name__ == "__main__":
tools.quickrun(BestMarkowitz())