Skip to content

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).

Verified in Python and R Python and R agree to 10 decimals Also called Diebold-Mariano, DM test, Harvey-Leybourne-Newbold…

A real result

Example “Dm a vs c”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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).
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).

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)).
Python

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,
})
R

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.