ufo_ts <- read_csv("data/multiTimelineUFO.csv", skip = 2, show_col_types = FALSE) |>
clean_names() |>
rename(interest = ufo_united_states) |>
mutate(
month = yearmonth(month),
interest = parse_number(as.character(interest))
) |>
as_tsibble(index = month)
books_ts <- aus_retail |>
filter(Industry == "Newspaper and book retailing") |>
summarise(Turnover = sum(Turnover))Note 31: Reproducible Time Series Reporting with Quarto
Module 7: Wrangling, Case Studies & Ethics
Learning Objectives
- Structure clean, publication-ready Quarto reports using modern
#|hashpipe chunk options (label,fig-cap,tbl-cap,echo,code-fold) and native cross-references (@fig-...,@tbl-...). - Replace fragile manual code appendices and legacy R Markdown table hacks (
results='asis') with Quarto’s built-incode-fold: true,code-tools: true, andknitr::kable(). - Execute an end-to-end reproducible forecasting workflow on two real monthly series: U.S. Google Trends UFO searches (
data/multiTimelineUFO.csv) and Australian retail book turnover (aus_retail). - Evaluate Box-Cox
ARIMAversusETSstrictly on out-of-sample holdout accuracy alongside formal innovation residual diagnostics.
1. Modern Quarto Architecture for Forecasting Reports
A credible forecasting report separates narrative interpretation from code mechanics without sacrificing reproducibility. In legacy R Markdown workflows, analysts often hid code in the main text and pasted duplicate copies into an eval=FALSE appendix. Duplicate code inevitably drifts out of sync with the figures whenever a model or sample cutoff changes.
Modern Quarto solves this cleanly through document-level YAML and #| hashpipe execution options:
format:
html:
code-fold: true
code-tools: true
fig-format: png
fig-dpi: 300
toc: trueInside individual chunks, place execution directives at the top using #| comments rather than crowded chunk headers:
#| include: falseruns setup code (packages, shared themes) without printing code or output.#| label: fig-books-fcpaired with#| fig-cap: "..."creates a numbered figure referenced cleanly in prose as@fig-books-fc.#| label: tbl-holdout-accpaired with#| tbl-cap: "..."creates a numbered table referenced as@tbl-holdout-accviaknitr::kable()(noresults='asis'required!).#| fig-width: 7.5and#| fig-height: 4.5control aspect ratios explicitly so axis labels and legends never collide.
With code-fold: true and code-tools: true, decision-makers read clean prose, figures, and tables by default, while technical reviewers can unfold any single chunk or inspect the entire exact source file in one click.
2. Case Study Data Preparation & Exploration
We demonstrate a complete report workflow on two contrasting monthly series:
- U.S. UFO Search Interest (
data/multiTimelineUFO.csv): monthly Google Trends index (2004 Jan–2025 Apr, 256 months). Google Trends exports carry two preamble metadata lines (skip = 2) and can encode tiny values as"<1", so converting viareadr::parse_number(as.character(...))guards against character coercion. - Australian Newspaper & Book Retailing (
aus_retail): national monthly turnover in millions of AUD (1982 Apr–2018 Dec, 441 months), featuring strong multiplicative December seasonality and a structural secular decline after 2008.
p_ufo <- ufo_ts |>
autoplot(interest, color = ts_pal["navy"], linewidth = 0.7) +
labs(
title = "U.S. Google Trends: 'UFO' Search Interest",
subtitle = "Episodic news-driven spikes over a stable baseline (2004–2025)",
x = NULL,
y = "Index (0–100)"
)
p_books <- books_ts |>
autoplot(Turnover, color = ts_pal["teal"], linewidth = 0.7) +
labs(
title = "Australian Newspaper & Book Retail Turnover",
subtitle = "Strong December seasonality with post-2008 structural decline (1982–2018)",
x = "Month",
y = "Turnover (AUD millions)"
)
(p_ufo / p_books) +
plot_layout(guides = "collect") &
theme(legend.position = "bottom")
Inspecting Figure 1 reveals sharp episodic news spikes in UFO searches (such as mid-2023 congressional hearings peaking at 100), whereas Australian book retailing exhibits textbook seasonal regularity overlaid on a post-2008 digital-era decline. Seasonal plots (Figure 2) quantify the recurring calendar structure before modeling.
p_s1 <- ufo_ts |>
gg_season(interest, labels = "none") +
guides(colour = guide_colorbar(
barwidth = grid::unit(4.2, "cm"),
barheight = grid::unit(0.32, "cm"),
title.vjust = 0.85
)) +
labs(
title = "UFO Search Seasonality",
subtitle = "Mild summer lift plus news spikes (2004–2025)",
x = "Month",
y = "Index",
colour = "UFO year"
)
p_s2 <- books_ts |>
gg_season(Turnover, labels = "none") +
guides(colour = guide_colorbar(
barwidth = grid::unit(4.2, "cm"),
barheight = grid::unit(0.32, "cm"),
title.vjust = 0.85
)) +
labs(
title = "Book Retail Seasonality",
subtitle = "Sharp ~40% December holiday surge (1982–2018)",
x = "Month",
y = "Turnover (AUD millions)",
colour = "Book year"
)
(p_s1 | p_s2) +
plot_layout(guides = "collect") &
theme(legend.position = "bottom")
December holiday demand dominates book retailing (peaking nearly 40% above typical months), while UFO searches display a gentler warm-weather lift during June–August alongside occasional news-driven spikes.
3. Out-of-Sample Model Comparison: Box-Cox ARIMA vs. ETS
In-sample training errors reward complexity and cannot reliably rank competing model families. A disciplined Quarto report evaluates models on an out-of-sample holdout window (here the final 36 months of each series). For each training set, we estimate the Guerrero Box-Cox parameter \(\lambda\) to stabilize multiplicative seasonal variance inside ARIMA:
\[w_t = \begin{cases} \dfrac{y_t^\lambda - 1}{\lambda}, & \lambda \ne 0, \\ \log(y_t), & \lambda = 0. \end{cases}\]
books_train <- books_ts |> filter(Month < yearmonth("2016 Jan"))
lam_books <- books_train |> features(Turnover, guerrero) |> pull(lambda_guerrero)
fit_books <- books_train |>
model(
ARIMA = ARIMA(box_cox(Turnover, lam_books) ~ pdq(0:2, 0:1, 0:2) + PDQ(0:1, 0:1, 0:1)),
ETS = ETS(Turnover)
)
ufo_train <- ufo_ts |> filter(month < yearmonth("2022 May"))
lam_ufo <- ufo_train |> features(interest, guerrero) |> pull(lambda_guerrero)
fit_ufo <- ufo_train |>
model(
ARIMA = ARIMA(box_cox(interest, lam_ufo)),
ETS = ETS(interest)
)
fc_books <- fit_books |> forecast(h = 36)
fc_ufo <- fit_ufo |> forecast(h = 36)
bind_rows(
fabletools::accuracy(fc_books, books_ts) |> mutate(Series = "AUS Book Retail", .before = 1),
fabletools::accuracy(fc_ufo, ufo_ts) |> mutate(Series = "U.S. UFO Trends", .before = 1)
) |>
select(Series, .model, RMSE, MAE, MAPE, MASE) |>
fmt_tbl(digits = 2)| Series | .model | RMSE | MAE | MAPE | MASE |
|---|---|---|---|---|---|
| AUS Book Retail | ARIMA | 21.84 | 19.39 | 7.79 | 1.01 |
| AUS Book Retail | ETS | 29.48 | 27.01 | 10.91 | 1.41 |
| U.S. UFO Trends | ARIMA | 14.59 | 7.52 | 21.88 | 0.91 |
| U.S. UFO Trends | ETS | 14.48 | 7.36 | 21.20 | 0.89 |
As reported in Table 1, on Australian book retail turnover (Guerrero \(\hat{\lambda} = -0.18\)), Box-Cox ARIMA(2,1,1)(1,1,1)[12] outperforms ETS(M,Ad,M) across every metric (RMSE = 21.8 vs. 29.5, MAPE = 7.79% vs. 10.9%), tracking the continuing downward trajectory shown in Figure 3. Conversely, on the spike-driven UFO series (Guerrero \(\hat{\lambda} = 0.23\)), simple ETS(A,N,N) edges out ARIMA(0,1,2)(1,0,0)[12] slightly (RMSE = 14.5 vs. 14.6), because neither linear model can predict news-driven spikes (interest = 100 in 2023).
fc_books |>
anchor_fc(books_train) |>
autoplot(books_ts |> filter(Month >= yearmonth("2010 Jan")), level = 80, alpha = 0.35) +
scale_color_manual(values = c(ARIMA = unname(ts_pal["teal"]), ETS = unname(ts_pal["orange"]))) +
scale_fill_manual(values = c(ARIMA = unname(ts_pal["teal"]), ETS = unname(ts_pal["orange"]))) +
labs(
title = "Australian Book Retail: 36-Month Holdout Forecasts",
subtitle = TeX(sprintf(r"(Box-Cox ARIMA ($\hat{\lambda} = %.2f$) tracks the decline better than ETS(M,Ad,M))", lam_books)),
x = "Month",
y = "Turnover (AUD millions)",
color = NULL,
fill = NULL
)
4. Residual Diagnostics & Cross-Referenced Verification
Every forecasting report should conclude its modeling section with innovation residual diagnostics so readers can judge whether the winning specification leaves unmodeled autocorrelation.
p_books_res <- fit_books |>
select(ARIMA) |>
gg_tsresiduals(lag_max = 24)
p_books_res[[2]] <- p_books_res[[2]] + labs(y = "ACF")
p_books_res[[3]] <- p_books_res[[3]] + labs(x = "Innovation residual", y = "Count")
ts_panel(
p_books_res,
title = TeX(sprintf(r"(Innovation Residuals: Box-Cox ARIMA ($\hat{\lambda} = %.2f$) on Book Retail)", lam_books), bold = TRUE),
subtitle = "Training split (1982–2015); ARIMA(2,1,1)(1,1,1)[12] with Guerrero transform"
)
books_dof <- sum(grepl("^(ar|ma|sar|sma)[0-9]+$", tidy(fit_books |> select(ARIMA))$term))
fit_books |>
select(ARIMA) |>
augment() |>
features(.innov, ljung_box, lag = 24, dof = books_dof) |>
mutate(dof = books_dof) |>
fmt_tbl(digits = 4)| .model | lb_stat | lb_pvalue | dof |
|---|---|---|---|
| ARIMA | 43.23 | 0.0012 | 5 |
In Figure 4, residuals fluctuate symmetrically around zero with stable variance across 34 years, yet the formal Ljung-Box test (Table 2, using exact dof = p + q + P + Q = 5) rejects strict white noise (\(Q^* = 43.2\), \(p = 0.0012\)). That contrast demonstrates why honest reporting pairs visual plots with formal tests: even when a model clearly wins on holdout accuracy, subtle evolving seasonality or post-2008 structural drift can leave detectable residual structure that warrants noting as a caveat for prediction intervals.
Practice Exercises
- Reproducible Model Comparison Section. Build a concise, cross-referenceable model comparison on
aus_retailforIndustry == "Clothing retailing"(2000 Jan–2018 Dec) using a 36-month holdout (2016 Jan–2018 Dec). Fit Guerrero Box-CoxARIMAandETS, and present the accuracy table viafmt_tbl().
Solution
Aggregate nationally across Australian states, estimate Guerrero’s \(\lambda\) strictly on the training split (never on the full series, to prevent data leakage), and compare holdout accuracy:
clothing_ts <- aus_retail |>
filter(Industry == "Clothing retailing", year(Month) >= 2000) |>
summarise(Turnover = sum(Turnover))
cloth_train <- clothing_ts |> filter(Month < yearmonth("2016 Jan"))
lam_cloth <- cloth_train |> features(Turnover, guerrero) |> pull(lambda_guerrero)
fit_cloth <- cloth_train |>
model(
ARIMA = ARIMA(box_cox(Turnover, lam_cloth) ~ pdq(0:2, 0:1, 0:2) + PDQ(0:1, 0:1, 0:1)),
ETS = ETS(Turnover)
)
fit_cloth |>
forecast(h = 36) |>
fabletools::accuracy(clothing_ts) |>
select(.model, RMSE, MAE, MAPE, MASE) |>
fmt_tbl(digits = 2)| .model | RMSE | MAE | MAPE | MASE |
|---|---|---|---|---|
| ARIMA | 48.28 | 40.01 | 2.93 | 0.74 |
| ETS | 42.01 | 29.67 | 2.13 | 0.55 |
Here multiplicative ETS(M,A,M) (RMSE = 42.0, MAPE = 2.13%, MASE = 0.55) outperforms Box-Cox ARIMA(2,1,1)(1,1,1)[12] (RMSE = 48.3, MAPE = 2.93%) on the 3-year holdout, underscoring why out-of-sample comparison, not model-family preference, should select the winning model.
- Automated Ljung-Box Diagnostics for the UFO Model. Extract the ARMA degree of freedom dynamically from
fit_ufo |> select(ARIMA)usingtidy(), run a lag-24 Ljung-Box test on its innovation residuals, and explain whyETS(A,N,N)performs just as well asARIMAon the UFO holdout.
Solution
Counting all ar, ma, sar, and sma parameters programmatically prevents hard-coded dof mistakes when models refit:
ufo_dof <- sum(grepl("^(ar|ma|sar|sma)[0-9]+$", tidy(fit_ufo |> select(ARIMA))$term))
fit_ufo |>
select(ARIMA) |>
augment() |>
features(.innov, ljung_box, lag = 24, dof = ufo_dof) |>
mutate(dof = ufo_dof) |>
fmt_tbl(digits = 4, caption = "Ljung-Box whiteness check on U.S. UFO Box-Cox ARIMA innovation residuals.")| .model | lb_stat | lb_pvalue | dof |
|---|---|---|---|
| ARIMA | 17.84 | 0.6593 | 3 |
Because UFO search spikes are driven by unpredictable external news events rather than persistent multi-year momentum or strong seasonal cycles, both ARIMA(0,1,2)(1,0,0)[12] and simple exponential smoothing (ETS(A,N,N)) produce flat baseline forecasts with nearly identical holdout error (MASE ≈ 0.90).
Key Takeaways
- Use Quarto
#|chunk options (label,fig-cap,tbl-cap) with@fig-...and@tbl-...cross-references so numbering updates automatically as sections evolve. - Enable
code-fold: trueandcode-tools: truein YAML instead of maintaining error-prone duplicate code appendices. - Always estimate Box-Cox parameters (\(\lambda\)) and fit candidate models strictly on the training split, ranking
ARIMAagainstETSon an out-of-sample holdout window. - Compute
ljung_box()degrees of freedom programmatically fromtidy()so residual diagnostics stay synchronized whenever model orders change.