Skip to main content

Note 09: Residual Diagnostics, Nonlinearity & Cross-Correlation

Module 2: Stationarity & Regression

Learning Objectives

  • Distinguish response residuals (.resid) from innovation residuals (.innov) and apply gg_tsresiduals() and Ljung-Box diagnostics with proper degrees of freedom.
  • Detect and model nonlinear predictor-response relationships using residual-vs-predictor plots on daily electricity demand (vic_elec).
  • Interpret exact stats::ccf() and feasts::CCF() lag-sign conventions and apply prewhitening to eliminate spurious cross-correlation peaks.

1. Response Residuals vs. Innovation Residuals

After fitting a time series model, augment() returns two residual columns:

  • Response (raw) residuals .resid: \(e_t = y_t - \hat{y}_t\) on the original measurement scale. These assess forecast error magnitudes in native units.
  • Innovation residuals .innov: residuals on the transformed/modeled scale (identical to .resid when no transformation is used, but measured on the log or Box-Cox scale whenever a transformation is applied).

All white-noise checks (histogram, residual ACF, and Ljung-Box tests) must inspect .innov. When testing residuals from a fitted model, adjust the Ljung-Box degrees of freedom (dof) to reflect the number of estimated ARMA error parameters (for plain TSLM(), dof = 0, whereas ARIMA(p, d, q) sets dof = p + q). Also note a plotting detail: because gg_tsresiduals() returns a multi-panel gg_tsensemble object whose title cannot be attached with + labs(title = ...), wrap it with ts_panel(..., title = ...) to produce a cleanly titled patchwork layout.

2. Detecting and Modeling Nonlinearity (vic_elec)

Residual plots against fitted values and against each predictor quickly expose unmodeled curvature. Consider half-hourly electricity demand in Victoria, Australia (vic_elec), aggregated to daily total demand (GWh) and daily maximum temperature (°C). Electricity demand rises both on cold winter days (electric heating) and hot summer days (air conditioning), forming a clear U-shaped curve.

vic_daily <- vic_elec |>
  index_by(Date = as_date(Time)) |>
  summarise(
    Demand = sum(Demand) / 1e3,
    Temperature = max(Temperature),
    Holiday = any(Holiday)
  ) |>
  mutate(
    Day_Type = case_when(
      Holiday ~ "Holiday",
      wday(Date) %in% 2:6 ~ "Weekday",
      TRUE ~ "Weekend"
    )
  )

fit_vic <- vic_daily |>
  model(
    Linear = TSLM(Demand ~ Temperature),
    Quadratic = TSLM(Demand ~ Temperature + I(Temperature^2))
  )

glance(fit_vic) |>
  select(.model, r_squared, adj_r_squared, AICc, BIC) |>
  fmt_tbl(digits = 3, caption = "Linear vs. quadratic TSLM fit on daily Victoria electricity demand (2012–2014).")
Linear vs. quadratic TSLM fit on daily Victoria electricity demand (2012–2014).
.model r_squared adj_r_squared AICc BIC
Linear 0.002 0.001 7100 7115
Quadratic 0.361 0.360 6613 6633
aug_vic <- augment(fit_vic) |>
  left_join(vic_daily |> as_tibble() |> select(Date, Temperature), by = "Date")

r2_vic <- glance(fit_vic) |>
  select(.model, r_squared) |>
  tibble::deframe()

p_curve <- vic_daily |>
  ggplot(aes(x = Temperature, y = Demand)) +
  geom_point(alpha = 0.25, size = 1.1, colour = ts_pal["slate"]) +
  geom_line(data = filter(aug_vic, .model == "Linear"),
            aes(y = .fitted, colour = "Linear"), linewidth = 0.9) +
  geom_line(data = filter(aug_vic, .model == "Quadratic"),
            aes(y = .fitted, colour = "Quadratic"), linewidth = 0.95) +
  scale_colour_manual(values = c("Linear" = unname(ts_pal["crimson"]), "Quadratic" = unname(ts_pal["navy"]))) +
  labs(
    title = "Demand vs. Max Temperature",
    subtitle = TeX(r"(U-shaped load curve ($T$ vs. $T^2$))"),
    x = "Max Temp (°C)",
    y = "Demand (GWh)",
    colour = NULL
  )

p_res_lin <- aug_vic |>
  filter(.model == "Linear") |>
  ggplot(aes(x = Temperature, y = .innov)) +
  geom_point(alpha = 0.25, size = 1.1, colour = ts_pal["crimson"]) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  labs(
    title = "Linear Residuals",
    subtitle = TeX(sprintf(r"(Parabolic bias ($R^2 = %.3f$))", r2_vic["Linear"])),
    x = "Max Temp (°C)",
    y = "Residual (GWh)"
  )

p_res_quad <- aug_vic |>
  filter(.model == "Quadratic") |>
  ggplot(aes(x = Temperature, y = .innov)) +
  geom_point(alpha = 0.25, size = 1.1, colour = ts_pal["teal"]) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  labs(
    title = "Quadratic Residuals",
    subtitle = TeX(sprintf(r"(Curvature removed ($R^2 = %.3f$))", r2_vic["Quadratic"])),
    x = "Max Temp (°C)",
    y = NULL
  )

(p_curve | p_res_lin | p_res_quad) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")
Figure 1: Daily Victoria electricity demand vs. maximum temperature with linear and quadratic fits (left), and residuals vs. temperature showing strong parabolic bias under the linear fit (middle) eliminated by the quadratic term (right).

3. Cross-Correlation Function (CCF) and Prewhitening

To detect whether a predictor \(x_t\) leads a response \(y_t\), we estimate the cross-correlation function (CCF) across positive and negative lags \(k\). Always verify the exact argument order and sign convention in R:

  • Both stats::ccf(x, y) and feasts::CCF(data, y, x) (note that feasts::CCF() takes the response y first and the predictor x second, passing them to stats::ccf(y = y, x = x)) evaluate: \[\rho_{xy}(k) = \operatorname{Corr}(x_{t+k}, y_t).\]
  • Under CCF(data, y, x), a peak at negative lag \(k = -h < 0\) means past \(x_{t-h}\) correlates with current \(y_t\), so \(x\) leads \(y\) by \(h\) periods. Calling CCF(data, x, y) reverses the roles to \(\operatorname{Corr}(y_{t+k}, x_t)\), flipping the lag sign.

A crucial diagnostic pitfall arises when \(x_t\) and \(y_t\) are individually autocorrelated: the raw sample CCF inherits both series’ internal serial dependence, smearing correlations across dozens of lags and triggering false significance.

Prewhitening solves this cleanly in three steps:

  1. Fit an autoregressive (or ARIMA) filter \(\hat{\phi}(B)\) to the input series \(x_t\) so that \(\tilde{x}_t = \hat{\phi}(B)(x_t - \bar{x})\) is approximately white noise.
  2. Apply the exact same filter \(\hat{\phi}(B)\) to the response series \(y_t\) to obtain \(\tilde{y}_t = \hat{\phi}(B)(y_t - \bar{y})\).
  3. Compute the CCF between \(\tilde{y}_t\) and \(\tilde{x}_t\). Because linear filtering preserves transfer-function lag relationships while removing input autocorrelation, spikes in the prewhitened CCF isolate true lead-lag timing.

Consider the classic Pacific climate-fisheries pair in astsa: monthly Southern Oscillation Index (soi) and new fish Recruitment (rec, 1950–1987).

soi_rec <- as_tsibble(soi) |>
  rename(Month = index, SOI = value) |>
  mutate(Rec = as.numeric(rec))

ar_soi <- ar(soi_rec$SOI, aic = TRUE)
ar_filt <- c(1, -ar_soi$ar)

soi_pw_df <- soi_rec |>
  mutate(
    soi_pw = as.numeric(stats::filter(SOI - mean(SOI), ar_filt, sides = 1)),
    rec_pw = as.numeric(stats::filter(Rec - mean(Rec), ar_filt, sides = 1))
  ) |>
  drop_na()

soi_pw_df |>
  CCF(rec_pw, soi_pw, lag_max = 10) |>
  as_tibble() |>
  arrange(desc(abs(ccf))) |>
  slice_head(n = 5) |>
  fmt_tbl(digits = 3, caption = "Top five prewhitened CCF lags for CCF(rec_pw, soi_pw): negative lags indicate SOI leading Recruitment.")
Top five prewhitened CCF lags for CCF(rec_pw, soi_pw): negative lags indicate SOI leading Recruitment.
lag ccf
-5M -0.371
-6M -0.255
-7M -0.178
-10M -0.173
-8M -0.161
c_raw <- soi_rec |>
  CCF(Rec, SOI, lag_max = 18) |>
  autoplot() +
  labs(
    title = "Raw CCF: Rec vs. SOI",
    subtitle = "Smeared by strong autocorrelation",
    x = TeX(r"(Lag $k$ (Months))", bold = TRUE),
    y = TeX(r"($\hat{\rho}_{XY}(k)$)", bold = TRUE)
  )

c_pw <- soi_pw_df |>
  CCF(rec_pw, soi_pw, lag_max = 18) |>
  autoplot() +
  labs(
    title = "Prewhitened CCF: Rec vs. SOI",
    subtitle = TeX(r"(Sharp negative peaks at lags $-5$ and $-6$)"),
    x = TeX(r"(Lag $k$ (Months))", bold = TRUE),
    y = TeX(r"(Prewhitened $\hat{\rho}_{XY}(k)$)", bold = TRUE)
  )

(c_raw | c_pw) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")
Figure 2: Raw CCF(Rec, SOI) smeared across many lags by internal autocorrelation (left) versus prewhitened CCF(rec_pw, soi_pw) isolating a sharp negative peak at lags -5 and -6 months (right).

The prewhitened CCF reveals a crisp physical mechanism: shifts in the Southern Oscillation Index lead fish recruitment by 5 to 6 months with an inverse relationship (negative lags under CCF(rec_pw, soi_pw)).

Practice Exercises

Exercise 1: Calendar Effects and Remaining Autocorrelation in vic_elec

Add Day_Type (Weekday, Weekend, Holiday) to the quadratic vic_elec regression. Compare adj_r_squared and AICc against the quadratic-only model, plot residual diagnostics with ts_panel(gg_tsresiduals(), ...), and run a Ljung-Box test (lag = 14, dof = 0). Are the residuals white noise yet?

Solution

Adding Day_Type lifts adjusted \(R^2\) substantially because weekday commercial load exceeds weekend and holiday demand. However, gg_tsresiduals() and Ljung-Box reveal strong residual autocorrelation remaining at lags 1 to 7 — motivating dynamic regression with ARIMA errors in Note 10.

fit_vic2 <- vic_daily |>
  model(
    Quad = TSLM(Demand ~ Temperature + I(Temperature^2)),
    Quad_Day = TSLM(Demand ~ Temperature + I(Temperature^2) + Day_Type)
  )

glance(fit_vic2) |>
  select(.model, adj_r_squared, AICc) |>
  fmt_tbl(digits = 2, caption = "Improvement from adding Day_Type to quadratic daily electricity regression.")
Improvement from adding Day_Type to quadratic daily electricity regression.
.model adj_r_squared AICc
Quad 0.36 6613
Quad_Day 0.78 5422
fit_vic2 |>
  select(Quad_Day) |>
  augment() |>
  features(.innov, ljung_box, lag = 14, dof = 0) |>
  fmt_tbl(digits = 4, caption = "Ljung-Box test on TSLM residuals confirms persistent autocorrelation.")
Ljung-Box test on TSLM residuals confirms persistent autocorrelation.
.model lb_stat lb_pvalue
Quad_Day 2487 0
fit_vic2 |>
  select(Quad_Day) |>
  gg_tsresiduals() |>
  ts_panel(
    title = "Residual Diagnostics: Quadratic Temperature + Day Type (TSLM)",
    subtitle = "Strong autocorrelation at lags 1-7 violates white-noise OLS assumptions"
  )
Figure 3: Residual diagnostics for daily Victoria electricity demand regression with quadratic temperature and day type.

Exercise 2: Prewhitened CCF for Predator-Prey Cycles (pelt)

Using pelt, treat Hare (prey) as the input \(x_t\) and Lynx (predator) as the response \(y_t\). Fit an AR model to Hare with ar(), apply the same filter to both Hare and Lynx, and compare the raw CCF(Lynx, Hare) against the prewhitened CCF(lynx_pw, hare_pw) over lags \(-6\) to \(6\). At what lag does prey lead predator?

Solution

The prewhitened CCF isolates a primary positive peak at lag \(-1\) year under CCF(lynx_pw, hare_pw): an increase in hare abundance predicts higher lynx abundance one year later.

ar_h <- ar(pelt$Hare, aic = TRUE)
f_h  <- c(1, -ar_h$ar)

pelt_pw <- pelt |>
  mutate(
    hare_pw = as.numeric(stats::filter(Hare - mean(Hare), f_h, sides = 1)),
    lynx_pw = as.numeric(stats::filter(Lynx - mean(Lynx), f_h, sides = 1))
  ) |>
  drop_na()

pelt_pw |>
  CCF(lynx_pw, hare_pw, lag_max = 6) |>
  as_tibble() |>
  filter(as.numeric(lag) %in% -3:3) |>
  fmt_tbl(digits = 3, caption = "Prewhitened CCF(lynx_pw, hare_pw) near lag 0: peak at -1Y confirms Hare leads Lynx by 1 year.")
Prewhitened CCF(lynx_pw, hare_pw) near lag 0: peak at -1Y confirms Hare leads Lynx by 1 year.
lag ccf
-3Y 0.051
-2Y 0.084
-1Y 0.267
0Y 0.113
1Y 0.000
2Y -0.047
3Y -0.225

Key Takeaways

  • Always run white-noise checks on innovation residuals (.innov), adjust Ljung-Box dof for estimated ARMA error parameters, and wrap gg_tsresiduals() in ts_panel() for clean multi-panel titles.
  • Plot residuals against individual predictors to diagnose nonlinearities such as the U-shaped temperature-demand curve in electricity load.
  • Under feasts::CCF(data, y, x) (and stats::ccf(x, y)), lag \(k\) measures \(\operatorname{Corr}(x_{t+k}, y_t)\), so negative lags indicate that \(x\) leads \(y\).
  • Always prewhiten with the input series’ AR/ARIMA filter before interpreting cross-correlations between autocorrelated time series.
Back to top