10.12.2019 Views

Python for Finance

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6

Here, yi is the ith observation for dependent variable y, 1 is the intercept, 0.8 is the

slope (beta), xi is the ith observation for an independent variable of x, and is the

random value. For the preceding equation, after we have generated a set of y and x,

we could run a linear regression. For this purpose, a set of random numbers are used:

from scipy import stats

import scipy as sp

sp.random.seed(12456)

alpha=1

beta=0.8

n=100

x=sp.arange(n)

y=alpha+beta*x+sp.random.rand(n)

(beta,alpha,r_value,p_value,std_err)=stats.linregress(y,x)

print(alpha,beta)

print("R-squared=", r_value**2)

print("p-value =", p_value)

In the preceding code, the sp.random.rand() function would call a set of random

numbers. In order to get the same set of random numbers, the sp.random.

seed() function is applied. In other words, whenever the same seed is used, any

programmers would get the same set of random numbers. This will be discussed in

more detail in Chapter 12, Monte Carlo Simulation. The result is shown here:

%run "C:/yan/teaching/Python2/codes/c6_02_random_OLS.py"

(-1.9648401142472594,1.2521836174247121,)

('R-squared=', 0.99987143193925765)

('p-value =', 1.7896498998980323e-192)

Now let's look at how to estimate the beta (market risk) for Microsoft. Assume that

we are interested in the period from 1/1/2012 to 12/31/2016, for a total of five year's

data. The complete Python program is shown here:

from scipy import stats

from matplotlib.finance import quotes_historical_yahoo_ochl as getData

begdate=(2012,1,1)

enddate=(2016,12,31)

ticker='MSFT'

p =getData(ticker, begdate, enddate,asobject=True,adjusted=True)

retIBM = p.aclose[1:]/p.aclose[:1]-1

ticker='^GSPC'

[ 189 ]

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

Saved successfully!

Ooh no, something went wrong!