/
unitroot.py
1714 lines (1503 loc) · 59.1 KB
/
unitroot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import, division
from arch.compat.python import add_metaclass, lmap, long, range
import warnings
from numpy import (abs, amin, arange, argwhere, array, ceil, cumsum, diag,
diff, empty, float64, full, hstack, inf, int32, int64,
interp, log, nan, ones, pi, polyval, power, sort, sqrt,
squeeze, sum)
from numpy.linalg import inv, matrix_rank, pinv, qr, solve
from pandas import DataFrame
from scipy.stats import norm
from statsmodels.iolib.summary import Summary
from statsmodels.iolib.table import SimpleTable
from statsmodels.regression.linear_model import OLS
from statsmodels.tsa.tsatools import lagmat
from arch.unitroot.critical_values.dfgls import (dfgls_cv_approx,
dfgls_large_p, dfgls_small_p,
dfgls_tau_max, dfgls_tau_min,
dfgls_tau_star)
from arch.unitroot.critical_values.dickey_fuller import (adf_z_cv_approx,
adf_z_large_p,
adf_z_max, adf_z_min,
adf_z_small_p,
adf_z_star, tau_2010,
tau_large_p, tau_max,
tau_min, tau_small_p,
tau_star)
from arch.unitroot.critical_values.kpss import kpss_critical_values
from arch.unitroot.critical_values.zivot_andrews import za_critical_values
from arch.utility import cov_nw
from arch.utility.array import DocStringInheritor, ensure1d, ensure2d
from arch.utility.exceptions import InvalidLengthWarning, invalid_length_doc
from arch.utility.timeseries import add_trend
__all__ = ['ADF', 'DFGLS', 'PhillipsPerron', 'KPSS', 'VarianceRatio',
'kpss_crit', 'mackinnoncrit', 'mackinnonp', 'ZivotAndrews']
TREND_MAP = {None: 'nc', 0: 'c', 1: 'ct', 2: 'ctt'}
TREND_DESCRIPTION = {'nc': 'No Trend',
'c': 'Constant',
'ct': 'Constant and Linear Time Trend',
'ctt': 'Constant, Linear and Quadratic Time Trends',
't': 'Linear Time Trend (No Constant)'}
def _select_best_ic(method, nobs, sigma2, tstat):
"""
Comutes the best information criteria
Parameters
----------
method : {'aic', 'bic', 't-stat'}
Method to use when finding the lag length
nobs : int
Number of observations in time series
sigma2 : ndarray
maxlag + 1 array containins MLE estimates of the residual variance
tstat : ndarray
maxlag + 1 array containing t-statistic values. Only used if method
is 't-stat'
Returns
-------
icbest : float
Minimum value of the information criteria
lag : int
The lag length that maximizes the information criterion.
"""
llf = -nobs / 2.0 * (log(2 * pi) + log(sigma2) + 1)
maxlag = len(sigma2) - 1
if method == 'aic':
crit = -2 * llf + 2 * arange(float(maxlag + 1))
icbest, lag = min(zip(crit, arange(maxlag + 1)))
elif method == 'bic':
crit = -2 * llf + log(nobs) * arange(float(maxlag + 1))
icbest, lag = min(zip(crit, arange(maxlag + 1)))
elif method == 't-stat':
stop = 1.6448536269514722
large_tstat = abs(tstat) >= stop
lag = int(squeeze(max(argwhere(large_tstat))))
icbest = float(tstat[lag])
else:
raise ValueError('Unknown method')
return icbest, lag
def _autolag_ols_low_memory(y, maxlag, trend, method):
"""
Compules the lag length that minimizes an info criterion .
Parameters
----------
y : ndarray
Variable being tested for a unit root
maxlag : int
The highest lag order for lag length selection.
trend : {'nc', 'c', 'ct','ctt'}
Trend in the model
method : {'aic', 'bic', 't-stat'}
Method to use when finding the lag length
Returns
-------
icbest : float
Minimum value of the information criteria
lag : int
The lag length that maximizes the information criterion.
Notes
-----
Minimizes creation of large arrays. Uses approx 6 * nobs temporary values
"""
method = method.lower()
deltay = diff(y)
deltay = deltay / sqrt(deltay.dot(deltay))
lhs = deltay[maxlag:][:, None]
level = y[maxlag:-1]
level = level / sqrt(level.dot(level))
trendx = []
nobs = lhs.shape[0]
if trend == 'nc':
trendx = empty((nobs, 0))
else:
if 'tt' in trend:
tt = arange(1, nobs + 1, dtype=float64)[:, None] ** 2
tt *= (sqrt(5) / float(nobs) ** (5 / 2))
trendx.append(tt)
if 't' in trend:
t = arange(1, nobs + 1, dtype=float64)[:, None]
t *= (sqrt(3) / float(nobs) ** (3 / 2))
trendx.append(t)
if trend.startswith('c'):
trendx.append(ones((nobs, 1)) / sqrt(nobs))
trendx = hstack(trendx)
rhs = hstack([level[:, None], trendx])
m = rhs.shape[1]
xpx = empty((m + maxlag, m + maxlag)) * nan
xpy = empty((m + maxlag, 1)) * nan
xpy[:m] = rhs.T.dot(lhs)
xpx[:m, :m] = rhs.T.dot(rhs)
for i in range(maxlag):
x1 = deltay[maxlag - i - 1:-(1 + i)]
block = rhs.T.dot(x1)
xpx[m + i, :m] = block
xpx[:m, m + i] = block
xpy[m + i] = x1.dot(lhs)
for j in range(i, maxlag):
x2 = deltay[maxlag - j - 1:-(1 + j)]
x1px2 = x1.dot(x2)
xpx[m + i, m + j] = x1px2
xpx[m + j, m + i] = x1px2
ypy = lhs.T.dot(lhs)
sigma2 = empty(maxlag + 1)
tstat = empty(maxlag + 1)
tstat[0] = inf
for i in range(m, m + maxlag + 1):
xpx_sub = xpx[:i, :i]
b = solve(xpx_sub, xpy[:i])
sigma2[i - m] = (ypy - b.T.dot(xpx_sub).dot(b)) / nobs
if method == 't-stat':
xpxi = inv(xpx_sub)
stderr = sqrt(sigma2[i - m] * xpxi[-1, -1])
tstat[i - m] = b[-1] / stderr
return _select_best_ic(method, nobs, sigma2, tstat)
def _autolag_ols(endog, exog, startlag, maxlag, method):
"""
Returns the results for the lag length that maximizes the info criterion.
Parameters
----------
endog : {ndarray, Series}
nobs array containing endogenous variable
exog : {ndarray, DataFrame}
nobs by (startlag + maxlag) array containing lags and possibly other
variables
startlag : int
The first zero-indexed column to hold a lag. See Notes.
maxlag : int
The highest lag order for lag length selection.
method : {'aic', 'bic', 't-stat'}
aic - Akaike Information Criterion
bic - Bayes Information Criterion
t-stat - Based on last lag
Returns
-------
icbest : float
Minimum value of the information criteria
lag : int
The lag length that maximizes the information criterion.
Notes
-----
Does estimation like mod(endog, exog[:,:i]).fit()
where i goes from lagstart to lagstart + maxlag + 1. Therefore, lags are
assumed to be in contiguous columns from low to high lag length with
the highest lag in the last column.
"""
method = method.lower()
q, r = qr(exog)
qpy = q.T.dot(endog)
ypy = endog.T.dot(endog)
xpx = exog.T.dot(exog)
effective_max_lag = min(maxlag, matrix_rank(xpx) - startlag)
sigma2 = empty(effective_max_lag + 1)
tstat = empty(effective_max_lag + 1)
nobs = float(endog.shape[0])
tstat[0] = inf
for i in range(startlag, startlag + effective_max_lag + 1):
b = solve(r[:i, :i], qpy[:i])
sigma2[i - startlag] = (ypy - b.T.dot(xpx[:i, :i]).dot(b)) / nobs
if method == 't-stat' and i > startlag:
xpxi = inv(xpx[:i, :i])
stderr = sqrt(sigma2[i - startlag] * xpxi[-1, -1])
tstat[i - startlag] = b[-1] / stderr
return _select_best_ic(method, nobs, sigma2, tstat)
def _df_select_lags(y, trend, max_lags, method, low_memory=False):
"""
Helper method to determine the best lag length in DF-like regressions
Parameters
----------
y : ndarray
The data for the lag selection exercise
trend : {'nc','c','ct','ctt'}
The trend order
max_lags : int
The maximum number of lags to check. This setting affects all
estimation since the sample is adjusted by max_lags when
fitting the models
method : {'AIC','BIC','t-stat'}
The method to use when estimating the model
low_memory : bool
Flag indicating whether to use the low-memory algorithm for
lag-length selection.
Returns
-------
best_ic : float
The information criteria at the selected lag
best_lag : int
The selected lag
Notes
-----
If max_lags is None, the default value of 12 * (nobs/100)**(1/4) is used.
"""
nobs = y.shape[0]
# This is the absolute maximum number of lags possible,
# only needed to very short time series.
max_max_lags = nobs // 2 - 1
if trend != 'nc':
max_max_lags -= len(trend)
if max_lags is None:
max_lags = int(ceil(12. * power(nobs / 100., 1 / 4.)))
max_lags = max(min(max_lags, max_max_lags), 0)
if low_memory:
out = _autolag_ols_low_memory(y, max_lags, trend, method)
return out
delta_y = diff(y)
rhs = lagmat(delta_y[:, None], max_lags, trim='both', original='in')
nobs = rhs.shape[0]
rhs[:, 0] = y[-nobs - 1:-1] # replace 0 with level of y
lhs = delta_y[-nobs:]
if trend != 'nc':
full_rhs = add_trend(rhs, trend, prepend=True)
else:
full_rhs = rhs
start_lag = full_rhs.shape[1] - rhs.shape[1] + 1
ic_best, best_lag = _autolag_ols(lhs, full_rhs, start_lag, max_lags, method)
return ic_best, best_lag
def _add_column_names(rhs, lags):
"""Return a DataFrame with named columns"""
lag_names = ['Diff.L{0}'.format(i) for i in range(1, lags + 1)]
return DataFrame(rhs, columns=['Level.L1'] + lag_names)
def _estimate_df_regression(y, trend, lags):
"""Helper function that estimates the core (A)DF regression
Parameters
----------
y : ndarray
The data for the lag selection
trend : {'nc','c','ct','ctt'}
The trend order
lags : int
The number of lags to include in the ADF regression
Returns
-------
ols_res : OLSResults
A results class object produced by OLS.fit()
Notes
-----
See statsmodels.regression.linear_model.OLS for details on the results
returned
"""
delta_y = diff(y)
rhs = lagmat(delta_y[:, None], lags, trim='both', original='in')
nobs = rhs.shape[0]
lhs = rhs[:, 0].copy() # lag-0 values are lhs, Is copy() necessary?
rhs[:, 0] = y[-nobs - 1:-1] # replace lag 0 with level of y
rhs = _add_column_names(rhs, lags)
if trend != 'nc':
rhs = add_trend(rhs.iloc[:, :lags + 1], trend)
return OLS(lhs, rhs).fit()
class UnitRootTest(object):
"""Base class to be used for inheritance in unit root bootstrap"""
def __init__(self, y, lags, trend, valid_trends):
self._y = ensure1d(y, 'y')
self._delta_y = diff(y)
self._nobs = self._y.shape[0]
self._lags = None
self.lags = lags
self._valid_trends = valid_trends
self._trend = ''
self.trend = trend
self._stat = None
self._critical_values = None
self._pvalue = None
self.trend = trend
self._null_hypothesis = 'The process contains a unit root.'
self._alternative_hypothesis = 'The process is weakly stationary.'
self._test_name = None
self._title = None
self._summary_text = None
def __str__(self):
return self.summary().__str__()
def __repr__(self):
return str(type(self)) + '\n"""\n' + self.__str__() + '\n"""'
def _repr_html_(self):
"""Display as HTML for IPython notebook.
"""
return self.summary().as_html()
def _compute_statistic(self):
"""This is the core routine that computes the test statistic, computes
the p-value and constructs the critical values.
"""
raise NotImplementedError("Subclass must implement")
def _reset(self):
"""Resets the unit root test so that it will be recomputed
"""
self._stat = None
assert self._stat is None
def _compute_if_needed(self):
"""Checks whether the statistic needs to be computed, and computed if
needed
"""
if self._stat is None:
self._compute_statistic()
@property
def null_hypothesis(self):
"""The null hypothesis
"""
return self._null_hypothesis
@property
def alternative_hypothesis(self):
"""The alternative hypothesis
"""
return self._alternative_hypothesis
@property
def nobs(self):
"""The number of observations used when computing the test statistic.
Accounts for loss of data due to lags for regression-based bootstrap."""
return self._nobs
@property
def valid_trends(self):
"""List of valid trend terms."""
return self._valid_trends
@property
def pvalue(self):
"""Returns the p-value for the test statistic
"""
self._compute_if_needed()
return self._pvalue
@property
def stat(self):
"""The test statistic for a unit root
"""
self._compute_if_needed()
return self._stat
@property
def critical_values(self):
"""Dictionary containing critical values specific to the test, number of
observations and included deterministic trend terms.
"""
self._compute_if_needed()
return self._critical_values
def summary(self):
"""Summary of test, containing statistic, p-value and critical values
"""
table_data = [('Test Statistic', '{0:0.3f}'.format(self.stat)),
('P-value', '{0:0.3f}'.format(self.pvalue)),
('Lags', '{0:d}'.format(self.lags))]
title = self._title
if not title:
title = self._test_name + " Results"
table = SimpleTable(table_data, stubs=None, title=title, colwidths=18,
datatypes=[0, 1], data_aligns=("l", "r"))
smry = Summary()
smry.tables.append(table)
cv_string = 'Critical Values: '
cv = self._critical_values.keys()
cv_numeric = array(lmap(lambda x: float(x.split('%')[0]), cv))
cv_numeric = sort(cv_numeric)
for val in cv_numeric:
p = str(int(val)) + '%'
cv_string += '{0:0.2f}'.format(self._critical_values[p])
cv_string += ' (' + p + ')'
if val != cv_numeric[-1]:
cv_string += ', '
extra_text = ['Trend: ' + TREND_DESCRIPTION[self._trend],
cv_string,
'Null Hypothesis: ' + self.null_hypothesis,
'Alternative Hypothesis: ' + self.alternative_hypothesis]
smry.add_extra_txt(extra_text)
if self._summary_text:
smry.add_extra_txt(self._summary_text)
return smry
@property
def lags(self):
"""Sets or gets the number of lags used in the model.
When bootstrap use DF-type regressions, lags is the number of lags in the
regression model. When bootstrap use long-run variance estimators, lags
is the number of lags used in the long-run variance estimator.
"""
self._compute_if_needed()
return self._lags
@lags.setter
def lags(self, value):
types = (int, long, int32, int64)
if value is not None and not isinstance(value, types) or \
(isinstance(value, types) and value < 0):
raise ValueError('lags must be a non-negative integer or None')
if self._lags != value:
self._reset()
self._lags = value
@property
def y(self):
"""Returns the data used in the test statistic
"""
return self._y
@property
def trend(self):
"""Sets or gets the deterministic trend term used in the test. See
valid_trends for a list of supported trends
"""
return self._trend
@trend.setter
def trend(self, value):
if value not in self.valid_trends:
raise ValueError('trend not understood')
if self._trend != value:
self._reset()
self._trend = value
@add_metaclass(DocStringInheritor)
class ADF(UnitRootTest):
"""
Augmented Dickey-Fuller unit root test
Parameters
----------
y : {ndarray, Series}
The data to test for a unit root
lags : int, optional
The number of lags to use in the ADF regression. If omitted or None,
`method` is used to automatically select the lag length with no more
than `max_lags` are included.
trend : {'nc', 'c', 'ct', 'ctt'}, optional
The trend component to include in the ADF test
'nc' - No trend components
'c' - Include a constant (Default)
'ct' - Include a constant and linear time trend
'ctt' - Include a constant and linear and quadratic time trends
max_lags : int, optional
The maximum number of lags to use when selecting lag length
method : {'AIC', 'BIC', 't-stat'}, optional
The method to use when selecting the lag length
'AIC' - Select the minimum of the Akaike IC
'BIC' - Select the minimum of the Schwarz/Bayesian IC
't-stat' - Select the minimum of the Schwarz/Bayesian IC
low_memory : bool
Flag indicating whether to use a low memory implementation of the
lag selection algorithm. The low memory algorithm is slower than
the standard algorithm but will use 2-4% of the memory required for
the standard algorithm. This options allows automatic lag selection
to be used in very long time series. If None, use automatic selection
of algorithm.
Attributes
----------
stat
pvalue
critical_values
null_hypothesis
alternative_hypothesis
summary
regression
valid_trends
y
trend
lags
Notes
-----
The null hypothesis of the Augmented Dickey-Fuller is that there is a unit
root, with the alternative that there is no unit root. If the pvalue is
above a critical size, then the null cannot be rejected that there
and the series appears to be a unit root.
The p-values are obtained through regression surface approximation from
MacKinnon (1994) using the updated 2010 tables.
If the p-value is close to significant, then the critical values should be
used to judge whether to reject the null.
The autolag option and maxlag for it are described in Greene.
Examples
--------
>>> from arch.unitroot import ADF
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.macrodata.load().data
>>> inflation = np.diff(np.log(data['cpi']))
>>> adf = ADF(inflation)
>>> print('{0:0.4f}'.format(adf.stat))
-3.0931
>>> print('{0:0.4f}'.format(adf.pvalue))
0.0271
>>> adf.lags
2
>>> adf.trend='ct'
>>> print('{0:0.4f}'.format(adf.stat))
-3.2111
>>> print('{0:0.4f}'.format(adf.pvalue))
0.0822
References
----------
.. [*] Greene, W. H. 2011. Econometric Analysis. Prentice Hall: Upper
Saddle River, New Jersey.
.. [*] Hamilton, J. D. 1994. Time Series Analysis. Princeton: Princeton
University Press.
.. [*] MacKinnon, J.G. 1994. "Approximate asymptotic distribution
functions for unit-root and cointegration bootstrap. `Journal of
Business and Economic Statistics` 12, 167-76.
.. [*] MacKinnon, J.G. 2010. "Critical Values for Cointegration Tests."
Queen's University, Dept of Economics, Working Papers. Available at
http://ideas.repec.org/p/qed/wpaper/1227.html
"""
def __init__(self, y, lags=None, trend='c',
max_lags=None, method='AIC', low_memory=None):
valid_trends = ('nc', 'c', 'ct', 'ctt')
super(ADF, self).__init__(y, lags, trend, valid_trends)
self._max_lags = max_lags
self._method = method
self._test_name = 'Augmented Dickey-Fuller'
self._regression = None
self._summary_text = None
self._low_memory = low_memory
if low_memory is None:
self._low_memory = True if self.y.shape[0] > 1e5 else False
def _select_lag(self):
ic_best, best_lag = _df_select_lags(self._y, self._trend,
self._max_lags, self._method,
low_memory=self._low_memory)
self._ic_best = ic_best
self._lags = best_lag
def _compute_statistic(self):
if self._lags is None:
self._select_lag()
y, trend, lags = self._y, self._trend, self._lags
resols = _estimate_df_regression(y, trend, lags)
self._regression = resols
self._stat = stat = resols.tvalues[0]
self._nobs = int(resols.nobs)
self._pvalue = mackinnonp(stat, regression=trend,
num_unit_roots=1)
critical_values = mackinnoncrit(num_unit_roots=1,
regression=trend,
nobs=resols.nobs)
self._critical_values = {"1%": critical_values[0],
"5%": critical_values[1],
"10%": critical_values[2]}
@property
def regression(self):
"""Returns the OLS regression results from the ADF model estimated
"""
self._compute_if_needed()
return self._regression
@property
def max_lags(self):
"""Sets or gets the maximum lags used when automatically selecting lag
length"""
return self._max_lags
@max_lags.setter
def max_lags(self, value):
if self._max_lags != value:
self._reset()
self._lags = None
self._max_lags = value
@add_metaclass(DocStringInheritor)
class DFGLS(UnitRootTest):
"""
Elliott, Rothenberg and Stock's GLS version of the Dickey-Fuller test
Parameters
----------
y : {ndarray, Series}
The data to test for a unit root
lags : int, optional
The number of lags to use in the ADF regression. If omitted or None,
`method` is used to automatically select the lag length with no more
than `max_lags` are included.
trend : {'c', 'ct'}, optional
The trend component to include in the ADF test
'c' - Include a constant (Default)
'ct' - Include a constant and linear time trend
max_lags : int, optional
The maximum number of lags to use when selecting lag length
method : {'AIC', 'BIC', 't-stat'}, optional
The method to use when selecting the lag length
'AIC' - Select the minimum of the Akaike IC
'BIC' - Select the minimum of the Schwarz/Bayesian IC
't-stat' - Select the minimum of the Schwarz/Bayesian IC
Attributes
----------
stat
pvalue
critical_values
null_hypothesis
alternative_hypothesis
summary
regression
valid_trends
y
trend
lags
Notes
-----
The null hypothesis of the Dickey-Fuller GLS is that there is a unit
root, with the alternative that there is no unit root. If the pvalue is
above a critical size, then the null cannot be rejected and the series
appears to be a unit root.
DFGLS differs from the ADF test in that an initial GLS detrending step
is used before a trend-less ADF regression is run.
Critical values and p-values when trend is 'c' are identical to
the ADF. When trend is set to 'ct, they are from ...
Examples
--------
>>> from arch.unitroot import DFGLS
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.macrodata.load().data
>>> inflation = np.diff(np.log(data['cpi']))
>>> dfgls = DFGLS(inflation)
>>> print('{0:0.4f}'.format(dfgls.stat))
-2.7611
>>> print('{0:0.4f}'.format(dfgls.pvalue))
0.0059
>>> dfgls.lags
2
>>> dfgls.trend = 'ct'
>>> print('{0:0.4f}'.format(dfgls.stat))
-2.9036
>>> print('{0:0.4f}'.format(dfgls.pvalue))
0.0447
References
----------
.. [*] Elliott, G. R., T. J. Rothenberg, and J. H. Stock. 1996. Efficient
bootstrap for an autoregressive unit root. Econometrica 64: 813-836
"""
def __init__(self, y, lags=None, trend='c',
max_lags=None, method='AIC', low_memory=None):
valid_trends = ('c', 'ct')
super(DFGLS, self).__init__(y, lags, trend, valid_trends)
self._max_lags = max_lags
self._method = method
self._regression = None
self._low_memory = low_memory
if low_memory is None:
self._low_memory = True if self.y.shape[0] >= 1e5 else False
self._test_name = 'Dickey-Fuller GLS'
if trend == 'c':
self._c = -7.0
else:
self._c = -13.5
def _compute_statistic(self):
"""Core routine to estimate DF-GLS test statistic"""
# 1. GLS detrend
trend, c = self._trend, self._c
nobs = self._y.shape[0]
ct = c / nobs
z = add_trend(nobs=nobs, trend=trend)
delta_z = z.copy()
delta_z[1:, :] = delta_z[1:, :] - (1 + ct) * delta_z[:-1, :]
delta_y = self._y.copy()[:, None]
delta_y[1:] = delta_y[1:] - (1 + ct) * delta_y[:-1]
detrend_coef = pinv(delta_z).dot(delta_y)
y = self._y
y_detrended = y - z.dot(detrend_coef).ravel()
# 2. determine lag length, if needed
if self._lags is None:
max_lags, method = self._max_lags, self._method
icbest, bestlag = _df_select_lags(y_detrended, 'nc', max_lags, method,
low_memory=self._low_memory)
self._lags = bestlag
# 3. Run Regression
lags = self._lags
resols = _estimate_df_regression(y_detrended,
lags=lags,
trend='nc')
self._regression = resols
self._nobs = int(resols.nobs)
self._stat = resols.tvalues[0]
self._pvalue = mackinnonp(self._stat,
regression=trend,
dist_type='DFGLS')
critical_values = mackinnoncrit(regression=trend,
nobs=self._nobs,
dist_type='DFGLS')
self._critical_values = {"1%": critical_values[0],
"5%": critical_values[1],
"10%": critical_values[2]}
@UnitRootTest.trend.setter
def trend(self, value):
if value not in self.valid_trends:
raise ValueError('trend not understood')
if self._trend != value:
self._reset()
self._trend = value
if value == 'c':
self._c = -7.0
else:
self._c = -13.5
@property
def regression(self):
"""Returns the OLS regression results from the ADF model estimated
"""
self._compute_if_needed()
return self._regression
@property
def max_lags(self):
"""Sets or gets the maximum lags used when automatically selecting lag
length"""
return self._max_lags
@max_lags.setter
def max_lags(self, value):
if self._max_lags != value:
self._reset()
self._lags = None
self._max_lags = value
@add_metaclass(DocStringInheritor)
class PhillipsPerron(UnitRootTest):
"""
Phillips-Perron unit root test
Parameters
----------
y : {ndarray, Series}
The data to test for a unit root
lags : int, optional
The number of lags to use in the Newey-West estimator of the long-run
covariance. If omitted or None, the lag length is set automatically to
12 * (nobs/100) ** (1/4)
trend : {'nc', 'c', 'ct'}, optional
The trend component to include in the ADF test
'nc' - No trend components
'c' - Include a constant (Default)
'ct' - Include a constant and linear time trend
test_type : {'tau', 'rho'}
The test to use when computing the test statistic. 'tau' is based on
the t-stat and 'rho' uses a test based on nobs times the re-centered
regression coefficient
Attributes
----------
stat
pvalue
critical_values
test_type
null_hypothesis
alternative_hypothesis
summary
valid_trends
y
trend
lags
Notes
-----
The null hypothesis of the Phillips-Perron (PP) test is that there is a
unit root, with the alternative that there is no unit root. If the pvalue
is above a critical size, then the null cannot be rejected that there
and the series appears to be a unit root.
Unlike the ADF test, the regression estimated includes only one lag of
the dependant variable, in addition to trend terms. Any serial
correlation in the regression errors is accounted for using a long-run
variance estimator (currently Newey-West).
The p-values are obtained through regression surface approximation from
MacKinnon (1994) using the updated 2010 tables.
If the p-value is close to significant, then the critical values should be
used to judge whether to reject the null.
Examples
--------
>>> from arch.unitroot import PhillipsPerron
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.macrodata.load().data
>>> inflation = np.diff(np.log(data['cpi']))
>>> pp = PhillipsPerron(inflation)
>>> print('{0:0.4f}'.format(pp.stat))
-8.1356
>>> print('{0:0.4f}'.format(pp.pvalue))
0.0000
>>> pp.lags
15
>>> pp.trend = 'ct'
>>> print('{0:0.4f}'.format(pp.stat))
-8.2022
>>> print('{0:0.4f}'.format(pp.pvalue))
0.0000
>>> pp.test_type = 'rho'
>>> print('{0:0.4f}'.format(pp.stat))
-120.3271
>>> print('{0:0.4f}'.format(pp.pvalue))
0.0000
References
----------
.. [*] Hamilton, J. D. 1994. Time Series Analysis. Princeton: Princeton
University Press.
.. [*] Newey, W. K., and K. D. West. 1987. "A simple, positive
semidefinite, heteroskedasticity and autocorrelation consistent covariance
matrix". Econometrica 55, 703-708.
.. [*] Phillips, P. C. B., and P. Perron. 1988. "Testing for a unit root in
time series regression". Biometrika 75, 335-346.
.. [*] MacKinnon, J.G. 1994. "Approximate asymptotic distribution
functions for unit-root and cointegration bootstrap". Journal of
Business and Economic Statistics. 12, 167-76.
.. [*] MacKinnon, J.G. 2010. "Critical Values for Cointegration Tests."
Queen's University, Dept of Economics, Working Papers. Available at
http://ideas.repec.org/p/qed/wpaper/1227.html
"""
def __init__(self, y, lags=None, trend='c', test_type='tau'):
valid_trends = ('nc', 'c', 'ct')
super(PhillipsPerron, self).__init__(y, lags, trend, valid_trends)
self._test_type = test_type
self._stat_rho = None
self._stat_tau = None
self._test_name = 'Phillips-Perron Test'
self._lags = lags
def _compute_statistic(self):
"""Core routine to estimate PP test statistics"""
# 1. Estimate Regression
y, trend = self._y, self._trend
nobs = y.shape[0]
if self._lags is None:
self._lags = int(ceil(12. * power(nobs / 100., 1 / 4.)))
lags = self._lags
rhs = y[:-1, None]
rhs = _add_column_names(rhs, 0)
lhs = y[1:, None]
if trend != 'nc':
rhs = add_trend(rhs, trend)
resols = OLS(lhs, rhs).fit()
k = rhs.shape[1]
n, u = resols.nobs, resols.resid
lam2 = cov_nw(u, lags, demean=False)
lam = sqrt(lam2)
# 2. Compute components
s2 = u.dot(u) / (n - k)
s = sqrt(s2)
gamma0 = s2 * (n - k) / n
sigma = resols.bse[0]
sigma2 = sigma ** 2.0
rho = resols.params[0]
# 3. Compute statistics
self._stat_tau = sqrt(gamma0 / lam2) * ((rho - 1) / sigma) \
- 0.5 * ((lam2 - gamma0) / lam) * (n * sigma / s)
self._stat_rho = n * (rho - 1) \
- 0.5 * (n ** 2.0 * sigma2 / s2) * (lam2 - gamma0)
self._nobs = int(resols.nobs)
if self._test_type == 'rho':
self._stat = self._stat_rho
dist_type = 'ADF-z'
else:
self._stat = self._stat_tau
dist_type = 'ADF-t'
self._pvalue = mackinnonp(self._stat,
regression=trend,
dist_type=dist_type)
critical_values = mackinnoncrit(regression=trend,
nobs=n,
dist_type=dist_type)
self._critical_values = {"1%": critical_values[0],
"5%": critical_values[1],
"10%": critical_values[2]}
self._title = self._test_name + ' (Z-' + self._test_type + ')'
@property
def test_type(self):