Created
September 18, 2018 15:09
-
-
Save jcorrius/c3212b991b4f484cd502a50e7b92d41b to your computer and use it in GitHub Desktop.
Augmented Dickey-Fuller unit root test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from statsmodels.regression.linear_model import OLS | |
from statsmodels.tsa.tsatools import lagmat, add_trend | |
from statsmodels.tsa.adfvalues import mackinnonp | |
def adf(ts): | |
""" | |
Augmented Dickey-Fuller unit root test | |
""" | |
# make sure we are working with an array, convert if necessary | |
ts = np.asarray(ts) | |
# Get the dimension of the array | |
nobs = ts.shape[0] | |
# We use 1 as maximum lag in our calculations | |
maxlag = 1 | |
# Calculate the discrete difference | |
tsdiff = np.diff(ts) | |
# Create a 2d array of lags, trim invalid observations on both sides | |
tsdall = lagmat(tsdiff[:, None], maxlag, trim='both', original='in') | |
# Get dimension of the array | |
nobs = tsdall.shape[0] | |
# replace 0 xdiff with level of x | |
tsdall[:, 0] = ts[-nobs - 1:-1] | |
tsdshort = tsdiff[-nobs:] | |
# Calculate the linear regression using an ordinary least squares model | |
results = OLS(tsdshort, add_trend(tsdall[:, :maxlag + 1], 'c')).fit() | |
adfstat = results.tvalues[0] | |
# Get approx p-value from a precomputed table (from stattools) | |
pvalue = mackinnonp(adfstat, 'c', N=1) | |
return pvalue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment