Skip to content
svgdm-matrix

Diebold–Mariano matrix

Which forecasts are significantly more accurate than which?

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

How to read it

  1. Read the diagonal as each forecast's mean loss.
  2. Read an off-diagonal cell as a comparison of its row with its column.
  3. Blue: the row is more accurate. Red: the column is. Pale: too close to separate.
  1. Callout 1: Diagonal: this forecast's mean loss.
  2. Callout 2: Strong colour: a clear difference between this pair.
  3. 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