[英]SciPy optimization - args in constraint function
我正在嘗試構建一個投資組合優化算法,該算法在權重邊界和收益約束的約束下,將預期缺口(CVaR)降至最低。 盡管它已經可以滿足最小返回要求,但是添加返回約束會導致以下錯誤:“ 所有輸入數組必須具有相同數量的維數 ”。
我現在花了幾個小時在不同的論壇和示例中進行搜索,但仍然不知道是什么導致了此錯誤。
感謝您的意見!
碼:
#Inputs
w_mkt = np.array([[.5203, .1439, .3358]])
mu = np.array([[.005, .003, .002]])
vol = np.array([[.02, .03, .01]])
rho = np.array([[1.00, 0.50, 0.25],
[0.50, 1.00, 0.60],
[0.25, 0.60, 1.00]])
sd_matrix = np.zeros((3,3))
np.fill_diagonal(sd_matrix, vol)
sigma = np.dot(sd_matrix, np.dot(rho, sd_matrix.T))
#Function to be optimized:
def C_VaR(w, mu, sigma, alpha=0.99):
w = np.matrix(w)
mu = np.matrix(mu)
cvar = -np.dot(mu, w.T) + sqrt(np.dot(w, np.dot(sigma, w.T)))/(1-alpha)*norm.pdf(norm.ppf(alpha))
return cvar
#Boundaries:
b_ = [(0.0, 1.0) for i in range(mu.shape[1])]
b_
#Constraints (return constraint is achivable):
c_ = ({'type':'eq', 'fun': lambda w: sum(w) - 1}, #weights sum up to zero
{'type':'eq',
'fun': lambda w, mu: np.matrix(w).dot(mu.T) - .0036,
'args': (mu,)}) #return requirement
c_
#Finally, optimization function:
minCVAR = optimize.minimize(C_VaR,
w_mkt,
args=(mu, sigma),
method="SLSQP",
bounds=tuple(b_),
constraints=c_)
錯誤:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-157-be7467bdec1d> in <module>()
4 method="SLSQP",
5 bounds=tuple(b_),
----> 6 constraints=c_)
~/miniconda3/lib/python3.6/site-packages/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
609 elif meth == 'slsqp':
610 return _minimize_slsqp(fun, x0, args, jac, bounds,
--> 611 constraints, callback=callback, **options)
612 elif meth == 'trust-constr':
613 return _minimize_trustregion_constr(fun, x0, args, jac, hess, hessp,
~/miniconda3/lib/python3.6/site-packages/scipy/optimize/slsqp.py in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, callback, **unknown_options)
385 if cons['eq']:
386 c_eq = concatenate([atleast_1d(con['fun'](x, *con['args']))
--> 387 for con in cons['eq']])
388 else:
389 c_eq = zeros(0)
ValueError: all the input arrays must have same number of dimensions
將約束更改為'fun': lambda w, mu: (np.matrix(w).dot(mu.T) - .0036)[0,0]
解決了該問題。
將“ sigma”添加到“ c_”的“ args”中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.