Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scipy.optimize.minimize Objective function must return a scalar

I try to optimize my function:

def get_ret(weights):
   weights = np.array(weights)
   ret = np.sum(log_ret.mean() * weights)*252
   vol = np.sqrt(np.dot(weights.T,np.dot(log_ret.cov()*252,weights)))
   sr = ret / vol
   return [ret,vol,sr]

def neg_sharp(weights):
   return get_ret(weights[2]) * -1

and my constraints is:

def check_sum(weights):
   return np.sum(weights) -1


cons = ({"type":"eq", "fun":check_sum})

my bonds is:
bounds = ((0,1),(0,1),(0,1),(0,1))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and:

init_guess = np.array([.25,.25,.25,.25])

so i run this:

opt_res = minimize(fun=neg_sharp,x0=init_guess.flatten(),
         method="SLSQP",bounds=bounds,constraints=cons)

and got this error:

ValueError: Objective function must return a scalar

>Solution :

It seems like the problem is here return get_ret(weights)[2] * -1
get_ret returns a list, I guess you want to take one element out of this list (the 3rd one?) and multiply by -1.

Try:

def get_ret(weights):
   weights = np.array(weights)
   ret = np.sum(log_ret.mean() * weights)*252
   vol = np.sqrt(np.dot(weights.T,np.dot(log_ret.cov()*252,weights)))
   sr = ret / vol
   return [ret,vol,sr]

def neg_sharp(weights):
   return get_ret(weights)[2] * -1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading