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

Technical Analysis

You may hear about Technical Analyst. That’s the basis of quantitative analysis of the stock market. There is a package in Python that makes the calculation of all the technical indicator much easier. I chose some of my favorite indicators and integrate into my code library.

Applying the talib is a little bit tricky, but take a look at this one line of code.

price.loc[price.Ticker==i,"ADXR"]= ta.ADXR(price.loc[price.Ticker==i].High.values, price.loc[price.Ticker==i].Low.values, price.loc[price.Ticker==i].Close.values, timeperiod=14)

The variable price is a DataFrame that return from our data getting object. Since we only want to analyze one stock’s time series feature, we want to filter the one ticker at one calculation, using price.Ticker == i. Then, the ADXR,  Average Directional Movement Index Rating indicator takes in High, Low and close. Basically, put them in the function of ta.ADXR()

Here’s the full picture of the function.

In [16]:
import talib as ta
import data_source_lib as da

In [15]:
get_data = da.get_stock_data(["AAPL"],freq = "daily")
price = get_data.get_ondemand_data()

Finished AAPL

100%|████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00,  1.56it/s]

In [40]:
 def get_technicals(price) :
import pandas as pd
import tqdm
from IPython.display import clear_output
if not isinstance(price, pd.DataFrame):
raise "Please feed a DataFrame object"
for i in tqdm.tqdm(range(len(set(price.Ticker)))):

i = list(set(price.Ticker))
#print price .loc[price.Ticker==i]

#price.groupby('Ticker').get_group(list(set(price.Ticker))[i])
price.loc[price.Ticker==i].Close.values, timeperiod=14)
price.loc[price.Ticker==i,"APO"]= ta.APO(price.loc[price.Ticker==i].Close.values, fastperiod=12, slowperiod=26, matype=0)
price.loc[price.Ticker==i,"AROONOSC"]= ta.AROONOSC(price.loc[price.Ticker==i].High.values,price.loc[price.Ticker==i].Close.values, timeperiod=14)
price.loc[price.Ticker==i,"CCI"]= ta.CCI(price.loc[price.Ticker==i].High.values,price.loc[price.Ticker==i].Low.values,price.loc[price.Ticker==i].Close.values, timeperiod=14)
price.loc[price.Ticker==i,"MFI"]= ta.MFI(price.loc[price.Ticker==i].High.values, price.loc[price.Ticker==i].Low.values, price.loc[price.Ticker==i].Close.values,\
price.loc[price.Ticker==i].loc[price.Ticker==i].Volume.values.astype(float),timeperiod=14)
price.loc[price.Ticker==i,"MACD"], price.loc[price.Ticker==i,"MACD_signal"], price.loc[price.Ticker==i,"MACD_hist"] = ta.MACD(price.loc[price.Ticker==i].Close.values, fastperiod=12, slowperiod=26, signalperiod=9)
price.loc[price.Ticker==i,"ROCP"]= ta.ROCP(price.loc[price.Ticker==i].Close.values, timeperiod=10)
#price.loc[price.Ticker==i,"ROCR100"]= ta.ROCR100(price.loc[price.Ticker==i].Close.values, timeperiod=10)
price.loc[price.Ticker==i,"RSI"]= ta.RSI(price.loc[price.Ticker==i].Close.values, timeperiod=14)
price.loc[price.Ticker==i,"MA_fast"] = price.Close.rolling(10).mean()
price.loc[price.Ticker==i,"MA_slow"] = price.Close.rolling(30).mean()
clear_output()
print "\nDone:", i