Book Image

Mastering Pandas for Finance

By : Michael Heydt
Book Image

Mastering Pandas for Finance

By: Michael Heydt

Overview of this book

Table of Contents (16 chapters)
Mastering pandas for Finance
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 a DataFrame of returns, and a risk-free rate will run a minimization process on our negative sharpe function. The process is seeded...