Skip to content
svgbacktest-errors

Backtest errors by horizon

How does forecast error grow with the horizon, and how stable is it across origins?

Demo data · seed 20261101 · 144 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read thin lines as individual backtest windows, the thick line as the mean.
  2. Rising with horizon is normal; compare how fast.
  3. Thin lines far apart mean accuracy depends on when you start.
  1. Callout 1: Mean error at short horizons.
  2. Callout 2: Thin line: one forecast origin.
  3. Callout 3: Mean error at the longest horizon.

Watch out

  • Few windows make these noisy; check a naive baseline on the same windows.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Each origin is one backtest window (rolling origin, fixed horizon); the thick line is the arithmetic mean of the windows' errors at each horizon.
# Backtest errors by horizon — Codesplash Chart Lab (recipe "backtest-errors")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("backtest-errors-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["origin"] = pd.Categorical(df["origin"].astype("string"), categories=["1958-12", "1959-03", "1959-06", "1959-09", "1959-12", "1960-03"])
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["MAE", "MAPE"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
H = "months ahead"
E = "error"
ORIG = "origin"
MET = "metric"
d = df.dropna(subset=[H, E]).sort_values(H)
metrics = levels_of(d[MET]) if MET else [None]
fig, axes = plt.subplots(1, len(metrics), figsize=(4.2 * len(metrics) + 1, 4), squeeze=False)
for i, (ax, met) in enumerate(zip(axes[0], metrics)):  # one panel per metric
    g = d if met is None else d[d[MET].astype(str) == str(met)]
    col = PALETTE[i % len(PALETTE)]
    if ORIG:
        for _, s in g.groupby(ORIG, observed=True):  # each rolling-origin window
            ax.plot(s[H], s[E], color=GREY, linewidth=0.8)
    mean = g.groupby(H)[E].mean()
    ax.plot(mean.index, mean.values, color=col, linewidth=2.6, marker="o", ms=3.5, label="mean across origins")
    ax.set_title(str(met) if met is not None else E, fontsize=10)
    ax.set_xlabel(H)
axes[0, 0].set_ylabel(E)
axes[0, 0].legend(fontsize=8)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads backtest-errors-demo.csv · app theme from the optional codesplash helper