0

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!

Nick ODell
  • 15,465
  • 3
  • 32
  • 66
Y.cady
  • 21
  • 1
  • 3
  • Why no running code incl. data? Why no mentioning of the size of N? Obvious things to try: (1) Add symbolic gradient (you probably pay for finite-diff approximation here) (2) Try the other optimizers (i think only SLSQP natively supports this problem, but cobyla can work too if you formulate eq as two ineq's) – sascha Jul 16 '17 at 02:30
  • sorry ,ive edited the problem. and i also add such a jac fun. but i don't know how to write the minimize() def jac(x,mat): diag = np.diagonal(mat) sigma = x.dot(mat).dot(x.T) return(diag.T/sigma - ((mat.dot(x)).T)/sigma**3) – Y.cady Jul 16 '17 at 03:22

0 Answers0