-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
stattools.py
2361 lines (2096 loc) · 79.8 KB
/
stattools.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
"""
Statistical tools for time series analysis
"""
import warnings
from statsmodels.compat.numpy import lstsq
from statsmodels.compat.pandas import deprecate_kwarg
from statsmodels.compat.python import lrange, lzip
from statsmodels.compat.scipy import _next_regular
import numpy as np
from numpy.linalg import LinAlgError
import pandas as pd
from scipy import stats
from statsmodels.regression.linear_model import OLS, yule_walker
from statsmodels.tools.sm_exceptions import (
CollinearityWarning,
InterpolationWarning,
MissingDataError,
)
from statsmodels.tools.tools import Bunch, add_constant
from statsmodels.tools.validation import (
array_like,
bool_like,
dict_like,
float_like,
int_like,
string_like,
)
from statsmodels.tsa._bds import bds
from statsmodels.tsa._innovations import innovations_algo, innovations_filter
from statsmodels.tsa.adfvalues import mackinnoncrit, mackinnonp
from statsmodels.tsa.arima_model import ARMA
from statsmodels.tsa.tsatools import add_trend, lagmat, lagmat2ds
__all__ = [
"acovf",
"acf",
"pacf",
"pacf_yw",
"pacf_ols",
"ccovf",
"ccf",
"q_stat",
"coint",
"arma_order_select_ic",
"adfuller",
"kpss",
"bds",
"pacf_burg",
"innovations_algo",
"innovations_filter",
"levinson_durbin_pacf",
"levinson_durbin",
"zivot_andrews",
]
SQRTEPS = np.sqrt(np.finfo(np.double).eps)
def _autolag(
mod,
endog,
exog,
startlag,
maxlag,
method,
modargs=(),
fitargs=(),
regresults=False,
):
"""
Returns the results for the lag length that maximizes the info criterion.
Parameters
----------
mod : Model class
Model estimator class
endog : array_like
nobs array containing endogenous variable
exog : array_like
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
modargs : tuple, optional
args to pass to model. See notes.
fitargs : tuple, optional
args to pass to fit. See notes.
regresults : bool, optional
Flag indicating to return optional return results
Returns
-------
icbest : float
Best information criteria.
bestlag : int
The lag length that maximizes the information criterion.
results : dict, optional
Dictionary containing all estimation results
Notes
-----
Does estimation like mod(endog, exog[:,:i], *modargs).fit(*fitargs)
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.
"""
# TODO: can tcol be replaced by maxlag + 2?
# TODO: This could be changed to laggedRHS and exog keyword arguments if
# this will be more general.
results = {}
method = method.lower()
for lag in range(startlag, startlag + maxlag + 1):
mod_instance = mod(endog, exog[:, :lag], *modargs)
results[lag] = mod_instance.fit()
if method == "aic":
icbest, bestlag = min((v.aic, k) for k, v in results.items())
elif method == "bic":
icbest, bestlag = min((v.bic, k) for k, v in results.items())
elif method == "t-stat":
# stop = stats.norm.ppf(.95)
stop = 1.6448536269514722
# Default values to ensure that always set
bestlag = startlag + maxlag
icbest = 0.0
for lag in range(startlag + maxlag, startlag - 1, -1):
icbest = np.abs(results[lag].tvalues[-1])
bestlag = lag
if np.abs(icbest) >= stop:
# Break for first lag with a significant t-stat
break
else:
raise ValueError(f"Information Criterion {method} not understood.")
if not regresults:
return icbest, bestlag
else:
return icbest, bestlag, results
# this needs to be converted to a class like HetGoldfeldQuandt,
# 3 different returns are a mess
# See:
# Ng and Perron(2001), Lag length selection and the construction of unit root
# tests with good size and power, Econometrica, Vol 69 (6) pp 1519-1554
# TODO: include drift keyword, only valid with regression == "c"
# just changes the distribution of the test statistic to a t distribution
# TODO: autolag is untested
def adfuller(
x,
maxlag=None,
regression="c",
autolag="AIC",
store=False,
regresults=False,
):
"""
Augmented Dickey-Fuller unit root test.
The Augmented Dickey-Fuller test can be used to test for a unit root in a
univariate process in the presence of serial correlation.
Parameters
----------
x : array_like, 1d
The data series to test.
maxlag : int
Maximum lag which is included in test, default 12*(nobs/100)^{1/4}.
regression : {"c","ct","ctt","nc"}
Constant and trend order to include in regression.
* "c" : constant only (default).
* "ct" : constant and trend.
* "ctt" : constant, and linear and quadratic trend.
* "nc" : no constant, no trend.
autolag : {"AIC", "BIC", "t-stat", None}
Method to use when automatically determining the lag.
* if None, then maxlag lags are used.
* if "AIC" (default) or "BIC", then the number of lags is chosen
to minimize the corresponding information criterion.
* "t-stat" based choice of maxlag. Starts with maxlag and drops a
lag until the t-statistic on the last lag length is significant
using a 5%-sized test.
store : bool
If True, then a result instance is returned additionally to
the adf statistic. Default is False.
regresults : bool, optional
If True, the full regression results are returned. Default is False.
Returns
-------
adf : float
The test statistic.
pvalue : float
MacKinnon"s approximate p-value based on MacKinnon (1994, 2010).
usedlag : int
The number of lags used.
nobs : int
The number of observations used for the ADF regression and calculation
of the critical values.
critical values : dict
Critical values for the test statistic at the 1 %, 5 %, and 10 %
levels. Based on MacKinnon (2010).
icbest : float
The maximized information criterion if autolag is not None.
resstore : ResultStore, optional
A dummy class with results attached as attributes.
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 we cannot reject that there is a unit root.
The p-values are obtained through regression surface approximation from
MacKinnon 1994, but 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.
References
----------
.. [1] W. Green. "Econometric Analysis," 5th ed., Pearson, 2003.
.. [2] Hamilton, J.D. "Time Series Analysis". Princeton, 1994.
.. [3] MacKinnon, J.G. 1994. "Approximate asymptotic distribution functions for
unit-root and cointegration tests. `Journal of Business and Economic
Statistics` 12, 167-76.
.. [4] 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
Examples
--------
See example notebook
"""
x = array_like(x, "x")
maxlag = int_like(maxlag, "maxlag", optional=True)
regression = string_like(
regression, "regression", options=("c", "ct", "ctt", "nc")
)
autolag = string_like(
autolag, "autolag", optional=True, options=("aic", "bic", "t-stat")
)
store = bool_like(store, "store")
regresults = bool_like(regresults, "regresults")
if regresults:
store = True
trenddict = {None: "nc", 0: "c", 1: "ct", 2: "ctt"}
if regression is None or isinstance(regression, int):
regression = trenddict[regression]
regression = regression.lower()
nobs = x.shape[0]
ntrend = len(regression) if regression != "nc" else 0
if maxlag is None:
# from Greene referencing Schwert 1989
maxlag = int(np.ceil(12.0 * np.power(nobs / 100.0, 1 / 4.0)))
# -1 for the diff
maxlag = min(nobs // 2 - ntrend - 1, maxlag)
if maxlag < 0:
raise ValueError(
"sample size is too short to use selected "
"regression component"
)
elif maxlag > nobs // 2 - ntrend - 1:
raise ValueError(
"maxlag must be less than (nobs/2 - 1 - ntrend) "
"where n trend is the number of included "
"deterministic regressors"
)
xdiff = np.diff(x)
xdall = lagmat(xdiff[:, None], maxlag, trim="both", original="in")
nobs = xdall.shape[0]
xdall[:, 0] = x[-nobs - 1 : -1] # replace 0 xdiff with level of x
xdshort = xdiff[-nobs:]
if store:
from statsmodels.stats.diagnostic import ResultsStore
resstore = ResultsStore()
if autolag:
if regression != "nc":
fullRHS = add_trend(xdall, regression, prepend=True)
else:
fullRHS = xdall
startlag = fullRHS.shape[1] - xdall.shape[1] + 1
# 1 for level
# search for lag length with smallest information criteria
# Note: use the same number of observations to have comparable IC
# aic and bic: smaller is better
if not regresults:
icbest, bestlag = _autolag(
OLS, xdshort, fullRHS, startlag, maxlag, autolag
)
else:
icbest, bestlag, alres = _autolag(
OLS,
xdshort,
fullRHS,
startlag,
maxlag,
autolag,
regresults=regresults,
)
resstore.autolag_results = alres
bestlag -= startlag # convert to lag not column index
# rerun ols with best autolag
xdall = lagmat(xdiff[:, None], bestlag, trim="both", original="in")
nobs = xdall.shape[0]
xdall[:, 0] = x[-nobs - 1 : -1] # replace 0 xdiff with level of x
xdshort = xdiff[-nobs:]
usedlag = bestlag
else:
usedlag = maxlag
icbest = None
if regression != "nc":
resols = OLS(
xdshort, add_trend(xdall[:, : usedlag + 1], regression)
).fit()
else:
resols = OLS(xdshort, xdall[:, : usedlag + 1]).fit()
adfstat = resols.tvalues[0]
# adfstat = (resols.params[0]-1.0)/resols.bse[0]
# the "asymptotically correct" z statistic is obtained as
# nobs/(1-np.sum(resols.params[1:-(trendorder+1)])) (resols.params[0] - 1)
# I think this is the statistic that is used for series that are integrated
# for orders higher than I(1), ie., not ADF but cointegration tests.
# Get approx p-value and critical values
pvalue = mackinnonp(adfstat, regression=regression, N=1)
critvalues = mackinnoncrit(N=1, regression=regression, nobs=nobs)
critvalues = {
"1%": critvalues[0],
"5%": critvalues[1],
"10%": critvalues[2],
}
if store:
resstore.resols = resols
resstore.maxlag = maxlag
resstore.usedlag = usedlag
resstore.adfstat = adfstat
resstore.critvalues = critvalues
resstore.nobs = nobs
resstore.H0 = (
"The coefficient on the lagged level equals 1 - " "unit root"
)
resstore.HA = "The coefficient on the lagged level < 1 - stationary"
resstore.icbest = icbest
resstore._str = "Augmented Dickey-Fuller Test Results"
return adfstat, pvalue, critvalues, resstore
else:
if not autolag:
return adfstat, pvalue, usedlag, nobs, critvalues
else:
return adfstat, pvalue, usedlag, nobs, critvalues, icbest
@deprecate_kwarg("unbiased", "adjusted")
def acovf(x, adjusted=False, demean=True, fft=None, missing="none", nlag=None):
"""
Estimate autocovariances.
Parameters
----------
x : array_like
Time series data. Must be 1d.
adjusted : bool, default False
If True, then denominators is n-k, otherwise n.
demean : bool, default True
If True, then subtract the mean x from each element of x.
fft : bool, default None
If True, use FFT convolution. This method should be preferred
for long time series.
missing : str, default "none"
A string in ["none", "raise", "conservative", "drop"] specifying how
the NaNs are to be treated. "none" performs no checks. "raise" raises
an exception if NaN values are found. "drop" removes the missing
observations and then estimates the autocovariances treating the
non-missing as contiguous. "conservative" computes the autocovariance
using nan-ops so that nans are removed when computing the mean
and cross-products that are used to estimate the autocovariance.
When using "conservative", n is set to the number of non-missing
observations.
nlag : {int, None}, default None
Limit the number of autocovariances returned. Size of returned
array is nlag + 1. Setting nlag when fft is False uses a simple,
direct estimator of the autocovariances that only computes the first
nlag + 1 values. This can be much faster when the time series is long
and only a small number of autocovariances are needed.
Returns
-------
ndarray
The estimated autocovariances.
References
-----------
.. [1] Parzen, E., 1963. On spectral analysis with missing observations
and amplitude modulation. Sankhya: The Indian Journal of
Statistics, Series A, pp.383-392.
"""
adjusted = bool_like(adjusted, "adjusted")
demean = bool_like(demean, "demean")
fft = bool_like(fft, "fft", optional=True)
missing = string_like(
missing, "missing", options=("none", "raise", "conservative", "drop")
)
nlag = int_like(nlag, "nlag", optional=True)
if fft is None:
msg = (
"fft=True will become the default after the release of the 0.12 "
"release of statsmodels. To suppress this warning, explicitly "
"set fft=False."
)
warnings.warn(msg, FutureWarning)
fft = False
x = array_like(x, "x", ndim=1)
missing = missing.lower()
if missing == "none":
deal_with_masked = False
else:
deal_with_masked = has_missing(x)
if deal_with_masked:
if missing == "raise":
raise MissingDataError("NaNs were encountered in the data")
notmask_bool = ~np.isnan(x) # bool
if missing == "conservative":
# Must copy for thread safety
x = x.copy()
x[~notmask_bool] = 0
else: # "drop"
x = x[notmask_bool] # copies non-missing
notmask_int = notmask_bool.astype(int) # int
if demean and deal_with_masked:
# whether "drop" or "conservative":
xo = x - x.sum() / notmask_int.sum()
if missing == "conservative":
xo[~notmask_bool] = 0
elif demean:
xo = x - x.mean()
else:
xo = x
n = len(x)
lag_len = nlag
if nlag is None:
lag_len = n - 1
elif nlag > n - 1:
raise ValueError("nlag must be smaller than nobs - 1")
if not fft and nlag is not None:
acov = np.empty(lag_len + 1)
acov[0] = xo.dot(xo)
for i in range(lag_len):
acov[i + 1] = xo[i + 1 :].dot(xo[: -(i + 1)])
if not deal_with_masked or missing == "drop":
if adjusted:
acov /= n - np.arange(lag_len + 1)
else:
acov /= n
else:
if adjusted:
divisor = np.empty(lag_len + 1, dtype=np.int64)
divisor[0] = notmask_int.sum()
for i in range(lag_len):
divisor[i + 1] = notmask_int[i + 1 :].dot(
notmask_int[: -(i + 1)]
)
divisor[divisor == 0] = 1
acov /= divisor
else: # biased, missing data but npt "drop"
acov /= notmask_int.sum()
return acov
if adjusted and deal_with_masked and missing == "conservative":
d = np.correlate(notmask_int, notmask_int, "full")
d[d == 0] = 1
elif adjusted:
xi = np.arange(1, n + 1)
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"
d = n * np.ones(2 * n - 1)
if fft:
nobs = len(xo)
n = _next_regular(2 * nobs + 1)
Frf = np.fft.fft(xo, n=n)
acov = np.fft.ifft(Frf * np.conjugate(Frf))[:nobs] / d[nobs - 1 :]
acov = acov.real
else:
acov = np.correlate(xo, xo, "full")[n - 1 :] / d[n - 1 :]
if nlag is not None:
# Copy to allow gc of full array rather than view
return acov[: lag_len + 1].copy()
return acov
def q_stat(x, nobs, type=None):
"""
Compute Ljung-Box Q Statistic.
Parameters
----------
x : array_like
Array of autocorrelation coefficients. Can be obtained from acf.
nobs : int, optional
Number of observations in the entire sample (ie., not just the length
of the autocorrelation function results.
Returns
-------
q-stat : ndarray
Ljung-Box Q-statistic for autocorrelation parameters.
p-value : ndarray
P-value of the Q statistic.
Notes
-----
Designed to be used with acf.
"""
x = array_like(x, "x")
nobs = int_like(nobs, "nobs")
if type is not None:
warnings.warn(
"The `type` argument is deprecated and has no effect. This "
"argument will be removed after the 0.12 release.",
FutureWarning,
)
ret = (
nobs
* (nobs + 2)
* np.cumsum((1.0 / (nobs - np.arange(1, len(x) + 1))) * x ** 2)
)
chi2 = stats.chi2.sf(ret, np.arange(1, len(x) + 1))
return ret, chi2
# NOTE: Changed unbiased to False
# see for example
# http://www.itl.nist.gov/div898/handbook/eda/section3/autocopl.htm
@deprecate_kwarg("unbiased", "adjusted")
def acf(
x,
adjusted=False,
nlags=None,
qstat=False,
fft=None,
alpha=None,
missing="none",
):
"""
Calculate the autocorrelation function.
Parameters
----------
x : array_like
The time series data.
adjusted : bool, default False
If True, then denominators for autocovariance are n-k, otherwise n.
nlags : int, default 40
Number of lags to return autocorrelation for.
qstat : bool, default False
If True, returns the Ljung-Box q statistic for each autocorrelation
coefficient. See q_stat for more information.
fft : bool, default None
If True, computes the ACF via FFT.
alpha : scalar, default None
If a number is given, the confidence intervals for the given level are
returned. For instance if alpha=.05, 95 % confidence intervals are
returned where the standard deviation is computed according to
Bartlett"s formula.
missing : str, default "none"
A string in ["none", "raise", "conservative", "drop"] specifying how
the NaNs are to be treated. "none" performs no checks. "raise" raises
an exception if NaN values are found. "drop" removes the missing
observations and then estimates the autocovariances treating the
non-missing as contiguous. "conservative" computes the autocovariance
using nan-ops so that nans are removed when computing the mean
and cross-products that are used to estimate the autocovariance.
When using "conservative", n is set to the number of non-missing
observations.
Returns
-------
acf : ndarray
The autocorrelation function.
confint : ndarray, optional
Confidence intervals for the ACF. Returned if alpha is not None.
qstat : ndarray, optional
The Ljung-Box Q-Statistic. Returned if q_stat is True.
pvalues : ndarray, optional
The p-values associated with the Q-statistics. Returned if q_stat is
True.
Notes
-----
The acf at lag 0 (ie., 1) is returned.
For very long time series it is recommended to use fft convolution instead.
When fft is False uses a simple, direct estimator of the autocovariances
that only computes the first nlag + 1 values. This can be much faster when
the time series is long and only a small number of autocovariances are
needed.
If adjusted is true, the denominator for the autocovariance is adjusted
for the loss of data.
References
----------
.. [1] Parzen, E., 1963. On spectral analysis with missing observations
and amplitude modulation. Sankhya: The Indian Journal of
Statistics, Series A, pp.383-392.
"""
adjusted = bool_like(adjusted, "adjusted")
nlags = int_like(nlags, "nlags", optional=True)
qstat = bool_like(qstat, "qstat")
fft = bool_like(fft, "fft", optional=True)
alpha = float_like(alpha, "alpha", optional=True)
missing = string_like(
missing, "missing", options=("none", "raise", "conservative", "drop")
)
if nlags is None:
warnings.warn(
"The default number of lags is changing from 40 to"
"min(int(10 * np.log10(nobs)), nobs - 1) after 0.12"
"is released. Set the number of lags to an integer to "
" silence this warning.",
FutureWarning,
)
nlags = 40
if fft is None:
warnings.warn(
"fft=True will become the default after the release of the 0.12 "
"release of statsmodels. To suppress this warning, explicitly "
"set fft=False.",
FutureWarning,
)
fft = False
x = array_like(x, "x")
nobs = len(x) # TODO: should this shrink for missing="drop" and NaNs in x?
avf = acovf(x, adjusted=adjusted, demean=True, fft=fft, missing=missing)
acf = avf[: nlags + 1] / avf[0]
if not (qstat or alpha):
return acf
if alpha is not None:
varacf = np.ones_like(acf) / nobs
varacf[0] = 0
varacf[1] = 1.0 / nobs
varacf[2:] *= 1 + 2 * np.cumsum(acf[1:-1] ** 2)
interval = stats.norm.ppf(1 - alpha / 2.0) * np.sqrt(varacf)
confint = np.array(lzip(acf - interval, acf + interval))
if not qstat:
return acf, confint
if qstat:
qstat, pvalue = q_stat(acf[1:], nobs=nobs) # drop lag 0
if alpha is not None:
return acf, confint, qstat, pvalue
else:
return acf, qstat, pvalue
def pacf_yw(x, nlags=None, method="adjusted"):
"""
Partial autocorrelation estimated with non-recursive yule_walker.
Parameters
----------
x : array_like
The observations of time series for which pacf is calculated.
nlags : int, default 40
The largest lag for which pacf is returned.
method : {"adjusted", "mle"}, default "adjusted"
The method for the autocovariance calculations in yule walker.
Returns
-------
ndarray
The partial autocorrelations, maxlag+1 elements.
See Also
--------
statsmodels.tsa.stattools.pacf
Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_ols
Partial autocorrelation estimation using OLS.
statsmodels.tsa.stattools.pacf_burg
Partial autocorrelation estimation using Burg"s method.
Notes
-----
This solves yule_walker for each desired lag and contains
currently duplicate calculations.
"""
x = array_like(x, "x")
nlags = int_like(nlags, "nlags", optional=True)
if nlags is None:
warnings.warn(
"The default number of lags is changing from 40 to"
"min(int(10 * np.log10(nobs)), nobs - 1) after 0.12"
"is released. Set the number of lags to an integer to "
" silence this warning.",
FutureWarning,
)
nlags = 40
method = string_like(
method, "method", options=("adjusted", "unbiased", "mle")
)
if method == "unbiased":
warnings.warn(
"unbiased is deprecated in factor of adjusted to reflect that the "
"term is adjusting the sample size used in the autocovariance "
"calculation rather than estimating an unbiased autocovariance. "
"After release 0.13, using 'unbiased' will raise.",
FutureWarning,
)
method = "adjusted"
pacf = [1.0]
for k in range(1, nlags + 1):
pacf.append(yule_walker(x, k, method=method)[0][-1])
return np.array(pacf)
def pacf_burg(x, nlags=None, demean=True):
"""
Calculate Burg"s partial autocorrelation estimator.
Parameters
----------
x : array_like
Observations of time series for which pacf is calculated.
nlags : int, optional
Number of lags to compute the partial autocorrelations. If omitted,
uses the smaller of 10(log10(nobs)) or nobs - 1.
demean : bool, optional
Flag indicating to demean that data. Set to False if x has been
previously demeaned.
Returns
-------
pacf : ndarray
Partial autocorrelations for lags 0, 1, ..., nlag.
sigma2 : ndarray
Residual variance estimates where the value in position m is the
residual variance in an AR model that includes m lags.
See Also
--------
statsmodels.tsa.stattools.pacf
Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_yw
Partial autocorrelation estimation using Yule-Walker.
statsmodels.tsa.stattools.pacf_ols
Partial autocorrelation estimation using OLS.
References
----------
.. [1] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
and forecasting. Springer.
"""
x = array_like(x, "x")
if demean:
x = x - x.mean()
nobs = x.shape[0]
p = nlags if nlags is not None else min(int(10 * np.log10(nobs)), nobs - 1)
if p > nobs - 1:
raise ValueError("nlags must be smaller than nobs - 1")
d = np.zeros(p + 1)
d[0] = 2 * x.dot(x)
pacf = np.zeros(p + 1)
u = x[::-1].copy()
v = x[::-1].copy()
d[1] = u[:-1].dot(u[:-1]) + v[1:].dot(v[1:])
pacf[1] = 2 / d[1] * v[1:].dot(u[:-1])
last_u = np.empty_like(u)
last_v = np.empty_like(v)
for i in range(1, p):
last_u[:] = u
last_v[:] = v
u[1:] = last_u[:-1] - pacf[i] * last_v[1:]
v[1:] = last_v[1:] - pacf[i] * last_u[:-1]
d[i + 1] = (1 - pacf[i] ** 2) * d[i] - v[i] ** 2 - u[-1] ** 2
pacf[i + 1] = 2 / d[i + 1] * v[i + 1 :].dot(u[i:-1])
sigma2 = (1 - pacf ** 2) * d / (2.0 * (nobs - np.arange(0, p + 1)))
pacf[0] = 1 # Insert the 0 lag partial autocorrel
return pacf, sigma2
@deprecate_kwarg("unbiased", "adjusted")
def pacf_ols(x, nlags=None, efficient=True, adjusted=False):
"""
Calculate partial autocorrelations via OLS.
Parameters
----------
x : array_like
Observations of time series for which pacf is calculated.
nlags : int
Number of lags for which pacf is returned. Lag 0 is not returned.
efficient : bool, optional
If true, uses the maximum number of available observations to compute
each partial autocorrelation. If not, uses the same number of
observations to compute all pacf values.
adjusted : bool, optional
Adjust each partial autocorrelation by n / (n - lag).
Returns
-------
ndarray
The partial autocorrelations, (maxlag,) array corresponding to lags
0, 1, ..., maxlag.
See Also
--------
statsmodels.tsa.stattools.pacf
Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_yw
Partial autocorrelation estimation using Yule-Walker.
statsmodels.tsa.stattools.pacf_burg
Partial autocorrelation estimation using Burg"s method.
Notes
-----
This solves a separate OLS estimation for each desired lag using method in
[1]_. Setting efficient to True has two effects. First, it uses
`nobs - lag` observations of estimate each pacf. Second, it re-estimates
the mean in each regression. If efficient is False, then the data are first
demeaned, and then `nobs - maxlag` observations are used to estimate each
partial autocorrelation.
The inefficient estimator appears to have better finite sample properties.
This option should only be used in time series that are covariance
stationary.
OLS estimation of the pacf does not guarantee that all pacf values are
between -1 and 1.
References
----------
.. [1] Box, G. E., Jenkins, G. M., Reinsel, G. C., & Ljung, G. M. (2015).
Time series analysis: forecasting and control. John Wiley & Sons, p. 66
"""
x = array_like(x, "x")
nlags = int_like(nlags, "nlags", optional=True)
efficient = bool_like(efficient, "efficient")
adjusted = bool_like(adjusted, "adjusted")
if nlags is None:
warnings.warn(
"The default number of lags is changing from 40 to"
"min(int(10 * np.log10(nobs)), nobs - 1) after 0.12"
"is released. Set the number of lags to an integer to "
" silence this warning.",
FutureWarning,
)
nlags = 40
pacf = np.empty(nlags + 1)
pacf[0] = 1.0
if efficient:
xlags, x0 = lagmat(x, nlags, original="sep")
xlags = add_constant(xlags)
for k in range(1, nlags + 1):
params = lstsq(xlags[k:, : k + 1], x0[k:], rcond=None)[0]
pacf[k] = params[-1]
else:
x = x - np.mean(x)
# Create a single set of lags for multivariate OLS
xlags, x0 = lagmat(x, nlags, original="sep", trim="both")
for k in range(1, nlags + 1):
params = lstsq(xlags[:, :k], x0, rcond=None)[0]
# Last coefficient corresponds to PACF value (see [1])
pacf[k] = params[-1]
if adjusted:
n = len(x)
pacf *= n / (n - np.arange(nlags + 1))
return pacf
def pacf(x, nlags=None, method="ywadjusted", alpha=None):
"""
Partial autocorrelation estimate.
Parameters
----------
x : array_like
Observations of time series for which pacf is calculated.
nlags : int
The largest lag for which the pacf is returned. The default
is currently 40, but will change to
min(int(10 * np.log10(nobs)), nobs // 2 - 1) in the future
method : str, default "ywunbiased"
Specifies which method for the calculations to use.
- "yw" or "ywadjusted" : Yule-Walker with sample-size adjustment in
denominator for acovf. Default.
- "ywm" or "ywmle" : Yule-Walker without adjustment.
- "ols" : regression of time series on lags of it and on constant.
- "ols-inefficient" : regression of time series on lags using a single
common sample to estimate all pacf coefficients.
- "ols-adjusted" : regression of time series on lags with a bias
adjustment.
- "ld" or "ldadjusted" : Levinson-Durbin recursion with bias
correction.
- "ldb" or "ldbiased" : Levinson-Durbin recursion without bias
correction.
alpha : float, optional
If a number is given, the confidence intervals for the given level are
returned. For instance if alpha=.05, 95 % confidence intervals are
returned where the standard deviation is computed according to
1/sqrt(len(x)).
Returns
-------
pacf : ndarray
Partial autocorrelations, nlags elements, including lag zero.
confint : ndarray, optional
Confidence intervals for the PACF. Returned if confint is not None.
See Also
--------
statsmodels.tsa.stattools.acf
Estimate the autocorrelation function.
statsmodels.tsa.stattools.pacf
Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_yw
Partial autocorrelation estimation using Yule-Walker.
statsmodels.tsa.stattools.pacf_ols
Partial autocorrelation estimation using OLS.
statsmodels.tsa.stattools.pacf_burg
Partial autocorrelation estimation using Burg"s method.
Notes
-----
Based on simulation evidence across a range of low-order ARMA models,
the best methods based on root MSE are Yule-Walker (MLW), Levinson-Durbin
(MLE) and Burg, respectively. The estimators with the lowest bias included
included these three in addition to OLS and OLS-adjusted.
Yule-Walker (adjusted) and Levinson-Durbin (adjusted) performed
consistently worse than the other options.
"""
nlags = int_like(nlags, "nlags", optional=True)
renames = {
"ydu": "yda",
"ywu": "ywa",
"ywunbiased": "ywadjusted",
"ldunbiased": "ldadjusted",
"ld_unbiased": "ld_adjusted",
"ldu": "lda",
"ols-unbiased": "ols-adjusted",
}
if method in renames:
warnings.warn(
f"{method} has been renamed {renames[method]}. After release 0.13, "
"using the old name will raise.",
FutureWarning,
)
method = renames[method]
methods = (
"ols",
"ols-inefficient",