我正在尝试实施投资组合优化,该优化使用约束来定义,例如最大限度地接触到国家/行业/行业等。我在下面的代码中实现了以下代码,我在其中传递了一个“非洲”矢量来将股票映射到非洲国家,在我的约束中,我将其限制为不超过40%的权重总体。我设法实现它的唯一方法是在非洲= 1的索引上使用sum_weights。我也尝试使用Parameter函数但没有成功。希望必须有更优雅的方式来应用这些约束。任何建议表示赞赏。此外,如果有人知道一个显示使用跟踪误差约束,周转限制或波动约束的示例,那么这些也是我仍在努力的地方。
import numpy as np
from cvxpy import *
np.random.seed(1)
n = 10 # number of assets
mu = np.abs(np.random.randn(n,1)) #mean
Sigma = np.random.randn(n,n)
Sigma = Sigma.T.dot(Sigma)
# Long only PFO Opt
w = Variable(n)
#africa = Parameter(10, sign='positive')
#africa.value = [1,1,1,0,0,0,0,0,0,0]
africa = [0,0,0,0,0,0,0,1,1,1]
gamma = Parameter(sign='positive')
ret = mu.T*w
risk = quad_form(w,Sigma)
filters = [i for i in range(len(africa)) if africa[i] == 1]
constraints = [sum_entries(w) == 1, w >=0, w[1] > 0.50, w[0] == 0, sum_entries(w[filters]) == 0.4]
#prob = Problem(Maximize(ret - gamma*risk), [sum_entries(w) == 1, w >=0])
prob = Problem(Minimize(risk), constraints)
SAMPLE = 1000
risk_data = np.zeros(SAMPLE)
ret_data = np.zeros(SAMPLE)
gamma_vals = np.logspace(-2,3,num=SAMPLE)
for i in range(SAMPLE):
gamma.value = gamma_vals[i]
prob.solve()
risk_data[i] = sqrt(risk).value
ret_data[i] = ret.value
print(prob.status)
print(prob.value)
print('OPT WEIGHTS : ')
for i in range(n):
print(round(w[i].value,3))
答案 0 :(得分:-2)
我想你可能想看看这些例子。开发者已将投资组合风险约束纳入如下:
import cvxpy as cp
w = cp.Variable(n)
gamma = cp.Parameter(nonneg=True)
ret = mu.T*w
risk = cp.quad_form(w, Sigma)
Lmax = cp.Parameter()
# Portfolio optimization with a leverage limit and a bound on risk.
prob = cp.Problem(cp.Maximize(ret),
[cp.sum(w) == 1,
cp.norm(w, 1) <= Lmax,
risk <= 2])
这是 jupyter nbviewer 的链接