Calculating stock price changes
You have learned in the video how to calculate returns using current and shifted prices as input. Now you'll practice a similar calculation to calculate absolute changes from current and shifted prices, and compare the result to the function .diff().
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. We have also loaded Yahoo stock prices for the years 2013 to 2015, set the frequency to business daily, and assigned the result to yahoo.
- Create a new column called
shifted_30that contains the'price'shifted by 30 business days into the future. - Subtract
'shifted_30'from'price', and assign the result to a new column,'change_30'. - Apply
.diff(), settingperiodsto 30, and assign the result to a new column,'diff_30'. - Inspect the last five rows of
yahooto verify the calculation. - Subtract
diff_30fromchange_30using the.sub()method and print the.value_counts()of the result to show both columns are equal.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Created shifted_30 here
yahoo['shifted_30'] = ____
# Subtract shifted_30 from price
yahoo['change_30'] = ____
# Get the 30-day price difference
yahoo['diff_30'] = ____
# Inspect the last five rows of price
print(____)
# Show the value_counts of the difference between change_30 and diff_30
print(____)