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
tickers
containing the two stock symbols. - Use
pd.read_csv()
to import'msft_aapl.csv'
and'sp500.csv'
, creating aDatetimeIndex
for each from the'date'
column usingparse_dates
andindex_col
, and assign the result tostocks
andsp500
, respectively. - Use
pd.concat()
to concatenatestocks
andsp500
alongaxis=1
, apply.dropna()
to drop all missing values, and assign the result todata
. - Normalize
data
by dividing by the first price, multiply by 100 and assign the output tonormalized
. - Select
tickers
fromnormalized
, and subtractnormalized['SP500']
with keywordaxis=0
to 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