Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to calculate asset beta giving incorrect result

I started programming about a week ago, and I completed the code-academy tutorial and watched some lectures online. My first goal is to build is an interactive portfolio optimization program.

I have written a script to find the beta of an asset (co-variance of a and b / variance of b) however my results are no where near the actual beta's for the assets that I plug in. Using 'AAPL' and 'SPY' the result should be around .75, and it's yielding ~.16.

I'd like to return the r^2 as well if possible, and use monthly data over a longer period of time.

Here is my code:

from pandas.io.data import DataReader
from datetime import datetime
from datetime import date
import numpy

### Enter the stocks to be analyzed

s1 = input('Input the first ticker in quotations: ')
s2 = input('Input the second ticker in quotations: ')


### Pulling stock data from yahoo finance

today = date.today()

stock_one = DataReader((s1),'yahoo', datetime(2013,1,1), today)
stock_two = DataReader((s2),'yahoo', datetime(2013,1,1), today)

a = stock_one['Adj Close']
b = stock_two['Adj Close']

### Calculating the beta for the stock

covariance = numpy.cov(a,b)[0][1]
variance = numpy.var(a)

beta = covariance / variance

print 'The beta for your stock is ' + str(beta)
like image 497
user3263684 Avatar asked Sep 04 '26 05:09

user3263684


1 Answers

You have a mistake at the line:

    variance = numpy.var(a)

It should be:

    variance = numpy.var(b)

Since the formula for beta is:

    covar(a,b)/var(b)

In the original way you wrote your code, you are getting the beta of b to a not of a to b.

like image 116
Overclocker Avatar answered Sep 05 '26 19:09

Overclocker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!