Getting an error “could not broadcast input array from shape (252,4) into shape (4)” in optimization

不想你离开。 提交于 2019-12-25 07:16:07

问题


I a relatively new to python scipy library. I was trying to use the scipy.optimize to find the maximum value of the sharpe() function in the following code

def sharpe(dr, wts):
    portfolio=np.ones(dr.shape[0])
    dr[0:]=wts*dr[0:]
    sharpe_ratio=-np.mean(np.sum(dr, axis=1))/np.std(np.sum(dr, axis=1))
    return sharpe_ratio

def wts_con(wts):
    return wts[0]+wts[1]+wts[2]+wts[3]-1

def sharpe_optimize(dr, sharpe_func):
    wts_guess=np.array([0.25,0.25,0.25,0.25])

    con=[{"type":"eq", "fun":wts_con}]
    bnds=((0,1),(0,1),(0,1),(0,1))

    result=spo.minimize(sharpe_func, wts_guess, args=(dr,), method="SLSQP", constraints=con, bounds=bnds, options={"disp":True})
   return result

In the above code dr is a size(252,4) array and wts is a size(4) array

I am getting the following error in line 3 when I call the sharpe_optimize() function

could not broadcast input array from shape (252,4) into shape (4)


回答1:


I think you need to swap the arguments in your definition of the sharpe function. It is defined as sharpe(dr,wts) but then it looks like you call minimize as sharpe(wts,dr) based on your use of args. Edit: I have just seen that this is pointed out in the above comments!



来源:https://stackoverflow.com/questions/39310546/getting-an-error-could-not-broadcast-input-array-from-shape-252-4-into-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!