Skip to content

Intermittent demand and hierarchies

Forecast spare parts that sell only now and then with Croston-type methods, and make store, region and total forecasts add up with reconciliation.

Advanced ~13 min10 steps

What runs in CodeSplash

You will be able to

  • Classify a demand series with ADI and CV², and pick a Croston variant
  • Explain why ordinary metrics mislead on intermittent series
  • Explain reconciliation, and choose between bottom-up, top-down and MinT

Read first

01

Mostly zeros

Read

A spare part sells in a few months a year, with long gaps in between. Smoothing the raw series decays toward zero after each gap, then jumps after each sale. Its forecast is lowest right before the next sale is likely.

Croston's method smooths two things separately: the size of non-zero demands, and the interval between them. Its forecast is a rate:

y^=z^/p^\hat y = \hat z / \hat p

Here, the smoothed size is 5.12 and the smoothed interval is 3.94.

02

Classify first

Predict

Predict first

Syntetos and Boylan's scheme uses two numbers: ADI, the average gap between demands, cut at 1.321.32, and CV², the squared variation of demand sizes, cut at 0.490.49.

A part has ADI = 3.43 and CV² = 0.10. How do you classify it?

SmoothIntermittentLumpy
Reveal

It's intermittent: long gaps, but stable sizes. If sizes varied a lot too, it'd be lumpy. With a shorter average gap, it'd be smooth or erratic, and ordinary methods could apply.

03

The variants

In the app
Intermittent demand (Croston, SBA, TSB, ADIDA)Recorded · Python and R agreeRecorded 2026-11-25 · 26 values compared
R

Croston: 12-step forecasts of demand (monthly data, 72 observations). Backtest MAE 2.05 over 2 origins.

MAE
2.051
RMSE
2.331
SMAPE
1.700

Plots

Forecast of demandWhere is the series heading, and how uncertain is the forecast?
View data
kindmonthdemand
actual1,546,300,800,0000
actual1,548,979,200,0000
actual1,551,398,400,0000
actual1,554,076,800,0005
actual1,556,668,800,0000
actual1,559,347,200,0005
actual1,561,939,200,0000
actual1,564,617,600,0006
actual1,567,296,000,0003
actual1,569,888,000,0000
actual1,572,566,400,0000
actual1,575,158,400,0000
actual1,577,836,800,0007
actual1,580,515,200,0000
actual1,583,020,800,0000
actual1,585,699,200,0000
actual1,588,291,200,0008
actual1,590,969,600,0000
actual1,593,561,600,0003
actual1,596,240,000,0006
actual1,598,918,400,0000
actual1,601,510,400,0000
actual1,604,188,800,0000
actual1,606,780,800,0000
actual1,609,459,200,0000
actual1,612,137,600,0000
actual1,614,556,800,0000
actual1,617,235,200,0000
actual1,619,827,200,0000
actual1,622,505,600,0007
actual1,625,097,600,0000
actual1,627,776,000,0004
actual1,630,454,400,0000
actual1,633,046,400,0006
actual1,635,724,800,0000
actual1,638,316,800,0000
actual1,640,995,200,0005
actual1,643,673,600,0000
actual1,646,092,800,0008
actual1,648,771,200,0004
actual1,651,363,200,0000
actual1,654,041,600,0005
actual1,656,633,600,0000
actual1,659,312,000,0000
actual1,661,990,400,0000
actual1,664,582,400,0000
actual1,667,260,800,0000
actual1,669,852,800,0000
actual1,672,531,200,0000
actual1,675,209,600,0000
actual1,677,628,800,0004
actual1,680,307,200,0005
actual1,682,899,200,0000
actual1,685,577,600,0000
actual1,688,169,600,0000
actual1,690,848,000,0002
actual1,693,526,400,0000
actual1,696,118,400,0000
actual1,698,796,800,0000
actual1,701,388,800,0008

First 60 of 84 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
−2.02512022-12-01
−2.02522022-12-01
1.97532022-12-01
2.97542022-12-01
−2.02552022-12-01
−2.02562022-12-01
−2.02572022-12-01
−0.025082022-12-01
−2.02592022-12-01
−2.025102022-12-01
−2.025112022-12-01
5.975122022-12-01
−1.50812023-12-01
4.49222023-12-01
−1.50832023-12-01
−1.50842023-12-01
−1.50852023-12-01
−1.50862023-12-01
−1.50872023-12-01
−1.50882023-12-01
−1.50892023-12-01
2.492102023-12-01
−1.508112023-12-01
−1.508122023-12-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
−0.13590.23771
0.13380.23772
0.00730.23773
−0.01390.23774
−0.01520.23775
−0.20580.23776
−0.03170.23777
−0.05720.23778
−0.01310.23779
0.05020.237710
−0.03960.237711
−0.01600.237712
−0.02310.237713
−0.05960.237714
−0.11180.237715
−0.24590.237716
0.09720.237717
−0.01980.237718
0.00280.237719
0.11920.237720
0.11500.237721
0.21240.237722
0.08300.237723
−0.02170.237724

Backtest accuracy (2 origins, horizon 12)

MetricValue
MAE2.051
RMSE2.331
sMAPE1.700
MASE0.8119
WAPE1.697
Coverage of the 90% interval0.9583

Forecast

monthForecast90% low90% high
2025-01-011.29805.643
2025-02-011.29805.643
2025-03-011.29805.643
2025-04-011.29805.643
2025-05-011.29805.643
2025-06-011.29805.643
2025-07-011.29805.643
2025-08-011.29805.643
2025-09-011.29805.643
2025-10-011.29805.643
2025-11-011.29805.643
2025-12-011.29805.643
The exact R script · R R version 4.5.1 (2025-06-13)
# Intermittent demand (Croston, SBA, TSB, ADIDA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.croston 1.0.0 · spec 3d379bbcb2fb9d24
# Dataset: l3_spares_bearing (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 <- "month"
VALUE <- "demand"
SERIES <- NULL
H <- 12
LEVELS <- as.numeric(c(90))
SEASON <- NULL  # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 2
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(
  method = "croston",
  alpha = 0.15,
  beta = 0.1,
  aggregation = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/l3_spares_bearing.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.croston/croston_one_series/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
# Intermittent demand by the codesplashr twins (cs_fc_intermittent ↔ codesplash.ml.forecast_adv).
# forecast::croston(type = "sba") is the classic equivalent for Croston/SBA/SBJ (see known differences).
METHOD <- PARAMS$method
LABEL <- c(croston = "Croston", sba = "Croston (SBA)", sbj = "Croston (SBJ)", tsb = "TSB", adida = "ADIDA")[[METHOD]]
min_train <- function(m) 4
prepare_series <- function(y, t, m, freq) NULL
fit_forecast <- function(y, t, h, m, levels, spec) {
  res <- cs_fc_intermittent(y, METHOD, alpha = PARAMS$alpha, beta = PARAMS$beta, aggregation = PARAMS$aggregation,
                            h = h, levels = levels)
  c(res, list(label = LABEL))
}

# %% 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")
  ))
}

# %% 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 = "Intermittent demand (Croston, SBA, TSB, ADIDA)",
  engine = cs_engine_info("codesplashr", "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

Croston: 12-step forecasts of demand (monthly data, 72 observations). Backtest MAE 2.05 over 2 origins.

MAE
2.051
RMSE
2.331
SMAPE
1.700

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

Backtest accuracy (2 origins, horizon 12)

MetricValue
MAE2.051
RMSE2.331
sMAPE1.700
MASE0.8119
WAPE1.697
Coverage of the 90% interval0.9583

Forecast

monthForecast90% low90% high
2025-01-011.29805.643
2025-02-011.29805.643
2025-03-011.29805.643
2025-04-011.29805.643
2025-05-011.29805.643
2025-06-011.29805.643
2025-07-011.29805.643
2025-08-011.29805.643
2025-09-011.29805.643
2025-10-011.29805.643
2025-11-011.29805.643
2025-12-011.29805.643
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Intermittent demand (Croston, SBA, TSB, ADIDA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.croston 1.0.0 · spec 3d379bbcb2fb9d24
# Dataset: l3_spares_bearing (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_adv as fca

# %% Data
TIME = "month"
VALUE = "demand"
SERIES = None
H = 12
LEVELS = [float(v) for v in [90]]
SEASON = None  # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 2
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 = {
    "method": "croston",
    "alpha": 0.15,
    "beta": 0.1,
    "aggregation": None,
}
df = pd.read_parquet("tests/parity/fixtures/l3_spares_bearing.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.croston/croston_one_series/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
# Intermittent demand by the codesplash twins (codesplash.ml.forecast_adv ↔ codesplashr::cs_fc_*).
METHOD = PARAMS["method"]
LABEL = {"croston": "Croston", "sba": "Croston (SBA)", "sbj": "Croston (SBJ)", "tsb": "TSB", "adida": "ADIDA"}[METHOD]


def min_train(m):
    return 4


def prepare_series(y, t, m, freq):
    return None


def fit_forecast(y, t, h, m, levels, spec):
    res = fca.intermittent(
        y, METHOD, alpha=PARAMS["alpha"], beta=PARAMS["beta"], aggregation=PARAMS["aggregation"], h=h, levels=levels
    )
    return {**res, "label": LABEL}


# %% 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"),
            },
        )
    )

# %% 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": "Intermittent demand (Croston, SBA, TSB, ADIDA)",
        "engine": cs.engine_info("numpy", "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,
    }
)
MethodIdea
CrostonSize / interval, which is known to run high
SBACroston with a bias correction, the default
SBJA different correction
TSBSmooths the probability of demand, so it can fall to zero for an obsolete part
ADIDAAdds up into buckets, then smooths

MASE on this card is 0.81. Which variant would you use for a part that's being phased out?

04

Scoring zeros

Predict

Predict first

A part sells 1 unit in 1 month out of 5. You compare forecasting 0 with forecasting the true rate of 0.20.2 per month, using MAE.

Which scores better?

Zero winsThe true rate winsThey tie
Reveal

Forecasting zero wins: MAE is 1/51/5 for zero, and (4×0.2+0.8)/5=0.32(4 \times 0.2 + 0.8)/5 = 0.32 for the rate. MAE favors the median, and that's zero. An inventory planner would run out of stock with that "accurate" forecast. Prefer RMSE-type scores, or score the stock outcome itself.

05

Forecasts that add up

Read

A retailer forecasts each store, each region and the total. Fit separately, they won't add up: stores may sum to more than their region. That's incoherent, and it causes arguments in planning meetings.

ReconciliationForecast reconciliationAdjusting forecasts at every level of a hierarchy so they add up. adjusts them so they add up:

y~=S G y^\tilde{\mathbf y} = S\, G\, \hat{\mathbf y}

SS encodes the hierarchy, and GG decides how to map the base forecasts to the bottom level.

06

Four routes

Reflect
ReconciliationIdea
Bottom-upForecast the bottom level, then add up
Top-downForecast the total, then split by historical proportions
OLS, WLSAdjust all levels using a simple weighting
MinT with shrinkageWeight using the estimated error covariance

MinT here has 5 bottom series and 8 nodes, with a shrinkage of 0.15.

When would top-down lose information you care about? When would bottom-up be too noisy?

07

Is it better?

In the app
Hierarchical forecast (reconciliation)Recorded · Python and R agreeRecorded 2026-11-25 · 37 values compared
R

ETS(A,A,A) base forecasts reconciled by MinT (shrinkage): 6-step forecasts of sales for 8 series (5 at the bottom, monthly data, 48 periods). Backtest MASE 0.65 reconciled vs 0.649 base.

MAE
5.692
RMSE
8.533
MASE
0.6497

Plots

Reconciled forecasts of salesWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95seriesmonthsales
——actual——Total1,609,459,200,000371.10
——actual——Total1,612,137,600,000393.20
——actual——Total1,614,556,800,000397.40
——actual——Total1,617,235,200,000407.40
——actual——Total1,619,827,200,000397.50
——actual——Total1,622,505,600,000422.20
——actual——Total1,625,097,600,000383.50
——actual——Total1,627,776,000,000357.30
——actual——Total1,630,454,400,000312.10
——actual——Total1,633,046,400,000300.20
——actual——Total1,635,724,800,000316
——actual——Total1,638,316,800,000349.50
——actual——Total1,640,995,200,000386.30
——actual——Total1,643,673,600,000411.70
——actual——Total1,646,092,800,000419
——actual——Total1,648,771,200,000415.60
——actual——Total1,651,363,200,000432.90
——actual——Total1,654,041,600,000430.70
——actual——Total1,656,633,600,000397
——actual——Total1,659,312,000,000375.50
——actual——Total1,661,990,400,000327.70
——actual——Total1,664,582,400,000324.70
——actual——Total1,667,260,800,000324.50
——actual——Total1,669,852,800,000378.40
——actual——Total1,672,531,200,000409.80
——actual——Total1,675,209,600,000437.60
——actual——Total1,677,628,800,000434.30
——actual——Total1,680,307,200,000432
——actual——Total1,682,899,200,000451.70
——actual——Total1,685,577,600,000456.50
——actual——Total1,688,169,600,000419.90
——actual——Total1,690,848,000,000391.70
——actual——Total1,693,526,400,000340
——actual——Total1,696,118,400,000332.10
——actual——Total1,698,796,800,000351.90
——actual——Total1,701,388,800,000405.20
——actual——Total1,704,067,200,000442.60
——actual——Total1,706,745,600,000452.90
——actual——Total1,709,251,200,000472.10
——actual——Total1,711,929,600,000473.70
——actual——Total1,714,521,600,000481.70
——actual——Total1,717,200,000,000468.30
——actual——Total1,719,792,000,000458.20
——actual——Total1,722,470,400,000412.30
——actual——Total1,725,148,800,000368.40
——actual——Total1,727,740,800,000332.80
——actual——Total1,730,419,200,000351.10
——actual——Total1,733,011,200,000430.60
464.43470.31forecast442.19436.30Total1,735,689,600,000453.31
485.83491.72forecast463.59457.70Total1,738,368,000,000474.71
492.68498.57forecast470.43464.54Total1,740,787,200,000481.56
494.17500.06forecast471.91466.02Total1,743,465,600,000483.04
502.94508.83forecast480.68474.78Total1,746,057,600,000491.81
506.42512.32forecast484.15478.25Total1,748,736,000,000495.28
——actual——region=north1,609,459,200,000214
——actual——region=north1,612,137,600,000225.60
——actual——region=north1,614,556,800,000230.30
——actual——region=north1,617,235,200,000233
——actual——region=north1,619,827,200,000226.50
——actual——region=north1,622,505,600,000244.40

First 60 of 432 rows.

Backtest errors of the total by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
15.45212023-12-01
0.652322023-12-01
17.11732023-12-01
17.28442023-12-01
16.25152023-12-01
−6.25062023-12-01
15.72812024-06-01
−4.87022024-06-01
−0.538032024-06-01
−28.54142024-06-01
−22.04052024-06-01
10.56362024-06-01

Backtest accuracy by level — base vs reconciled (2 origins, horizon 6)

LevelSeriesMAE (base)MAE (reconciled)MASE (base)MASE (reconciled)
Total112.97912.9400.65200.6500
region27.0117.0120.66120.6612
store53.7113.7150.64380.6450

Reconciled forecast

SeriesmonthBaseReconciled80% low80% high95% low95% high
Total2025-01-01453.51453.31442.19464.43436.30470.31
Total2025-02-01474.92474.71463.59485.83457.70491.72
Total2025-03-01481.76481.56470.43492.68464.54498.57
Total2025-04-01483.24483.04471.91494.17466.02500.06
Total2025-05-01492.01491.81480.68502.94474.78508.83
Total2025-06-01495.49495.28484.15506.42478.25512.32
region=north2025-01-01263.83263.75254.02273.47248.87278.62
region=north2025-02-01275.41275.33265.60285.05260.45290.20
region=north2025-03-01278.81278.73269.00288.45263.86293.59
region=north2025-04-01279.04278.95269.23288.67264.09293.82
region=north2025-05-01285.98285.90276.18295.62271.03300.76
region=north2025-06-01285.81285.72276.01295.44270.86300.59
region=south2025-01-01189.75189.56183.83195.28180.80198.32
region=south2025-02-01199.57199.38193.64205.13190.60208.17
region=south2025-03-01203.02202.83197.07208.60194.01211.65
region=south2025-04-01204.28204.08198.30209.87195.24212.93
region=south2025-05-01206.10205.91200.11211.72197.03214.79
region=south2025-06-01209.75209.56203.74215.38200.65218.47
region=north / store=N12025-01-01169.13169.08162.13176.03158.46179.71
region=north / store=N12025-02-01172.85172.81165.86179.76162.19183.44
region=north / store=N12025-03-01172.68172.64165.69179.58162.01183.26
region=north / store=N12025-04-01173.53173.49166.54180.43162.87184.11
region=north / store=N12025-05-01181.73181.68174.74188.62171.07192.30
region=north / store=N12025-06-01180.60180.56173.62187.50169.95191.17
region=north / store=N22025-01-0194.61994.66488.254101.0784.861104.47
region=north / store=N22025-02-01102.47102.5296.105108.9392.711112.32
region=north / store=N22025-03-01106.05106.0999.678112.5096.284115.90
region=north / store=N22025-04-01105.42105.4799.053111.8895.658115.27
region=north / store=N22025-05-01104.17104.2297.801110.6394.406114.02
region=north / store=N22025-06-01105.12105.1798.752111.5895.356114.98
region=south / store=S12025-01-0182.96383.07979.61786.54077.78588.372
region=south / store=S12025-02-0188.91389.02985.51792.54183.65894.400
region=south / store=S12025-03-0190.23790.35386.79193.91584.90695.800
region=south / store=S12025-04-0193.91294.02990.41897.64088.50799.551
region=south / store=S12025-05-0193.53793.65489.99597.31388.05899.250
region=south / store=S12025-06-0195.13795.25591.54998.96189.587100.92
region=south / store=S22025-01-0145.27945.35041.97648.72440.19050.510
region=south / store=S22025-02-0144.55644.62641.25348.00039.46749.786
region=south / store=S22025-03-0145.78045.85042.47749.22440.69151.010
region=south / store=S22025-04-0143.73043.80140.42747.17438.64248.960

First 40 of 48 rows.

  • Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.
The exact R script · R R version 4.5.1 (2025-06-13)
# Hierarchical forecast (reconciliation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.hierarchical 1.0.1 · spec 4f5f4c8bf5f828be
# Dataset: l3_stores (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(forecast))

# %% Data
# Hierarchical forecasting (Phase 9, stream L3): base forecasts for every node of the hierarchy
# (total → each level → bottom series), then reconciliation so the forecasts add up. Twins:
# codesplashr::cs_fc_reconcile ↔ codesplash.ml.forecast_adv (hts / fabletools::reconcile are the
# classic equivalents).
TIME <- "month"
VALUE <- "sales"
LEVEL_COLS <- c("region", "store")  # top level first
H <- 6
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL
WINDOWS <- 2
STEP <- NULL
BASE <- "ets"
METHOD <- "mint_shrink"
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/l3_stores.parquet", col_select = unique(c(TIME, VALUE, LEVEL_COLS))))
warnings <- list()
notes <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
keys_df <- as.data.frame(lapply(df[LEVEL_COLS], as.character), stringsAsFactors = FALSE)
ok <- !is.na(times_all) & stats::complete.cases(keys_df)
if (sum(!ok)) warnings <- c(warnings, sprintf("%d rows without a time or a hierarchy value were left out.", sum(!ok)))
missing_values <- sum(is.na(values_all[ok]))
if (missing_values) warnings <- c(warnings, sprintf("%d missing values were counted as zero.", missing_values))
times <- times_all[ok]
vals <- values_all[ok]
vals[is.na(vals)] <- 0
keys <- as.matrix(keys_df[ok, , drop = FALSE])
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.hierarchical/mint_ets_two_levels/out-r")

# %% The hierarchy on one time grid (a missing period of a series counts as zero)
tu <- sort(unique(times))
freq <- cs_ml_fc_detect_frequency(tu, TEMPORAL)
pos_u <- cs_fc_grid_position(tu, freq)
if (any(abs(pos_u - round(pos_u)) > 1e-6)) stop("The time steps are irregular — forecasting needs evenly spaced times")
n <- as.integer(round(pos_u[length(pos_u)])) + 1L
grid_t <- if (n > 1) c(tu[1], cs_ml_fc_future_times(tu[1], freq, n - 1)) else tu[1]
pos <- as.integer(round(pos_u[match(times, tu)])) + 1L
hn <- cs_fc_hierarchy_nodes(keys, LEVEL_COLS)
labels <- hn$labels
depths <- hn$depth
S <- hn$S
bottom <- hn$bottom
bkey <- function(mat) apply(mat, 1, function(r) paste(r, collapse = "\x1f"))
col_of <- match(bkey(keys), bkey(bottom))
Yb <- matrix(0, n, nrow(bottom))
for (i in seq_along(vals)) Yb[pos[i], col_of[i]] <- Yb[pos[i], col_of[i]] + vals[i]
Y <- Yb %*% t(S)  # n x nodes
n_nodes <- length(labels)
m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
ref <- if (95 %in% LEVELS) 95 else if (length(LEVELS)) max(LEVELS) else 95
z_ref <- cs_ml_fc_z(ref)
min_train <- function(m) if (BASE == "ets" && m > 1) 2 * m + 2 else if (BASE == "snaive" && m > 1) m + 2 else 6
if (n < min_train(m) + 1) stop(sprintf("The series have %d periods — too few to forecast (needs more than %d)", n, min_train(m)))

# %% Base models: the model form is chosen once per node on its whole history
choose <- function(y) {
  if (BASE != "ets") return(NULL)
  cands <- cs_ml_fc_ets_candidates(as.numeric(y), m, allow_multiplicative = FALSE)
  if (length(cands) == 1) return(cands[[1]])
  best <- cs_ml_fc_ets_auto(as.numeric(y), m, cands)$fit
  list(error = best$error, trend = best$trend, damped = best$damped, season = best$season)
}
base_forecast <- function(y, spec, h) {
  y <- as.numeric(y)
  if (BASE == "ets") {
    fit <- cs_ml_fc_ets_fit(y, m, spec$error, spec$trend, spec$damped, spec$season)
    f <- cs_ml_fc_ets_forecast(fit, h, ref, seed = SEED)
    fitted <- fit$fitted
    label <- fit$label
    lo <- f$lower[[as.character(ref)]]; hi <- f$upper[[as.character(ref)]]; mean_ <- f$mean
  } else {
    yt <- stats::ts(y, frequency = max(m, 1))
    f <- switch(BASE,
      naive = forecast::naive(yt, h = h, level = ref),
      snaive = forecast::snaive(yt, h = h, level = ref),
      drift = forecast::rwf(yt, h = h, drift = TRUE, level = ref),
      mean = forecast::meanf(yt, h = h, level = ref)
    )
    fitted <- as.numeric(f$fitted)
    label <- c(naive = "Naive", snaive = "Seasonal naive", drift = "Drift", mean = "Mean")[[BASE]]
    lo <- as.numeric(f$lower[, 1]); hi <- as.numeric(f$upper[, 1]); mean_ <- as.numeric(f$mean)
  }
  list(mean = as.numeric(mean_), sd = (hi - lo) / (2 * z_ref), fitted = as.numeric(fitted), label = label)
}
specs <- lapply(seq_len(n_nodes), function(i) choose(Y[, i]))
forecast_all <- function(o, h) {
  bm <- matrix(0, n_nodes, h); bs <- matrix(0, n_nodes, h); res <- matrix(0, o, n_nodes); names_ <- character(n_nodes)
  for (i in seq_len(n_nodes)) {
    b <- base_forecast(Y[seq_len(o), i], specs[[i]], h)
    bm[i, ] <- b$mean; bs[i, ] <- b$sd
    res[, i] <- Y[seq_len(o), i] - b$fitted
    names_[i] <- b$label
  }
  rec <- cs_fc_reconcile(S, METHOD, bm, bs, res, Yb[seq_len(o), , drop = FALSE])
  list(bm = bm, bs = bs, rec = rec, names = names_)
}
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)

# %% Backtests
step <- if (!is.null(STEP)) as.integer(STEP) else H
bt_rows <- list(); bt_base <- list()
n_origins <- 0
for (o in cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))) {
  fa <- tryCatch(forecast_all(o, H), error = function(e) e)
  if (inherits(fa, "error")) {
    warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(grid_t[o], TEMPORAL), conditionMessage(fa)))
    next
  }
  n_origins <- n_origins + 1
  lag <- if (m > 1 && o > m) m else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
  for (i in seq_len(n_nodes)) {
    scale <- cs_ml_fc_mase_scale(Y[seq_len(o), i], m)
    scale2 <- cs_ml_fc_rmsse_scale(Y[seq_len(o), i], m)
    for (k in seq_len(H)) {
      # The columns the host's backtest reader expects (cs-data forecastio.rs), like the shared driver's.
      common <- list(series = labels[i], level = depths[i], origin = cs_ml_fc_format_time(grid_t[o], TEMPORAL),
                     time = cs_ml_fc_format_time(grid_t[o + k], TEMPORAL), h = k, actual = Y[o + k, i], scale = scale,
                     scale2 = scale2, last = Y[o, i], snaive = Y[o - lag + (k - 1) %% lag + 1, i])
      row <- c(common, list(mean = fa$rec$mean[i, k]))
      brow <- c(common, list(mean = fa$bm[i, k]))
      for (level in LEVELS) {
        zq <- cs_ml_fc_z(level)
        row[[paste0("lo_", lv(level))]] <- row$mean - zq * fa$rec$sd[i, k]
        row[[paste0("hi_", lv(level))]] <- row$mean + zq * fa$rec$sd[i, k]
        brow[[paste0("lo_", lv(level))]] <- brow$mean - zq * fa$bs[i, k]
        brow[[paste0("hi_", lv(level))]] <- brow$mean + zq * fa$bs[i, k]
      }
      bt_rows[[length(bt_rows) + 1]] <- row
      bt_base[[length(bt_base) + 1]] <- brow
    }
  }
}

# %% Final forecasts
fa <- forecast_all(n, H)
future <- cs_ml_fc_future_times(grid_t[n], freq, H)
fc_rows <- list()
for (i in seq_len(n_nodes)) {
  for (j in seq_len(n)) {
    fc_rows[[length(fc_rows) + 1]] <- list(series = labels[i], level = depths[i], time = cs_ml_fc_format_time(grid_t[j], TEMPORAL),
                                           t = grid_t[j], kind = "actual", mean = Y[j, i])
  }
  for (k in seq_len(H)) {
    row <- list(series = labels[i], level = depths[i], time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k],
                kind = "forecast", mean = fa$rec$mean[i, k], base = fa$bm[i, k])
    for (level in LEVELS) {
      zq <- cs_ml_fc_z(level)
      row[[paste0("lo_", lv(level))]] <- row$mean - zq * fa$rec$sd[i, k]
      row[[paste0("hi_", lv(level))]] <- row$mean + zq * fa$rec$sd[i, k]
    }
    fc_rows[[length(fc_rows) + 1]] <- row
  }
}
nb <- nrow(bottom)
coherence <- max(abs(S %*% fa$rec$mean[(n_nodes - nb + 1):n_nodes, , drop = FALSE] - fa$rec$mean))

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

# %% Accuracy (reconciled vs base, overall and by level)
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
btb <- if (length(bt_base)) as_frame(bt_base) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
base_acc <- if (nrow(btb)) cs_ml_fc_accuracy(btb, LEVELS) else list()
level_names <- c("Total", LEVEL_COLS)
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
wsum <- function(xs) sum(weights * xs) / sum(weights)
METHOD_LABEL <- c(bottom_up = "bottom-up", top_down = "top-down (average historical proportions)", ols = "OLS",
                  wls_struct = "WLS (structural weights)", wls_var = "WLS (residual variances)", mint_shrink = "MinT (shrinkage)")[[METHOD]]
values <- list(
  n_series = nb, n_nodes = n_nodes, n_levels = length(LEVEL_COLS) + 1, n_obs = n, horizon = H, season = m,
  n_origins = n_origins, fc_check = wsum(forecasts$mean), coherence = coherence,
  model_label = sprintf("%s base forecasts reconciled by %s", fa$names[1], METHOD_LABEL), method_label = METHOD_LABEL,
  freq_label = freq$label, frequency = cs_ml_fc_alias(freq$unit)
)
if (!is.nan(fa$rec$lambda) && METHOD %in% c("mint_shrink", "wls_var")) values$lambda <- fa$rec$lambda
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
for (k in names(base_acc)) values[[sprintf("bt_base[%s]", k)]] <- base_acc[[k]]
by_level <- list()
for (d in seq_along(level_names) - 1L) {
  a <- if (nrow(bt)) cs_ml_fc_accuracy(bt[bt$level == d, , drop = FALSE], numeric(0)) else list()
  b <- if (nrow(btb)) cs_ml_fc_accuracy(btb[btb$level == d, , drop = FALSE], numeric(0)) else list()
  nm <- level_names[d + 1]
  by_level[[length(by_level) + 1]] <- list(level = nm, nodes = sum(depths == d), mae_base = b$mae, mae = a$mae, mase_base = b$mase, mase = a$mase)
  if (!is.null(a$mase)) values[[sprintf("bt_level[mase][%s]", nm)]] <- a$mase
}

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 <- utils::head(labels, 8)
fan <- fc_df[fc_df$series %in% shown, , 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")),
  series = cs_col("series", fan$series, kind = "categorical", levels = shown)
)
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")
  }
}
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Reconciled forecasts of %s", VALUE), roles)
if (nrow(bt)) {
  errs <- bt[bt$level == 0, , drop = FALSE]
  charts[[2]] <- cs_chart("backtest", "backtest-errors", "Backtest errors of the total by horizon", list(
    h = cs_col("horizon", errs$h, kind = "numeric"),
    error = cs_col("error", errs$actual - errs$mean, kind = "numeric"),
    origin = cs_col("origin", errs$origin, kind = "categorical")
  ))
}

# %% Result
tables <- list()
if (nrow(bt)) {
  tables[[1]] <- list(
    key = "levels",
    title = sprintf("Backtest accuracy by level — base vs reconciled (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
    columns = list(list(key = "level", label = "Level"), list(key = "nodes", label = "Series", type = "number"),
                   list(key = "mae_base", label = "MAE (base)", type = "number"), list(key = "mae", label = "MAE (reconciled)", type = "number"),
                   list(key = "mase_base", label = "MASE (base)", type = "number"), list(key = "mase", label = "MASE (reconciled)", type = "number")),
    rows = by_level
  )
}
fc_cols <- list(list(key = "series", label = "Series"), list(key = "time", label = TIME), list(key = "base", label = "Base", type = "number"),
                list(key = "mean", label = "Reconciled", 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")))
}
keep <- setdiff(names(forecasts), c("t", "kind", "level"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Reconciled forecast", columns = fc_cols,
  rows = lapply(seq_len(min(300, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
notes <- c(notes, "Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.")
summary <- sprintf("%s: %d-step forecasts of %s for %d series (%d at the bottom, %s data, %d periods).", values$model_label, H, VALUE, n_nodes, nb, freq$label, n)
if (!is.null(accuracy$mase) && !is.null(base_acc$mase)) {
  summary <- paste0(summary, sprintf(" Backtest MASE %s reconciled vs %s base.", format(signif(accuracy$mase, 3)), format(signif(base_acc$mase, 3))))
}
cs_publish(list(
  title = "Hierarchical forecast (reconciliation)",
  engine = cs_engine_info("forecast", "nanoparquet"),
  n = length(times),
  summary = summary,
  statistics = lapply(intersect(c("mae", "rmse", "mase"), names(accuracy)), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
  tables = tables,
  values = values,
  warnings = warnings,
  notes = notes,
  charts = charts,
  artifacts = artifacts
))
Python

ETS(A,A,A) base forecasts reconciled by MinT (shrinkage): 6-step forecasts of sales for 8 series (5 at the bottom, monthly data, 48 periods). Backtest MASE 0.65 reconciled vs 0.649 base.

MAE
5.692
RMSE
8.533
MASE
0.6497

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

Backtest accuracy by level — base vs reconciled (2 origins, horizon 6)

LevelSeriesMAE (base)MAE (reconciled)MASE (base)MASE (reconciled)
Total112.97912.9400.65200.6500
region27.0117.0120.66120.6612
store53.7113.7150.64380.6450

Reconciled forecast

SeriesmonthBaseReconciled80% low80% high95% low95% high
Total2025-01-01453.51453.31442.19464.43436.30470.31
Total2025-02-01474.92474.71463.59485.83457.70491.72
Total2025-03-01481.76481.56470.43492.68464.54498.57
Total2025-04-01483.24483.04471.91494.17466.02500.06
Total2025-05-01492.01491.81480.68502.94474.78508.83
Total2025-06-01495.49495.28484.15506.42478.25512.32
region=north2025-01-01263.83263.75254.02273.47248.87278.62
region=north2025-02-01275.41275.33265.60285.05260.45290.20
region=north2025-03-01278.81278.73269.00288.45263.86293.59
region=north2025-04-01279.04278.95269.23288.67264.09293.82
region=north2025-05-01285.98285.90276.18295.62271.03300.76
region=north2025-06-01285.81285.72276.01295.44270.86300.59
region=south2025-01-01189.75189.56183.83195.28180.80198.32
region=south2025-02-01199.57199.38193.64205.13190.60208.17
region=south2025-03-01203.02202.83197.07208.60194.01211.65
region=south2025-04-01204.28204.08198.30209.87195.24212.93
region=south2025-05-01206.10205.91200.11211.72197.03214.79
region=south2025-06-01209.75209.56203.74215.38200.65218.47
region=north / store=N12025-01-01169.13169.08162.13176.03158.46179.71
region=north / store=N12025-02-01172.85172.81165.86179.76162.19183.44
region=north / store=N12025-03-01172.68172.64165.69179.58162.01183.26
region=north / store=N12025-04-01173.53173.49166.54180.43162.87184.11
region=north / store=N12025-05-01181.73181.68174.74188.62171.07192.30
region=north / store=N12025-06-01180.60180.56173.62187.50169.95191.17
region=north / store=N22025-01-0194.61994.66488.254101.0784.861104.47
region=north / store=N22025-02-01102.47102.5296.105108.9392.711112.32
region=north / store=N22025-03-01106.05106.0999.678112.5096.284115.90
region=north / store=N22025-04-01105.42105.4799.053111.8895.658115.27
region=north / store=N22025-05-01104.17104.2297.801110.6394.406114.02
region=north / store=N22025-06-01105.12105.1798.752111.5895.356114.98
region=south / store=S12025-01-0182.96383.07979.61786.54077.78588.372
region=south / store=S12025-02-0188.91389.02985.51792.54183.65894.400
region=south / store=S12025-03-0190.23790.35386.79193.91584.90695.800
region=south / store=S12025-04-0193.91294.02990.41897.64088.50799.551
region=south / store=S12025-05-0193.53793.65489.99597.31388.05899.250
region=south / store=S12025-06-0195.13795.25591.54998.96189.587100.92
region=south / store=S22025-01-0145.27945.35041.97648.72440.19050.510
region=south / store=S22025-02-0144.55644.62641.25348.00039.46749.786
region=south / store=S22025-03-0145.78045.85042.47749.22440.69151.010
region=south / store=S22025-04-0143.73043.80140.42747.17438.64248.960

First 40 of 48 rows.

  • Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hierarchical forecast (reconciliation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.hierarchical 1.0.1 · spec 4f5f4c8bf5f828be
# Dataset: l3_stores (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_adv as fca

# %% Data
# Hierarchical forecasting (Phase 9, stream L3): base forecasts for every node of the hierarchy
# (total → each level → bottom series), then reconciliation so the forecasts add up. Twins:
# codesplash.ml.forecast_adv ↔ codesplashr::cs_fc_reconcile (hts / fabletools::reconcile are the
# classic equivalents).
TIME = "month"
VALUE = "sales"
LEVEL_COLS = ["region", "store"]  # top level first
H = 6
LEVELS = [float(v) for v in [80, 95]]
SEASON = None
WINDOWS = 2
STEP = None
BASE = "ets"
METHOD = "mint_shrink"
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/l3_stores.parquet", columns=list(dict.fromkeys([TIME, VALUE] + LEVEL_COLS)))
warnings = []
notes = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
keys_df = df[LEVEL_COLS].astype("object")
ok = ~np.isnan(times_all) & keys_df.notna().all(axis=1).to_numpy()
if (~ok).sum():
    warnings.append(f"{int((~ok).sum())} rows without a time or a hierarchy value were left out.")
missing_values = int(np.isnan(values_all[ok]).sum())
if missing_values:
    warnings.append(f"{missing_values} missing values were counted as zero.")
times = times_all[ok]
vals = np.nan_to_num(values_all[ok], nan=0.0)
keys = [tuple(str(v) for v in row) for row in keys_df.to_numpy()[ok]]
out = csml.out_dir("target/academy-parity/run-8142/forecast.hierarchical/mint_ets_two_levels/out-python")

# %% The hierarchy on one time grid (a missing period of a series counts as zero)
tu = np.unique(times)
freq = fc.detect_frequency(tu, TEMPORAL)
pos_u = fc.grid_position(tu, freq)
if np.any(np.abs(pos_u - np.round(pos_u)) > 1e-6):
    raise ValueError("The time steps are irregular — forecasting needs evenly spaced times")
n = int(round(pos_u[-1])) + 1
grid_t = np.concatenate([[tu[0]], fc.future_times(tu[0], freq, n - 1)]) if n > 1 else np.array([tu[0]])
pos_of = {float(t): int(round(p)) for t, p in zip(tu, pos_u)}
labels, depths, S = fca.hierarchy_nodes(keys, LEVEL_COLS)
bottom = sorted(set(keys))
col_of = {b: j for j, b in enumerate(bottom)}
Yb = np.zeros((n, len(bottom)))
for t, k, v in zip(times, keys, vals):
    Yb[pos_of[float(t)], col_of[k]] += v
Y = Yb @ S.T  # n × nodes
n_nodes = len(labels)
m = int(SEASON) if SEASON else int(freq["season"])
ref = 95.0 if 95.0 in LEVELS else (max(LEVELS) if LEVELS else 95.0)
z_ref = fc.z_value(ref)


def min_train(m):
    return 2 * m + 2 if (BASE == "ets" and m > 1) else (m + 2 if BASE == "snaive" and m > 1 else 6)


if n < min_train(m) + 1:
    raise ValueError(f"The series have {n} periods — too few to forecast (needs more than {min_train(m)})")


# %% Base models: the model form is chosen once per node on its whole history
def choose(y):
    if BASE != "ets":
        return None
    cands = fc.ets_candidates(list(y), m, allow_multiplicative=False)
    if len(cands) == 1:
        return cands[0]
    best, _ = fc.ets_auto(list(y), m, cands)
    return (best["error"], best["trend"], best["damped"], best["season"])


def base_forecast(y, spec, h):
    """Mean, standard error and one-step fitted values of one node's base forecast."""
    y = [float(v) for v in y]
    if BASE == "ets":
        fit = fc.ets_fit(y, m, *spec)
        f = fc.ets_forecast(fit, h, [ref], seed=SEED)
        fitted = fit["fitted"]
        label = fit["label"]
    else:
        f = fc.baseline(y, BASE, m, h, [ref])
        fitted = f["fitted"]
        label = {"naive": "Naive", "snaive": "Seasonal naive", "drift": "Drift", "mean": "Mean"}[BASE]
    mean = np.array(f["mean"], dtype=float)
    sd = (np.array(f["upper"][ref]) - np.array(f["lower"][ref])) / (2.0 * z_ref)
    return mean, sd, np.array([float("nan") if v is None else float(v) for v in fitted]), label


specs = [choose(Y[:, i]) for i in range(n_nodes)]


def forecast_all(o, h):
    """Base and reconciled forecasts from the first `o` periods."""
    bm = np.empty((n_nodes, h))
    bs = np.empty((n_nodes, h))
    res = np.empty((o, n_nodes))
    names = []
    for i in range(n_nodes):
        mean, sd, fitted, label = base_forecast(Y[:o, i], specs[i], h)
        bm[i], bs[i] = mean, sd
        res[:, i] = Y[:o, i] - fitted
        names.append(label)
    rec = fca.reconcile(S, METHOD, bm, bs, res, Yb[:o])
    return bm, bs, rec, names


def lv(level):
    return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")


# %% Backtests
step = int(STEP) if STEP else H
bt_rows, bt_base = [], []
n_origins = 0
for o in fc.backtest_origins(n, H, WINDOWS, step, min_train(m)):
    try:
        bm, bs, rec, _ = forecast_all(o, H)
    except Exception as e:  # a failed origin is skipped, not fatal
        warnings.append(f"Backtest from {fc.format_time(grid_t[o - 1], TEMPORAL)} failed: {e}")
        continue
    n_origins += 1
    lag = m if (m > 1 and o > m) else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
    for i in range(n_nodes):
        scale = fc.mase_scale(list(Y[:o, i]), m)
        scale2 = fc.rmsse_scale(list(Y[:o, i]), m)
        for k in range(H):
            # The columns the host's backtest reader expects (cs-data forecastio.rs), like the shared driver's.
            common = {
                "series": labels[i],
                "level": depths[i],
                "origin": fc.format_time(grid_t[o - 1], TEMPORAL),
                "time": fc.format_time(grid_t[o + k], TEMPORAL),
                "h": k + 1,
                "actual": float(Y[o + k, i]),
                "scale": scale,
                "scale2": scale2,
                "last": float(Y[o - 1, i]),
                "snaive": float(Y[o - lag + k % lag, i]),
            }
            row = {**common, "mean": float(rec["mean"][i, k])}
            brow = {**common, "mean": float(bm[i, k])}
            for level in LEVELS:
                zq = fc.z_value(level)
                row[f"lo_{lv(level)}"] = row["mean"] - zq * float(rec["sd"][i, k])
                row[f"hi_{lv(level)}"] = row["mean"] + zq * float(rec["sd"][i, k])
                brow[f"lo_{lv(level)}"] = brow["mean"] - zq * float(bs[i, k])
                brow[f"hi_{lv(level)}"] = brow["mean"] + zq * float(bs[i, k])
            bt_rows.append(row)
            bt_base.append(brow)

# %% Final forecasts
bm, bs, rec, base_labels = forecast_all(n, H)
future = fc.future_times(grid_t[-1], freq, H)
fc_rows = []
for i in range(n_nodes):
    for j in range(n):
        fc_rows.append({"series": labels[i], "level": depths[i], "time": fc.format_time(grid_t[j], TEMPORAL), "t": float(grid_t[j]), "kind": "actual", "mean": float(Y[j, i])})
    for k in range(H):
        row = {"series": labels[i], "level": depths[i], "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(rec["mean"][i, k]), "base": float(bm[i, k])}
        for level in LEVELS:
            zq = fc.z_value(level)
            row[f"lo_{lv(level)}"] = row["mean"] - zq * float(rec["sd"][i, k])
            row[f"hi_{lv(level)}"] = row["mean"] + zq * float(rec["sd"][i, k])
        fc_rows.append(row)
coherence = float(np.max(np.abs(S @ rec["mean"][n_nodes - len(bottom) :] - rec["mean"])))

# %% Accuracy (reconciled vs base, overall and by level)
accuracy = fc.accuracy(bt_rows, LEVELS)
base_acc = fc.accuracy(bt_base, LEVELS)
level_names = ["Total"] + LEVEL_COLS
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]


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


METHOD_LABEL = {
    "bottom_up": "bottom-up",
    "top_down": "top-down (average historical proportions)",
    "ols": "OLS",
    "wls_struct": "WLS (structural weights)",
    "wls_var": "WLS (residual variances)",
    "mint_shrink": "MinT (shrinkage)",
}[METHOD]
values = {
    "n_series": len(bottom),
    "n_nodes": n_nodes,
    "n_levels": len(LEVEL_COLS) + 1,
    "n_obs": n,
    "horizon": H,
    "season": m,
    "n_origins": n_origins,
    "fc_check": wsum([r["mean"] for r in forecasts]),
    "coherence": coherence,
    "model_label": f"{base_labels[0]} base forecasts reconciled by {METHOD_LABEL}",
    "method_label": METHOD_LABEL,
    "freq_label": freq["label"],
    "frequency": fc.ALIASES.get(freq["unit"], ""),
}
if rec["lambda"] == rec["lambda"] and METHOD in ("mint_shrink", "wls_var"):
    values["lambda"] = rec["lambda"]
for k, v in accuracy.items():
    values[f"bt[{k}]"] = v
for k, v in base_acc.items():
    values[f"bt_base[{k}]"] = v
by_level = []
for d, name in enumerate(level_names):
    rr = [r for r in bt_rows if r["level"] == d]
    bb = [r for r in bt_base if r["level"] == d]
    a, b = fc.accuracy(rr, []), fc.accuracy(bb, [])
    by_level.append({"level": name, "nodes": int(sum(1 for x in depths if x == d)), "mae_base": b.get("mae"), "mae": a.get("mae"), "mase_base": b.get("mase"), "mase": a.get("mase")})
    if a.get("mase") is not None:
        values[f"bt_level[mase][{name}]"] = a["mase"]

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 = labels[: min(n_nodes, 8)]
fan = [r for r in fc_rows if r["series"] in shown]
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"]),
    "series": cs.col("series", [r["series"] for r in fan], kind="categorical", levels=shown),
}
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")
charts.append(cs.chart("forecast", "forecast-fan", f"Reconciled forecasts of {VALUE}", roles))
if bt_rows:
    errs = [r for r in bt_rows if r["level"] == 0]
    charts.append(
        cs.chart(
            "backtest",
            "backtest-errors",
            "Backtest errors of the total by horizon",
            {
                "h": cs.col("horizon", [r["h"] for r in errs], kind="numeric"),
                "error": cs.col("error", [r["actual"] - r["mean"] for r in errs], kind="numeric"),
                "origin": cs.col("origin", [r["origin"] for r in errs], kind="categorical"),
            },
        )
    )

# %% Result
tables = []
if bt_rows:
    tables.append(
        {
            "key": "levels",
            "title": f"Backtest accuracy by level — base vs reconciled ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
            "columns": [
                {"key": "level", "label": "Level"},
                {"key": "nodes", "label": "Series", "type": "number"},
                {"key": "mae_base", "label": "MAE (base)", "type": "number"},
                {"key": "mae", "label": "MAE (reconciled)", "type": "number"},
                {"key": "mase_base", "label": "MASE (base)", "type": "number"},
                {"key": "mase", "label": "MASE (reconciled)", "type": "number"},
            ],
            "rows": by_level,
        }
    )
tables.append(
    {
        "key": "forecast",
        "title": "Reconciled forecast",
        "columns": [{"key": "series", "label": "Series"}, {"key": "time", "label": TIME}, {"key": "base", "label": "Base", "type": "number"}, {"key": "mean", "label": "Reconciled", "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", "level")} for r in forecasts[:300]],
    }
)
notes.append("Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.")
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} for {n_nodes} series ({len(bottom)} at the bottom, {freq['label']} data, {n} periods)."
if "mase" in accuracy and "mase" in base_acc:
    summary += f" Backtest MASE {accuracy['mase']:.3g} reconciled vs {base_acc['mase']:.3g} base."
cs.publish(
    {
        "title": "Hierarchical forecast (reconciliation)",
        "engine": cs.engine_info("numpy", "pandas"),
        "n": int(len(times)),
        "summary": summary,
        "statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in ("mae", "rmse", "mase") if k in accuracy],
        "tables": tables,
        "values": values,
        "warnings": warnings,
        "notes": notes,
        "charts": charts,
        "artifacts": artifacts,
    }
)

The result records coherence: how far forecasts are from adding up. It's essentially zero here, 0.000.

Open Backtest accuracy by level, which compares base and reconciled scores. Reconciling can improve accuracy, but it doesn't have to: with top-down on drift forecasts, the reconciled scores come out worse. Check each level you care about.

08

Check your understanding

Checkpoint

Check yourself

Smoothed demand size is 10 and the smoothed interval is 5 periods. What is Croston's forecast per period?

Show the answer

Answer: 2

10/5=210 / 5 = 2.

Check yourself

A part is being phased out, so demand has stopped. Which method responds best?

Show the answer

Answer: c

TSB smooths the probability of demand every period, so it falls during the gap. Croston only updates when demand happens.

Check yourself

Why can MAE mislead on intermittent demand?

Show the answer

Answer: a

MAE targets the median. If most periods are zero, so is the best MAE forecast.

Check yourself

A hierarchy has 5 stores in 2 regions, and a total. How many nodes does it have?

Show the answer

Answer: 8

5+2+1=85 + 2 + 1 = 8.

Check yourself

What does coherent mean here?

Show the answer

Answer: b

Coherence is about adding up, not accuracy. You can have coherent bad forecasts.

Check yourself

Why is shrinkage used in MinT?

Show the answer

Answer: b

Shrinkage trades a little bias for a much more stable estimate.

09

Do it in CodeSplash

In the app

In Forecast, choose Intermittent demand (Croston, SBA, TSB, ADIDA) or Hierarchical forecast (reconciliation). Hierarchy levels takes columns from the top down.

Python
import numpy as np

def croston(y, alpha=0.1):
    """Size over interval, updated only when demand occurs."""
    y = np.asarray(y, float)
    idx = np.flatnonzero(y)
    z, p, gap = y[idx[0]], max(idx[0] + 1, 1), 1
    for v in y[idx[0] + 1:]:
        if v > 0:
            z += alpha * (v - z)
            p += alpha * (gap - p)
            gap = 1
        else:
            gap += 1
    return z / p
R
# install.packages("tsintermittent")
tsintermittent::crost(read.csv("demand.csv")$demand, h = 12, type = "sba")$frc.out
10

Recap

Recap
  • Croston-type methods forecast a rate, using size and gap. TSB handles obsolescence.
  • Classify with ADI and CV², and beware of MAE on mostly-zero series.
  • Reconciliation makes levels add up. Its gain in accuracy isn't guaranteed.
  • Check each level you actually use.

Concepts in this lesson