10.12.2019 Views

Python for Finance

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Capital Asset Pricing Model

Moving beta

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

print(year)

2017

print(today.strftime("%Y"))

'2017'

[ 192 ]

# Method I

# Method II

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',begdate,enddate))

#

d=quotes_historical_yahoo_ochl('^GSPC', begdate, enddate,asobject=True

,adjusted=True).date[0:-1]

lag_year=d[0].strftime("%Y")

y1=[]

x1=[]

beta=[]

index0=[]

for i in sp.arange(1,len(d)):

year=d[i].strftime("%Y")

if(year==lag_year):

x1.append(x0[i])

y1.append(y0[i])

else:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!