# Checking a time series model
# https://tidyecology.com/posts/checking-a-time-series-model/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-14

## ---- setup ----
library(ggplot2)
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) + theme(
    text = element_text(colour = "#2c3a31"),
    plot.title = element_text(colour = "#16241d", face = "bold", size = rel(0.95)),
    plot.subtitle = element_text(colour = "#46604a", size = rel(0.80)),
    axis.title = element_text(colour = "#46604a", size = rel(0.88)),
    axis.text = element_text(colour = "#5d6b61", size = rel(0.78)),
    panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
    panel.grid.minor = element_blank(),
    plot.background = element_rect(fill = "#f5f4ee", colour = NA),
    panel.background = element_rect(fill = "#f5f4ee", colour = NA),
    legend.position = "top")
}
FOREST <- "#275139"; GOLD <- "#c9b458"; RUST <- "#b5534e"; SAGE <- "#93a87f"

## ---- residuals ----
set.seed(4243)
phi1 <- 1.2; phi2 <- -0.6; n <- 200
y <- as.numeric(arima.sim(list(ar = c(phi1, phi2)), n = n, sd = 1))

fit_ok <- arima(y, order = c(2, 0, 0))    # correct
fit_un <- arima(y, order = c(1, 0, 0))    # under-fitted
res_ok <- residuals(fit_ok); res_un <- residuals(fit_un)

# Ljung-Box portmanteau test; fitdf subtracts the estimated AR parameters
lb_ok <- Box.test(res_ok, lag = 15, type = "Ljung-Box", fitdf = 2)
lb_un <- Box.test(res_un, lag = 15, type = "Ljung-Box", fitdf = 1)
band <- 1.96 / sqrt(n)
acf_ok <- as.numeric(acf(res_ok, lag.max = 15, plot = FALSE)$acf)[-1]
acf_un <- as.numeric(acf(res_un, lag.max = 15, plot = FALSE)$acf)[-1]

## ---- fig-resid ----
mk_acf <- function(a, ttl, sub, ymax = 0.45) {
  ggplot(data.frame(lag = seq_along(a), v = a), aes(lag, v)) +
    geom_hline(yintercept = 0, colour = "#46604a", linewidth = 0.4) +
    geom_hline(yintercept = c(-band, band), colour = RUST, linetype = "dashed", linewidth = 0.4) +
    geom_segment(aes(xend = lag, yend = 0), colour = FOREST, linewidth = 0.8) +
    geom_point(colour = FOREST, size = 1.6) +
    labs(title = ttl, subtitle = sub, x = "Lag", y = "Residual ACF") +
    coord_cartesian(ylim = c(-ymax, ymax)) + theme_te()
}
pA <- mk_acf(acf_ok, "Correct AR(2): residuals are white",
             sprintf("Ljung-Box p = %.2f; %d of 15 spikes outside the band", lb_ok$p.value,
                     sum(abs(acf_ok) > band)))
pB <- mk_acf(acf_un, "Under-fitted AR(1): structure remains",
             "Ljung-Box p < 0.001; lag-1 residual ACF ~ 0.40 pokes out")
grid::grid.newpage(); grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- prewhiten ----
set.seed(51)
x <- as.numeric(arima.sim(list(ar = 0.7), n = n))
z <- as.numeric(arima.sim(list(ar = 0.7), n = n))    # generated independently of x

cc_raw <- ccf(x, z, lag.max = 20, plot = FALSE)      # raw, misleading
raw_sig <- sum(abs(cc_raw$acf) > band)

ar_x <- arima(x, order = c(1, 0, 0))                 # fit the input's AR model
phx <- coef(ar_x)["ar1"]
xw <- residuals(ar_x)                                # prewhitened input (white)
zw <- z[-1] - phx * z[-length(z)]                    # SAME filter applied to output
cc_pw <- ccf(xw[-1], zw, lag.max = 20, plot = FALSE)
b_pw <- 1.96 / sqrt(length(zw))
pw_sig <- sum(abs(cc_pw$acf) > b_pw)

## ---- fig-ccf ----
dfR <- data.frame(lag = as.numeric(cc_raw$lag), v = as.numeric(cc_raw$acf))
dfP <- data.frame(lag = as.numeric(cc_pw$lag), v = as.numeric(cc_pw$acf))
pC <- ggplot(dfR, aes(lag, v)) +
  geom_hline(yintercept = 0, colour = "#46604a", linewidth = 0.4) +
  geom_hline(yintercept = c(-band, band), colour = RUST, linetype = "dashed", linewidth = 0.4) +
  geom_segment(aes(xend = lag, yend = 0), colour = GOLD, linewidth = 0.7) +
  geom_point(colour = GOLD, size = 1.3) +
  annotate("text", x = 0, y = 0.30, label = "14 of 41 lags 'significant'\n(all spurious)", colour = "#16241d", size = 3) +
  labs(title = "Raw CCF of two INDEPENDENT series",
       subtitle = "Each series' own autocorrelation fakes cross-correlation",
       x = "Lag", y = "Cross-correlation") +
  coord_cartesian(ylim = c(-0.35, 0.35)) + theme_te()
pD <- ggplot(dfP, aes(lag, v)) +
  geom_hline(yintercept = 0, colour = "#46604a", linewidth = 0.4) +
  geom_hline(yintercept = c(-b_pw, b_pw), colour = RUST, linetype = "dashed", linewidth = 0.4) +
  geom_segment(aes(xend = lag, yend = 0), colour = FOREST, linewidth = 0.7) +
  geom_point(colour = FOREST, size = 1.3) +
  annotate("text", x = 0, y = 0.30, label = "1 of 41 lags out\n(chance alone gives two)", colour = "#16241d", size = 3) +
  labs(title = "Prewhitened CCF: the spurious peaks vanish",
       subtitle = "Filter both series by the input's AR model first",
       x = "Lag", y = "Cross-correlation") +
  coord_cartesian(ylim = c(-0.35, 0.35)) + theme_te()
grid::grid.newpage(); grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pC, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pD, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
