Getting an error "could not broadcast input array from shape (252,4) into shape (4)" in optimization
<p>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</p>

<pre><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
</code></pre>

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

<p>I am getting the following error in line 3 when I call the sharpe_optimize() function</p>

<blockquote>
  <p>could not broadcast input array from shape (252,4) into shape (4)</p>
</blockquote>

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

python optimization scipy