I am trying to maximize the function below using Python's scipy.optimize.minimize(it is a way to get the diversified portfolio called maximimum diversification). However, there are always some problem.
The objective function:
max f = x'*sigma/sqrt(x'Cx)
C is a covariance matrix of N*N(N=800), sigma is the diagonal elements of C of N*1, x is the variable array of N*1
constraints : x>=0 and sum(x)=1
code:
def obj_md(x,mat):
diag = np.diagonal(mat)
return(-x.dot(diag)/x.dot(mat).dot(x.T))
def jac_deri(x,mat):
## x=x0
diag = np.sqrt(np.diagonal(mat))
sigma = np.sqrt(x.dot(mat).dot(x.T))
avg_w = x.dot(diag)
return(- diag.T/sigma + ((mat.dot(x.T)).T)*avg_w/sigma**3)
x0=np.array([[1.0/mat.shape[0]]*mat.shape[0]])
res=minimize(obj_md,x0,args=(mat),constraints=({'type': 'eq', 'fun': lambda x: np.sum(x)-1}),bounds = [(0,1)]*len(x0[0]),tol=0.0001)
the error is :
Traceback (most recent call last):
File "<ipython-input-381-2186cbe3d1f3>", line 1, in <module>
res=minimize(obj_md,x0,args=(mat),jac=jac_deri,constraints=cons,bounds = [(0,1)]*len(x0[0]),tol=0.0001,options={'disp': True})
File "D:\spyder\lib\site-packages\scipy\optimize\_minimize.py", line 458, in minimize
constraints, callback=callback, **options)
File "D:\spyder\lib\site-packages\scipy\optimize\slsqp.py", line 410, in _minimize_slsqp
slsqp(m, meq, x, xl, xu, fx, c, g, a, acc, majiter, mode, w, jw)
error: failed in converting 8th argument `g' of _slsqp.slsqp to C/Fortran array
can anyone help me solve the problem. Thanks a loooooooooooot!