Course Name: Mean Reversion Strategies In Python, Section No: 12, Unit No: 4, Unit type: Notebook
-
Computation of Halflife via Ols
-
We calculated the half-life for the pair HDFCAMC and SBICARD using 480 data points and the course’s implementation code. Despite the clean data, the half-life values were negative. Is half-life not always expected to be positive? Find the Implementation Code Below :-
import pandas as pd
import statsmodels.api as sm
import numpy as np
import math
y = stock_data.iloc[:,0]
x = stock_data.iloc[:,1]
# Hedge Ratio
model = sm.OLS(y.iloc[:], x.iloc[:])
model = model.fit()
# Spread GLD - hedge ratio * GDX
spread = -model.params[0]*x + y
spread = spread.iloc[:]
# Spread and difference between spread
spread_x = np.mean(spread) - spread
spread_y = spread.shift(-1) - spread
spread_df = pd.DataFrame({'x': spread_x, 'y': spread_y}).dropna()
# Theta as regression beta between spread and difference between spread
model_s = sm.OLS(spread_df['y'], spread_df['x']).fit()
theta = model_s.params[0]
# Type your code below
hl = math.log(2) / theta
print("Half Life:", hl)```