-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacf
More file actions
74 lines (61 loc) · 1.96 KB
/
acf
File metadata and controls
74 lines (61 loc) · 1.96 KB
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
# acf
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
y = np.array([29,20,25,29,31,33,34,27,26,30,
29,28,28,26,27,26,30,28,26,30,
31,30,37,30,33,31,27,33,37,29,
28,30,29,34,30,20,17,23,24,34,
36,35,33,29,25,27,30,29,28,32])
y_mean = np.mean(y)
y_demeaned = y - y_mean
def calculate_acf(series, max_lags):
n = len(series)
demeanded_series = series - series.mean()
c0 = np.sum(demeanded_series**2)
acf_vals = []
for k in range(max_lags + 1):
if k==0:
ck = c0
else:
ck = np.sum(demeanded_series[k:]*demeanded_series[:-k])
acf_vals.append(ck/c0)
return acf_vals
def pacf(series, lags):
rho = calculate_acf(y, lags)
pacf_vals = [1.0]
for k in range(1, lags+1):
P_k = np.array([[rho[abs(i-j)] for j in range(k)] for i in range(k)])
rho_k = np.array(rho[1:k+1])
phi_k = np.linalg.solve(P_k, rho_k)
pacf_vals.append(phi_k[-1])
return np.array(pacf_vals)
lags = len(y)-1
max_lags = min(50, lags)
acf_vals = calculate_acf(y, max_lags)
pacf_vals = pacf(y, max_lags)
acf_df = pd.DataFrame({'Lag': range(max_lags+1), 'ACF': acf_vals})
pacf_df = pd.DataFrame({'Lags': range(max_lags+1), 'PACF': pacf_vals})
fig, ax = plt.subplots(figsize=(10, 6))
ax.stem(acf_df['Lag'], acf_df['ACF'])
conf_interval = 1.96/np.sqrt(len(y))
ax.axhline(y=conf_interval, color='r', linestyle='--', label='95% conf')
ax.axhline(y=-conf_interval, color='r', linestyle='--')
ax.set_title('ACF')
ax.set_xlabel('lag')
ax.set_ylabel('acf')
ax.set_ylim(-1, 1)
ax.legend()
plt.tight_layout()
plt.show()
fig, ax = plt.subplots(figsize=(10, 6))
ax.stem(pacf_df['Lags'], pacf_df['PACF'])
ax.axhline(y=conf_interval, color='r', linestyle='--')
ax.axhline(y=-conf_interval, color='r', linestyle='--')
ax.set_title('pacf')
ax.set_xlabel('lags')
ax.set_ylabel('pacf')
ax.set_ylim(-1, 1)
ax.legend()
plt.tight_layout()
plt.show()