Cumulative return on $1,000 invested in google vs apple II
Apple outperformed Google over the entire period, but this may have been different over various 1-year sub periods, so that switching between the two stocks might have yielded an even better result.
To analyze this, calculate that cumulative return for rolling 1-year periods, and then plot the returns to see when each stock was superior.
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 the GOOG
and AAPL
close prices from the last exercise into data
.
- Define a
multi_period_return()
function that returns the cumulative return from an array of period returns. - Calculate
daily_returns
by applying.pct_change()
todata
. - Create a
'360D'
.rolling()
window ondaily_returns
, and.apply()
multi_period_returns
. Assign the result torolling_annual_returns
. - Plot
rolling_annual_returns
after multiplying it by 100.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import numpy
import numpy as np
# Define a multi_period_return function
def multi_period_return(period_returns):
return ____(____)
# Calculate daily returns
daily_returns = ____
# Calculate rolling_annual_returns
rolling_annual_returns = ____
# Plot rolling_annual_returns