Compare annual stock price trends
In the video, you have seen how to select sub-periods from a time series.
You'll use this to compare the performance for three years of Yahoo stock prices.
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 and we have already loaded the 'yahoo.csv' file in a variable yahoo with DateTimeIndex and a single column price.
- Create an empty
pd.DataFrame()calledprices. - Iterate over a list containing the three years, 2013, 2014, and 2015, as
string, and in each loop:- Use the iteration variable to select the data for this year and the column
price. - Use
.reset_index()withdrop=Trueto remove theDatetimeIndex. - Rename the column
pricecolumn to the appropriateyear. - Use
pd.concat()to combine the yearly data with the data inpricesalongaxis=1.
- Use the iteration variable to select the data for this year and the column
- Plot
prices.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create dataframe prices here
prices = ____
# Select data for each year and concatenate with prices here
for year in [___, ___, ___]:
price_per_year = yahoo.loc[___, [___]].reset_index(drop=True)
price_per_year.rename(columns={___: year}, inplace=True)
prices = pd.concat([prices, ___], axis=1)
# Plot prices