python - Running Half life codes for a mean reverting series -
i trying compute half life results multiple columns of data. have tried incorporate codes got 'pythonforfinance.com' link.
however, seem have missed few edits resulting in errors being thrown.
this how df looks like: link
and code running:
import pandas pd import numpy np import statsmodels.api sm df1=pd.read_excel('c:\\users\sai\desktop\test\spreads.xlsx') halflife_results={} col in df1.columns.values: spread_lag = df1.shift(periods=1, axis=1) spread_lag.ix([0]) = spread_lag.ix([1]) spread_ret = df1.columns - spread_lag spread_ret.ix([0]) = spread_ret.ix([1]) spread_lag2 = sm.add_constant(spread_lag) md = sm.ols(spread_ret,spread_lag2) mdf = md.fit() half_life = round(-np.log(2) / mdf.params[1],0) print('half life:', half_life)
the error being thrown is:
file "c:/users/sai/desktop/test/half life test 2.py", line 12 spread_lag.ix([0]) = spread_lag.ix([1]) ^ syntaxerror: can't assign function call
based on error message, seem have made basic mistake since beginner not able fix issue. if not solution code, explanation these lines of codes of great help:
spread_lag = df1.shift(periods=1, axis=1) spread_lag.ix([0]) = spread_lag.ix([1]) spread_ret = df1.columns - spread_lag spread_ret.ix([0]) = spread_ret.ix([1]) spread_lag2 = sm.add_constant(spread_lag)
as explained error message, pd.series.ix
isn't callable: should change spread_lag.ix([0])
spread_lag.ix[0]
.
also, shouldn't shift on axis=1
(rows) since you're interested in differences along each column (axis=0
, default value).
defining get_halflife
function allows directly apply each column, removing need loop.
def get_halflife(s): s_lag = s.shift(1) s_lag.ix[0] = s_lag.ix[1] s_ret = s - s_lag s_ret.ix[0] = s_ret.ix[1] s_lag2 = sm.add_constant(s_lag) model = sm.ols(s_ret,s_lag2) res = model.fit() halflife = round(-np.log(2) / res.params[1],0) return halflife df1.apply(get_halflife)
Comments
Post a Comment