File size: 4,381 Bytes
b47743b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Step 5 of the ARIMA experiments: ACF/PACF identification on the 6 EDA cities (window 1969-2018).

Each series is made stationary two ways, matching the two hypotheses of Step 4:
  * detrended:   residual of an OLS line on year   (trend-stationary, d=0 + trend)
  * differenced: first difference                   (difference-stationary, d=1)
ACF and PACF (lags 1..10) are drawn with ±1.96/√N bands. Course rule: a PACF cut-off after lag p
suggests AR(p); an ACF cut-off after lag q suggests MA(q); both decaying suggests ARMA.
The suggestion below is mechanical (number of leading significant lags, capped at 2) and only
proposes candidates; the backtest decides.
Outputs: results/arima_eda/acf_pacf_<city>.png and results/arima_acf_pacf.csv
Run: python code/arima_identify.py
"""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import acf, pacf

from arima_prep import EDA_CITIES, prepare
from common import CUTOFF_YEAR, METRICS, ROOT, load_annual, long_valid

START = 1969
NLAGS = 10
OUT = ROOT / "results" / "arima_eda"


def leading(sig):
    """Number of consecutive significant lags starting at lag 1."""
    n = 0
    for s in sig:
        if not s:
            break
        n += 1
    return n


def suggest(acf_sig, pacf_sig):
    """(p, q) from the course rule; both capped at 2."""
    la, lp = leading(acf_sig), leading(pacf_sig)
    if la == 0 and lp == 0:
        return 0, 0, "white noise"
    late_a, late_p = acf_sig[la + 1:].sum(), pacf_sig[lp + 1:].sum()
    if lp and late_p == 0 and (la > lp or la == 0 or late_a > 0):
        return min(lp, 2), 0, "PACF cuts off -> AR"
    if la and late_a == 0 and (lp > la or lp == 0 or late_p > 0):
        return 0, min(la, 2), "ACF cuts off -> MA"
    return min(max(lp, 1), 2), min(max(la, 1), 2), "both decay -> ARMA"


def transforms(y, years):
    b = np.polyfit(years, y, 1)
    return {"detrended": y - np.polyval(b, years), "differenced": np.diff(y)}


def main():
    lv = long_valid(load_annual())
    prep = {m: prepare(lv, m, CUTOFF_YEAR, START) for m in METRICS}
    rows = []
    for cid, name in EDA_CITIES.items():
        fig, ax = plt.subplots(4, 4, figsize=(16, 12))
        fig.suptitle(f"{name} ({cid}), {START}-{CUTOFF_YEAR}: ACF / PACF of the stationary series (band ±1.96/√N)")
        for i, m in enumerate(METRICS):
            s = prep[m][cid]
            for j, (tname, z) in enumerate(transforms(s.y, s.years.astype(float)).items()):
                band = 1.96 / np.sqrt(len(z))
                a = acf(z, nlags=NLAGS, fft=False)[1:]
                p = pacf(z, nlags=NLAGS, method="ywm")[1:]
                for k, (vals, lab) in enumerate([(a, "ACF"), (p, "PACF")]):
                    axx = ax[i, 2 * j + k]
                    axx.bar(range(1, NLAGS + 1), vals, width=0.4, color=np.where(np.abs(vals) > band, "C3", "C0"))
                    axx.axhline(band, ls="--", c="r", lw=0.8); axx.axhline(-band, ls="--", c="r", lw=0.8)
                    axx.axhline(0, c="k", lw=0.5); axx.set_ylim(-0.8, 0.8)
                    axx.set_title(f"{m} | {tname} | {lab}", fontsize=9)
                sa, sp = np.abs(a) > band, np.abs(p) > band
                pq = suggest(sa, sp)
                rows.append(dict(city=name, ID=cid, metric=m, transform=tname, n=len(z),
                                 acf_sig_lags=",".join(str(l + 1) for l in np.where(sa)[0]) or "-",
                                 pacf_sig_lags=",".join(str(l + 1) for l in np.where(sp)[0]) or "-",
                                 acf1=round(a[0], 2), pacf1=round(p[0], 2),
                                 p=pq[0], q=pq[1], pattern=pq[2],
                                 suggested=f"ARIMA({pq[0]},{0 if tname == 'detrended' else 1},{pq[1]})"
                                           + (" + trend" if tname == "detrended" else "")))
        fig.tight_layout()
        fig.savefig(OUT / f"acf_pacf_{name.lower()}.png", dpi=100)
        plt.close(fig)
    t = pd.DataFrame(rows)
    t.to_csv(ROOT / "results" / "arima_acf_pacf.csv", index=False)
    pd.set_option("display.width", 250)
    print(t.drop(columns=["ID"]).to_string(index=False))
    print("\nSuggested orders, count over 6 cities x 4 metrics:")
    print(t.groupby(["transform", "suggested"]).size().to_string())


if __name__ == "__main__":
    main()