Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 75 additions & 32 deletions statsmodels/tsa/stattools.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def acovf(x, unbiased=False, demean=True, fft=False, missing='none'):
missing : str
A string in ['none', 'raise', 'conservative', 'drop'] specifying how the NaNs
are to be treated.

Returns
-------
acovf : array
Expand All @@ -335,7 +335,7 @@ def acovf(x, unbiased=False, demean=True, fft=False, missing='none'):
else:
deal_with_masked = has_missing(x)
if deal_with_masked:
if missing == 'raise':
if missing == 'raise':
raise MissingDataError("NaNs were encountered in the data")
notmask_bool = ~np.isnan(x) #bool
if missing == 'conservative':
Expand All @@ -362,7 +362,7 @@ def acovf(x, unbiased=False, demean=True, fft=False, missing='none'):
d = np.hstack((xi, xi[:-1][::-1]))
elif deal_with_masked: #biased and NaNs given and ('drop' or 'conservative')
d = notmask_int.sum() * np.ones(2*n-1)
else: #biased and no NaNs or missing=='none'
else: #biased and no NaNs or missing=='none'
d = n * np.ones(2 * n - 1)

if fft:
Expand Down Expand Up @@ -921,32 +921,53 @@ def grangercausalitytests(x, maxlag, addconst=True, verbose=True):
return resli


def coint(y1, y2, regression="c"):
"""
This is a simple cointegration test. Uses unit-root test on residuals to
test for cointegrated relationship
def coint(y0, y1, trend='c', method='aeg', maxlag=None, autolag='aic',
return_results=None):
"""Test for no-cointegration of a univariate equation

The null hypothesis is no cointegration. Variables in y0 and y1 are
assumed to be integrated of order 1, I(1).

See Hamilton (1994) 19.2
This uses the augmented Engle-Granger two-step cointegration test.
Constant or trend is included in 1st stage regression, i.e. in
cointegrating equation.

Parameters
----------
y1 : array_like, 1d
first element in cointegrating vector
y2 : array_like
remaining elements in cointegrating vector
c : str {'c'}
Included in regression
* 'c' : Constant
trend : str {'c', 'ct'}
trend term included in regression for cointegrating equation
* 'c' : constant
* 'ct' : constant and linear trend
* also available quadratic trend 'ctt', and no constant 'nc'

method : string
currently only 'aeg' for augmented Engle-Granger test is available.
default might change.
maxlag : None or int
keyword for `adfuller`, largest or given number of lags
autolag : string
keyword for `adfuller`, lag selection criterion.
return_results : bool
for future compatibility, currently only tuple available.
If True, then a results instance is returned. Otherwise, a tuple
with the test outcome is returned.
Set `return_results=False` to avoid future changes in return.


Returns
-------
coint_t : float
t-statistic of unit-root test on residuals
pvalue : float
MacKinnon's approximate p-value based on MacKinnon (1994)
MacKinnon's approximate, asymptotic p-value based on MacKinnon (1994)
crit_value : dict
Critical values for the test statistic at the 1 %, 5 %, and 10 %
levels.
levels based on regression curve. This depends on the number of
observations.

Notes
-----
Expand All @@ -955,30 +976,52 @@ def coint(y1, y2, regression="c"):
small, below a critical size, then we can reject the hypothesis that there
is no cointegrating relationship.

P-values are obtained through regression surface approximation from
MacKinnon 1994.
P-values and critical values are obtained through regression surface
approximation from MacKinnon 1994 and 2010.

TODO: We could handle gaps in data by dropping rows with nans in the
auxiliary regressions. Not implemented yet, currently assumes no nans
and no gaps in time series.

References
----------
MacKinnon, J.G. 1994. "Approximate asymptotic distribution functions for
unit-root and cointegration tests. `Journal of Business and Economic
Statistics` 12, 167-76.

MacKinnon, J.G. 1994 "Approximate Asymptotic Distribution Functions for
Unit-Root and Cointegration Tests." Journal of Business & Economics
Statistics, 12.2, 167-76.
MacKinnon, J.G. 2010. "Critical Values for Cointegration Tests."
Queen's University, Dept of Economics Working Papers 1227.
http://ideas.repec.org/p/qed/wpaper/1227.html
"""
regression = regression.lower()
if regression not in ['c', 'nc', 'ct', 'ctt']:
raise ValueError("regression option %s not understood" % regression)

trend = trend.lower()
if trend not in ['c', 'nc', 'ct', 'ctt']:
raise ValueError("trend option %s not understood" % trend)
y0 = np.asarray(y0)
y1 = np.asarray(y1)
y2 = np.asarray(y2)
if regression == 'c':
y2 = add_constant(y2, prepend=False)
st1_resid = OLS(y1, y2).fit().resid # stage one residuals
lgresid_cons = add_constant(st1_resid[0:-1], prepend=False)
uroot_reg = OLS(st1_resid[1:], lgresid_cons).fit()
coint_t = (uroot_reg.params[0] - 1) / uroot_reg.bse[0]
pvalue = mackinnonp(coint_t, regression="c", N=2, lags=None)
crit_value = mackinnoncrit(N=1, regression="c", nobs=len(y1))
return coint_t, pvalue, crit_value
if y1.ndim < 2:
y1 = y1[:, None]
nobs, k_vars = y1.shape
k_vars += 1 # add 1 for y0

if trend == 'nc':
xx = y1
else:
xx = add_trend(y1, trend=trend, prepend=False)

res_co = OLS(y0, xx).fit()

res_adf = adfuller(res_co.resid, maxlag=maxlag, autolag=None,
regression='nc')
# no constant or trend, see egranger in Stata and MacKinnon
if trend == 'nc':
crit = [np.nan] * 3 # 2010 critical values not available
else:
crit = mackinnoncrit(N=k_vars, regression=trend, nobs=nobs - 1)
# nobs - 1, the -1 is to match egranger in Stata, I don't know why.
# TODO: check nobs or df = nobs - k

pval_asy = mackinnonp(res_adf[0], regression=trend, N=k_vars)
return res_adf[0], pval_asy, crit


def _safe_arma_fit(y, order, model_kw, trend, fit_kw, start_params=None):
Expand Down
104 changes: 89 additions & 15 deletions statsmodels/tsa/tests/test_stattools.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from statsmodels.tsa.base.datetools import dates_from_range
import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal, assert_warns,
assert_raises, dec, assert_)
assert_raises, dec, assert_, assert_allclose)
from numpy import genfromtxt
from statsmodels.datasets import macrodata, sunspots
from pandas import Series, Index, DataFrame
Expand Down Expand Up @@ -169,45 +169,45 @@ def test_acf(self):
def test_qstat(self):
#todo why is res1/qstat 1 short
assert_almost_equal(self.res1[1], self.qstat, DECIMAL_3)

class TestACFMissing(CheckCorrGram):
# Test Autocorrelation Function using Missing
def __init__(self):
self.x = np.concatenate((np.array([np.nan]),self.x))
self.acf = self.results['acvar'] # drop and conservative
self.qstat = self.results['Q1']
self.res_drop = acf(self.x, nlags=40, qstat=True, alpha=.05,
self.res_drop = acf(self.x, nlags=40, qstat=True, alpha=.05,
missing='drop')
self.res_conservative = acf(self.x, nlags=40, qstat=True, alpha=.05,
missing='conservative')
self.res_conservative = acf(self.x, nlags=40, qstat=True, alpha=.05,
missing='conservative')
self.acf_none = np.empty(40) * np.nan # lags 1 to 40 inclusive
self.qstat_none = np.empty(40) * np.nan
self.res_none = acf(self.x, nlags=40, qstat=True, alpha=.05,
missing='none')

def test_raise(self):
assert_raises(MissingDataError, acf, self.x, nlags=40,
assert_raises(MissingDataError, acf, self.x, nlags=40,
qstat=True, alpha=.05, missing='raise')

def test_acf_none(self):
assert_almost_equal(self.res_none[0][1:41], self.acf_none, DECIMAL_8)

def test_acf_drop(self):
assert_almost_equal(self.res_drop[0][1:41], self.acf, DECIMAL_8)

def test_acf_conservative(self):
assert_almost_equal(self.res_conservative[0][1:41], self.acf,
assert_almost_equal(self.res_conservative[0][1:41], self.acf,
DECIMAL_8)

def test_qstat_none(self):
#todo why is res1/qstat 1 short
assert_almost_equal(self.res_none[2], self.qstat_none, DECIMAL_3)
# how to do this test? the correct q_stat depends on whether nobs=len(x) is

# how to do this test? the correct q_stat depends on whether nobs=len(x) is
# used when x contains NaNs or whether nobs<len(x) when x contains NaNs
# def test_qstat_drop(self):
# assert_almost_equal(self.res_drop[2][:40], self.qstat, DECIMAL_3)


class TestPACF(CheckCorrGram):
def __init__(self):
Expand Down Expand Up @@ -254,13 +254,87 @@ class CheckCoint(object):
def test_tstat(self):
assert_almost_equal(self.coint_t,self.teststat, DECIMAL_4)

# this doesn't produce the old results anymore
class TestCoint_t(CheckCoint):
"""
Get AR(1) parameter on residuals
"""
def __init__(self):
self.coint_t = coint(self.y1, self.y2, regression ="c")[0]
#self.coint_t = coint(self.y1, self.y2, trend="c")[0]
self.coint_t = coint(self.y1, self.y2, trend="c", maxlag=0, autolag=None)[0]
self.teststat = -1.8208817
self.teststat = -1.830170986148


def test_coint():
nobs = 200
scale_e = 1
const = [1, 0, 0.5, 0]
np.random.seed(123)
unit = np.random.randn(nobs).cumsum()
y = scale_e * np.random.randn(nobs, 4)
y[:, :2] += unit[:, None]
y += const
y = np.round(y, 4)

for trend in []:#['c', 'ct', 'ctt', 'nc']:
print('\n', trend)
print(coint(y[:, 0], y[:, 1], trend=trend, maxlag=4, autolag=None))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cleanup or keep for debugging?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

leave it, this is convenient for checking. I just used it to get regressiontest numbers for 'nc'

print(coint(y[:, 0], y[:, 1:3], trend=trend, maxlag=4, autolag=None))
print(coint(y[:, 0], y[:, 2:], trend=trend, maxlag=4, autolag=None))
print(coint(y[:, 0], y[:, 1:], trend=trend, maxlag=4, autolag=None))

# results from Stata egranger
res_egranger = {}
# trend = 'ct'
res = res_egranger['ct'] = {}
res[0] = [-5.615251442239, -4.406102369132, -3.82866685109, -3.532082997903]
res[1] = [-5.63591313706, -4.758609717199, -4.179130554708, -3.880909696863]
res[2] = [-2.892029275027, -4.758609717199, -4.179130554708, -3.880909696863]
res[3] = [-5.626932544079, -5.08363327039, -4.502469783057, -4.2031051091]

# trend = 'c'
res = res_egranger['c'] = {}
# first critical value res[0][1] has a discrepancy starting at 4th decimal
res[0] = [-5.760696844656, -3.952043522638, -3.367006313729, -3.065831247948]
# manually adjusted to have higher precision as in other cases
res[0][1] = -3.952321293401682
res[1] = [-5.781087068772, -4.367111915942, -3.783961136005, -3.483501524709]
res[2] = [-2.477444137366, -4.367111915942, -3.783961136005, -3.483501524709]
res[3] = [-5.778205811661, -4.735249216434, -4.152738973763, -3.852480848968]

# trend = 'ctt'
res = res_egranger['ctt'] = {}
res[0] = [-5.644431269946, -4.796038299708, -4.221469431008, -3.926472577178]
res[1] = [-5.665691609506, -5.111158174219, -4.53317278104, -4.23601008516]
res[2] = [-3.161462374828, -5.111158174219, -4.53317278104, -4.23601008516]
res[3] = [-5.657904558563, -5.406880189412, -4.826111619543, -4.527090164875]

# The following for 'nc' are only regression test numbers
# trend = 'nc' not allowed in egranger
# trend = 'nc'
res = res_egranger['nc'] = {}
nan = np.nan # shortcut for table
res[0] = [-3.7146175989071137, nan, nan, nan]
res[1] = [-3.8199323012888384, nan, nan, nan]
res[2] = [-1.6865000791270679, nan, nan, nan]
res[3] = [-3.7991270451873675, nan, nan, nan]

for trend in ['c', 'ct', 'ctt', 'nc']:
res1 = {}
res1[0] = coint(y[:, 0], y[:, 1], trend=trend, maxlag=4, autolag=None)
res1[1] = coint(y[:, 0], y[:, 1:3], trend=trend, maxlag=4,
autolag=None)
res1[2] = coint(y[:, 0], y[:, 2:], trend=trend, maxlag=4, autolag=None)
res1[3] = coint(y[:, 0], y[:, 1:], trend=trend, maxlag=4, autolag=None)

for i in range(4):
res = res_egranger[trend]

assert_allclose(res1[i][0], res[i][0], rtol=1e-11)
r2 = res[i][1:]
r1 = res1[i][2]
assert_allclose(r1, r2, rtol=0, atol=6e-7)


class TestGrangerCausality(object):
Expand Down