2

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!

Po Steve
  • 21
  • 1
  • Are you confusing minimisation with minimisation of the absolute value? The output it gives seems to be more minimised than the one you give (-13.8 < -12.8) – llama Sep 04 '20 at 23:04
  • I've put a negative sign in front of the formula : return -(r - riskfree_rate)/vol in def neg_sharpe. And therefore it would be able to return the maximum sharpe ratio. – Po Steve Sep 06 '20 at 14:20
  • Have you looked at the full output of the minimize function? Sometimes it will return a result even when there's some soft error which makes it useless for your application – llama Sep 07 '20 at 18:13

0 Answers0