Skip to content
Course Notes: Introduction to Portfolio Analysis in Python
  • AI Chat
  • Code
  • Report
  • Spinner

    Course Notes

    Use this workspace to take notes, store code snippets, or build your own interactive cheatsheet! For courses that use data, the datasets will be available in the datasets folder.

    # Import any packages you want to use here
    import numpy as np
    import pandas as pd
    
    import matplotlib.pyplot as plt
    from matplotlib.dates import YearLocator

    Portfolio versus fund versus index

    • Portfolio: a collection of investments (stocks, bonds, commodities, other funds) often owned by an individual
    • Fund: a pool of investments that is managed by a professional fund manager. Individual investors buy "units" of the fund and the manager invests the money
    • Index: a smaller sample of the market that is representative of the whole, e.g. S&P500, Nasdaq, Russell 2000, MSCI World Index

    Active versus passive investing

    • Passive investing: following a benchmark as closely as possible. A passive investor aims to mimic the investment holdings of a particular index and thereby doesn't try to beat a benchmark or maximize returns.
    • Active investing: taking active "bets" that are different from a benchmark. An active investor typically tries to beat a benchmark or to maximize return for a given level or risk. Active investors pay close attention to market trends, shifts in the economy, changes to the political landscape, and factors that may affect specific companies, and use that information to buy and sell stocks. Within the active space, long only investment strategies try to outperform a benchmark, whereas absolute return hedgefunds are not bound by a benchmark and just aim for a best possible risk-return trade-off.
      • Long only strategies: small deviations from a benchmark.
      • Hedgefunds: no benchmark but a 'total return strategies'

    Diversification

    1. Single stock investments expose you to: a sudden change in management, disappointing financial performance, weak economy, an industry slump, etc
    2. Good diversification means combining stocks that are different: risk, cyclical, counter-cyclical, industry, country

    By smartly combining assets with different characteristics and different risk and return profiles, you can reduce the overall risk of your investments.

    Typical Portfolio strategies

    • Equal weighted portfolios: combine stocks and gives them all the same weight
    • Market-cap weighted portfolios: create individual weights based on the size of the companies, measured by market capitalizations (the value of the company calculated by multiplying the company's shres by the current market price of one share)
    • Risk-return optimized portfolios: have optmized risk-return trade-off

    Portfolio Weights

    The portfolio weight of an asset is the percentage of the total value invested in that particular asset. The portfolio weights summed together add up to 100%. By setting many relatively small weights, you can diversify your portfolio. The larger the weights to individual stocks, the more exposed you are to fluctuations in that stock.

    The portfolio manager's job is to determine the optimal portfolio weights given certain risk and return constraints, and change those as market conditions change.

    Portfolio Returns

    Portfolio returns are changes in value over time.

    Historic returns are often used to calculate expected returns for the future

    Caveat: Always take into consideration the probability that an asset will achieve its historical return given the current investing environment.

    • Some assets like bonds are more likely to match their historical returns
    • Others like stocks may vary more widely from year to year
    Types of returns:
    • Average returns: the geometric mean of a return series of a given time span
    • Cumulative return: the total return over a period
    • Active return: the relative performance to a benchmark
    • Annualized return:

    Exercise: Calculate Mean Returns

    In this exercise, you're going to calculate performance for a four stock portfolio over the period January 2015 through March 2019. The portfolio consists of Proctor & Gamble, Microsoft, JP Morgan and General Electric stocks. You'll discover that multiplying the mean return of each stock with its portfolio weight, is a very quick and straightforward way to calculate portfolio performance over a given period of time.

    • Calculate the percentage returns of the stocks in the DataFrame data by comparing today's price with yesterday's price.
    • Calculate the mean returns of each stock in the new returns DataFrame.
    • Assign the weights of the stocks to the weights array. The weights are 0.5, 0.2, 0.2 and 0.1.
    • Multiply the percentage returns with the weights, and take the total sum, to calculate the total portfolio performance and print the results.
    data = pd.read_csv("datasets/small_portfolio.csv", index_col="date")
    data.head()
    # calculate percentage returns
    returns = data.pct_change()
    
    # calculate individual mean returns
    mean_daily_returns = returns.mean()
    
    # define weights for the portfolio
    weights = np.array([0.5, 0.2, 0.2, 0.1])
    
    # calculate expected portfolio performance
    portfolio_return = np.sum(mean_daily_returns * weights)
    portfolio_return

    Exercise: Portfolio cumulative returns

    In the previous exercise, you've calculated the mean performance over a period of time. This gives you one performance number for that entire period. To calculate performance over time, you will need the cumulative performance.

    • Calculate the daily portfolio returns and assign it to a new column called ['Portfolio'] in the returns dataset. Use dot multiplication to multiply the returns data with the portfolio weights.
    • Transform the daily returns dataset to a cumulative returns dataset by using the cumprod() function.
    # create a portfolio returns column
    returns["Portfolio"] = returns.dot(weights)
    
    # calculate cumulative returns
    daily_cum_return = (1 + returns).cumprod()
    
    daily_cum_return
    fig, ax = plt.subplots()
    ax.plot(daily_cum_return.index, daily_cum_return.Portfolio, color='purple', label="portfolio")
    ax.xaxis.set_major_locator(YearLocator())
    ax.set_title("Cumulative Performance");