我通过两个约束进行股票投资组合波动率最小化:
但是,第二个约束由于某种原因不起作用。有人可以解释一下如何正确设置这些界限吗?
import scipy.optimize as spo
def portfolio_vol(w):
#compute porfolio volatility
portfolio_volatility = np.sqrt(w.T.dot(cov_matrix).dot(w))
return portfolio_volatility
def find_optimal_allocations():
bnds = tuple((0.00, 0.02) for x in weights)
cons = ({'type': 'eq', 'fun': lambda x: 1 - sum(x)}, {'type': 'ineq', 'fun': lambda x: sum(x**2) - 0.02})
result = spo.minimize(portfolio_vol, weights, method='SLSQP', bounds = bnds, constraints = cons)
return result.x
答案 0 :(得分:0)
如果您不喜欢scipy,可以使用cvxpy
。
此代码应该适合您。 (我假设权重是非负的。否则,只需从约束中删除x >= 0
。)
import cvxpy as cvx
import numpy as np
n = 100
M = np.random.random((n,n))
cov_matrix = np.cov(M)
x = cvx.Variable(n)
constraints = [x >= 0, cvx.sum_entries(x) == 1, cvx.sum_squares(x) <= 0.02]
objective = cvx.Minimize(cvx.quad_form(x,cov_matrix))
prob = cvx.Problem(objective,constraints)
prob.solve()
print(prob.value)
print(prob.variables()[0].value