Beta Calulation

Usually, the very first step of analyzing a stock is to know how it relates to the benchmark. That’s the Beta. Let’s build a function to calculate it.

 




Beta Calculation







In [ ]:
from data_source_lib import *
#Import our data getting library, I just name it data_source_lib.py in my folder
In [54]:
def beta(ticker,bench = "SPY", interval="day"):    
    # will return a dataframe     
    betas = []
    volos = []
    data_get = get_stock_data([bench,ticker],freq = "daily")  
    data_get = data_get.get_ondemand_data()
    ben_mark= data_get[data_get.Ticker == bench]
    stock = data_get[data_get.Ticker == ticker]
        # get return and put them in a new dataframe
    ben_mark = ben_mark.rename(columns={"Return":bench + "_bench_re","Ticker":bench}).reset_index()
    stock = stock.rename(columns={"Return":ticker + "_stock_re","Ticker":ticker}).reset_index()
    new = pd.concat([ben_mark,stock],axis =1)
    new = new[[bench,bench + "_bench_re",ticker, ticker + "_stock_re" ]]
    new = new.dropna()
    #calculate beta using covariance matrix
    covmat = np.cov(new[bench+ "_bench_re"],new[ticker+ "_stock_re"])
    #beta calculation
    beta = covmat[0,1]/  np.sqrt(covmat[1,1]*covmat[0,0])
    volotity = np.sqrt(covmat[1,1])
    betas.append(beta)
    volos.append(volotity)
    betas = pd.DataFrame(betas)
    betas.columns=["Beta"]
    return betas, covmat, volos
In [57]:
beta("AAPL")[0]
Finished AAPL
100%|████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:01<00:00,  1.81it/s]
Out[57]:
Beta
0 0.559557

Write a Comment