O'Reilly logo

Mastering pandas for Finance by Michael Heydt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Constructing an optimal portfolio

We are now able to create a function to use fmin() to determine the set of weights that maximize the Sharpe ratio for a given set of returns representing the stocks in our portfolio.

Since fmin() finds a minimum of the applied function, and the efficient portfolio exists at the maximized Sharpe ratio, we need to provide a function that, in essence, returns the negative of the Sharpe ratio, hence allowing fmin() to find a minimum:

In [24]:
   def negative_sharpe_ratio_n_minus_1_stock(weights, 
                                             returns, 
                                             risk_free_rate):
       """
       Given n-1 weights, return a negative sharpe ratio
       """
       weights2 = sp.append(weights, 1-np.sum(weights))
       return -sharpe_ratio(returns, weights2, risk_free_rate)

Our final function is given ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required