PeaBox Lab › PeaLang › Learn › Chapter 18 › Lesson 6

Part III — Advanced Systems · Chapter 18 · Lesson 6 of 7 · 8 min read

Lesson 6: Grouped Forecasts, Confidence Bands, and Chart-Ready Output

Lesson level: Advanced

Purpose: Produce forecasts for many series at once, express their uncertainty as bands that users can act on, keep totals consistent across levels, and deliver results in a stable, chart-ready format.

Learning objectives

By the end of this lesson you will be able to:

6.1 Forecasting many series

A grouped forecast applies a fit and predict pair to each series independently. At scale, three engineering concerns dominate:

Illustrative listing.

def forecast_group(key, series, horizon, methods, default="seasonal_naive"):
    try:
        if series.height < 8 * 7:
            name = default
        else:
            name = choose_method(series, methods)     # from backtest results
        model = methods[name].fit(series)
        values = methods[name].predict(model, horizon)
        return {"key": key, "method": name, "values": values, "error": None}
    except Exception as exc:
        fallback = methods[default]
        values = fallback.predict(fallback.fit(series), horizon)
        return {"key": key, "method": default, "values": values,
                "error": type(exc).__name__}

results = [forecast_group(k, g, 28, METHODS)
           for k, g in sorted(panel.group_by("store_id"))]

Keep the error column in the output. A dashboard that shows which groups fell back, and why, prevents silent degradation: a run in which 30% of series fell back is a run someone should look at, even if every number looks plausible.

6.2 Short, new, and intermittent series

6.3 Prediction intervals from backtest residuals

A point forecast says "about 420 orders". A prediction interval says "between 360 and 490 orders, with 80% probability". Planners need the interval: safety stock, staffing buffers, and capacity limits are all set from the upper or lower band, not from the middle.

Strictly, a confidence interval describes uncertainty in an estimated parameter, and a prediction interval describes where a future observation is likely to fall. Business users often say "confidence band" for both; in forecast output, label the bands as prediction intervals and state the coverage level.

The most practical method for baselines uses the empirical errors from the backtest. For each horizon h, collect the errors from all origins, take their quantiles, and add them to the point forecast. Because errors usually grow with the horizon, quantiles must be computed per horizon.

Illustrative listing.

def interval_offsets(backtest, levels=(0.1, 0.9)):
    # backtest has columns: horizon, actual, forecast
    errors = backtest.with_column("e", col("actual") - col("forecast"))
    return errors.group_by("horizon").agg(
        lo = col("e").quantile(levels[0]),
        hi = col("e").quantile(levels[1]),
        n  = col("e").count())

bands = (forecast
    .join(interval_offsets(bt), on="horizon", how="left")
    .with_column("lower", (col("point") + col("lo")).clip(lower=0))
    .with_column("upper",  col("point") + col("hi")))

This method makes no distributional assumption, captures bias (the interval is asymmetric if errors are), and is easy to explain. It needs enough backtest errors per horizon — at least about 30 is a reasonable working minimum — and it assumes future errors resemble past errors. Clip lower bounds at zero for quantities that cannot be negative, and note that clipping slightly changes coverage.

Model-based intervals, such as those derived from the error variance of an exponential-smoothing model, are an alternative. They are elegant but rely on assumptions — normal, independent errors — that business data often violates. Whichever method you use, verify it empirically, as described next.

6.4 Checking coverage

An 80% interval is honest only if about 80% of actual values fall inside it in out-of-sample tests. Measure coverage on a later backtest window than the one used to compute the offsets:

Also report the average interval width. Two methods with the same coverage are not equal: the narrower one is more useful. Coverage and width together are the interval equivalent of bias and error for point forecasts.

6.5 Reconciling across levels

Forecasts are usually needed at several levels: item, store, region, total. If each level is forecast independently, the store forecasts will not sum to the region forecast, and planners at different levels will disagree. Reconciliation makes the levels coherent:

Prediction intervals do not add up like point forecasts: the 90th percentile of a total is less than the sum of the 90th percentiles of its parts, because not every part has a bad day at once. Compute intervals for aggregates from aggregated backtest errors, not by summing lower and upper bounds.

6.6 Chart-ready output

Dashboards and reports consume forecasts more reliably when the output follows a fixed, long schema: one row per series, date, and value type. Long data is easy to filter, plot as overlaid lines and bands, and extend with new methods without changing columns.

ColumnTypeMeaning
run_idstringIdentifier of the forecast run
generated_attimestamp (UTC)When the run produced the forecast
origin_datedateLast date of data used
series_keystringGroup identifier, for example store or product
levelstringHierarchy level: item, store, region, total
datedateDate being described
horizonintegerPeriods after the origin; 0 or null for actuals
kindstringactual, point, lower, or upper
valuefloatThe number
interval_levelfloatNominal coverage for bands, for example 0.8
methodstringMethod name and version
statusstringok, fallback, or failed, with reason

Include recent actuals in the same table so that a chart can draw history and forecast together without a second query. Write each run as an immutable, versioned batch; never overwrite a previous run. Keeping old runs lets you measure accuracy after the fact and explain why a plan was made from the numbers available at the time.

Write the output with the data layer's writer to the agreed format — for example CSV or JSONL for interchange, or a database table through the SQLite reference backend from Chapter 17 — and validate it against the schema before publishing.

Common mistakes

Guided practice

Hands-on lab: A grouped forecast with bands

Review questions

Applied challenge

A distributor forecasts 3,000 products across 12 warehouses. Planners order at warehouse level, finance budgets at the national total, and many products sell only a few units a month. Design the full grouped forecasting pipeline: method selection rules, handling of new and intermittent items, interval method and coverage targets, reconciliation strategy, output schema, and run-health reporting. Implement it on a 100-product sample and report coverage and accuracy by level.

Lesson summary

Production forecasting is grouped forecasting: isolate failures, choose methods per group, and treat short, new, and intermittent series specially. Express uncertainty with prediction intervals built per horizon and verified by coverage and width. Reconcile across levels so that plans agree, and publish versioned results in a long, validated, chart-ready schema.

Lesson status: Ready for review.

← Previous Next →