svgdm-matrix
Diebold–Mariano matrix
Which forecasts are significantly more accurate than which?
How to read it
- Read the diagonal as each forecast's mean loss.
- Read an off-diagonal cell as a comparison of its row with its column.
- Blue: the row is more accurate. Red: the column is. Pale: too close to separate.
- Callout 1: Diagonal: this forecast's mean loss.
- Callout 2: Strong colour: a clear difference between this pair.
- Callout 3: Pale cell: compatible with equal accuracy.
Watch out
- Each cell is one test: with many forecasts, adjust for multiple comparisons.
Defaults
- Horizon h
- 1
- How many steps ahead the forecasts were made.
- Range 1 to 52, step 1
- Loss
- Squared error
- How forecast errors are scored: squared error punishes large misses more than absolute error.
- Also: Absolute error
Pinned in the code
- d_t = L(e_row) − L(e_col); DM = d̄ / √(Σ_{|k|<h} γ_k / n) × √((n + 1 − 2h + h(h − 1)/n)/n), two-sided p from t(n − 1) (forecast::dm.test).
- Rows with any missing forecast are dropped so every pair uses the same origins.
- With many forecasts, adjust for multiple comparisons (or use the Model Confidence Set).
# Diebold–Mariano matrix — Codesplash Chart Lab (recipe "dm-matrix")
# controls: horizon=1, loss=squared
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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("dm-matrix-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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 dm_hln(y, a, b, h=1, loss="squared"):
"""Diebold–Mariano with the Harvey–Leybourne–Newbold factor; two-sided p from t(n − 1)."""
ea, eb = y - a, y - b
d = ea * ea - eb * eb if loss == "squared" else np.abs(ea) - np.abs(eb)
n = len(d)
dc = d - d.mean()
v = sum((1 if k == 0 else 2) * (dc[k:] * dc[:n - k]).sum() / n for k in range(h)) / n
if not v > 0:
return 0.0, 1.0
stat = d.mean() / np.sqrt(v) * np.sqrt((n + 1 - 2 * h + h * (h - 1) / n) / n)
return stat, 2 * stats.t.sf(abs(stat), n - 1)
ACTUAL = "actual"
FORECASTS = ["model A","model B","model C"]
H, LOSS = 1, "squared"
d = df.dropna(subset=[ACTUAL] + FORECASTS)
y = d[ACTUAL].to_numpy(dtype=float)
k = len(FORECASTS)
M = np.full((k, k), np.nan)
for i, fa in enumerate(FORECASTS):
for j, fb in enumerate(FORECASTS):
if i != j:
M[i, j] = dm_hln(y, d[fa].to_numpy(dtype=float), d[fb].to_numpy(dtype=float), H, LOSS)[0]
fig, ax = plt.subplots(figsize=(1.4 * k + 2, 1.2 * k + 1.5))
lim = np.nanmax(np.abs(M)) if np.isfinite(M).any() else 1
im = ax.imshow(M, cmap="RdBu", vmin=-lim, vmax=lim) # negative: the row forecast is more accurate
for i in range(k):
for j in range(k):
if i != j:
ax.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center", fontsize=9)
ax.set_xticks(range(k), FORECASTS, rotation=30, ha="right")
ax.set_yticks(range(k), FORECASTS)
fig.colorbar(im, ax=ax, label="DM statistic (row vs column)")
plt.show()Needs pandas, numpy, matplotlib, scipy · reads dm-matrix-demo.csv · app theme from the optional codesplash helper
# Diebold–Mariano matrix — Codesplash Chart Lab (recipe "dm-matrix")
# controls: horizon=1, loss=squared
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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("dm-matrix-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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 dm_hln(y, a, b, h=1, loss="squared"):
"""Diebold–Mariano with the Harvey–Leybourne–Newbold factor; two-sided p from t(n − 1)."""
ea, eb = y - a, y - b
d = ea * ea - eb * eb if loss == "squared" else np.abs(ea) - np.abs(eb)
n = len(d)
dc = d - d.mean()
v = sum((1 if k == 0 else 2) * (dc[k:] * dc[:n - k]).sum() / n for k in range(h)) / n
if not v > 0:
return 0.0, 1.0
stat = d.mean() / np.sqrt(v) * np.sqrt((n + 1 - 2 * h + h * (h - 1) / n) / n)
return stat, 2 * stats.t.sf(abs(stat), n - 1)
ACTUAL = "actual"
FORECASTS = ["model A","model B","model C"]
H, LOSS = 1, "squared"
d = df.dropna(subset=[ACTUAL] + FORECASTS)
y = d[ACTUAL].to_numpy(dtype=float)
k = len(FORECASTS)
M = np.full((k, k), np.nan)
for i, fa in enumerate(FORECASTS):
for j, fb in enumerate(FORECASTS):
if i != j:
M[i, j] = dm_hln(y, d[fa].to_numpy(dtype=float), d[fb].to_numpy(dtype=float), H, LOSS)[0]
lim = float(np.nanmax(np.abs(M))) if np.isfinite(M).any() else 1.0
fig = go.Figure(go.Heatmap(z=M, x=FORECASTS, y=FORECASTS, colorscale="RdBu", zmin=-lim, zmax=lim, text=np.round(M, 2), texttemplate="%{text}"))
fig.update_layout(yaxis_autorange="reversed", xaxis_title="compared with", yaxis_title="forecast")
fig.show()Needs pandas, numpy, plotly, scipy · reads dm-matrix-demo.csv · app theme from the optional codesplash helper
# Diebold–Mariano matrix — Codesplash Chart Lab (recipe "dm-matrix")
# controls: horizon=1, loss=squared
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("dm-matrix-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
actual_col <- "actual"
forecasts <- c("model A", "model B", "model C")
H <- 1
LOSS <- "squared"
dm_hln <- function(y, a, b, h = 1, loss = "squared") {
d <- if (loss == "squared") (y - a)^2 - (y - b)^2 else abs(y - a) - abs(y - b)
n <- length(d)
dc <- d - mean(d)
v <- sum(vapply(0:(h - 1), function(k) (if (k == 0) 1 else 2) * sum(dc[(k + 1):n] * dc[1:(n - k)]) / n, 0)) / n
if (!(v > 0)) return(0)
mean(d) / sqrt(v) * sqrt((n + 1 - 2 * h + h * (h - 1) / n) / n)
}
d <- df[stats::complete.cases(df[, c(actual_col, forecasts)]), , drop = FALSE]
grid <- expand.grid(row = forecasts, col = forecasts, stringsAsFactors = FALSE)
grid$dm <- mapply(function(a, b) if (a == b) NA else dm_hln(d[[actual_col]], d[[a]], d[[b]], H, LOSS), grid$row, grid$col)
lim <- max(abs(grid$dm), na.rm = TRUE)
p <- ggplot(grid, aes(factor(col, levels = forecasts), factor(row, levels = rev(forecasts)), fill = dm)) + geom_tile(colour = "white") +
geom_text(aes(label = ifelse(is.na(dm), "", sprintf("%.2f", dm))), size = 3) +
scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[2], high = div_ramp[3], limits = c(-lim, lim), na.value = grey_col, name = "DM") +
labs(x = "compared with", y = "forecast") + theme_cs
print(p)Needs ggplot2 · reads dm-matrix-demo.csv · app theme from the optional codesplashr helper