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

Modeling a portfolio with pandas

A basic portfolio model consists of a specification of one or more investments and their quantities. A portfolio can be modeled in pandas using a DataFrame with one column representing the particular instrument (such as a stock symbol) and the other representing the quantity of the item held.

The following command will create a DataFrame representing a portfolio:

In [2]:
   def create_portfolio(tickers, weights=None):
       if (weights is None): 
           shares = np.ones(len(tickers))/len(tickers)
       portfolio = pd.DataFrame({'Tickers': tickers, 
                                 'Weights': weights}, 
                                index=tickers)
       return portfolio

Using this, we can create a portfolio of two instruments, Stock A and Stock B. The amount of shares for each is initialized to ...

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