Blogs

Beta Calculation

Different methods will be used to calculate beta. No suprise, all methods give the same answer. 

Import all libraries at first:

from yahoo_fin.stock_info import get_data
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
from statsmodels.api import OLS
import scipy.stats

Get data (IHAK, cybersecurity ETF and NASDAQ as benchmark in this case):

start_date = "10/12/2020"
end_date = "14/11/2021"
IHAK = get_data('IHAK', start_date, end_date, index_as_date = True, interval = "1d")
QQQ = get_data('QQQ', start_date, end_date, index_as_date = True, interval = "1d")

Calculate asset returns:

ihak_rets = IHAK['adjclose'].pct_change().dropna().values
qqq_rets = QQQ['adjclose'].pct_change().dropna().values
ihak_std = np.std(ihak_rets)*np.sqrt(252)
qqq_std = np.std(qqq_rets)*np.sqrt(252)

In first method, use std and corr for beta calculation:

# Calculating Beta with Std and Corr
corr = scipy.stats.pearsonr(ihak_rets, qqq_rets) # gives corr coef and p
ihak_beta = ihak_std / qqq_std * corr[0]
Corr:  0.72
Beta:  0.83

Second method is to use linear regression for beta estimation. Two different libraries can be used: sklearn and statsmodels. 

Let's try sklearn first and compare the result with statsmodels and the previous calculation.

# Finding Beta with Linear Regression
X = qqq_rets.reshape(-1, 1)
y = ihak_rets.reshape(-1, 1)

# linear regression using Sci-Kit Learn
model1 = LinearRegression().fit(X, y)
beta = model1.coef_[0][0]
Beta Linear Regression (Sklearn):  0.83
# lineaer regression using Statsmodels
X_const = sm.add_constant(X)
model2 = OLS(y, X_const)
result = model2.fit()
result.summary()

The summary report is a feautre of statsmodel library.

As seen in x1 coef = 0.8306, all three beta calculation are identical. 

Lastly, visualize the linear regression: