Skip to content

Is one forecast really better?

Test forecast accuracy with Diebold–Mariano, Giacomini–White and Pesaran–Timmermann, use a Model Confidence Set, and avoid crowning a winner from a noisy leaderboard.

Advanced ~13 min11 steps

What runs in CodeSplash

You will be able to

  • Run and read a Diebold–Mariano test on two sets of forecasts
  • Explain what Giacomini–White and Pesaran–Timmermann add
  • Read the Compare tab, the baseline verdict and the Model Confidence Set

Read first

01

Lower isn't the same as better

Read

Model A has an RMSE of 41 and model B has 43. On a different set of windows, they might swap. Before you switch models in production, ask if that gap is larger than chance would give.

02

Why not a paired t test?

Predict

Predict first

You have squared errors from two models on the same dates. Can you run a paired t test on their differences?

Yes: it's exactly a paired t testAlmost, but losses can be autocorrelatedNo: errors can't be compared
Reveal

Almost. The loss differences can be autocorrelated, especially for forecasts more than one step ahead, where windows overlap. The Diebold–MarianoDiebold–Mariano testTests whether two forecasts have the same expected loss, allowing for the autocorrelation of multi-step forecast errors. test is that paired comparison, with a variance that allows for this.

03

Diebold–Mariano

Read

With loss differences dt=L(eA,t)−L(eB,t)d_t = L(e_{A,t}) - L(e_{B,t}):

DM=dˉVar⁡^(dˉ)\text{DM} = \frac{\bar d}{\sqrt{\widehat{\operatorname{Var}}(\bar d)}}

CodeSplash uses the Harvey–Leybourne–Newbold small-sample correction, and a t distribution.

Two settings under Long-run variance and Small-sample correction reproduce other conventions. Bartlett weights (1 − k/h at lag k) keep the variance positive more often at longer horizons; the original 1995 statistic, with no correction, is referred to the normal distribution. On the same forecasts the uncorrected statistic gives p < .001 against p < .001 with the correction: in short samples the normal version rejects too often, which is why the correction is the default.

Check yourself

Why is the Harvey–Leybourne–Newbold correction the default for Diebold–Mariano?

Show the answer

Answer: b

Harvey, Leybourne and Newbold (1997) scale the statistic and use t(n − 1) because the normal approximation overstates significance with few forecasts.

H0H_0 says the two have equal expected loss. It compares forecasts, not models, so it applies to any two columns of forecasts.

04

Read a result

In the app

Three simulated forecasts of one series, over 120 weeks:

Forecast accuracy comparisonRecorded · Python and R agreeRecorded 2026-11-21 · 10 values compared
R

DM = -5.59, p < .001

Diebold–Mariano (HLN)
−5.592
p
1.452e-7
MSE model_a
1.406
MSE model_c
4.962

Plots

Pairwise Diebold–MarianoWhich forecasts are significantly more accurate than which?
View data
actualmodel_amodel_c
51.06250.73153.964
48.60048.65052.107
50.11750.94650.239
52.29951.59151.193
52.86151.85553.251
51.91554.41453.332
46.87046.12547.969
47.02547.24746.581
49.97150.12553.550
51.18651.64951.934
49.61448.90551.664
51.23152.36950.042
53.67052.79958.902
56.28854.59860.176
57.14058.46759.387
54.45252.63854.377
55.77653.39056.058
57.28157.71263.074
54.92354.92353.579
58.44258.86761.166
54.96855.87957.512
57.00555.62758.393
57.71857.12961.065
56.96257.15655.895
55.29957.73856.470
52.51252.48354.165
51.91750.19156.991
50.53950.25053.975
47.44547.33750.334
48.17349.68048.616
47.58350.11449.885
47.59949.32352.177
53.60553.99354.399
52.95753.53353.798
56.42455.99161.169
57.95155.14460.904
54.92355.98456.099
56.45856.68255.592
53.91954.35453.975
58.98858.15757.711
58.90256.92060.199
58.78456.43661.040
60.17660.20360.569
60.19859.10762.112
60.75660.08563.178
61.08662.90161.568
56.28856.18857.316
57.25257.54958.599
55.32055.34658.642
54.16255.01456.974
56.06356.72054.421
54.51453.77755.212
52.58653.10055.462
51.78751.33754.071
54.15052.66054.920
56.27957.27357.232
53.85151.28256.104
56.58154.70153.854
55.39454.90257.258
53.25153.11554.045

First 60 of 120 rows.

Accuracy

ForecastMSEMAEMean error
model_a1.4060.91600.0788
model_c4.9621.822−1.462
  • Compare forecasts made out of sample from the same origins; in-sample fits favor bigger models.
  • Diebold–Mariano compares forecasts, not models: nested models need adjusted tests (Clark & West).
The exact R script · R R version 4.5.1 (2025-06-13)
# Forecast accuracy comparison
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.forecast_compare 1.1.0 · spec c3023ff01d46c217
# Dataset: ts_forecasts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_forecasts.parquet", col_select = c("actual", "model_a", "model_c", "week")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("actual", "model_a", "model_c", "week")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("actual", "model_a", "model_c", "week"))  # infinite values stop the run (registry/errors.yaml)

# %% Series
ACT <- "actual"
FA <- "model_a"
FB <- "model_c"
TIME <- "week"
TEMPORAL <- TRUE
TEST <- "dm"
H <- 1
LOSS <- "squared"
DM_VARIANCE <- "acf"
DM_CORRECTION <- "hln"
s <- cs_ts_ordered(df, ACT, TIME, TEMPORAL)
a <- s$x
fa <- as.numeric(s$df[[FA]])
fb <- as.numeric(s$df[[FB]])
n <- length(a)
# Each test's minimum: Diebold-Mariano refers to t(n - 1); Pesaran-Timmermann uses n - 1 changes; Giacomini-White
# regresses on two terms over n - 1 points (registry/errors.yaml; the same in Python).
cs_check_rows(n, c(dm = 2, pt = 3, gw = 4)[[TEST]], "The forecast comparison")
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: forecasts are compared in row order.", s$dups))
ea <- a - fa
eb <- a - fb
loss_a <- mean(if (LOSS == "squared") ea * ea else abs(ea))
loss_b <- mean(if (LOSS == "squared") eb * eb else abs(eb))
values <- list(n_obs = n, test = TEST, loss_a = loss_a, loss_b = loss_b)
lname <- if (LOSS == "squared") "MSE" else "MAE"

# %% Test
if (TEST == "dm") {
  r <- if (DM_VARIANCE == "acf" && DM_CORRECTION == "hln") cs_ts_diebold_mariano(a, fa, fb, H, LOSS) else
    cs_ts_diebold_mariano_opt(a, fa, fb, H, LOSS, DM_VARIANCE, DM_CORRECTION)  # Bartlett variance / uncorrected DM
  if (!is.finite(r$stat)) cs_error("CS_E_UNDEFINED", what = "The Diebold–Mariano test", reason = sprintf("the loss difference between %s and %s is the same at every point", FA, FB))
  if (r$h_used != H) warnings <- c(warnings, sprintf("The Diebold–Mariano variance was not positive at horizon %d, so the test uses h = 1 (as forecast::dm.test does).", as.integer(H)))
  values$stat <- r$stat; values$p <- r$p; values$reject <- as.integer(r$p < 0.05); values$horizon <- H; values$mean_diff <- r$mean_diff; values$df <- n - 1
  dm_name <- "HLN"
  if (DM_CORRECTION == "none") {
    values$df <- NULL  # referred to N(0, 1)
    dm_name <- "uncorrected, normal"
  }
  if (DM_VARIANCE == "bartlett") dm_name <- paste0(dm_name, ", Bartlett variance")
  better <- if (r$stat < 0) FA else FB
  summary <- paste0(sprintf("%s %.4g (%s) vs %.4g (%s): Diebold–Mariano (%s) = %.3f, %s — ", lname, loss_a, FA, loss_b, FB, dm_name, r$stat, cs_fmt_p(r$p)),
                    if (r$p < 0.05) sprintf("%s is significantly more accurate.", better) else "no significant difference in accuracy.")
  apa <- sprintf("DM = %.2f, %s", r$stat, cs_fmt_p(r$p))
  label <- sprintf("Diebold–Mariano (%s)", dm_name)
} else if (TEST == "gw") {
  r <- cs_ts_giacomini_white(a, fa, fb, LOSS)
  values$stat <- r$stat; values$p <- r$p; values$reject <- as.integer(r$p < 0.05); values$df <- 2
  summary <- paste0(sprintf("Giacomini–White conditional test of %s vs %s: χ²(2) = %.3f, %s — ", FA, FB, r$stat, cs_fmt_p(r$p)),
                    if (r$p < 0.05) "the relative accuracy is predictable (one forecast wins in some conditions)." else "no evidence of conditional differences.")
  apa <- sprintf("GW χ²(2) = %.2f, %s", r$stat, cs_fmt_p(r$p))
  label <- "Giacomini–White χ²"
} else {
  r <- cs_ts_pesaran_timmermann(diff(a), fa[-1] - a[-n])
  values$stat <- r$stat; values$p <- r$p; values$reject <- as.integer(r$p < 0.05); values$hit_rate <- r$hit_rate
  summary <- paste0(sprintf("%s predicts the direction of change %.0f%% of the time: Pesaran–Timmermann z = %.3f, %s — ", FA, 100 * r$hit_rate, r$stat, cs_fmt_p(r$p)),
                    if (r$p < 0.05) "better than chance." else "not better than chance.")
  apa <- sprintf("PT z = %.2f, %s", r$stat, cs_fmt_p(r$p))
  label <- "Pesaran–Timmermann z"
}
cs_publish(list(
  method = "ts.forecast_compare",
  methodVersion = "1.1.0",
  title = "Forecast accuracy comparison",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = apa,
  statistics = list(list(key = "stat", label = label, value = values$stat), list(key = "p", label = "p", value = values$p),
                    list(key = "loss_a", label = sprintf("%s %s", lname, FA), value = loss_a), list(key = "loss_b", label = sprintf("%s %s", lname, FB), value = loss_b)),
  tables = list(list(
    key = "losses", title = "Accuracy",
    columns = list(list(key = "forecast", label = "Forecast", type = "string"), list(key = "mse", label = "MSE", type = "number"),
                   list(key = "mae", label = "MAE", type = "number"), list(key = "bias", label = "Mean error", type = "number")),
    rows = list(list(forecast = FA, mse = mean(ea * ea), mae = mean(abs(ea)), bias = mean(ea)),
                list(forecast = FB, mse = mean(eb * eb), mae = mean(abs(eb)), bias = mean(eb)))
  )),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = list("Compare forecasts made out of sample from the same origins; in-sample fits favor bigger models.",
               "Diebold–Mariano compares forecasts, not models: nested models need adjusted tests (Clark & West)."),
  charts = list(cs_chart("dm", "dm-matrix", "Pairwise Diebold–Mariano", list(actual = cs_col(ACT, a), forecasts = list(cs_col(FA, fa), cs_col(FB, fb))),
                         controls = list(horizon = H, loss = LOSS))),
  values = values
))
Python

DM = -5.59, p < .001

Diebold–Mariano (HLN)
−5.592
p
1.452e-7
MSE model_a
1.406
MSE model_c
4.962

To keep this page light, the plots are shown once, under the R tab.

Accuracy

ForecastMSEMAEMean error
model_a1.4060.91600.0788
model_c4.9621.822−1.462
  • Compare forecasts made out of sample from the same origins; in-sample fits favor bigger models.
  • Diebold–Mariano compares forecasts, not models: nested models need adjusted tests (Clark & West).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Forecast accuracy comparison
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.forecast_compare 1.1.0 · spec c3023ff01d46c217
# Dataset: ts_forecasts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_forecasts.parquet", columns=["actual", "model_a", "model_c", "week"])
n_input = len(df)
df = df.dropna(subset=["actual", "model_a", "model_c", "week"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["actual", "model_a", "model_c", "week"])  # infinite values stop the run (registry/errors.yaml)

# %% Series
ACT = "actual"
FA = "model_a"
FB = "model_c"
TIME = "week"
TEMPORAL = True
TEST = "dm"
H = 1
LOSS = "squared"
DM_VARIANCE = "acf"
DM_CORRECTION = "hln"
s = ts.ordered(df, ACT, TIME, TEMPORAL)
a = s["x"]
fa = s["df"][FA].to_numpy(dtype=float)
fb = s["df"][FB].to_numpy(dtype=float)
n = len(a)
# Each test's minimum: Diebold–Mariano refers to t(n − 1); Pesaran–Timmermann uses n − 1 changes; Giacomini–White
# regresses on two terms over n − 1 points (registry/errors.yaml; the same in R).
cs.check_rows(n, {"dm": 2, "pt": 3, "gw": 4}[TEST], "The forecast comparison")
if s["dups"]:
    warnings.append(f"{s['dups']} repeated time values: forecasts are compared in row order.")
ea, eb = a - fa, a - fb
loss_a = float(np.mean(ea * ea if LOSS == "squared" else np.abs(ea)))
loss_b = float(np.mean(eb * eb if LOSS == "squared" else np.abs(eb)))
values = {"n_obs": n, "test": TEST, "loss_a": loss_a, "loss_b": loss_b}
lname = "MSE" if LOSS == "squared" else "MAE"

# %% Test
if TEST == "dm":
    if DM_VARIANCE == "acf" and DM_CORRECTION == "hln":
        r = ts.diebold_mariano(a, fa, fb, H, LOSS)
    else:
        from codesplash.stats import dm_options as dmo  # Bartlett variance / uncorrected DM (twin of R's cs_ts_diebold_mariano_opt)
        r = dmo.diebold_mariano_opt(a, fa, fb, H, LOSS, DM_VARIANCE, DM_CORRECTION)
    if not np.isfinite(r["stat"]):
        cs.cs_error("CS_E_UNDEFINED", what="The Diebold–Mariano test", reason=f"the loss difference between {FA} and {FB} is the same at every point")
    if r["h_used"] != H:
        warnings.append(f"The Diebold–Mariano variance was not positive at horizon {H}, so the test uses h = 1 (as forecast::dm.test does).")
    values.update({"stat": r["stat"], "p": r["p"], "reject": int(r["p"] < 0.05), "horizon": H, "mean_diff": r["mean_diff"], "df": n - 1})
    dm_name = "HLN"
    if DM_CORRECTION == "none":
        del values["df"]  # referred to N(0, 1)
        dm_name = "uncorrected, normal"
    if DM_VARIANCE == "bartlett":
        dm_name += ", Bartlett variance"
    better = FA if r["stat"] < 0 else FB
    summary = (f"{lname} {loss_a:.4g} ({FA}) vs {loss_b:.4g} ({FB}): Diebold–Mariano ({dm_name}) = {r['stat']:.3f}, {cs.fmt_p(r['p'])} — "
               + (f"{better} is significantly more accurate." if r["p"] < 0.05 else "no significant difference in accuracy."))
    apa = f"DM = {r['stat']:.2f}, {cs.fmt_p(r['p'])}"
    label = f"Diebold–Mariano ({dm_name})"
elif TEST == "gw":
    r = ts.giacomini_white(a, fa, fb, LOSS)
    values.update({"stat": r["stat"], "p": r["p"], "reject": int(r["p"] < 0.05), "df": 2})
    summary = (f"Giacomini–White conditional test of {FA} vs {FB}: χ²(2) = {r['stat']:.3f}, {cs.fmt_p(r['p'])} — "
               + ("the relative accuracy is predictable (one forecast wins in some conditions)." if r["p"] < 0.05 else "no evidence of conditional differences."))
    apa = f"GW χ²(2) = {r['stat']:.2f}, {cs.fmt_p(r['p'])}"
    label = "Giacomini–White χ²"
else:
    r = ts.pesaran_timmermann(np.diff(a), fa[1:] - a[:-1])
    values.update({"stat": r["stat"], "p": r["p"], "reject": int(r["p"] < 0.05), "hit_rate": r["hit_rate"]})
    summary = (f"{FA} predicts the direction of change {100 * r['hit_rate']:.0f}% of the time: Pesaran–Timmermann z = {r['stat']:.3f}, {cs.fmt_p(r['p'])} — "
               + ("better than chance." if r["p"] < 0.05 else "not better than chance."))
    apa = f"PT z = {r['stat']:.2f}, {cs.fmt_p(r['p'])}"
    label = "Pesaran–Timmermann z"
cs.publish({
    "method": "ts.forecast_compare",
    "methodVersion": "1.1.0",
    "title": "Forecast accuracy comparison",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": apa,
    "statistics": [{"key": "stat", "label": label, "value": values["stat"]}, {"key": "p", "label": "p", "value": values["p"]},
                   {"key": "loss_a", "label": f"{lname} {FA}", "value": loss_a}, {"key": "loss_b", "label": f"{lname} {FB}", "value": loss_b}],
    "tables": [{
        "key": "losses", "title": "Accuracy",
        "columns": [{"key": "forecast", "label": "Forecast", "type": "string"}, {"key": "mse", "label": "MSE", "type": "number"},
                    {"key": "mae", "label": "MAE", "type": "number"}, {"key": "bias", "label": "Mean error", "type": "number"}],
        "rows": [{"forecast": FA, "mse": float(np.mean(ea * ea)), "mae": float(np.mean(np.abs(ea))), "bias": float(np.mean(ea))},
                 {"forecast": FB, "mse": float(np.mean(eb * eb)), "mae": float(np.mean(np.abs(eb))), "bias": float(np.mean(eb))}],
    }],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": ["Compare forecasts made out of sample from the same origins; in-sample fits favor bigger models.",
              "Diebold–Mariano compares forecasts, not models: nested models need adjusted tests (Clark & West)."],
    "charts": [cs.chart("dm", "dm-matrix", "Pairwise Diebold–Mariano", {"actual": cs.col(ACT, a), "forecasts": [cs.col(FA, fa), cs.col(FB, fb)]},
                        controls={"horizon": H, "loss": LOSS})],
    "values": values,
})

Mean squared error is 1.41 for A and 4.96 for C, so dˉ\bar d = −3.56. DM = −5.59, t(119), p < .001.

Look at the Pairwise Diebold–Mariano chart. With absolute loss and hh = 3, A against B gives −7.08. Why does your choice of loss matter?

05

Better for what?

Reflect

Squared loss penalizes big misses, and absolute loss treats every miss by its size. A retailer who pays heavily for stock-outs may want neither.

Choose your loss from the decision the forecast feeds, not from whichever gives the smallest p-value. What does a big miss cost you, compared with several small ones?

06

When is it better?

Read

Giacomini–White asks a conditional question: can you predict which forecast will do better, from what you know now? A model may win in stable periods and lose after shocks.

For A against B: χ2\chi^2(2) = 26.0, p < .001.

Unlike DM, GW compares forecasting methods with their estimation uncertainty, so it stays valid when models are refit on a limited window.

07

Does direction count?

Predict

Predict first

A model's forecast gets the direction of change right 0.84 of the time. Does that alone show skill?

Yes, alwaysNot necessarily: compare against chance given the base ratesNo: direction doesn't matter
Reveal

Not necessarily. If a series nearly always rises, always saying "up" scores well. Pesaran–Timmermann compares the hit rate with what you'd get from the two series' base rates alone. Here, 7.45, p < .001.

08

In a forecast experiment

In the app

In Forecast, New experiment runs several models on the same origins. Its steps are Setup, Models, Leaderboard and Compare.

Compare answers Is the difference real?:

  • Does it beat the baseline? gives each model a verdict, using Holm-adjusted DM tests: beats naive, ≈ naive, or worse than naive.
  • Model Confidence Set lists the models that can't be separated from the best.
  • Direction of change gives Pesaran–Timmermann for each model.

A model's run page adds By horizon, By origin, a PIT histogram and Coverage by horizon. If several models share the confidence set, what would you ship?

09

Check your understanding

Checkpoint

Check yourself

Model A has mean squared error 1.4061 and model C has 4.9623. What is the mean loss difference, A − C? Give two decimals.

Show the answer

Answer: -3.55619148710009

1.4061−4.9623≈−3.561.4061 - 4.9623 \approx -3.56. The negative value favors A.

Check yourself

With three origins, a model's verdict is "≈ naive", and its MASE is a little lower. What do you conclude?

Show the answer

Answer: c

Prefer the simpler model while the evidence is unclear, and add origins if you need a firmer answer.

Check yourself

A series rises in 90% of periods. A forecast predicts "up" every time, and it's right 90% of the time. What would Pesaran–Timmermann say?

Show the answer

Answer: b

A constant forecast has no directional information. The Compare step shows a dash here, since the test can't run.

Check yourself

You compare 10 models pairwise with DM at 0.05, and report the single significant pair. What's wrong?

Show the answer

Answer: a

Many pairwise tests inflate the false-positive rate, the same as any family of tests.

10

Do it in CodeSplash

In the app

For two forecast columns you already have, use Forecast accuracy comparison. Set Actual values, Forecast A and Forecast B, then Test and Loss.

Python
import numpy as np
import pandas as pd
from scipy import stats

df = pd.read_csv("forecasts.csv")
d = (df["actual"] - df["model_a"]) ** 2 - (df["actual"] - df["model_c"]) ** 2
n, h = len(d), 1
hln = np.sqrt((n + 1 - 2 * h + h * (h - 1) / n) / n)
dm = hln * d.mean() / np.sqrt(d.var(ddof=0) / n)
print(dm, 2 * stats.t.sf(abs(dm), n - 1))
R
# install.packages("forecast")
library(forecast)
df <- read.csv("forecasts.csv")
dm.test(df$actual - df$model_a, df$actual - df$model_c, h = 1, power = 2)
11

Recap

Recap
  • A lower score may be noise, so test the gap.
  • DM is a paired comparison that allows for dependent losses, and GW adds a conditional question.
  • Choose the loss from the decision, in advance.
  • Hit rates need a base-rate comparison, and leaderboards need multiplicity control.

Concepts in this lesson