rheon.polars.eval.diebold_mariano¶
- rheon.polars.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]¶
- rheon.polars.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
- rheon.polars.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, useseqtest(), which asks a different question: which spec is closer on more rows (see Notes).Parameters
dfA 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,bThe names of the two specs’ output columns. The statistic is positive when
awas closer.targets,a_suffix,b_suffixseqtest()’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.lagsThe 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=0understates 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 atlags=0. Read the differentials’ autocorrelation, or givelags.For a target that looks
hrows ahead, rows fewer thanhapart share shocks, so their differentials correlate whatever the specs. Give about2 h, as many as the bank’s diagnostics take for the same variance: Newey and West’s weights count laglat1 - l / (lags + 1), soh - 1lags 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 accurateh-step forecasts, ath = 5andh = 20,lags=2hrejected at 5% on 6% of streams of 20,000 rows, 7% of streams of 2,000 and 9% to 15% of streams of 200, whereh - 1rejected 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, whatevermin_samplesis. The deviations from the mean sum to zero, so the variance’s sum over a key shrinks toward zero aslagsnears the key’s rows, and the statistic grows with no meaning: on 40 rows of noise,lags=10rejected at 5% on 15% of streams andlags=19on 21%, and on two rowslags=10read 11.7. The 4 is a rule of thumb; give a key many timeslagsrows.groupseqtest()’s: the key columns to test each group apart.half_lifeNone, 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 counts0.5 ** (age / half_life), whereageis the number of rows with a differential after it, up to this row, so the row itself has age 0.min_samplesThe fewest rows with a differential a key is tested on, 30 by default. Without
half_life, a key with fewer rows keeps its row, withnfilled and the other three columns null, as Polars gives null below itsmin_samples. Withhalf_life, a key’s statistic is null on its rows before itsmin_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 fromN(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, atlags=0, and on 72% and 21% to 24% atlags=4.nameWith
half_life, the name of the record column added,"diebold_mariano"by default.
Returns
Without
half_life, aDataFramewith one row pergroupkey and target:n, the rows read;mean, the mean differential;dm, the statistic, null where every differential is the same value; andp_value, its two-sided p-value. Admabove 1.96 saysapredicted better at the 5% level, and one below -1.96 saysbdid.With
half_life,dfwith a record columnnameadded, holdingdm_<t>per targett: null on a row where a side has no residual, on a key’s rows before itsmin_samples-th with a differential and while it has at most4 (lags + 1)of them (seelags), and whereSis zero but for rounding (see Notes); it has a value on every other row. Given aLazyFrame, aLazyFrameof the same, which readsdfone 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 about2.9 · half_liferows however long the stream ((1 + λ) / (1 - λ), withλthe weight’s decay a row), so keephalf_lifewell abovelagsand above the differentials’ memory. On simulated noise it passed 1.96 on 8% of rows athalf_life=5(17% atlags=4), on 5% athalf_life=20(8% atlags=4), and on 5% athalf_life=100(5% to 6% atlags=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 athalf_life=100and 65% athalf_life=500.seqtest()is the test to act on as the rows come.Raises
Whatever
seqtest()raises fora,b,targets, the suffixes andgroup.ValueErrortoo, forlagsbelow 0, for ahalf_lifethat is not finite and above 0, or so long that0.5 ** (1 / half_life)is 1.0 in a double (from about 1.25e16 rows), and, withhalf_life, for anamethatdfalready has as a column, which the result would replace.WrongTypeError, both aTypeErrorand aValueError, for alagsthat is not a whole number, such as1.5.Update equation
Per target
t, the loss differential on a row isd = resid_b² - resid_a², over thenrows where both have a residual. Withd̄its mean, and Bartlett weights1 - l / (lags + 1)on lagslup tolags: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 accuracySis Newey and West’s estimate of the differential’s long-run variance, timesn.icounts the rows that have a differential: a row without one is left out before the lags are taken, sod_(i-l)is thel-th earlier row that has one, not the rowlplaces back.Examples
This code reads
dffrom Example data:x0_only = rp.spec.ewridge("x0_only", targets=["y"], features=["x0"], half_life=500.0) x1_only = rp.spec.ewridge("x1_only", targets=["y"], features=["x1"], half_life=500.0) out = rp.ModelBank([x0_only, x1_only]).fit_predict(df) test = rp.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 whereawas closer on 3,415 rows but its mean squared error was 4.80 againstb’s 1.01,seqtest()’s log evidence thatawas closer reached 339 (ln 20is 3.0), and this test readdm-8.7,bbetter 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
lagsdifferentials and a few sums, beside what Polars reads of the query ahead of it. Withouthalf_life, each lag’s sum inSis a co-moment aboutd̄of the pairs of rowslapart, and withxthe later of a pair andythe earlier,Σ (x - d̄)(y - d̄) = C + n (x̄ - d̄)(ȳ - d̄), whereCis 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 asmerge_sums()adds its sums, and the lastlagsdifferentials 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,Sis read from weighted means and variances (see below), each over the rowsj ≤ tat 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, aboutE / (2 S)ofdm, so they are within aboutE / Sof 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 athalf_life=5in chunks of 7 rows). A row whoseSis within its rounding ofEcan be null in one and not the other. Written to a file withsink_parquet, the test by the row withlags=2andhalf_life=500held 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,Sis summed about the weighted means, anddmis null whereSis 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 inSis a sum at the weightsω²: withW = Σ ω², andm₂andv₂the mean and variance ofdat those weights, lag 0’s isW (v₂ + (m₂ - d̄)²), and lagl’s, over the pairs(u, v) = (d_i, d_(i-l)), isλ^l W_l (c_l + (μ_l - d̄)(ν_l - d̄)), withW_l,μ_l,ν_landc_lthe 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 by1 / weightof 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-16of the value held, and the next keeps1 - 1 / weightof 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λ = 1they are withinη_w = ε / ((1 - λ²) Σ ω²). From there, withS₀lag 0’s sum andR = Σ ω² d²,Sis withinE = 10 (1 + lags) ((η_r + η_w) S₀ + η_r sqrt(S₀ R) + η_r² R)of its value:η_r²ofRwhere the differentials have been one value (the means’ offsets squared), andη_r + η_wof the sums where they have not.dmis null whereS <= 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 aboutE / (2 S)of it, and the mean’s, aboutη_rof the differentials’ size. At a half-life near the longest a double can tell from no decay, about 1e16 rows,η_wnears1 / nand nulls a key’s first rows, a few dozen atlags=3, though its statistic is right there to 1e-12.Without
half_life,dmis null where every differential of the key is the same value, whoseSis 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.