# Fitting ARIMA models to ecological time series
# https://tidyecology.com/posts/fitting-arima-models/
#
# 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-01

## ---- 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.title = element_text(colour = "#46604a", size = rel(0.80)),
    legend.text = element_text(colour = "#5d6b61", size = rel(0.78)),
    legend.position = "top")
}
FOREST <- "#275139"; GOLD <- "#c9b458"; RUST <- "#b5534e"; MOWN <- "#2f8f63"; SAGE <- "#93a87f"; GREY <- "#5d6b61"

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

pseudo_T <- 2 * pi / acos(phi1 / (2 * sqrt(-phi2)))   # induced pseudo-period
pac <- as.numeric(pacf(y, lag.max = 12, plot = FALSE)$acf)

## ---- fig-identify ----
K <- 16; band <- 1.96 / sqrt(n)
ac <- as.numeric(acf(y, lag.max = K, plot = FALSE)$acf)[-1]
pa <- as.numeric(pacf(y, lag.max = K, plot = FALSE)$acf)
pA <- ggplot(data.frame(lag = 1:K, v = ac), 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 = "ACF: damped oscillation, no clean cutoff",
       subtitle = "A decaying, wavy ACF points to an autoregressive process",
       x = "Lag", y = "Autocorrelation") +
  coord_cartesian(ylim = c(-0.75, 1)) + theme_te()
pB <- ggplot(data.frame(lag = 1:K, v = pa), 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) +
  annotate("text", x = 8, y = -0.62, label = "two spikes, then silence -> p = 2", colour = GREY, size = 3) +
  labs(title = "PACF: two spikes (lags 1 and 2), then silence",
       subtitle = "The PACF cutoff gives the AR order directly",
       x = "Lag", y = "Partial autocorrelation") +
  coord_cartesian(ylim = c(-0.75, 1)) + theme_te()
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))

## ---- fit ----
fit <- arima(y, order = c(2, 0, 0), include.mean = TRUE)
b <- coef(fit); se <- sqrt(diag(fit$var.coef))

## ---- aic ----
orders <- list("AR(1)" = c(1,0,0), "AR(2)" = c(2,0,0), "AR(3)" = c(3,0,0),
               "ARMA(1,1)" = c(1,0,1), "ARMA(2,1)" = c(2,0,1))
aics <- sapply(orders, function(o) AIC(arima(y, order = o, include.mean = TRUE)))
d_aic <- round(aics - min(aics), 1)

## ---- over-diff ----
set.seed(4241)
z <- as.numeric(arima.sim(list(ar = 0.5), n = 160))   # stationary: the correct d is 0
dz <- diff(z)                                          # differenced anyway
od <- arima(dz, order = c(0, 0, 1), include.mean = FALSE)
od2 <- arima(dz, order = c(1, 0, 1), include.mean = FALSE)
acf_dz <- as.numeric(acf(dz, lag.max = 3, plot = FALSE)$acf)

## ---- forecast-demo ----
ntr <- 120; h <- 24
ytr <- y[1:ntr]; yte <- y[(ntr + 1):(ntr + h)]
fit_tr <- arima(ytr, order = c(2, 0, 0))
pr <- predict(fit_tr, n.ahead = h)
se_fc <- as.numeric(pr$se)         # predict.Arima returns ts; keep the frame numeric
pred <- as.numeric(pr$pred); lo <- pred - 1.96 * se_fc; hi <- pred + 1.96 * se_fc
in_band <- sum(yte >= lo & yte <= hi)

## ---- coverage-mc ----
ntr2 <- 90; H <- 12; B <- 1500
cov2 <- cov1 <- matrix(NA_real_, B, H)
set.seed(4243)
for (bb in seq_len(B)) {
  s <- as.numeric(arima.sim(list(ar = c(phi1, phi2)), n = ntr2 + H, sd = 1))
  tr <- s[1:ntr2]; te <- s[(ntr2 + 1):(ntr2 + H)]
  f2 <- tryCatch(arima(tr, order = c(2, 0, 0)), error = function(e) NULL)  # correct
  f1 <- tryCatch(arima(tr, order = c(1, 0, 0)), error = function(e) NULL)  # misspecified
  if (!is.null(f2)) { p <- predict(f2, n.ahead = H); cov2[bb, ] <- as.numeric(te >= p$pred - 1.96 * p$se & te <= p$pred + 1.96 * p$se) }
  if (!is.null(f1)) { p <- predict(f1, n.ahead = H); cov1[bb, ] <- as.numeric(te >= p$pred - 1.96 * p$se & te <= p$pred + 1.96 * p$se) }
}
e2 <- colMeans(cov2, na.rm = TRUE); e1 <- colMeans(cov1, na.rm = TRUE)

## ---- fig-forecast ----
dfHist <- data.frame(t = 1:ntr, y = ytr)
dfF <- data.frame(t = (ntr + 1):(ntr + h), pred = pred, lo = lo, hi = hi, obs = yte)
pC <- ggplot() +
  geom_ribbon(data = dfF, aes(t, ymin = lo, ymax = hi), fill = SAGE, alpha = 0.35) +
  geom_line(data = dfHist, aes(t, y), colour = FOREST, linewidth = 0.5) +
  geom_line(data = dfF, aes(t, pred), colour = RUST, linewidth = 0.7) +
  geom_point(data = dfF, aes(t, obs), colour = "#16241d", size = 1.2) +
  geom_vline(xintercept = ntr + 0.5, colour = GREY, linetype = "dotted", linewidth = 0.4) +
  annotate("text", x = ntr - 2, y = max(ytr), label = "fit", colour = FOREST, size = 3, hjust = 1) +
  annotate("text", x = ntr - 2,
           y = max(ytr) - 0.6,
           label = "forecast + 95% band", colour = RUST, size = 3, hjust = 1) +
  labs(title = "AR(2) forecast with a 95% prediction band",
       subtitle = "Red: forecast; band: 95% interval; dots: held-out truth",
       x = "Time (steps)", y = "Population index") + theme_te()
dfCov <- rbind(data.frame(h = 1:H, cover = e2, model = "AR(2) correct"),
               data.frame(h = 1:H, cover = e1, model = "AR(1) misspecified"))
pD <- ggplot(dfCov, aes(h, cover, colour = model)) +
  geom_hline(yintercept = 0.95, colour = RUST, linetype = "dashed", linewidth = 0.5) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.6) +
  scale_colour_manual(values = c("AR(2) correct" = FOREST, "AR(1) misspecified" = GOLD)) +
  annotate("text", x = 10.5, y = 0.955, label = "nominal 0.95", colour = RUST, size = 2.9, hjust = 1) +
  labs(title = "Real coverage of the nominal 95% band",
       subtitle = "Plug-in intervals undercover; a wrong model form undercovers more",
       x = "Forecast horizon (steps)", y = "Empirical coverage", colour = NULL) +
  coord_cartesian(ylim = c(0.84, 0.98)) + 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))
