Plot performance difference vs benchmark index
In the video, you learned how to calculate and plot the performance difference of a stock in percentage points relative to a benchmark index.
Let's compare the performance of Microsoft (MSFT) and Apple (AAPL) to the S&P 500 over the last 10 years.
This exercise is part of the course
Manipulating Time Series Data in Python
Exercise instructions
We have already imported pandas as pd and matplotlib.pyplot as plt.
- Create the list
tickerscontaining the two stock symbols. - Use
pd.read_csv()to import'msft_aapl.csv'and'sp500.csv', creating aDatetimeIndexfor each from the'date'column usingparse_datesandindex_col, and assign the result tostocksandsp500, respectively. - Use
pd.concat()to concatenatestocksandsp500alongaxis=1, apply.dropna()to drop all missing values, and assign the result todata. - Normalize
databy dividing by the first price, multiply by 100 and assign the output tonormalized. - Select
tickersfromnormalized, and subtractnormalized['SP500']with keywordaxis=0to align the indexes, then plot the result.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create tickers
tickers = ____
# Import stock data here
stocks = ____
# Import index here
sp500 = ____
# Concatenate stocks and index here
data = ____
# Normalize data
normalized = ____
# Subtract the normalized index from the normalized stock prices, and plot the result