-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathport_opt.py
75 lines (61 loc) · 1.63 KB
/
port_opt.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
def ret2prices(ret_series, base_value):
import numpy as np
prices = np.zeros([len(ret_series)+1])
prices[0] = base_value
for i in range(len(ret_series)):
if np.isnan(ret_series[i]):
prices[i+1] = prices[i]
else:
prices[i+1] = prices[i] * np.exp(ret_series[i])
return prices
def is_pos_def(x):
import numpy as np
return np.all(np.linalg.eigvals(x) > 0)
def cv_opt(mu, Sigma, e_mu, glambda, h):
from cvxpy import quad_form, Variable, sum_entries, Problem, Maximize, norm
from sklearn.covariance import shrunk_covariance
import numpy as np
n = len(mu)
w = Variable(n)
ret = mu.T*w
if is_pos_def(Sigma):
risk = quad_form(w, Sigma)
else:
for i in np.linspace(0.01,10000,1000000):
test = shrunk_covariance(Sigma, shrinkage=i)
if is_pos_def(test):
Sigma = test
break
if not is_pos_def(Sigma):
print('Here you got a serious problem', flush=True)
print(Sigma)
rw = np.empty((len(mu)))
rw[:] = np.nan
rr = np.nan
rri = np.nan
return rw, rr, rri
risk = quad_form(w, Sigma)
if glambda == None:
if e_mu == None:
prob = Problem(Maximize(ret - risk), [sum_entries(w) == 1, w >= h])
else:
prob = Problem(Maximize(ret - risk), [sum_entries(w) == 1, w >= h,
ret==e_mu])
else:
if e_mu == None:
prob = Problem(Maximize(ret - risk - glambda*norm(w,1) ),
[sum_entries(w) == 1, w >= h])
else:
prob = Problem(Maximize(ret - risk - glambda*norm(w,1)),
[sum_entries(w) == 1, w >= h, ret==e_mu])
prob.solve()
try:
rw = w.value
rr = ret.value
rri = risk.value
except:
rw = np.empty((len(mu)))
rw[:] = np.nan
rr = np.nan
rri = np.nan
return rw, rr, rri