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.
What runs in CodeSplash
- Intermittent demand (Croston, SBA, TSB, ADIDA) Verified in Python and R
- Hierarchical forecast (reconciliation) Verified in Python and R
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
Mostly zeros
ReadA 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:
Here, the smoothed size is 5.12 and the smoothed interval is 3.94.
Classify first
PredictPredict first
Syntetos and Boylan's scheme uses two numbers: ADI, the average gap between demands, cut at , and CV², the squared variation of demand sizes, cut at .
A part has ADI = 3.43 and CV² = 0.10. How do you classify it?
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.
The variants
In the appCroston: 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
View data
| kind | month | demand |
|---|---|---|
| actual | 1,546,300,800,000 | 0 |
| actual | 1,548,979,200,000 | 0 |
| actual | 1,551,398,400,000 | 0 |
| actual | 1,554,076,800,000 | 5 |
| actual | 1,556,668,800,000 | 0 |
| actual | 1,559,347,200,000 | 5 |
| actual | 1,561,939,200,000 | 0 |
| actual | 1,564,617,600,000 | 6 |
| actual | 1,567,296,000,000 | 3 |
| actual | 1,569,888,000,000 | 0 |
| actual | 1,572,566,400,000 | 0 |
| actual | 1,575,158,400,000 | 0 |
| actual | 1,577,836,800,000 | 7 |
| actual | 1,580,515,200,000 | 0 |
| actual | 1,583,020,800,000 | 0 |
| actual | 1,585,699,200,000 | 0 |
| actual | 1,588,291,200,000 | 8 |
| actual | 1,590,969,600,000 | 0 |
| actual | 1,593,561,600,000 | 3 |
| actual | 1,596,240,000,000 | 6 |
| actual | 1,598,918,400,000 | 0 |
| actual | 1,601,510,400,000 | 0 |
| actual | 1,604,188,800,000 | 0 |
| actual | 1,606,780,800,000 | 0 |
| actual | 1,609,459,200,000 | 0 |
| actual | 1,612,137,600,000 | 0 |
| actual | 1,614,556,800,000 | 0 |
| actual | 1,617,235,200,000 | 0 |
| actual | 1,619,827,200,000 | 0 |
| actual | 1,622,505,600,000 | 7 |
| actual | 1,625,097,600,000 | 0 |
| actual | 1,627,776,000,000 | 4 |
| actual | 1,630,454,400,000 | 0 |
| actual | 1,633,046,400,000 | 6 |
| actual | 1,635,724,800,000 | 0 |
| actual | 1,638,316,800,000 | 0 |
| actual | 1,640,995,200,000 | 5 |
| actual | 1,643,673,600,000 | 0 |
| actual | 1,646,092,800,000 | 8 |
| actual | 1,648,771,200,000 | 4 |
| actual | 1,651,363,200,000 | 0 |
| actual | 1,654,041,600,000 | 5 |
| actual | 1,656,633,600,000 | 0 |
| actual | 1,659,312,000,000 | 0 |
| actual | 1,661,990,400,000 | 0 |
| actual | 1,664,582,400,000 | 0 |
| actual | 1,667,260,800,000 | 0 |
| actual | 1,669,852,800,000 | 0 |
| actual | 1,672,531,200,000 | 0 |
| actual | 1,675,209,600,000 | 0 |
| actual | 1,677,628,800,000 | 4 |
| actual | 1,680,307,200,000 | 5 |
| actual | 1,682,899,200,000 | 0 |
| actual | 1,685,577,600,000 | 0 |
| actual | 1,688,169,600,000 | 0 |
| actual | 1,690,848,000,000 | 2 |
| actual | 1,693,526,400,000 | 0 |
| actual | 1,696,118,400,000 | 0 |
| actual | 1,698,796,800,000 | 0 |
| actual | 1,701,388,800,000 | 8 |
First 60 of 84 rows.
View data
| error | horizon | origin |
|---|---|---|
| −2.025 | 1 | 2022-12-01 |
| −2.025 | 2 | 2022-12-01 |
| 1.975 | 3 | 2022-12-01 |
| 2.975 | 4 | 2022-12-01 |
| −2.025 | 5 | 2022-12-01 |
| −2.025 | 6 | 2022-12-01 |
| −2.025 | 7 | 2022-12-01 |
| −0.0250 | 8 | 2022-12-01 |
| −2.025 | 9 | 2022-12-01 |
| −2.025 | 10 | 2022-12-01 |
| −2.025 | 11 | 2022-12-01 |
| 5.975 | 12 | 2022-12-01 |
| −1.508 | 1 | 2023-12-01 |
| 4.492 | 2 | 2023-12-01 |
| −1.508 | 3 | 2023-12-01 |
| −1.508 | 4 | 2023-12-01 |
| −1.508 | 5 | 2023-12-01 |
| −1.508 | 6 | 2023-12-01 |
| −1.508 | 7 | 2023-12-01 |
| −1.508 | 8 | 2023-12-01 |
| −1.508 | 9 | 2023-12-01 |
| 2.492 | 10 | 2023-12-01 |
| −1.508 | 11 | 2023-12-01 |
| −1.508 | 12 | 2023-12-01 |
View data
| ACF | bound | lag |
|---|---|---|
| −0.1359 | 0.2377 | 1 |
| 0.1338 | 0.2377 | 2 |
| 0.0073 | 0.2377 | 3 |
| −0.0139 | 0.2377 | 4 |
| −0.0152 | 0.2377 | 5 |
| −0.2058 | 0.2377 | 6 |
| −0.0317 | 0.2377 | 7 |
| −0.0572 | 0.2377 | 8 |
| −0.0131 | 0.2377 | 9 |
| 0.0502 | 0.2377 | 10 |
| −0.0396 | 0.2377 | 11 |
| −0.0160 | 0.2377 | 12 |
| −0.0231 | 0.2377 | 13 |
| −0.0596 | 0.2377 | 14 |
| −0.1118 | 0.2377 | 15 |
| −0.2459 | 0.2377 | 16 |
| 0.0972 | 0.2377 | 17 |
| −0.0198 | 0.2377 | 18 |
| 0.0028 | 0.2377 | 19 |
| 0.1192 | 0.2377 | 20 |
| 0.1150 | 0.2377 | 21 |
| 0.2124 | 0.2377 | 22 |
| 0.0830 | 0.2377 | 23 |
| −0.0217 | 0.2377 | 24 |
Backtest accuracy (2 origins, horizon 12)
| Metric | Value |
|---|---|
| MAE | 2.051 |
| RMSE | 2.331 |
| sMAPE | 1.700 |
| MASE | 0.8119 |
| WAPE | 1.697 |
| Coverage of the 90% interval | 0.9583 |
Forecast
| month | Forecast | 90% low | 90% high |
|---|---|---|---|
| 2025-01-01 | 1.298 | 0 | 5.643 |
| 2025-02-01 | 1.298 | 0 | 5.643 |
| 2025-03-01 | 1.298 | 0 | 5.643 |
| 2025-04-01 | 1.298 | 0 | 5.643 |
| 2025-05-01 | 1.298 | 0 | 5.643 |
| 2025-06-01 | 1.298 | 0 | 5.643 |
| 2025-07-01 | 1.298 | 0 | 5.643 |
| 2025-08-01 | 1.298 | 0 | 5.643 |
| 2025-09-01 | 1.298 | 0 | 5.643 |
| 2025-10-01 | 1.298 | 0 | 5.643 |
| 2025-11-01 | 1.298 | 0 | 5.643 |
| 2025-12-01 | 1.298 | 0 | 5.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
))
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)
| Metric | Value |
|---|---|
| MAE | 2.051 |
| RMSE | 2.331 |
| sMAPE | 1.700 |
| MASE | 0.8119 |
| WAPE | 1.697 |
| Coverage of the 90% interval | 0.9583 |
Forecast
| month | Forecast | 90% low | 90% high |
|---|---|---|---|
| 2025-01-01 | 1.298 | 0 | 5.643 |
| 2025-02-01 | 1.298 | 0 | 5.643 |
| 2025-03-01 | 1.298 | 0 | 5.643 |
| 2025-04-01 | 1.298 | 0 | 5.643 |
| 2025-05-01 | 1.298 | 0 | 5.643 |
| 2025-06-01 | 1.298 | 0 | 5.643 |
| 2025-07-01 | 1.298 | 0 | 5.643 |
| 2025-08-01 | 1.298 | 0 | 5.643 |
| 2025-09-01 | 1.298 | 0 | 5.643 |
| 2025-10-01 | 1.298 | 0 | 5.643 |
| 2025-11-01 | 1.298 | 0 | 5.643 |
| 2025-12-01 | 1.298 | 0 | 5.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,
}
)
| Method | Idea |
|---|---|
| Croston | Size / interval, which is known to run high |
| SBA | Croston with a bias correction, the default |
| SBJ | A different correction |
| TSB | Smooths the probability of demand, so it can fall to zero for an obsolete part |
| ADIDA | Adds 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?
Scoring zeros
PredictPredict first
A part sells 1 unit in 1 month out of 5. You compare forecasting 0 with forecasting the true rate of per month, using MAE.
Which scores better?
Reveal
Forecasting zero wins: MAE is for zero, and 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.
Forecasts that add up
ReadA 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:
encodes the hierarchy, and decides how to map the base forecasts to the bottom level.
Four routes
Reflect| Reconciliation | Idea |
|---|---|
| Bottom-up | Forecast the bottom level, then add up |
| Top-down | Forecast the total, then split by historical proportions |
| OLS, WLS | Adjust all levels using a simple weighting |
| MinT with shrinkage | Weight 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?
Is it better?
In the appETS(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
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | series | month | sales |
|---|---|---|---|---|---|---|---|
| — | — | actual | — | — | Total | 1,609,459,200,000 | 371.10 |
| — | — | actual | — | — | Total | 1,612,137,600,000 | 393.20 |
| — | — | actual | — | — | Total | 1,614,556,800,000 | 397.40 |
| — | — | actual | — | — | Total | 1,617,235,200,000 | 407.40 |
| — | — | actual | — | — | Total | 1,619,827,200,000 | 397.50 |
| — | — | actual | — | — | Total | 1,622,505,600,000 | 422.20 |
| — | — | actual | — | — | Total | 1,625,097,600,000 | 383.50 |
| — | — | actual | — | — | Total | 1,627,776,000,000 | 357.30 |
| — | — | actual | — | — | Total | 1,630,454,400,000 | 312.10 |
| — | — | actual | — | — | Total | 1,633,046,400,000 | 300.20 |
| — | — | actual | — | — | Total | 1,635,724,800,000 | 316 |
| — | — | actual | — | — | Total | 1,638,316,800,000 | 349.50 |
| — | — | actual | — | — | Total | 1,640,995,200,000 | 386.30 |
| — | — | actual | — | — | Total | 1,643,673,600,000 | 411.70 |
| — | — | actual | — | — | Total | 1,646,092,800,000 | 419 |
| — | — | actual | — | — | Total | 1,648,771,200,000 | 415.60 |
| — | — | actual | — | — | Total | 1,651,363,200,000 | 432.90 |
| — | — | actual | — | — | Total | 1,654,041,600,000 | 430.70 |
| — | — | actual | — | — | Total | 1,656,633,600,000 | 397 |
| — | — | actual | — | — | Total | 1,659,312,000,000 | 375.50 |
| — | — | actual | — | — | Total | 1,661,990,400,000 | 327.70 |
| — | — | actual | — | — | Total | 1,664,582,400,000 | 324.70 |
| — | — | actual | — | — | Total | 1,667,260,800,000 | 324.50 |
| — | — | actual | — | — | Total | 1,669,852,800,000 | 378.40 |
| — | — | actual | — | — | Total | 1,672,531,200,000 | 409.80 |
| — | — | actual | — | — | Total | 1,675,209,600,000 | 437.60 |
| — | — | actual | — | — | Total | 1,677,628,800,000 | 434.30 |
| — | — | actual | — | — | Total | 1,680,307,200,000 | 432 |
| — | — | actual | — | — | Total | 1,682,899,200,000 | 451.70 |
| — | — | actual | — | — | Total | 1,685,577,600,000 | 456.50 |
| — | — | actual | — | — | Total | 1,688,169,600,000 | 419.90 |
| — | — | actual | — | — | Total | 1,690,848,000,000 | 391.70 |
| — | — | actual | — | — | Total | 1,693,526,400,000 | 340 |
| — | — | actual | — | — | Total | 1,696,118,400,000 | 332.10 |
| — | — | actual | — | — | Total | 1,698,796,800,000 | 351.90 |
| — | — | actual | — | — | Total | 1,701,388,800,000 | 405.20 |
| — | — | actual | — | — | Total | 1,704,067,200,000 | 442.60 |
| — | — | actual | — | — | Total | 1,706,745,600,000 | 452.90 |
| — | — | actual | — | — | Total | 1,709,251,200,000 | 472.10 |
| — | — | actual | — | — | Total | 1,711,929,600,000 | 473.70 |
| — | — | actual | — | — | Total | 1,714,521,600,000 | 481.70 |
| — | — | actual | — | — | Total | 1,717,200,000,000 | 468.30 |
| — | — | actual | — | — | Total | 1,719,792,000,000 | 458.20 |
| — | — | actual | — | — | Total | 1,722,470,400,000 | 412.30 |
| — | — | actual | — | — | Total | 1,725,148,800,000 | 368.40 |
| — | — | actual | — | — | Total | 1,727,740,800,000 | 332.80 |
| — | — | actual | — | — | Total | 1,730,419,200,000 | 351.10 |
| — | — | actual | — | — | Total | 1,733,011,200,000 | 430.60 |
| 464.43 | 470.31 | forecast | 442.19 | 436.30 | Total | 1,735,689,600,000 | 453.31 |
| 485.83 | 491.72 | forecast | 463.59 | 457.70 | Total | 1,738,368,000,000 | 474.71 |
| 492.68 | 498.57 | forecast | 470.43 | 464.54 | Total | 1,740,787,200,000 | 481.56 |
| 494.17 | 500.06 | forecast | 471.91 | 466.02 | Total | 1,743,465,600,000 | 483.04 |
| 502.94 | 508.83 | forecast | 480.68 | 474.78 | Total | 1,746,057,600,000 | 491.81 |
| 506.42 | 512.32 | forecast | 484.15 | 478.25 | Total | 1,748,736,000,000 | 495.28 |
| — | — | actual | — | — | region=north | 1,609,459,200,000 | 214 |
| — | — | actual | — | — | region=north | 1,612,137,600,000 | 225.60 |
| — | — | actual | — | — | region=north | 1,614,556,800,000 | 230.30 |
| — | — | actual | — | — | region=north | 1,617,235,200,000 | 233 |
| — | — | actual | — | — | region=north | 1,619,827,200,000 | 226.50 |
| — | — | actual | — | — | region=north | 1,622,505,600,000 | 244.40 |
First 60 of 432 rows.
View data
| error | horizon | origin |
|---|---|---|
| 15.452 | 1 | 2023-12-01 |
| 0.6523 | 2 | 2023-12-01 |
| 17.117 | 3 | 2023-12-01 |
| 17.284 | 4 | 2023-12-01 |
| 16.251 | 5 | 2023-12-01 |
| −6.250 | 6 | 2023-12-01 |
| 15.728 | 1 | 2024-06-01 |
| −4.870 | 2 | 2024-06-01 |
| −0.5380 | 3 | 2024-06-01 |
| −28.541 | 4 | 2024-06-01 |
| −22.040 | 5 | 2024-06-01 |
| 10.563 | 6 | 2024-06-01 |
Backtest accuracy by level — base vs reconciled (2 origins, horizon 6)
| Level | Series | MAE (base) | MAE (reconciled) | MASE (base) | MASE (reconciled) |
|---|---|---|---|---|---|
| Total | 1 | 12.979 | 12.940 | 0.6520 | 0.6500 |
| region | 2 | 7.011 | 7.012 | 0.6612 | 0.6612 |
| store | 5 | 3.711 | 3.715 | 0.6438 | 0.6450 |
Reconciled forecast
| Series | month | Base | Reconciled | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|---|---|
| Total | 2025-01-01 | 453.51 | 453.31 | 442.19 | 464.43 | 436.30 | 470.31 |
| Total | 2025-02-01 | 474.92 | 474.71 | 463.59 | 485.83 | 457.70 | 491.72 |
| Total | 2025-03-01 | 481.76 | 481.56 | 470.43 | 492.68 | 464.54 | 498.57 |
| Total | 2025-04-01 | 483.24 | 483.04 | 471.91 | 494.17 | 466.02 | 500.06 |
| Total | 2025-05-01 | 492.01 | 491.81 | 480.68 | 502.94 | 474.78 | 508.83 |
| Total | 2025-06-01 | 495.49 | 495.28 | 484.15 | 506.42 | 478.25 | 512.32 |
| region=north | 2025-01-01 | 263.83 | 263.75 | 254.02 | 273.47 | 248.87 | 278.62 |
| region=north | 2025-02-01 | 275.41 | 275.33 | 265.60 | 285.05 | 260.45 | 290.20 |
| region=north | 2025-03-01 | 278.81 | 278.73 | 269.00 | 288.45 | 263.86 | 293.59 |
| region=north | 2025-04-01 | 279.04 | 278.95 | 269.23 | 288.67 | 264.09 | 293.82 |
| region=north | 2025-05-01 | 285.98 | 285.90 | 276.18 | 295.62 | 271.03 | 300.76 |
| region=north | 2025-06-01 | 285.81 | 285.72 | 276.01 | 295.44 | 270.86 | 300.59 |
| region=south | 2025-01-01 | 189.75 | 189.56 | 183.83 | 195.28 | 180.80 | 198.32 |
| region=south | 2025-02-01 | 199.57 | 199.38 | 193.64 | 205.13 | 190.60 | 208.17 |
| region=south | 2025-03-01 | 203.02 | 202.83 | 197.07 | 208.60 | 194.01 | 211.65 |
| region=south | 2025-04-01 | 204.28 | 204.08 | 198.30 | 209.87 | 195.24 | 212.93 |
| region=south | 2025-05-01 | 206.10 | 205.91 | 200.11 | 211.72 | 197.03 | 214.79 |
| region=south | 2025-06-01 | 209.75 | 209.56 | 203.74 | 215.38 | 200.65 | 218.47 |
| region=north / store=N1 | 2025-01-01 | 169.13 | 169.08 | 162.13 | 176.03 | 158.46 | 179.71 |
| region=north / store=N1 | 2025-02-01 | 172.85 | 172.81 | 165.86 | 179.76 | 162.19 | 183.44 |
| region=north / store=N1 | 2025-03-01 | 172.68 | 172.64 | 165.69 | 179.58 | 162.01 | 183.26 |
| region=north / store=N1 | 2025-04-01 | 173.53 | 173.49 | 166.54 | 180.43 | 162.87 | 184.11 |
| region=north / store=N1 | 2025-05-01 | 181.73 | 181.68 | 174.74 | 188.62 | 171.07 | 192.30 |
| region=north / store=N1 | 2025-06-01 | 180.60 | 180.56 | 173.62 | 187.50 | 169.95 | 191.17 |
| region=north / store=N2 | 2025-01-01 | 94.619 | 94.664 | 88.254 | 101.07 | 84.861 | 104.47 |
| region=north / store=N2 | 2025-02-01 | 102.47 | 102.52 | 96.105 | 108.93 | 92.711 | 112.32 |
| region=north / store=N2 | 2025-03-01 | 106.05 | 106.09 | 99.678 | 112.50 | 96.284 | 115.90 |
| region=north / store=N2 | 2025-04-01 | 105.42 | 105.47 | 99.053 | 111.88 | 95.658 | 115.27 |
| region=north / store=N2 | 2025-05-01 | 104.17 | 104.22 | 97.801 | 110.63 | 94.406 | 114.02 |
| region=north / store=N2 | 2025-06-01 | 105.12 | 105.17 | 98.752 | 111.58 | 95.356 | 114.98 |
| region=south / store=S1 | 2025-01-01 | 82.963 | 83.079 | 79.617 | 86.540 | 77.785 | 88.372 |
| region=south / store=S1 | 2025-02-01 | 88.913 | 89.029 | 85.517 | 92.541 | 83.658 | 94.400 |
| region=south / store=S1 | 2025-03-01 | 90.237 | 90.353 | 86.791 | 93.915 | 84.906 | 95.800 |
| region=south / store=S1 | 2025-04-01 | 93.912 | 94.029 | 90.418 | 97.640 | 88.507 | 99.551 |
| region=south / store=S1 | 2025-05-01 | 93.537 | 93.654 | 89.995 | 97.313 | 88.058 | 99.250 |
| region=south / store=S1 | 2025-06-01 | 95.137 | 95.255 | 91.549 | 98.961 | 89.587 | 100.92 |
| region=south / store=S2 | 2025-01-01 | 45.279 | 45.350 | 41.976 | 48.724 | 40.190 | 50.510 |
| region=south / store=S2 | 2025-02-01 | 44.556 | 44.626 | 41.253 | 48.000 | 39.467 | 49.786 |
| region=south / store=S2 | 2025-03-01 | 45.780 | 45.850 | 42.477 | 49.224 | 40.691 | 51.010 |
| region=south / store=S2 | 2025-04-01 | 43.730 | 43.801 | 40.427 | 47.174 | 38.642 | 48.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
))
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)
| Level | Series | MAE (base) | MAE (reconciled) | MASE (base) | MASE (reconciled) |
|---|---|---|---|---|---|
| Total | 1 | 12.979 | 12.940 | 0.6520 | 0.6500 |
| region | 2 | 7.011 | 7.012 | 0.6612 | 0.6612 |
| store | 5 | 3.711 | 3.715 | 0.6438 | 0.6450 |
Reconciled forecast
| Series | month | Base | Reconciled | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|---|---|
| Total | 2025-01-01 | 453.51 | 453.31 | 442.19 | 464.43 | 436.30 | 470.31 |
| Total | 2025-02-01 | 474.92 | 474.71 | 463.59 | 485.83 | 457.70 | 491.72 |
| Total | 2025-03-01 | 481.76 | 481.56 | 470.43 | 492.68 | 464.54 | 498.57 |
| Total | 2025-04-01 | 483.24 | 483.04 | 471.91 | 494.17 | 466.02 | 500.06 |
| Total | 2025-05-01 | 492.01 | 491.81 | 480.68 | 502.94 | 474.78 | 508.83 |
| Total | 2025-06-01 | 495.49 | 495.28 | 484.15 | 506.42 | 478.25 | 512.32 |
| region=north | 2025-01-01 | 263.83 | 263.75 | 254.02 | 273.47 | 248.87 | 278.62 |
| region=north | 2025-02-01 | 275.41 | 275.33 | 265.60 | 285.05 | 260.45 | 290.20 |
| region=north | 2025-03-01 | 278.81 | 278.73 | 269.00 | 288.45 | 263.86 | 293.59 |
| region=north | 2025-04-01 | 279.04 | 278.95 | 269.23 | 288.67 | 264.09 | 293.82 |
| region=north | 2025-05-01 | 285.98 | 285.90 | 276.18 | 295.62 | 271.03 | 300.76 |
| region=north | 2025-06-01 | 285.81 | 285.72 | 276.01 | 295.44 | 270.86 | 300.59 |
| region=south | 2025-01-01 | 189.75 | 189.56 | 183.83 | 195.28 | 180.80 | 198.32 |
| region=south | 2025-02-01 | 199.57 | 199.38 | 193.64 | 205.13 | 190.60 | 208.17 |
| region=south | 2025-03-01 | 203.02 | 202.83 | 197.07 | 208.60 | 194.01 | 211.65 |
| region=south | 2025-04-01 | 204.28 | 204.08 | 198.30 | 209.87 | 195.24 | 212.93 |
| region=south | 2025-05-01 | 206.10 | 205.91 | 200.11 | 211.72 | 197.03 | 214.79 |
| region=south | 2025-06-01 | 209.75 | 209.56 | 203.74 | 215.38 | 200.65 | 218.47 |
| region=north / store=N1 | 2025-01-01 | 169.13 | 169.08 | 162.13 | 176.03 | 158.46 | 179.71 |
| region=north / store=N1 | 2025-02-01 | 172.85 | 172.81 | 165.86 | 179.76 | 162.19 | 183.44 |
| region=north / store=N1 | 2025-03-01 | 172.68 | 172.64 | 165.69 | 179.58 | 162.01 | 183.26 |
| region=north / store=N1 | 2025-04-01 | 173.53 | 173.49 | 166.54 | 180.43 | 162.87 | 184.11 |
| region=north / store=N1 | 2025-05-01 | 181.73 | 181.68 | 174.74 | 188.62 | 171.07 | 192.30 |
| region=north / store=N1 | 2025-06-01 | 180.60 | 180.56 | 173.62 | 187.50 | 169.95 | 191.17 |
| region=north / store=N2 | 2025-01-01 | 94.619 | 94.664 | 88.254 | 101.07 | 84.861 | 104.47 |
| region=north / store=N2 | 2025-02-01 | 102.47 | 102.52 | 96.105 | 108.93 | 92.711 | 112.32 |
| region=north / store=N2 | 2025-03-01 | 106.05 | 106.09 | 99.678 | 112.50 | 96.284 | 115.90 |
| region=north / store=N2 | 2025-04-01 | 105.42 | 105.47 | 99.053 | 111.88 | 95.658 | 115.27 |
| region=north / store=N2 | 2025-05-01 | 104.17 | 104.22 | 97.801 | 110.63 | 94.406 | 114.02 |
| region=north / store=N2 | 2025-06-01 | 105.12 | 105.17 | 98.752 | 111.58 | 95.356 | 114.98 |
| region=south / store=S1 | 2025-01-01 | 82.963 | 83.079 | 79.617 | 86.540 | 77.785 | 88.372 |
| region=south / store=S1 | 2025-02-01 | 88.913 | 89.029 | 85.517 | 92.541 | 83.658 | 94.400 |
| region=south / store=S1 | 2025-03-01 | 90.237 | 90.353 | 86.791 | 93.915 | 84.906 | 95.800 |
| region=south / store=S1 | 2025-04-01 | 93.912 | 94.029 | 90.418 | 97.640 | 88.507 | 99.551 |
| region=south / store=S1 | 2025-05-01 | 93.537 | 93.654 | 89.995 | 97.313 | 88.058 | 99.250 |
| region=south / store=S1 | 2025-06-01 | 95.137 | 95.255 | 91.549 | 98.961 | 89.587 | 100.92 |
| region=south / store=S2 | 2025-01-01 | 45.279 | 45.350 | 41.976 | 48.724 | 40.190 | 50.510 |
| region=south / store=S2 | 2025-02-01 | 44.556 | 44.626 | 41.253 | 48.000 | 39.467 | 49.786 |
| region=south / store=S2 | 2025-03-01 | 45.780 | 45.850 | 42.477 | 49.224 | 40.691 | 51.010 |
| region=south / store=S2 | 2025-04-01 | 43.730 | 43.801 | 40.427 | 47.174 | 38.642 | 48.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.
Check your understanding
CheckpointCheck 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
.
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
.
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.
Do it in CodeSplash
In the appIn Forecast, choose Intermittent demand (Croston, SBA, TSB, ADIDA) or Hierarchical forecast (reconciliation). Hierarchy levels takes columns from the top down.
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# install.packages("tsintermittent")
tsintermittent::crost(read.csv("demand.csv")$demand, h = 12, type = "sba")$frc.outRecap
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