我嘗試優化我的功能:
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
我的限制是:
def check_sum(weights):
return np.sum(weights) -1
cons = ({"type":"eq", "fun":check_sum})
我的債券是:bounds = ((0,1),(0,1),(0,1),(0,1))
和:
init_guess = np.array([.25,.25,.25,.25])
所以我運行這個:
opt_res = minimize(fun=neg_sharp,x0=init_guess.flatten(),
method="SLSQP",bounds=bounds,constraints=cons)
并得到這個錯誤:
ValueError:目標函式必須回傳一個標量
uj5u.com熱心網友回復:
似乎問題在于這里return get_ret(weights)[2] * -1
get_ret回傳了一個串列,我猜你想從這個串列中取出一個元素(第三個?)并乘以 -1。
嘗試:
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
uj5u.com熱心網友回復:
行。抱歉。這是我的錯。
return get_ret(weights[2]) * -1
必須改為:
return get_ret(weights)[2] * -1
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406017.html
標籤:
