polars_online.eval.diebold_mariano

polars_online.eval.diebold_mariano(df: pl.DataFrame, *, a: str, b: str, targets: Sequence[str] | None = None, a_suffix: str = '', b_suffix: str = '', lags: int = 0, group: str | Iterable[str] | None = None, half_life: float | None = None, min_samples: int = 30, name: str = 'diebold_mariano') → pl.DataFrame[source]
polars_online.eval.diebold_mariano(df: pl.LazyFrame, *, a: str, b: str, targets: Sequence[str] | None = None, a_suffix: str = '', b_suffix: str = '', lags: int = 0, group: str | Iterable[str] | None = None, half_life: None = None, min_samples: int = 30, name: str = 'diebold_mariano') → pl.DataFrame
polars_online.eval.diebold_mariano(df: pl.LazyFrame, *, a: str, b: str, targets: Sequence[str] | None = None, a_suffix: str = '', b_suffix: str = '', lags: int = 0, group: str | Iterable[str] | None = None, half_life: float, min_samples: int = 30, name: str = 'diebold_mariano') → pl.LazyFrame

Test whether two specs’ out-of-sample squared errors differ on average, by Diebold and Mariano’s test.

Use it to ask whether one spec predicts better than another that is not nested in it. It is Diebold and Mariano’s (1995) test, with Newey and West’s (1987) variance. When one spec’s features are a subset of the other’s, use clark_west(), since this test leans toward the smaller of two nested specs. For evidence you may read at every row as the rows come, use seqtest(), which asks a different question: which spec is closer on more rows (see Notes).

Parameters

df

A frame a bank returned, holding both specs’ output columns, or a query of one, a LazyFrame, which this reads one chunk at a time (see Notes).

a, b

The names of the two specs’ output columns. The statistic is positive when a was closer.

targets, a_suffix, b_suffix

seqtest()’s, in compare mode: the targets whose residuals are compared (every target the two share by default), and the suffix of each side’s residual field.

lags

The lags of the Newey-West variance, 0 by default. 0 is right only where the differentials are uncorrelated from row to row, which holds where neither spec’s one-step errors can be predicted from its past errors. Two specs that each leave out something persistent, such as a feature that moves slowly, make errors that run from row to row, and so differentials that do, however equal their accuracy; then lags=0 understates the variance. Two ridges, each on one of two features that follow an autoregression at 0.9, equally accurate by construction, were found to differ at 5% on 28% of simulated streams of 200 rows and 32% of streams of 2,000 at lags=0. Read the differentials’ autocorrelation, or give lags.

For a target that looks h rows ahead, rows fewer than h apart share shocks, so their differentials correlate whatever the specs. Give about 2 h, as many as the bank’s diagnostics take for the same variance: Newey and West’s weights count lag l at 1 - l / (lags + 1), so h - 1 lags count the overlap’s correlations at less than their weight, and the test rejects too often however long the stream. On simulated errors of two equally accurate h-step forecasts, at h = 5 and h = 20, lags=2h rejected at 5% on 6% of streams of 20,000 rows, 7% of streams of 2,000 and 9% to 15% of streams of 200, where h - 1 rejected on 8% to 9%, 9% to 10% and 10% to 13%. On short keys no number of lags holds 5%: read a p-value near 0.05 there as weaker evidence than it says.

A key with at most 4 (lags + 1) rows with a differential reads a null statistic, whatever min_samples is. The deviations from the mean sum to zero, so the variance’s sum over a key shrinks toward zero as lags nears the key’s rows, and the statistic grows with no meaning: on 40 rows of noise, lags=10 rejected at 5% on 15% of streams and lags=19 on 21%, and on two rows lags=10 read 11.7. The 4 is a rule of thumb; give a key many times lags rows.

group

seqtest()’s: the key columns to test each group apart.

half_life

None, the default, gives one statistic over every row. A number of rows, finite and above 0, gives the statistic on every row instead, exponentially weighted. Each row up to it counts 0.5 ** (age / half_life), where age is the number of rows with a differential after it, up to this row, so the row itself has age 0.

min_samples

The fewest rows with a differential a key is tested on, 30 by default. Without half_life, a key with fewer rows keeps its row, with n filled and the other three columns null, as Polars gives null below its min_samples. With half_life, a key’s statistic is null on its rows before its min_samples-th row with a differential. On a key’s first rows the statistic is a mean of a few rows over an estimate of its own spread, far from N(0, 1): on simulated noise it passed 1.96 on 32% of streams at a key’s second row and 8% to 9% at its tenth, at lags=0, and on 72% and 21% to 24% at lags=4.

name

With half_life, the name of the record column added, "diebold_mariano" by default.

Returns

Without half_life, a DataFrame with one row per group key and target: n, the rows read; mean, the mean differential; dm, the statistic, null where every differential is the same value; and p_value, its two-sided p-value. A dm above 1.96 says a predicted better at the 5% level, and one below -1.96 says b did.

With half_life, df with a record column name added, holding dm_<t> per target t: null on a row where a side has no residual, on a key’s rows before its min_samples-th with a differential and while it has at most 4 (lags + 1) of them (see lags), and where S is zero but for rounding (see Notes); it has a value on every other row. Given a LazyFrame, a LazyFrame of the same, which reads df one chunk at a time when it runs.

Each row’s value is about N(0, 1) when the two predict equally well, once its weight covers many rows. It rests on about 2.9 · half_life rows however long the stream ((1 + λ) / (1 - λ), with λ the weight’s decay a row), so keep half_life well above lags and above the differentials’ memory. On simulated noise it passed 1.96 on 8% of rows at half_life=5 (17% at lags=4), on 5% at half_life=20 (8% at lags=4), and on 5% at half_life=100 (5% to 6% at lags=4). It is one test per row, not a sequential test: acting the first time it passes 1.96 is not a test at 5%. Over 2,000 rows of noise some row past the 30th passed 1.96 on 96% of streams at half_life=100 and 65% at half_life=500. seqtest() is the test to act on as the rows come.

Raises

Whatever seqtest() raises for a, b, targets, the suffixes and group. ValueError too, for lags below 0, for a half_life that is not finite and above 0, or so long that 0.5 ** (1 / half_life) is 1.0 in a double (from about 1.25e16 rows), and, with half_life, for a name that df already has as a column, which the result would replace. WrongTypeError, both a TypeError and a ValueError, for a lags that is not a whole number, such as 1.5.

Update equation

Per target t, the loss differential on a row is d = resid_b² - resid_a², over the n rows where both have a residual. With d̄ its mean, and Bartlett weights 1 - l / (lags + 1) on lags l up to lags:

S  = Σ (d - d̄)² + 2 Σ_{l ≤ lags} (1 - l/(lags+1)) Σ_i (d_i - d̄)(d_{i-l} - d̄)
dm = d̄ · n / sqrt(S)                  ~ N(0, 1) with equal accuracy

S is Newey and West’s estimate of the differential’s long-run variance, times n. i counts the rows that have a differential: a row without one is left out before the lags are taken, so d_(i-l) is the l-th earlier row that has one, not the row l places back.

Examples

This code reads df from Example data:

x0_only = po.spec.ewridge("x0_only", targets=["y"], features=["x0"], half_life=500.0)
x1_only = po.spec.ewridge("x1_only", targets=["y"], features=["x1"], half_life=500.0)
out = po.ModelBank([x0_only, x1_only]).fit_predict(df)
test = po.eval.diebold_mariano(out, a="x0_only", b="x1_only")
n, dm, p = test.select("n", "dm", "p_value").row(0)
print(f"{n} rows, dm {dm:.2f}, p {p:.2g}")   # dm above 1.96: x0_only did better, at 5%
397 rows, dm 8.62, p 6.7e-18

See also

  • clark_west(), the test for two nested specs.

  • seqtest(), evidence to read at every row, of which spec is closer more often.

  • compare_specs(), whose Notes say when to use each test.

Notes

This test asks which spec has the smaller mean squared error; seqtest() asks which is closer on more rows. A spec with rare large errors can win the second and lose the first. On a simulated stream of 4,999 rows where a was closer on 3,415 rows but its mean squared error was 4.80 against b’s 1.01, seqtest()’s log evidence that a was closer reached 339 (ln 20 is 3.0), and this test read dm -8.7, b better at a p-value of 4e-18. Each answer is right for its question.

Given a query, this holds one chunk and, per key and target, the last lags differentials and a few sums, beside what Polars reads of the query ahead of it. Without half_life, each lag’s sum in S is a co-moment about d̄ of the pairs of rows l apart, and with x the later of a pair and y the earlier, Σ (x - d̄)(y - d̄) = C + n (x̄ - d̄)(ȳ - d̄), where C is the pairs’ co-moment about their own means. So each chunk keeps, per key and lag, the pairs’ count, means and co-moment, added chunk to chunk as merge_sums() adds its sums, and the last lags differentials of each key, which pair with the next chunk’s first rows. The result is the frame’s within rounding: within 1e-9 relative, and 1e-12 at the most measured, on a mean differential near zero read a row at a time.

A scan of a parquet file reads its row groups ahead of a slower consumer, as many as Polars’ thread count sizes, and under Polars’ defaults that read-ahead is most of what the process holds: Cut what Polars reads ahead bounds it. Measured on macOS (an M4 Pro, py-polars 2.0.0) as the most memory the process held, about 48 MiB of it Python and Polars before the call, testing two specs of a scan, a file in row groups of 100,000 rows, by a key of four values with lags=5: 97 MiB at a million rows, 97 MiB at four million and 101 MiB at sixteen million with four threads (POLARS_MAX_THREADS=4), the read-ahead cut to one row group (POLARS_ROW_GROUP_PREFETCH_SIZE=1) and the allocator told to return freed pages at once (_RJEM_MALLOC_CONF=dirty_decay_ms:0,muzzy_decay_ms:0), the bounded settings; under Polars’ defaults, 247, 409 and 793 MiB. The collected frame’s test held 252 MiB at a million rows under the bounded settings.

With half_life, S is read from weighted means and variances (see below), each over the rows j ≤ t at weights μ^(t-j), with μ the weight’s decay a row or its square, so a chunk carries in each key’s count, means and variances after the rows before it, decays their weight over its own rows, and pools them with its own as two groups’ means and variances pool. While the query is one chunk the result is the frame’s to the bit. Over many, frame and query each carry the rounding the next paragraph bounds, about E / (2 S) of dm, so they are within about E / S of each other: near 1e-14 where the differentials’ level is near their spread, and about 1e-10 at a level a million spreads from zero (7.9e-11 measured at half_life=5 in chunks of 7 rows). A row whose S is within its rounding of E can be null in one and not the other. Written to a file with sink_parquet, the test by the row with lags=2 and half_life=500 held 157 MiB at a million rows, 161 MiB at four million and 161 MiB at sixteen million under the bounded settings, and 395, 681 and 1,129 MiB under Polars’ defaults.

With half_life, S is summed about the weighted means, and dm is null where S is zero but for rounding. Each row’s weight is ω, d̄ is the mean at those weights, and ω_t ω_(t-l) = λ^l ω_t², so each sum in S is a sum at the weights ω²: with W = Σ ω², and m₂ and v₂ the mean and variance of d at those weights, lag 0’s is W (v₂ + (m₂ - d̄)²), and lag l’s, over the pairs (u, v) = (d_i, d_(i-l)), is λ^l W_l (c_l + (μ_l - d̄)(ν_l - d̄)), with W_l, μ_l, ν_l and c_l the pairs’ weight, means and covariance. No sum cancels the differentials’ level against itself, so a spread far below the level, or one first differential far from the rest, is read to the digits the means hold. Each mean and variance is a recursion that steps by 1 / weight of the gap to the new value, its weight the sum of its weights so far, at most the rows read and at most Σ ω. Each step rounds by about ε = 2.2e-16 of the value held, and the next keeps 1 - 1 / weight of that, so the roundings rest within η_r = ε Σ ω of its size; a mean of a constant can rest that far from it, since a step smaller than half its last digit rounds to nothing. A key with few rows has gathered few roundings, whatever the half-life. The totals Σ ω² are read from the count as (1 - λ^(2n)) / (1 - λ²), and λ^(2n) rounds to within ε, so near λ = 1 they are within η_w = ε / ((1 - λ²) Σ ω²). From there, with S₀ lag 0’s sum and R = Σ ω² d², S is within E = 10 (1 + lags) ((η_r + η_w) S₀ + η_r sqrt(S₀ R) + η_r² R) of its value: η_r² of R where the differentials have been one value (the means’ offsets squared), and η_r + η_w of the sums where they have not. dm is null where S <= E: on rows whose differentials have all been equal, and once a constant has run long enough that the rows before it weigh less than its rounding. Above it, dm’s rounding is at most about E / (2 S) of it, and the mean’s, about η_r of the differentials’ size. At a half-life near the longest a double can tell from no decay, about 1e16 rows, η_w nears 1 / n and nulls a key’s first rows, a few dozen at lags=3, though its statistic is right there to 1e-12.

Without half_life, dm is null where every differential of the key is the same value, whose S is zero but for the rounding of the mean. A key whose differentials take values a few units in the last place apart reads a statistic only as good as the rounding of that spread, 1e16 or more and not the same in a frame and a query, with a p-value of 0 either way.