-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathljungbox.py
127 lines (111 loc) · 2.82 KB
/
ljungbox.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
import numpy as np
import scipy.stats
def sac(x, k=1):
"""
Sample autocorrelation (As used in statistics with normalization)
http://en.wikipedia.org/wiki/Autocorrelation
Parameters
----------
x : 1d numpy array
Signal
k : int or list of ints
Lags to calculate sample autocorrelation for
Returns
-------
res : scalar or np array
The sample autocorrelation. A scalar value if k is a scalar, and a
numpy array if k is a interable.
"""
try:
res = []
for ki in k:
res.append(sac(x, ki))
return np.array(res)
except:
pass
mx = np.mean(x)
if k==0:
N = np.sum((x-mx)*(x-mx))
else:
N = np.sum((x[:-k]-mx)*(x[k:]-mx))
D = len(x) * np.var(x)
return N/D
def ljungbox(x, lags, alpha=0.1):
"""
The Ljung-Box test for determining if the data is independently distributed.
Parameters
----------
x : 1d numpy array
Signal to test
lags : int
Number of lags being tested
Returns
-------
Q : float
Test statistic
"""
n = len(x)
Q = 0
for k in range(1, lags+1):
Q += (sac(x, k)**2) / (n-k)
Q = n*(n+2)*Q
return Q
def boxpierce(x, lags, alpha=0.1):
"""
The Box-Pierce test for determining if the data is independently distributed.
Parameters
----------
x : 1d numpy array
Signal to test
lags : int
Number of lags being tested
Returns
-------
Q : float
Test statistic
"""
n = len(x)
Q = 0
for k in range(1, lags+1):
Q += (sac(x, k)**2)
Q = n*Q
return Q
def lbqtest(x, lags, alpha=0.1, method='lb'):
"""
The Ljung-Box test for determining if the data is independently distributed.
Parameters
----------
x : 1d numpy array
Signal to test
lags : list of ints
Lags being tested
alpha : float
Significance level used for the tests
method : string
Can be either 'lb' for Ljung-Box, or 'bp' for Box-Pierce
Returns
-------
h : np array
Numpy array of bool values, True == H0 hypothesis rejected
pV : np array
Test statistics p-values
Q : np array
Test statistics
cV : np array
Critical values used for determining if H0 should be rejected. The
critical values are calculated from the given alpha and lag.
"""
if method=='lb':
findq = ljungbox
else:
findq = boxpierce
n = len(x)
Q = np.zeros(len(lags))
pV = np.zeros(len(lags))
cV = np.zeros(len(lags))
for i, lag in enumerate(lags):
Q[i] = findq(x, lag)
pV[i] = 1.0 - scipy.stats.chi2.cdf(Q[i], lag)
cV[i] = scipy.stats.chi2.ppf(1-alpha, lag)
h = Q>cV
return h, pV, Q, cV