Skip to content

Volatility, ARCH and GARCH

See dependence that lives in squares, not levels, test for it with ARCH LM, McLeod–Li and BDS, and forecast how large the next moves may be with GARCH.

Advanced ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Explain volatility clustering, and why autocorrelation of levels can't see it
  • Use ARCH LM, McLeod–Li and BDS, and say what each one looks for
  • Read GARCH persistence, half-life and asymmetry, and check its residuals

Read first

01

Calm and storms

Read

Daily returns on a stock index look like noise. Their autocorrelations are tiny, and yesterday's return says little about today's.

But plot their size and a pattern appears: large moves cluster. Calm weeks follow calm weeks, and storms follow storms. That's volatility clusteringVolatility clusteringLarge moves tend to follow large moves and calm follows calm, even when the direction of the next move cannot be predicted.: dependence in the variance, not the mean.

02

Predict the plots

Predict

Predict first

Returns show almost no autocorrelation. What about their squares?

No pattern, the same as the returnsClear positive autocorrelationNegative autocorrelation
Reveal

Clear positive autocorrelation. A large move, in either direction, makes a large square, and these cluster. Uncorrelated doesn't mean independent, and a Ljung–Box test on the levels misses this.

03

Two tests for squares

Read

McLeod–Li is Ljung–Box on squared values. ARCH LM regresses squared values on their own lags (Engle, 1982).

On simulated returns with clustering:

  • McLeod–Li: Q = 63.3, p < .001.
  • ARCH LM: LM = 51.3 on 2 degrees of freedom, p < .001.

Both only look at squares. They would miss other nonlinear patterns.

04

A series that looks like noise

In the app

The BDS test asks if the series is i.i.d. against any form of dependence, using how often patterns of values stay close together.

Randomness and serial-dependence testsRecorded · Python and R agreeRecorded 2026-11-17 · 7 values compared · largest relative difference 2.6e-13
R

BDS z = 6.88, p < .001

BDS z
6.878
p
6.054e-12

Plots

Autocorrelation of chaoticIs the series autocorrelated, and at which lags (seasonality, AR order)?
View data
chaotic
0.3691
0.7254
0.5192
0.9213
0.1056
0.2074
0.4365
0.8532
0.2775
0.5901
0.8240
0.3671
0.7012
0.5436
0.8965
0.2220
0.4327
0.8446
0.3013
0.5902
0.8029
0.4023
0.7655
0.4485
0.8937
0.2301
0.4819
0.9503
0.0829
0.1949
0.3705
0.7596
0.5041
0.9401
0.0761
0.1655
0.3476
0.6693
0.6415
0.7237
0.5640
0.8652
0.2491
0.4872
0.9727
0.0282
0.0810
0.1785
0.3429
0.6891
0.6043
0.7897
0.4137
0.8202
0.3978
0.7542
0.4952
0.9737
0.0297
0.0483

First 60 of 240 rows.

Ljung–Box p by lag: chaoticUp to which lag is the series (or a model's residuals) indistinguishable from white noise?
View data
chaotic
0.3691
0.7254
0.5192
0.9213
0.1056
0.2074
0.4365
0.8532
0.2775
0.5901
0.8240
0.3671
0.7012
0.5436
0.8965
0.2220
0.4327
0.8446
0.3013
0.5902
0.8029
0.4023
0.7655
0.4485
0.8937
0.2301
0.4819
0.9503
0.0829
0.1949
0.3705
0.7596
0.5041
0.9401
0.0761
0.1655
0.3476
0.6693
0.6415
0.7237
0.5640
0.8652
0.2491
0.4872
0.9727
0.0282
0.0810
0.1785
0.3429
0.6891
0.6043
0.7897
0.4137
0.8202
0.3978
0.7542
0.4952
0.9737
0.0297
0.0483

First 60 of 240 rows.

Randomness tests

TestSensitive toStatisticdfpAt α = .05
BDS zany dependence, including nonlinear6.878—< .001not random
  • Portmanteau tests use 10 lags.
  • Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence.
The exact R script · R R version 4.5.1 (2025-06-13)
# Randomness and serial-dependence tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.randomness 1.1.1 · spec 1383867f19990650
# Dataset: ts_truth (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_truth.parquet", col_select = c("chaotic", "month")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("chaotic", "month")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("chaotic", "month"))  # infinite values stop the run (registry/errors.yaml)

# %% Series
VALUE <- "chaotic"
TIME <- "month"
TEMPORAL <- TRUE
TEST <- "bds"
LAG <- NULL
FITDF <- 0
WM_CORRECTION <- "always"
ARCH_LAGS <- 4
BDS_DIM <- 3
BDS_DIST <- 1.5
s <- cs_ts_ordered(df, VALUE, TIME, TEMPORAL)
x <- s$x
n <- length(x)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the tests assume one observation per evenly spaced time.", s$dups))
lag <- if (!is.null(LAG)) as.integer(LAG) else max(1L, min(10L, n %/% 5L))
if (TEST %in% c("ljung_box", "box_pierce", "battery") && lag - FITDF < 1) {
  stop(sprintf("Portmanteau tests need more lags (%d) than the model's degrees of freedom (%d); use at least %d lags.", as.integer(lag), as.integer(FITDF), as.integer(FITDF + 1)))
}
LABELS <- list(runs = "Runs test z", bartels = "Bartels rank z", wallis_moore = "Wallis–Moore z", turning_points = "Turning points z",
               von_neumann = "von Neumann ratio z", ljung_box = "Ljung–Box Q", box_pierce = "Box–Pierce Q", mcleod_li = "McLeod–Li Q",
               arch = "ARCH LM", bds = "BDS z", battery = "Battery")
LOOKS <- list(runs = "clustering or alternation", bartels = "trend or serial dependence", wallis_moore = "too few or many rises and falls",
              turning_points = "too few or many peaks and troughs", von_neumann = "successive values too alike or too different",
              ljung_box = "autocorrelation", box_pierce = "autocorrelation", mcleod_li = "autocorrelation of squares (volatility)",
              arch = "volatility clustering", bds = "any dependence, including nonlinear")
run_test <- function(t) switch(t,
  runs = cs_ts_runs(x), bartels = cs_ts_bartels(x), wallis_moore = cs_ts_wallis_moore(x, WM_CORRECTION), turning_points = cs_ts_turning_points(x),
  von_neumann = cs_ts_von_neumann(x), ljung_box = cs_ts_portmanteau(x, lag, "ljung", FITDF), box_pierce = cs_ts_portmanteau(x, lag, "box", FITDF),
  mcleod_li = cs_ts_mcleod_li(x, lag), arch = cs_ts_arch_lm(x, ARCH_LAGS), cs_ts_bds(x, BDS_DIM, BDS_DIST))

# %% Tests
tests <- if (TEST == "battery") c("runs", "bartels", "turning_points", "von_neumann", "ljung_box", "mcleod_li", "arch") else TEST
# The shortest series each test can use (the portmanteau tests need more values than lags, the ARCH regression
# more rows than coefficients), and a series that varies (registry/errors.yaml; the same checks in Python).
MIN_N <- c(runs = 3, bartels = 3, wallis_moore = 3, turning_points = 3, von_neumann = 3, ljung_box = lag + 2,
           box_pierce = lag + 2, mcleod_li = lag + 2, arch = 2 * ARCH_LAGS + 2, bds = BDS_DIM + 2)
cs_check_rows(n, max(MIN_N[tests]), "The randomness tests")
cs_check_not_constant(x, VALUE)
res <- lapply(stats::setNames(tests, tests), run_test)
rows <- lapply(tests, function(t) list(test = LABELS[[t]], looks_for = LOOKS[[t]], statistic = res[[t]]$stat, df = res[[t]]$df, p = res[[t]]$p,
                                       verdict = if (res[[t]]$p < 0.05) "not random" else "no evidence"))
values <- list(n_obs = n, test = TEST, test_label = LABELS[[TEST]], lag = lag)
main <- res[[tests[1]]]
values$stat <- main$stat
values$p <- main$p
values$reject <- as.integer(main$p < 0.05)
if (!is.null(main$df)) values$df <- main$df
if (TEST == "runs") values$runs <- main$runs
if (TEST == "battery") {
  for (t in tests) {
    values[[paste0(t, "_stat")]] <- res[[t]]$stat
    values[[paste0(t, "_p")]] <- res[[t]]$p
  }
  values$n_reject <- sum(vapply(tests, function(t) res[[t]]$p < 0.05, logical(1)))
  flagged <- unlist(lapply(tests, function(t) if (res[[t]]$p < 0.05) LOOKS[[t]]))
  summary <- paste0(sprintf("%d of %d randomness tests reject at α = .05 for %s (%d observations)", values$n_reject, length(tests), VALUE, n),
                    if (length(flagged)) paste0(": ", paste(flagged, collapse = "; "), ".") else " — consistent with independent noise.")
} else {
  summary <- paste0(sprintf("%s for %s: %.3f, %s — ", LABELS[[TEST]], VALUE, main$stat, cs_fmt_p(main$p)),
                    if (main$p < 0.05) sprintf("evidence of %s.", LOOKS[[TEST]]) else "no evidence against randomness.")
}
charts <- list(cs_chart("acf", "acf", sprintf("Autocorrelation of %s", VALUE), list(y = cs_col(VALUE, x))),
               cs_chart("lb", "ljung-box-p", sprintf("Ljung–Box p by lag: %s", VALUE), list(y = cs_col(VALUE, x)), controls = list(fitdf = FITDF)))
cs_publish(list(
  method = "ts.randomness",
  methodVersion = "1.1.1",
  title = "Randomness and serial-dependence tests",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = paste(vapply(rows, function(r) sprintf("%s = %.2f, %s", r$test, r$statistic, cs_fmt_p(r$p)), ""), collapse = "; "),
  statistics = list(list(key = "stat", label = LABELS[[tests[1]]], value = main$stat), list(key = "p", label = "p", value = main$p)),
  tables = list(list(
    key = "tests", title = "Randomness tests",
    columns = list(list(key = "test", label = "Test", type = "string"), list(key = "looks_for", label = "Sensitive to", type = "string"),
                   list(key = "statistic", label = "Statistic", type = "number"), list(key = "df", label = "df", type = "integer"),
                   list(key = "p", label = "p", type = "pvalue"), list(key = "verdict", label = "At α = .05", type = "string")),
    rows = rows
  )),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = list(paste0(sprintf("Portmanteau tests use %d lags", lag), if (FITDF > 0) sprintf(" and %d model degrees of freedom", FITDF) else "", "."),
               "Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence."),
  charts = charts,
  values = values
))
Python

BDS z = 6.88, p < .001

BDS z
6.878
p
6.054e-12

To keep this page light, the plots are shown once, under the R tab.

Randomness tests

TestSensitive toStatisticdfpAt α = .05
BDS zany dependence, including nonlinear6.878—< .001not random
  • Portmanteau tests use 10 lags.
  • Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Randomness and serial-dependence tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.randomness 1.1.1 · spec 1383867f19990650
# Dataset: ts_truth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_truth.parquet", columns=["chaotic", "month"])
n_input = len(df)
df = df.dropna(subset=["chaotic", "month"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["chaotic", "month"])  # infinite values stop the run (registry/errors.yaml)

# %% Series
VALUE = "chaotic"
TIME = "month"
TEMPORAL = True
TEST = "bds"
LAG = None
FITDF = 0
WM_CORRECTION = "always"
ARCH_LAGS = 4
BDS_DIM = 3
BDS_DIST = 1.5
s = ts.ordered(df, VALUE, TIME, TEMPORAL)
x = s["x"]
n = len(x)
if s["dups"]:
    warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
lag = int(LAG) if LAG is not None else max(1, min(10, n // 5))
if TEST in ("ljung_box", "box_pierce", "battery") and lag - FITDF < 1:
    raise ValueError(f"Portmanteau tests need more lags ({lag}) than the model's degrees of freedom ({FITDF}); use at least {FITDF + 1} lags.")
LABELS = {"runs": "Runs test z", "bartels": "Bartels rank z", "wallis_moore": "Wallis–Moore z", "turning_points": "Turning points z",
          "von_neumann": "von Neumann ratio z", "ljung_box": "Ljung–Box Q", "box_pierce": "Box–Pierce Q", "mcleod_li": "McLeod–Li Q",
          "arch": "ARCH LM", "bds": "BDS z", "battery": "Battery"}
LOOKS = {"runs": "clustering or alternation", "bartels": "trend or serial dependence", "wallis_moore": "too few or many rises and falls",
         "turning_points": "too few or many peaks and troughs", "von_neumann": "successive values too alike or too different",
         "ljung_box": "autocorrelation", "box_pierce": "autocorrelation", "mcleod_li": "autocorrelation of squares (volatility)",
         "arch": "volatility clustering", "bds": "any dependence, including nonlinear"}


def run(t):
    if t == "runs":
        return ts.runs_test(x)
    if t == "bartels":
        return ts.bartels(x)
    if t == "wallis_moore":
        return ts.wallis_moore(x, WM_CORRECTION)
    if t == "turning_points":
        return ts.turning_points(x)
    if t == "von_neumann":
        return ts.von_neumann(x)
    if t == "ljung_box":
        return ts.portmanteau(x, lag, "ljung", FITDF)
    if t == "box_pierce":
        return ts.portmanteau(x, lag, "box", FITDF)
    if t == "mcleod_li":
        return ts.mcleod_li(x, lag)
    if t == "arch":
        return ts.arch_lm(x, ARCH_LAGS)
    return ts.bds(x, BDS_DIM, BDS_DIST)


# %% Tests
tests = ["runs", "bartels", "turning_points", "von_neumann", "ljung_box", "mcleod_li", "arch"] if TEST == "battery" else [TEST]
# The shortest series each test can use (the portmanteau tests need more values than lags, the ARCH regression
# more rows than coefficients), and a series that varies (registry/errors.yaml; the same checks in R).
MIN_N = {"runs": 3, "bartels": 3, "wallis_moore": 3, "turning_points": 3, "von_neumann": 3, "ljung_box": lag + 2,
         "box_pierce": lag + 2, "mcleod_li": lag + 2, "arch": 2 * ARCH_LAGS + 2, "bds": BDS_DIM + 2}
cs.check_rows(n, max(MIN_N[t] for t in tests), "The randomness tests")
check_not_constant(x, VALUE)
res = {t: run(t) for t in tests}
rows = [{"test": LABELS[t], "looks_for": LOOKS[t], "statistic": res[t]["stat"], "df": res[t].get("df"), "p": res[t]["p"],
         "verdict": "not random" if res[t]["p"] < 0.05 else "no evidence"} for t in tests]
values = {"n_obs": n, "test": TEST, "test_label": LABELS[TEST], "lag": lag}
main = res[tests[0]]
values.update({"stat": main["stat"], "p": main["p"], "reject": int(main["p"] < 0.05)})
if main.get("df") is not None:
    values["df"] = main["df"]
if TEST == "runs":
    values["runs"] = main["runs"]
if TEST == "battery":
    for t in tests:
        values[f"{t}_stat"] = res[t]["stat"]
        values[f"{t}_p"] = res[t]["p"]
    values["n_reject"] = sum(1 for t in tests if res[t]["p"] < 0.05)
    flagged = [LOOKS[t] for t in tests if res[t]["p"] < 0.05]
    summary = (f"{values['n_reject']} of {len(tests)} randomness tests reject at α = .05 for {VALUE} ({n} observations)"
               + (": " + "; ".join(flagged) + "." if flagged else " — consistent with independent noise."))
else:
    summary = f"{LABELS[TEST]} for {VALUE}: {main['stat']:.3f}, {cs.fmt_p(main['p'])} — " + (f"evidence of {LOOKS[TEST]}." if main["p"] < 0.05 else "no evidence against randomness.")
kind = "temporal" if TEMPORAL else "numeric"
charts = [cs.chart("acf", "acf", f"Autocorrelation of {VALUE}", {"y": cs.col(VALUE, x)}),
          cs.chart("lb", "ljung-box-p", f"Ljung–Box p by lag: {VALUE}", {"y": cs.col(VALUE, x)}, controls={"fitdf": FITDF})]
cs.publish({
    "method": "ts.randomness",
    "methodVersion": "1.1.1",
    "title": "Randomness and serial-dependence tests",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": "; ".join(f"{r['test']} = {r['statistic']:.2f}, {cs.fmt_p(r['p'])}" for r in rows),
    "statistics": [{"key": "stat", "label": LABELS[tests[0]], "value": main["stat"]}, {"key": "p", "label": "p", "value": main["p"]}],
    "tables": [{
        "key": "tests", "title": "Randomness tests",
        "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "looks_for", "label": "Sensitive to", "type": "string"},
                    {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "df", "label": "df", "type": "integer"},
                    {"key": "p", "label": "p", "type": "pvalue"}, {"key": "verdict", "label": "At α = .05", "type": "string"}],
        "rows": rows,
    }],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": [f"Portmanteau tests use {lag} lags" + (f" and {FITDF} model degrees of freedom" if FITDF else "") + ".",
              "Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence."],
    "charts": charts,
    "values": values,
})

This simulated series comes from a deterministic rule, yet it can look random on a plot. BDS gives z = 6.9, p < .001.

A rejection doesn't say what kind of dependence is there, only that something is. When would that be useful? What would you do next?

05

GARCH

Read

A GARCH(1,1) model lets today's variance depend on yesterday's shock and yesterday's variance:

σt2=ω+α et−12+β σt−12\sigma_t^2 = \omega + \alpha\, e_{t-1}^2 + \beta\, \sigma_{t-1}^2

On daily DAX returns, α^\hat\alpha = 0.055 and β^\hat\beta = 0.942. Their sum is the persistence, 0.997: how slowly a shock to variance fades.

06

How long does a shock last?

Predict

Predict first

With persistence this close to 1, how long until half of a volatility shock has faded? These are trading days.

About a weekAbout a monthMany months
Reveal

Many months: the half-life is 257 days, from ln⁡(1/2)/ln⁡(α+β)\ln(1/2) / \ln(\alpha + \beta). So long-horizon forecasts lean on a long-run level that's hard to estimate. The next day's volatility forecast is 1.57, against a long-run 1.54.

07

Check the fit

In the app
GARCH volatility forecastRecorded · Python and R agreeRecorded 2026-11-25 · 36 values compared
R

GARCH(1,1): 5-step forecasts of dax (evenly spaced data, 749 observations). Backtest MAE 2.11 over 1 origin.

MAE
2.107
RMSE
2.285
MAPE
1.031

Assumptions

  • Volatility returns to a long-run level — Persistence 0.997. Close to 1: shocks to volatility fade very slowly, so long-horizon forecasts depend heavily on the model.
  • No volatility clustering left — ARCH LM on the standardized residuals: p = 0.414.
  • Standardized residuals look uncorrelated — Ljung–Box: p = 0.988.

Backtest accuracy (1 origin, horizon 5)

MetricValue
MAE2.107
RMSE2.285
MAPE1.031
sMAPE1.917
MASE1.771
WAPE1.011
Coverage of the 80% interval0.2000
Coverage of the 95% interval0.6000

Parameters (robust standard errors)

ParameterEstimateSEzp
mu0.11110.03263.4130.0006
omega0.00630.00611.0480.2944
alpha10.05500.01823.0230.0025
beta10.94230.020446.1210

Forecast

dayForecast80% low80% high95% low95% high
7510.1111−1.8972.120−2.9603.183
7520.1111−1.8972.119−2.9603.183
7530.1111−1.8972.119−2.9603.182
7540.1111−1.8972.119−2.9603.182
7550.1111−1.8972.119−2.9603.182
The exact R script · R R version 4.5.1 (2025-06-13)
# GARCH volatility forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.garch 1.0.1 · spec e37b02a59e96fe77
# Dataset: f7_dax (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
TIME <- "day"
VALUE <- "dax"
SERIES <- NULL
H <- 5
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL  # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 1
STEP <- NULL  # NULL = the horizon
OFFSETS <- NULL  # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL  # NULL = train on all values before each origin
TRAIN_START <- NULL  # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- character(0)
PARAMS <- list(
  input_transform = "log_return",
  volatility = "garch",
  p = 1,
  q = 1,
  distribution = "normal",
  mean_model = "constant"
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f7_dax.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
  cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
  early <- !is.na(times_all) & times_all < cut
  n_early <- sum(early)
  if (n_early > 0) {
    warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
    times_all[early] <- NA
  }
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.garch/dax_garch_normal/out-r")
extra_tables <- list()  # model blocks may add result tables (assign with <<-)
extra_assumptions <- list()  # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()

# %% Model
# GARCH family (Bollerslev 1986; Glosten, Jagannathan & Runkle 1993; Nelson 1991) by quasi-maximum likelihood: how large
# the next moves are likely to be, given how large recent ones were. The mean forecast is flat, so read the interval width
# (the Python script runs the same code).
FINAL <- list()
if (PARAMS$input_transform != "none") {
  # Turn prices into percentage returns, per series, in time order.
  for (key in series_keys) {
    sel <- which(!is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE))
    sel <- sel[order(times_all[sel], method = "radix")]
    p <- values_all[sel]
    k <- length(p)
    if (PARAMS$input_transform == "log_return") {
      if (min(p, na.rm = TRUE) <= 0) stop("Log returns need positive values")
      values_all[sel[-1]] <- 100 * (log(p[-1]) - log(p[-k]))
    } else {
      values_all[sel[-1]] <- 100 * (p[-1] / p[-k] - 1)
    }
    times_all[sel[1]] <- NA
  }
}
min_train <- function(m) 50L
prepare_series <- function(y, t, m, freq) {
  if (length(y) < 250) warnings <<- c(warnings, sprintf("%d observations is short for a volatility model; estimates are usually unstable below about 250.", length(y)))
  NULL
}
fit_forecast <- function(y, t, h, m, levels, spec) {
  fit <- cs_fcm_garch_fit(y, PARAMS$volatility, as.integer(PARAMS$p), as.integer(PARAMS$q), PARAMS$distribution, PARAMS$mean_model)
  res <- cs_fcm_garch_forecast(fit, h, levels, seed = SEED)
  FINAL[[if (is.null(current_series)) "_" else current_series]] <<- list(fit = fit, res = res, t = as.numeric(t))
  # The Residuals tab checks what cs_fcm_garch_facts checks: the standardized residuals, at its lags.
  DIAG[[if (is.null(current_series)) "_" else current_series]] <<- list(resid = as.numeric(fit$eps / sqrt(fit$s2)), lags = min(10L, fit$n %/% 5L))
  v <- fit$spec
  name <- c(garch = "GARCH", gjr = "GJR-GARCH", egarch = "EGARCH")[[v$vol]]
  res$fitted <- rep(res$mean[1], length(y))
  res$label <- paste0(sprintf("%s(%d,%d)", name, v$p, v$q), if (v$dist == "t") " with t errors" else "")
  res$facts <- cs_fcm_garch_facts(fit, res$sigma[1])
  res$sigma <- NULL
  res
}

# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
  current_series <- key  # model blocks may read it (e.g. table titles)
  sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
  t_raw <- times_all[sel]; y_raw <- values_all[sel]
  if (sum(!is.na(y_raw)) < 3) {  # too few values to read the time step from
    cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
  }
  x_later <- NULL
  if (length(XREG)) {  # rows after the last observed value carry known future regressors
    x_raw <- x_all[sel, , drop = FALSE]
    last_y <- max(t_raw[!is.na(y_raw)])
    later <- t_raw > last_y
    x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
    t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
  }
  freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
  reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
  t <- reg$t; y <- reg$y
  x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
  filled <- filled + reg$filled
  freq_label <- freq$label
  freq_alias <- cs_ml_fc_alias(freq$unit)
  m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
  seasons <- c(seasons, m)
  n <- length(y)
  n_obs <- n_obs + n
  if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
  spec <- prepare_series(y, t, m, freq)
  step <- if (!is.null(STEP)) as.integer(STEP) else H
  if (!is.null(OFFSETS)) {
    origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
    if (length(origins) < length(OFFSETS)) {
      warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
    }
  } else {
    origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
  }
  for (o in origins) {
    start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
    if (length(XREG)) {
      X_TRAIN <- x_grid[start:o, , drop = FALSE]
      X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
    }
    res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
    if (inherits(res, "error")) {
      warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
      next
    }
    n_origins <- n_origins + 1
    scale <- cs_ml_fc_mase_scale(y[1:o], m)
    scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
    lag <- if (m > 1 && o > m) m else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
    for (k in seq_len(H)) {
      row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
                  time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
                  mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
                  snaive = y[o - lag + (k - 1) %% lag + 1])
      for (level in LEVELS) {
        row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
        row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
      }
      bt_rows[[length(bt_rows) + 1]] <- row
    }
  }
  if (length(XREG)) {
    X_TRAIN <- x_grid
    X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
    if (nrow(x_later) < H) {
      warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
    }
  }
  final <- fit_forecast(y, t, H, m, LEVELS, spec)
  labels[[length(labels) + 1]] <- final$label
  for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
  fitted <- final$fitted
  diag <- DIAG[[if (is.null(key)) "_" else key]]
  resid <- diag$resid
  if (is.null(residuals_first) && !is.null(resid)) {
    residuals_first <- as.numeric(resid)
  } else if (is.null(residuals_first) && !is.null(fitted)) {
    ok <- !is.na(fitted)
    residuals_first <- (y - fitted)[ok]
  }
  skey <- if (is.null(key)) NA_character_ else key
  for (i in seq_len(n)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
    if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))]  # the last length(resid) times
    if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
    if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
    fc_rows[[length(fc_rows) + 1]] <- row
    if (!is.null(fitted) && !is.na(fitted[i])) {
      fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
    }
  }
  future <- cs_ml_fc_future_times(t[n], freq, H)
  for (k in seq_len(H)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
    for (level in LEVELS) {
      row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
      row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
    }
    fc_rows[[length(fc_rows) + 1]] <- row
  }
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))

as_frame <- function(rows) {
  cols <- unique(unlist(lapply(rows, names)))
  as.data.frame(stats::setNames(lapply(cols, function(cn) {
    v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
    unlist(v)
  }), cols), stringsAsFactors = FALSE, check.names = FALSE)
}

# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
  n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
  filled = filled, fc_check = wsum(forecasts$mean),
  model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
  freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
  values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
  values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)

nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
  nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
  artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}

# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
  time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
  value = cs_col(VALUE, fan$mean, kind = "numeric"),
  kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
  if (level %in% LEVELS) {
    roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
    roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
  }
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
  charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
    h = cs_col("horizon", bt$h, kind = "numeric"),
    error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
    origin = cs_col("origin", bt$origin, kind = "categorical")
  ))
}
if (length(residuals_first) > 4) {
  lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
  r_acf <- cs_ml_fc_acf(residuals_first, lags)
  bound <- 1.959963984540054 / sqrt(length(residuals_first))
  charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
    lag = cs_col("lag", seq_len(lags), kind = "numeric"),
    acf = cs_col("ACF", r_acf, kind = "numeric"),
    bound = cs_col("bound", rep(bound, lags), kind = "numeric")
  ))
}

# %% Volatility
first_key <- if (is.null(SERIES)) "_" else series_keys[1]
final0 <- FINAL[[first_key]]
fit0 <- final0$fit; res0 <- final0$res; t0 <- final0$t
extra_tables[[length(extra_tables) + 1]] <- list(
  key = "parameters",
  title = paste0("Parameters (robust standard errors)", if (!is.null(SERIES)) paste0(" — ", first_key) else ""),
  columns = list(list(key = "parameter", label = "Parameter"), list(key = "estimate", label = "Estimate", type = "number"),
                 list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"),
                 list(key = "p", label = "p", type = "number")),
  rows = cs_fcm_garch_table(fit0)
)
freq0 <- cs_ml_fc_detect_frequency(t0, TEMPORAL)
future0 <- cs_ml_fc_future_times(t0[length(t0)], freq0, H)
times0 <- c(vapply(t0, cs_ml_fc_format_time, if (TEMPORAL) "" else 0, temporal = TEMPORAL), vapply(future0, cs_ml_fc_format_time, if (TEMPORAL) "" else 0, temporal = TEMPORAL))
charts[[length(charts) + 1]] <- cs_chart("volatility", "volatility-band",
  paste0(sprintf("Conditional volatility of %s", VALUE), if (!is.null(SERIES)) paste0(" — ", first_key) else ""), list(
  time = cs_col(TIME, times0, kind = if (TEMPORAL) "temporal" else "numeric"),
  value = cs_col(if (PARAMS$input_transform == "none") VALUE else paste0(VALUE, " returns (%)"), c(fit0$z * fit0$scale, rep(NA_real_, H)), kind = "numeric"),
  sigma = cs_col("volatility", c(cs_fcm_garch_volatility(fit0), res0$sigma), kind = "numeric"),
  mean = cs_col("mean", rep(res0$mean[1], length(t0) + H), kind = "numeric"),
  kind = cs_col("kind", c(rep("fit", length(t0)), rep("forecast", H)), kind = "categorical", levels = c("fit", "forecast"))
))
facts0 <- cs_fcm_garch_facts(fit0, res0$sigma[1])
per0 <- facts0$persistence
extra_assumptions[[length(extra_assumptions) + 1]] <- list(
  key = "stationary_variance", label = "Volatility returns to a long-run level", status = if (per0 < 0.995) "pass" else "warn", statistic = per0,
  detail = paste0(sprintf("Persistence %.3f.", per0), if (per0 >= 0.995) " Close to 1: shocks to volatility fade very slowly, so long-horizon forecasts depend heavily on the model." else "")
)
if (!is.null(facts0$arch_p)) extra_assumptions[[length(extra_assumptions) + 1]] <- list(
  key = "arch_remaining", label = "No volatility clustering left", status = if (facts0$arch_p > 0.05) "pass" else "warn", statistic = facts0$arch_p,
  detail = paste0(sprintf("ARCH LM on the standardized residuals: p = %.3f.", facts0$arch_p), if (facts0$arch_p <= 0.05) " Clustering remains: try more lags or an asymmetric model." else "")
)
if (!is.null(facts0$lb_p)) extra_assumptions[[length(extra_assumptions) + 1]] <- list(
  key = "independence", label = "Standardized residuals look uncorrelated", status = if (facts0$lb_p > 0.05) "pass" else "warn", statistic = facts0$lb_p,
  detail = paste0(sprintf("Ljung–Box: p = %.3f.", facts0$lb_p), if (facts0$lb_p <= 0.05) " The mean has structure this model ignores: model it first (for example with ARIMA) and fit the volatility to its residuals." else "")
)
# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
  rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
  for (level in LEVELS) {
    ck <- paste0("coverage_", lv(level))
    if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
  }
  tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
                      columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
             list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
  fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
                             list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
  rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
  title = "GARCH volatility forecast",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_obs,
  summary = summary,
  statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
  tables = tables,
  values = values,
  assumptions = extra_assumptions,
  warnings = warnings,
  notes = list(),
  charts = charts,
  artifacts = artifacts
))
Python

GARCH(1,1): 5-step forecasts of dax (evenly spaced data, 749 observations). Backtest MAE 2.11 over 1 origin.

MAE
2.107
RMSE
2.285
MAPE
1.031

Assumptions

  • Volatility returns to a long-run level — Persistence 0.997. Close to 1: shocks to volatility fade very slowly, so long-horizon forecasts depend heavily on the model.
  • No volatility clustering left — ARCH LM on the standardized residuals: p = 0.414.
  • Standardized residuals look uncorrelated — Ljung–Box: p = 0.988.

Backtest accuracy (1 origin, horizon 5)

MetricValue
MAE2.107
RMSE2.285
MAPE1.031
sMAPE1.917
MASE1.771
WAPE1.011
Coverage of the 80% interval0.2000
Coverage of the 95% interval0.6000

Parameters (robust standard errors)

ParameterEstimateSEzp
mu0.11110.03263.4130.0006
omega0.00630.00611.0480.2944
alpha10.05500.01823.0230.0025
beta10.94230.020446.1210

Forecast

dayForecast80% low80% high95% low95% high
7510.1111−1.8972.120−2.9603.183
7520.1111−1.8972.119−2.9603.183
7530.1111−1.8972.119−2.9603.182
7540.1111−1.8972.119−2.9603.182
7550.1111−1.8972.119−2.9603.182
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# GARCH volatility forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.garch 1.0.1 · spec e37b02a59e96fe77
# Dataset: f7_dax (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.ml import forecast_models as fcm

# %% Data
TIME = "day"
VALUE = "dax"
SERIES = None
H = 5
LEVELS = [float(v) for v in [80, 95]]
SEASON = None  # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None  # None = the horizon
OFFSETS = None  # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None  # None = train on all values before each origin
TRAIN_START = None  # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
    "input_transform": "log_return",
    "volatility": "garch",
    "p": 1,
    "q": 1,
    "distribution": "normal",
    "mean_model": "constant",
}
df = pd.read_parquet("tests/parity/fixtures/f7_dax.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
    cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
    cut = fc.parse_time(TRAIN_START, TEMPORAL)
    early = np.nan_to_num(times_all, nan=np.inf) < cut
    if early.any():
        warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
        times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
    warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None]  # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
    warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
    cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
    cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.garch/dax_garch_normal/out-python")
extra_tables = []  # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = []  # … and assumption rows
current_series = None
X_TRAIN = None  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}


# %% Model
# GARCH family (Bollerslev 1986; Glosten, Jagannathan & Runkle 1993; Nelson 1991) by quasi-maximum likelihood: how large
# the next moves are likely to be, given how large recent ones were. The mean forecast is flat, so read the interval width
# (the R script runs the same code).
FINAL = {}


def to_returns():
    """Turn prices into percentage returns, per series, in time order."""
    for key in series_keys:
        sel = np.flatnonzero(~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True))
        sel = sel[np.argsort(times_all[sel], kind="stable")]
        p = values_all[sel]
        if PARAMS["input_transform"] == "log_return":
            if np.nanmin(p) <= 0:
                raise ValueError("Log returns need positive values")
            values_all[sel[1:]] = 100.0 * (np.log(p[1:]) - np.log(p[:-1]))
        else:
            values_all[sel[1:]] = 100.0 * (p[1:] / p[:-1] - 1.0)
        times_all[sel[0]] = np.nan


if PARAMS["input_transform"] != "none":
    values_all = values_all.copy()
    times_all = times_all.copy()
    to_returns()


def min_train(m):
    return 50


def prepare_series(y, t, m, freq):
    if len(y) < 250:
        warnings.append(f"{len(y)} observations is short for a volatility model; estimates are usually unstable below about 250.")
    return None


def fit_forecast(y, t, h, m, levels, spec):
    fit = fcm.garch_fit(y, PARAMS["volatility"], int(PARAMS["p"]), int(PARAMS["q"]), PARAMS["distribution"], PARAMS["mean_model"])
    res = fcm.garch_forecast(fit, h, levels, seed=SEED)
    FINAL[current_series] = (fit, res, [float(v) for v in t])
    # The Residuals tab checks what garch_facts checks: the standardized residuals, at its lags.
    z_std = [fit["eps"][i] / math.sqrt(fit["s2"][i]) for i in range(fit["n"])]
    DIAG[current_series] = {"resid": z_std, "lags": min(10, fit["n"] // 5)}
    v = fit["spec"]
    name = {"garch": "GARCH", "gjr": "GJR-GARCH", "egarch": "EGARCH"}[v["vol"]]
    label = f"{name}({v['p']},{v['q']})" + (" with t errors" if v["dist"] == "t" else "")
    return {**res, "fitted": [res["mean"][0]] * len(y), "label": label, "facts": fcm.garch_facts(fit, res["sigma"][0])}


# %% Backtests and forecasts
def lv(level):
    return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")


bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
    current_series = key  # model blocks may read it (e.g. table titles)
    sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
    t_raw, y_raw = times_all[sel], values_all[sel]
    if int(np.sum(~np.isnan(y_raw))) < 3:  # too few values to read the time step from
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
    x_later = None
    if XREG:  # rows after the last observed value carry known future regressors
        x_raw = x_all[sel]
        last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
        later = t_raw > last_y
        order_later = np.argsort(t_raw[later], kind="stable")
        x_later = x_raw[later][order_later]
        t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
    freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
    t, y, nfill = fc.regularize(t_raw, y_raw, freq)
    x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
    filled += nfill
    freq_label = freq["label"]
    freq_alias = fc.ALIASES.get(freq["unit"], "")
    m = int(SEASON) if SEASON else int(freq["season"])
    seasons.append(m)
    y = [float(v) for v in y]
    n = len(y)
    n_obs += n
    if n < min_train(m) + 1:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
    spec = prepare_series(y, t, m, freq)
    step = int(STEP) if STEP else H
    if OFFSETS is not None:
        origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
        if len(origins) < len(OFFSETS):
            warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
    else:
        origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
    for o in origins:
        start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
        if XREG:
            X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
        try:
            res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
        except Exception as e:  # a failed origin is skipped, not fatal
            warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
            continue
        n_origins += 1
        scale = fc.mase_scale(y[:o], m)
        scale2 = fc.rmsse_scale(y[:o], m)
        lag = m if (m > 1 and o > m) else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
        for k in range(H):
            row = {
                "series": key,
                "origin": fc.format_time(t[o - 1], TEMPORAL),
                "time": fc.format_time(t[o + k], TEMPORAL),
                "h": k + 1,
                "actual": y[o + k],
                "mean": float(res["mean"][k]),
                "scale": scale,
                "scale2": scale2,
                "last": y[o - 1],
                "snaive": y[o - lag + k % lag],
            }
            for level in LEVELS:
                row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
                row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
            bt_rows.append(row)
    if XREG:
        X_TRAIN = x_grid
        X_FUTURE = fc.future_regressors(x_grid, x_later, H)
        if len(x_later) < H:
            warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
    final = fit_forecast(y, t, H, m, LEVELS, spec)
    labels[key] = final["label"]
    for name, value in final["facts"].items():
        facts[name if not SERIES else f"{name}[{key}]"] = value
    fitted = final.get("fitted")
    diag = DIAG.get(key) or {}
    resid = diag.get("resid")
    if residuals_first is None and resid is not None:
        residuals_first = [float(v) for v in resid]
    elif residuals_first is None and fitted is not None:
        residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
    for i in range(n):
        row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
        if resid is not None and i >= n - len(resid):  # the last len(resid) times (differencing drops early ones)
            row["resid"] = float(resid[i - (n - len(resid))])
        if "fitdf" in diag:
            row["lb_fitdf"] = float(diag["fitdf"])
        if "lags" in diag:
            row["lb_lags"] = float(diag["lags"])
        fc_rows.append(row)
        if fitted is not None and not math.isnan(fitted[i]):
            fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
    future = fc.future_times(t[-1], freq, H)
    for k in range(H):
        row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
        for level in LEVELS:
            row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
            row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
        fc_rows.append(row)
if filled:
    warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")

# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None


def wsum(xs):
    return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)


values = {
    "n_series": len(series_keys),
    "n_obs": n_obs,
    "horizon": H,
    "season": seasons[0],
    "n_origins": n_origins,
    "filled": filled,
    "fc_check": wsum([r["mean"] for r in forecasts]),
    "model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
    "freq_label": freq_label,
    "frequency": freq_alias,
}
if top:
    values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
    values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
    values[f"bt[{k}]"] = v
values.update(facts)

pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
    pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
    artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})

# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
    "time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
    "value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
    "kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
    if level in LEVELS:
        roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
        roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
    roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
    charts.append(
        cs.chart(
            "backtest",
            "backtest-errors",
            "Backtest errors by horizon",
            {
                "h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
                "error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
                "origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
            },
        )
    )
if residuals_first and len(residuals_first) > 4:
    lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
    r_acf = fc.acf(residuals_first, lags)
    bound = 1.959963984540054 / math.sqrt(len(residuals_first))
    charts.append(
        cs.chart(
            "acf",
            "acf-plot",
            "Residual autocorrelation",
            {
                "lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
                "acf": cs.col("ACF", r_acf, kind="numeric"),
                "bound": cs.col("bound", [bound] * lags, kind="numeric"),
            },
        )
    )

# %% Volatility
fit0, res0, t0 = FINAL[series_keys[0]]
extra_tables.append(
    {
        "key": "parameters",
        "title": "Parameters (robust standard errors)" + (f" — {series_keys[0]}" if SERIES else ""),
        "columns": [
            {"key": "parameter", "label": "Parameter"},
            {"key": "estimate", "label": "Estimate", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"},
            {"key": "z", "label": "z", "type": "number"},
            {"key": "p", "label": "p", "type": "number"},
        ],
        "rows": fcm.garch_table(fit0),
    }
)
vol0 = fcm.garch_volatility(fit0)
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
future0 = fc.future_times(t0[-1], freq0, H)
times0 = [fc.format_time(v, TEMPORAL) for v in t0] + [fc.format_time(v, TEMPORAL) for v in future0]
returns0 = [fit0["z"][i] * fit0["scale"] for i in range(len(t0))] + [None] * H
charts.append(
    cs.chart(
        "volatility",
        "volatility-band",
        f"Conditional volatility of {VALUE}" + (f" — {series_keys[0]}" if SERIES else ""),
        {
            "time": cs.col(TIME, times0, kind="temporal" if TEMPORAL else "numeric"),
            "value": cs.col(VALUE if PARAMS["input_transform"] == "none" else f"{VALUE} returns (%)", returns0, kind="numeric"),
            "sigma": cs.col("volatility", vol0 + list(res0["sigma"]), kind="numeric"),
            "mean": cs.col("mean", [res0["mean"][0]] * (len(t0) + H), kind="numeric"),
            "kind": cs.col("kind", ["fit"] * len(t0) + ["forecast"] * H, kind="categorical", levels=["fit", "forecast"]),
        },
    )
)
facts0 = fcm.garch_facts(fit0, res0["sigma"][0])
per0 = facts0["persistence"]
extra_assumptions.append(
    {
        "key": "stationary_variance",
        "label": "Volatility returns to a long-run level",
        "status": "pass" if per0 < 0.995 else "warn",
        "statistic": per0,
        "detail": f"Persistence {per0:.3f}." + (" Close to 1: shocks to volatility fade very slowly, so long-horizon forecasts depend heavily on the model." if per0 >= 0.995 else ""),
    }
)
if "arch_p" in facts0:
    extra_assumptions.append(
        {
            "key": "arch_remaining",
            "label": "No volatility clustering left",
            "status": "pass" if facts0["arch_p"] > 0.05 else "warn",
            "statistic": facts0["arch_p"],
            "detail": f"ARCH LM on the standardized residuals: p = {facts0['arch_p']:.3f}." + ("" if facts0["arch_p"] > 0.05 else " Clustering remains: try more lags or an asymmetric model."),
        }
    )
if "lb_p" in facts0:
    extra_assumptions.append(
        {
            "key": "independence",
            "label": "Standardized residuals look uncorrelated",
            "status": "pass" if facts0["lb_p"] > 0.05 else "warn",
            "statistic": facts0["lb_p"],
            "detail": f"Ljung–Box: p = {facts0['lb_p']:.3f}." + ("" if facts0["lb_p"] > 0.05 else " The mean has structure this model ignores: model it first (for example with ARIMA) and fit the volatility to its residuals."),
        }
    )
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
    tables.append(
        {
            "key": "accuracy",
            "title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
            "columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
            "rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
            + [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
        }
    )
tables.extend(extra_tables)
tables.append(
    {
        "key": "forecast",
        "title": "Forecast",
        "columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
        + [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
        + [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
        "rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
    }
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
    summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
    {
        "title": "GARCH volatility forecast",
        "engine": cs.engine_info("numpy", "scipy", "numpy", "pandas"),
        "n": n_obs,
        "summary": summary,
        "statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
        "tables": tables,
        "values": values,
        "assumptions": extra_assumptions,
        "warnings": warnings,
        "notes": [],
        "charts": charts,
        "artifacts": artifacts,
    }
)

Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.

A good GARCH leaves nothing obvious behind. Ljung–Box on the standardized residuals: 0.99. On their squares: 0.78. ARCH LM: 0.41.

These are compatible with no clustering left. Look at the volatility band. Does it widen where the series is rough?

08

Bad news, fat tails

Reflect

GJR-GARCH adds a term γ\gamma for negative shocks. Simulated data with Student's t errors gives γ^\hat\gamma = 0.18 and ν^\hat\nu = 8.7 degrees of freedom. EGARCH models the log of variance, so no constraints are needed, and it also has an asymmetry term: −0.12. Note that its sign reads the opposite way.

Do falls and rises move your series' volatility equally? How would you check that with these models before deciding?

09

Check your understanding

Checkpoint

Check yourself

A GARCH(1,1) has α=0.1\alpha = 0.1 and β=0.85\beta = 0.85. What is its persistence?

Show the answer

Answer: 0.95

α+β=0.95\alpha + \beta = 0.95.

Check yourself

With ω=0.05\omega = 0.05 and α+β=0.95\alpha + \beta = 0.95, what is the long-run variance, ω/(1−α−β)\omega / (1 - \alpha - \beta)?

Show the answer

Answer: 1

0.05/0.05=10.05 / 0.05 = 1.

Check yourself

GJR-GARCH gives γ^\hat\gamma well above zero. What does that say?

Show the answer

Answer: b

γ\gamma adds to the effect of a negative shock. It describes how volatility responds, and says nothing about direction.

Check yourself

Ljung–Box on returns gives p = 0.5, and McLeod–Li gives p < 0.001. What's the reading?

Show the answer

Answer: b

Uncorrelated doesn't mean independent. Size can be predictable when direction isn't.

Check yourself

What does a BDS rejection tell you?

Show the answer

Answer: a

BDS is a broad test. Apply it to a model's residuals to see if the model missed something.

10

Do it in CodeSplash

In the app

Choose ARCH LM, McLeod–Li or BDS under Test in the randomness method. For the model, choose GARCH volatility forecast in Forecast. The values are tells it if you've given prices or returns.

Python
import pandas as pd
from arch import arch_model
from statsmodels.stats.diagnostic import het_arch

r = pd.read_csv("returns.csv")["ret"]
print(het_arch(r, nlags=4)[:2])
fit = arch_model(r, mean="Constant", vol="GARCH", p=1, q=1, dist="t").fit(disp="off")
print(fit.summary())
print(fit.forecast(horizon=5).variance.iloc[-1])
R
# install.packages("rugarch")
library(rugarch)
r <- read.csv("returns.csv")$ret
spec <- ugarchspec(
  variance.model = list(model = "gjrGARCH", garchOrder = c(1, 1)),
  mean.model = list(armaOrder = c(0, 0)),
  distribution.model = "std"
)
fit <- ugarchfit(spec, r)
show(fit)
11

Recap

Recap
  • Returns can be uncorrelated and still dependent: sizes cluster.
  • McLeod–Li and ARCH LM look at squares, while BDS looks for any dependence.
  • GARCH forecasts size, not direction. Report persistence and check the residuals.
  • GJR-GARCH and EGARCH allow for bad news to move volatility more.

Concepts in this lesson