Sunday, 5 October 2014

Calculation of Beta of Stocks Using Python Libraries (Stock Risk Analysis)

As an example, let us consider Coca Cola (NYSE:KO). Historical Coca Cola stock data can be downloaded from Google Finance:
Historical NYSE:KO Data

Suppose we consider NYSE:SPY as the market indicator/index in calculating beta. Historical stock data of NYSE:SPY can be downloaded from Google Finance:
Historical NYSE:SPY Data

The following python script finds the beta value for market indicator and symbol historical data file names passed as command line parameters:

import numpy as np
from sklearn import datasets, linear_model
import sys
fh = open(sys.argv[1], 'r')
lines = fh.readlines()
fh.close()
market_x = []
for i in range(len(lines)-1):
if i==0:
continue
line_i = lines[i].strip().split(',')[4]
line_i_1 = lines[i+1].strip().split(',')[4]
rate = (float(line_i) - float(line_i_1))/(float(line_i_1))
market_x.append([rate])
fh = open(sys.argv[2], 'r')
lines = fh.readlines()
fh.close()
stock_y = []
for i in range(len(lines)-1):
if i==0:
continue
line_i = lines[i].strip().split(',')[4]
line_i_1 = lines[i+1].strip().split(',')[4]
rate = (float(line_i) - float(line_i_1))/(float(line_i_1))
stock_y.append([rate])
regr = linear_model.LinearRegression()
regr.fit(market_x, stock_y)
print 'Beta: %s' % regr.coef_[0][0]
view raw beta_cal.py hosted with ❤ by GitHub

No comments:

Post a Comment