Scipy Optimizer cannot give the best result

Viewed 31

I am trying to run a ipynb file which download the data from yahoo and run the scipy optimizer. My objective is to find the optimum weight allocation with the max sharpe ratio.

Link for the ipynb : https://www.dropbox.com/s/fipg3f4kpakm8cj/msr.ipynb?dl=0

def msr(riskfree_rate, er, cov):
    n = er.shape[0]
    init_guess = np.repeat(1/n, n)
    bounds = ((0.0, 1.0),) * n 
    # construct the constraints
    weights_sum_to_1 = {'type': 'eq',
                        'fun': lambda weights: np.sum(weights) - 1
    }
    def neg_sharpe(weights, riskfree_rate, er, cov):
        r = portfolio_return(weights, er)
        vol = portfolio_vol(weights, cov)
        return -(r - riskfree_rate)/vol

    weights = minimize(neg_sharpe, init_guess,
                       args=(riskfree_rate, er, cov), method='SLSQP',
                       options={'disp': False},
                       constraints=(weights_sum_to_1,),
                       bounds=bounds)
    return weights.x

And it returns an array of weights

array([5.45508083e-13, 2.98622238e-13, 1.00000000e+00, 0.00000000e+00,
       1.88124516e-12, 0.00000000e+00])

The Sharpe Ratio which I put the riskfree rate = 0

ret = weight.T @ annualize_rets(df,period)
vol = (weight.T @ df.cov() @ weight)**0.5
ret/vol

Output :

-13.779468674840242

But I tested with another allocation and it gave a better result

test_weight = np.array([0,0,0,0,0,1])

test_ret = test_weight.T @ annualize_rets(df,period)
test_vol = (test_weight.T @ df.cov() @ test_weight)**0.5
test_ret/test_vol

Output :

-12.79174167620581

Any problem with the code? Any thoughts?

Thanks!

0 Answers
Related