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.
Cet exercice fait partie du cours
Manipulating Time Series Data in Python
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.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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