svgbacktest-errors
Backtest errors by horizon
How does forecast error grow with the horizon, and how stable is it across origins?
How to read it
- Read thin lines as individual backtest windows, the thick line as the mean.
- Rising with horizon is normal; compare how fast.
- Thin lines far apart mean accuracy depends on when you start.
- Callout 1: Mean error at short horizons.
- Callout 2: Thin line: one forecast origin.
- 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
# Backtest errors by horizon — Codesplash Chart Lab (recipe "backtest-errors")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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 px.colors.qualitative.Plotly
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 = make_subplots(rows=1, cols=len(metrics), subplot_titles=[str(m) if m is not None else E for m in metrics])
for i, met in enumerate(metrics, start=1):
g = d if met is None else d[d[MET].astype(str) == str(met)]
if ORIG:
for name, s in g.groupby(ORIG, observed=True):
fig.add_scatter(x=s[H], y=s[E], mode="lines", line=dict(color=GREY, width=1), name=str(name), showlegend=False, row=1, col=i)
mean = g.groupby(H)[E].mean()
fig.add_scatter(x=mean.index, y=mean.values, mode="lines+markers", line=dict(color=PALETTE[(i - 1) % len(PALETTE)], width=3), name="mean", showlegend=i == 1, row=1, col=i)
fig.update_xaxes(title_text=H, row=1, col=i)
fig.update_yaxes(title_text=E, row=1, col=1)
fig.show()Needs pandas, numpy, plotly · reads backtest-errors-demo.csv · app theme from the optional codesplash helper
# Backtest errors by horizon — Codesplash Chart Lab (recipe "backtest-errors")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("backtest-errors-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["origin"]] <- factor(df[["origin"]], levels = c("1958-12", "1959-03", "1959-06", "1959-09", "1959-12", "1960-03"))
df[["metric"]] <- factor(df[["metric"]], levels = c("MAE", "MAPE"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
h_col <- "months ahead"
e_col <- "error"
orig_col <- "origin"
met_col <- "metric"
d <- df[!is.na(df[[h_col]]) & !is.na(df[[e_col]]), ]
d <- data.frame(h = d[[h_col]], e = d[[e_col]], orig = if (is.null(orig_col)) "all" else as.character(d[[orig_col]]),
met = if (is.null(met_col)) e_col else factor(as.character(d[[met_col]]), levels = levels_of(d[[met_col]])))
avg <- aggregate(e ~ h + met, data = d, FUN = mean)
p <- ggplot(d[order(d$orig, d$h), ], aes(h, e)) +
{ if (!is.null(orig_col)) geom_line(aes(group = orig), colour = grey_col, linewidth = 0.4) } +
geom_line(data = avg, aes(colour = met), linewidth = 1.2) + geom_point(data = avg, aes(colour = met), size = 1.6) +
facet_wrap(~met, scales = "free_y", nrow = 1) + scale_colour_manual(values = cs_cat, guide = "none") +
labs(x = h_col, y = e_col) + theme_cs
print(p)Needs ggplot2 · reads backtest-errors-demo.csv · app theme from the optional codesplashr helper