Search code examples
pythonpandasfinancequandleconomics

Calculating 5 year rolling returns


I have the below code which has returns for U.S. stocks over the period Jan 1995 to Dec 2000. I wish to calculate the return for Jan 2001 using a 60-month rolling return in Python. As there is 5 years of returns, how is this possible?

I would like to calculate this for each stock over the time period Jan 2001 to Dec 2010. Any assistance would be awesome!

import quandl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Use Quandl to get adjusted close price
quandl.ApiConfig.api_key = 'Enter Your Key'
stocks = ['MSFT', 'AAPL', 'WMT', 'GE', 'KO', 'F', 'JNJ', 'BA', 'XOM']
stockdata = quandl.get_table('WIKI/PRICES', ticker = stocks, paginate=True,
                    qopts = { 'columns': ['date', 'ticker', 'adj_close'] },
                    date = { 'gte': '1995-1-1', 'lte': '2000-12-31' })

# Setting date as index with columns of tickers and adjusted closing 
# price
data1 = stockdata.set_index('date')
table = data1.pivot(columns='ticker')
table.head()

# Daily and annual returns of the stocks
returns_daily = table.pct_change()
returns_daily.head()

Solution

  • You can use .rolling() to create the subset for the 60 month rolling return

    returns_5year=table.rolling(250*6).pct_change()
    

    And if you want yearly returns, use 'asfreq('BA')`

    returns_yearly = table.asfreq('BA').pct_change()