Skip to content

Instantly share code, notes, and snippets.

@jcorrius
Created September 18, 2018 15:20
Show Gist options
  • Save jcorrius/4f3bd1b5c2163092f84547d9c1426fb3 to your computer and use it in GitHub Desktop.
Save jcorrius/4f3bd1b5c2163092f84547d9c1426fb3 to your computer and use it in GitHub Desktop.
Half-Life of Mean Reversion
import numpy as np
def half_life(ts):
"""
Calculates the half life of a mean reversion
"""
# make sure we are working with an array, convert if necessary
ts = np.asarray(ts)
# delta = p(t) - p(t-1)
delta_ts = np.diff(ts)
# calculate the vector of lagged values. lag = 1
lag_ts = np.vstack([ts[1:], np.ones(len(ts[1:]))]).T
# calculate the slope of the deltas vs the lagged values
beta = np.linalg.lstsq(lag_ts, delta_ts)
# compute and return half life
return (np.log(2) / beta[0])[0]
@edgetrader
Copy link

Hi, I think we should do regression yt-1 - yt on yt-1

    # calculate the vector of lagged values. lag = 1
    lag_ts = np.vstack([ts[1:], np.ones(len(ts[1:]))]).T
... ...
    # compute and return half life
    return (np.log(2) / beta[0])[0]

should be

    # calculate the vector of lagged values. lag = 1
    lag_ts = np.vstack([ts[:-1], np.ones(len(ts[:-1]))]).T
... ...
    # compute and return half life
    return -(np.log(2) / beta[0])[0]

Let me know if my understanding is not correct. Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment