[英]Scipy.optimize.minimize Objective function must return a scalar
I try to optimize my function:我尝试优化我的 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))我的债券是:bounds = ((0,1),(0,1),(0,1),(0,1))
and:和:
init_guess = np.array([.25,.25,.25,.25]) 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
ValueError: Objective function 必须返回一个标量
It seems like the problem is here return get_ret(weights)[2] * -1
似乎问题出在这里
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. get_ret
返回一个列表,我猜你想从这个列表中取出一个元素(第三个?)并乘以 -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
ok.好的。 I'm sorry.
对不起。 this is my fault.
这是我的错。
return get_ret(weights[2]) * -1
must change to:必须改为:
return get_ret(weights)[2] * -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.