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))
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