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.
What runs in CodeSplash
- STAT215Diebold–Mariano test Runs in CodeSplash
- STAT216Pesaran–Timmermann test Runs in CodeSplash
- Forecast accuracy comparison Verified in Python and R
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
Lower isn't the same as better
ReadModel 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.
Why not a paired t test?
PredictPredict first
You have squared errors from two models on the same dates. Can you run a paired t test on their differences?
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.
Diebold–Mariano
ReadWith loss differences :
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.
says the two have equal expected loss. It compares forecasts, not models, so it applies to any two columns of forecasts.
Read a result
In the appThree simulated forecasts of one series, over 120 weeks:
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
View data
| actual | model_a | model_c |
|---|---|---|
| 51.062 | 50.731 | 53.964 |
| 48.600 | 48.650 | 52.107 |
| 50.117 | 50.946 | 50.239 |
| 52.299 | 51.591 | 51.193 |
| 52.861 | 51.855 | 53.251 |
| 51.915 | 54.414 | 53.332 |
| 46.870 | 46.125 | 47.969 |
| 47.025 | 47.247 | 46.581 |
| 49.971 | 50.125 | 53.550 |
| 51.186 | 51.649 | 51.934 |
| 49.614 | 48.905 | 51.664 |
| 51.231 | 52.369 | 50.042 |
| 53.670 | 52.799 | 58.902 |
| 56.288 | 54.598 | 60.176 |
| 57.140 | 58.467 | 59.387 |
| 54.452 | 52.638 | 54.377 |
| 55.776 | 53.390 | 56.058 |
| 57.281 | 57.712 | 63.074 |
| 54.923 | 54.923 | 53.579 |
| 58.442 | 58.867 | 61.166 |
| 54.968 | 55.879 | 57.512 |
| 57.005 | 55.627 | 58.393 |
| 57.718 | 57.129 | 61.065 |
| 56.962 | 57.156 | 55.895 |
| 55.299 | 57.738 | 56.470 |
| 52.512 | 52.483 | 54.165 |
| 51.917 | 50.191 | 56.991 |
| 50.539 | 50.250 | 53.975 |
| 47.445 | 47.337 | 50.334 |
| 48.173 | 49.680 | 48.616 |
| 47.583 | 50.114 | 49.885 |
| 47.599 | 49.323 | 52.177 |
| 53.605 | 53.993 | 54.399 |
| 52.957 | 53.533 | 53.798 |
| 56.424 | 55.991 | 61.169 |
| 57.951 | 55.144 | 60.904 |
| 54.923 | 55.984 | 56.099 |
| 56.458 | 56.682 | 55.592 |
| 53.919 | 54.354 | 53.975 |
| 58.988 | 58.157 | 57.711 |
| 58.902 | 56.920 | 60.199 |
| 58.784 | 56.436 | 61.040 |
| 60.176 | 60.203 | 60.569 |
| 60.198 | 59.107 | 62.112 |
| 60.756 | 60.085 | 63.178 |
| 61.086 | 62.901 | 61.568 |
| 56.288 | 56.188 | 57.316 |
| 57.252 | 57.549 | 58.599 |
| 55.320 | 55.346 | 58.642 |
| 54.162 | 55.014 | 56.974 |
| 56.063 | 56.720 | 54.421 |
| 54.514 | 53.777 | 55.212 |
| 52.586 | 53.100 | 55.462 |
| 51.787 | 51.337 | 54.071 |
| 54.150 | 52.660 | 54.920 |
| 56.279 | 57.273 | 57.232 |
| 53.851 | 51.282 | 56.104 |
| 56.581 | 54.701 | 53.854 |
| 55.394 | 54.902 | 57.258 |
| 53.251 | 53.115 | 54.045 |
First 60 of 120 rows.
Accuracy
| Forecast | MSE | MAE | Mean error |
|---|---|---|---|
| model_a | 1.406 | 0.9160 | 0.0788 |
| model_c | 4.962 | 1.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
))
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
| Forecast | MSE | MAE | Mean error |
|---|---|---|---|
| model_a | 1.406 | 0.9160 | 0.0788 |
| model_c | 4.962 | 1.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 = −3.56. DM = −5.59, t(119), p < .001.
Look at the Pairwise Diebold–Mariano chart. With absolute loss and = 3, A against B gives −7.08. Why does your choice of loss matter?
Better for what?
ReflectSquared 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?
When is it better?
ReadGiacomini–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) = 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.
Does direction count?
PredictPredict first
A model's forecast gets the direction of change right 0.84 of the time. Does that alone show skill?
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.
In a forecast experiment
In the appIn 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?
Check your understanding
CheckpointCheck 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
. 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.
Do it in CodeSplash
In the appFor two forecast columns you already have, use Forecast accuracy comparison. Set Actual values, Forecast A and Forecast B, then Test and Loss.
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))# 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)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