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