import statsmodels.api as sm
from math import log
import numpy as np
def get_halflife(z_array):
z_lag = np.roll(z_array, 1)
z_lag[0] = 0
z_ret = z_array - z_lag
z_ret[0] = 0
s_lag2 = sm.add_constant(z_lag)
model = sm.OLS(z_ret,s_lag2)
res = model.fit()
halflife = round(-np.log(2) / res.params[1],0)
return halflife
z_array = [3, 4, 4, 5, 6, 7, 6, 6, 7, 8, 9, 12, 10]
get_halflife(z_array)
Posted in量化程序
均值回归半衰期计算

