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 ...

Get Mastering pandas for Finance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.