DTime series · ts.forecast_compare
Forecast accuracy comparison
Is one set of forecasts really more accurate than another, or do they predict the direction of change better than chance?
Diebold–Mariano test of equal predictive accuracy with the Harvey–Leybourne–Newbold small-sample correction, the Giacomini–White conditional test, and the Pesaran–Timmermann test of directional accuracy — on actual values and two columns of forecasts (out-of-sample, same origins).
A real result
Example “Dm a vs c”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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).
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).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Dm a vs cts_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_c · time: week
- Dm h3 absolutets_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_b · time: week
- Dm h4 bartlettts_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_b · time: week
- Dm uncorrected normalts_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_c · time: week
- Dm h3 bartlett uncorrectedts_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_b · time: week
- Gw a vs bts_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_b · time: week
- Pt model ats_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_b · time: week
- Degenerate n1ts_forecasts · actual: actual · forecast_a: model_a · forecast_b: model_c · time: week
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Actual valuesnumeric · 1 column
- The observed values the forecasts are scored against.
- Forecast Anumeric · 1 column
- Out-of-sample forecasts of the actual values (e.g. from a backtest).
- Forecast Bnumeric · 1 column
- The competing forecasts (not used by Pesaran–Timmermann).
- Timetemporal / numeric · 0–1 column
- Orders the rows (omit to use the row order).
Choices you make
hypothesis
- Testdefault dm
Diebold–Mariano compares average losses; Giacomini–White asks if one predicts better given recent data; PT checks direction.
- Diebold–Mariano (HLN-corrected)(default) — H₀: equal expected loss. Negative statistic = forecast A more accurate.
- Giacomini–White conditional — H₀: the loss difference is unpredictable from its own past (one-step forecasts).
- Pesaran–Timmermann directional — H₀: forecast A's predicted direction of change is independent of the actual direction.
- Forecast horizon hdefault 1
Steps ahead: h-step errors are autocorrelated up to lag h − 1.
- Lossdefault squared
How forecast errors are scored: squared (penalizes big misses) or absolute.
- Squared error(default) — Compares squared errors, so large misses count extra; matches RMSE.
- Absolute error — Compares absolute errors, so misses count by their size; matches MAE.
Advanced
- Long-run variancedefault acf
How the variance of the loss difference allows for h-step overlap: summed autocovariances, or Bartlett weights.
- Autocovariances up to h − 1(default) — Sums the autocovariances of the loss difference up to lag h − 1 (forecast::dm.test's default).
- Bartlett weights — Weights lag k by 1 − k/h, so the variance stays positive more often at longer horizons.
- Small-sample correctiondefault hln
Harvey–Leybourne–Newbold's correction with t(n − 1), or the original Diebold–Mariano statistic against N(0, 1).
- Harvey–Leybourne–Newbold (t)(default) — Scales the statistic for short samples and longer horizons and uses t(n − 1); the usual choice.
- None (original DM, normal) — The 1995 statistic against the standard normal; it rejects too often in short samples.
What it reports
- n_obs
- How many independent units the analysis used; it sets precision and power.
- stat
- A single number that summarizes how far your data are from what H₀ predicts.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- reject
- A p-value below the chosen α; it says the data are hard to explain by chance alone, not that the effect matters.
- loss_a
- Tests whether two forecasts have the same expected loss, allowing for the autocorrelation of multi-step forecast errors.
- loss_b
- Tests whether two forecasts have the same expected loss, allowing for the autocorrelation of multi-step forecast errors.
Per group, level or term: test, horizon, mean_diff, hit_rate, df
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Same twin in both engines; Diebold–Mariano matches forecast::dm.test (autocovariances to h − 1, HLN factor, t(n − 1)).
The exact script CodeSplash ran for example “Dm a vs c” · 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,
})
The exact script CodeSplash ran for example “Dm a vs c” · 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
))
Sources
- Diebold, F. X., & Mariano, R. S. (1995). Comparing predictive accuracy. JBES, 13, 253–263.
- Harvey, D., Leybourne, S., & Newbold, P. (1997). Testing the equality of prediction mean squared errors. Int. J. Forecasting, 13, 281–291.
- Giacomini, R., & White, H. (2006). Tests of conditional predictive ability. Econometrica, 74, 1545–1578.
- Pesaran, M. H., & Timmermann, A. (1992). A simple nonparametric test of predictive performance. JBES, 10, 461–465.
From the CodeSplash method registry · ts.forecast_compare v1.1.0.