1

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()
oceanbeach96
  • 604
  • 9
  • 19

1 Answers1

2

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()
Yuca
  • 6,010
  • 3
  • 22
  • 42
  • How did you arrive on "250*6" ? Are you assuming that data is present for 25 days in each month? – Kanishk Dudeja Nov 23 '21 at 12:21
  • the 250 is a short hand to give a quick example, it all depends on how you arrange your data – Yuca Nov 23 '21 at 15:22
  • Thanks for your response. I had a follow-up question about rolling(). From what I understand, rolling() returns even those windows which have periods less than (250*6). For example, it will return the first row too even though we don't have data for 60 months back. Is there a way to make it return only those windows which have exactly (250*6) periods between them? – Kanishk Dudeja Nov 23 '21 at 20:33