Sometimes, researchers need to generate a beta time series based on, for example, a three-year moving window. In such cases, we could write a loop or double loops. Let's look at a simpler case: estimating the annual beta for IBM over several years. First, let's look at two ways of getting years from a date variable:
import datetime today=datetime.date.today() year=today.year # Method I print(year) 2017 print(today.strftime("%Y")) # Method II '2017'
The Python program used to estimate the annual beta is shown here:
import numpy as np import scipy as sp import pandas as pd from scipy import stats from matplotlib.finance import quotes_historical_yahoo_ochl def ret_f(ticker,begdate, enddate): p = quotes_historical_yahoo_ochl(ticker, begdate, enddate,asobject=True,adjusted=True) return((p.aclose[1:] - p.aclose[:-1])/p.aclose[:-1]) # begdate=(2010,1,1) enddate=(2016,12,31) # y0=pd.Series(ret_f('IBM',begdate,enddate)) x0=pd.Series(ret_f('^GSPC...