build_cv_folds: Build rolling-origin (walk-forward) cross-validation folds

View source: R/rolling_cv.R

build_cv_foldsR Documentation

Build rolling-origin (walk-forward) cross-validation folds

Description

Builds up to k_requested chronological, non-overlapping walk-forward folds from one ds-ordered series. Each fold's test window is exactly horizon_periods rows long. Degrades gracefully: if the series can't support k_requested folds, fewer are returned instead of erroring – possibly zero, for a very short series.

Usage

build_cv_folds(
  df,
  horizon_periods,
  k_requested,
  min_train = 2,
  window = c("expanding", "rolling"),
  train_window = NULL
)

Arguments

df

A data frame with a ds column, in any row order (it's sorted internally).

horizon_periods

Integer, the length of each fold's test window, in the same units as df$ds's spacing.

k_requested

Integer, the number of folds requested (may return fewer).

min_train

Integer, the minimum number of training rows a fold must have to be included. Default 2.

window

"expanding" (the default – training windows always start from the beginning of the series, growing fold over fold) or "rolling" (each fold's training window is capped to the most recent train_window rows instead, a fixed width – useful for testing robustness to concept drift/regime change separately from an ever-larger training set).

train_window

Integer, the fixed training-window width used when window = "rolling". Ignored for "expanding". Defaults to NULL, which uses what would be the smallest (earliest) fold's expanding training size – a sensible width with no extra input needed.

Value

A list of folds, oldest-first (fold 1 has the smallest training window under "expanding", or the same fixed width under "rolling"), each a list with train and test data frames.

Examples

df <- data.frame(ds = as.Date("2024-01-01") + 0:29, y = 1:30)
folds <- build_cv_folds(df, horizon_periods = 5, k_requested = 3)
length(folds)
rolling_folds <- build_cv_folds(df, horizon_periods = 5, k_requested = 3,
                                 window = "rolling", train_window = 10)
length(rolling_folds)

forecastsuite documentation built on Oct. 18, 2026, 5:08 p.m.