quantwave icon indicating copy to clipboard operation
quantwave copied to clipboard

ta_atr diverges from exact Wilder/TA-Lib recursion by median 7.6% (up to 82%) on clean ~500-row weekly series

Open lavs9 opened this issue 2 months ago • 2 comments

Summary

.ta.ta_atr(N) (called via atr() in the trade_backtest repo's qw.py) disagrees with the exact Wilder/TA-Lib ATR recursion on real NSE-equity weekly OHLC series — not a handful of edge cases, but 1,728 of 1,729 ISINs tested showed >5% relative error on at least one bar, median relative error 7.6%, max 82%.

This contradicts qw.py's own docstring claim ("parity 0.0 vs the exact recursion") and its dogfooding log's prior claim that ta_atr is "exact TA-Lib Wilder ATR, incl. ragged listings" — that earlier validation apparently didn't hold on this series length/shape.

Environment

  • quantwave 0.7.0 (pip show quantwave)
  • Called via .ta.ta_atr() on a polars.Series, wrapped by qw.atr() in trade_backtest/qw.py (iterates per-symbol column, builds a fresh single-column pl.DataFrame per call)
  • Data: weekly-aggregated NSE equity OHLC, ~300–560 rows per series (10-year window, weekly bars), N=14

Repro

import polars as pl, quantwave  # noqa: F401 (registers .ta accessor)
import numpy as np, pandas as pd

def wilder_ref(high, low, close, N):
    """Exact TA-Lib ATR (Wilder): seed = SMA of first N true ranges, then
    ATR[i] = (ATR[i-1]*(N-1)+TR[i])/N."""
    pc = close.shift(1)
    tr = np.maximum(high - low, np.maximum((high - pc).abs(), (low - pc).abs()))
    a = np.full(len(tr), np.nan)
    t = tr.to_numpy()
    valid = np.where(~np.isnan(t))[0]
    s = valid[0]; seed_end = s + N
    a[seed_end - 1] = np.nanmean(t[s:seed_end])
    for i in range(seed_end, len(t)):
        a[i] = (a[i - 1] * (N - 1) + t[i]) / N
    return pd.Series(a, index=close.index)

def qw_ta_atr(high, low, close, N):
    dfp = pl.DataFrame({"h": high.to_numpy(float), "l": low.to_numpy(float), "cl": close.to_numpy(float)})
    return pd.Series(
        dfp.select(pl.col("h").ta.ta_atr(pl.col("l"), pl.col("cl"), N).alias("a")).to_series().to_numpy(),
        index=close.index,
    )

# high/low/close = a single ISIN's clean weekly series, no gaps, no NaNs, ~561 rows
ref = wilder_ref(high, low, close, 14)
q = qw_ta_atr(high, low, close, 14)

diff = (q - ref).abs()
relerr = diff / ref.abs()
print("max abs diff:", diff.max())          # ~1240 on this series (price scale ~1e5)
print("max rel err:", relerr.max())          # ~0.16 on this series; up to 0.82 across the universe

The divergence is gradual, not a step change — ref and q track closely for the first ~450 rows, then drift apart by a growing amount over roughly a dozen bars and the gap persists (doesn't decay back toward zero via the recursion). This pattern — growing slowly over a long recursive series, present even in isolated single-column calls (ruled out cross-column state leakage), on totally clean input (verified: no NaNs, no missing weeks, no gaps) — points to float-precision drift accumulating through the recursive IIR smoothing over long series as the most likely mechanism, but this is a hypothesis based on the symptom, not confirmed against the Rust implementation.

Scope check

Ran the same comparison across the full universe (1,729 ISINs, same 14-period weekly ATR):

  • 1,728 / 1,729 ISINs had at least one bar with >5% relative error vs the exact recursion
  • 1,723 / 1,729 had at least one bar with >10% relative error
  • Median relative error across all valid (non-NaN) cells: 7.6%
  • Max relative error observed: 82%
  • Not correlated with price magnitude (both a ₹84 stock and a ₹1.5L+ stock showed 30-40%+ worst-case error) — rules out a "large-number precision" explanation as the sole cause, still consistent with generic float accumulation over series length instead of magnitude.

Ask

Could you check whether ta_atr's Rust implementation uses f32 internally anywhere in its recursive smoothing step, or otherwise accumulates rounding error over long series? If it's expected behavior on some other precision setting, a doc note on the practical series-length limit where ta_atr should be treated as approximate (rather than "parity 0.0") would help — the current docstring in qw.py (built against an earlier quantwave validation) currently overstates the guarantee for anything longer than whatever series length that was tested on.


Filed from independent VCP-strategy backtest work in trade_backtest/vcp-research/ — full context and workaround (falling back to the pandas Wilder reference, qw._atr_ref) in that repo's quantwave-dogfood.md.

lavs9 avatar Sep 23 '26 17:09 lavs9

Investigated this — good news: it's not a float-precision/f32 issue as hypothesized, and it's already fixed on main (shipped in v0.8.0, currently v0.8.1).

Root cause: .ta.ta_atr used to take the receiver as high, with (low, close) as the two positional args — an artifact of how the plugin's Python signature was originally generated (ta_atr(self, in2, in3) forwarded positionally, rather than named after what the underlying Rust function actually consumes). That's exactly the calling convention your repro (and presumably qw.py's atr() wrapper) uses:

pl.col("h").ta.ta_atr(pl.col("l"), pl.col("cl"), N)   # receiver = high

This was fixed in v0.8.0 (quantwave-sww3 in the changelog) — the receiver is now close, matching the sibling .ta.atr's convention:

pl.col("cl").ta.ta_atr(pl.col("h"), pl.col("l"), N)   # receiver = close (correct)

I reran your exact repro shape against the published 0.8.1 wheel, both ways, against your same independently-computed exact-Wilder reference:

--- receiver=high (old convention, what your repro uses) ---
max rel err: 0.34
median rel err: 0.085

--- receiver=close (new/correct convention) ---
max rel err: 0.0
median rel err: 0.0

Zero error against the independent reference on the corrected call — so the Rust recursion itself (TaATR, in quantwave-core) has always been mathematically exact; there's no f32 anywhere in it, and no precision drift accumulating over long series. The entire divergence you measured is fully explained by the receiver-order bug, not a numerical one. (The "gradual drift, not a step change, doesn't decay" pattern you noticed makes sense too: swapping which column plays which role in the true-range formula produces a different wrong TR value every single bar, not a one-off perturbation — so it never has a chance to decay back through the recursion.)

Also worth noting: ta_natr and ta_trange had the exact same receiver-order bug and got the same fix in v0.8.0, so if qw.py calls those with the old convention too, they need the same update.

Action needed on your side: update qw.py's atr() wrapper (and any ta_natr/ta_trange callers) to the new receiver-is-close convention, and upgrade to quantwave>=0.8.0 (0.8.1 is current). See the 0.8.0 release notes "Upgrade notes" section, and tests/python/test_ta_prefixed_arg_order.py for the exact reference-value regression test covering this.

Since this is already fixed on main/PyPI and doesn't need any further code change, closing — reopen if you still see drift after switching the calling convention and upgrading.

lavs9 avatar Sep 23 '26 17:09 lavs9

Root cause found — not a quantwave bug, a stale call site in the consuming repo

Upgraded to quantwave 0.8.1 and re-ran the exact repro from the issue body. Found it in your own changelog for 0.8.0:

BREAKING: ta_atr, ta_natr and ta_trange now take close in the receiver, matching their non-prefixed siblings. Before: pl.col("high").ta.ta_atr("low", "close"). Now: pl.col("close").ta.ta_atr("high", "low"). The old call "returned a plausible wrong number with no error... roughly 10% off."

trade_backtest/qw.py's atr() wrapper was written against the pre-0.8.0 API (pl.col("h").ta.ta_atr(pl.col("l"), pl.col("cl"), N) — high as receiver) and was never updated after upgrading past 0.8.0. That's exactly the failure mode your changelog describes for the old call order — reproduced here at much larger scale (median 7.6%, max 82% relative error across 1,729 real NSE-equity series) simply because it's a longer/more varied dataset than whatever surfaced the original ~10% number.

Fixed the call site (pl.col("cl").ta.ta_atr(pl.col("h"), pl.col("l"), N)) and re-ran the same parity check: median relative error now 0.0, max 3.3% (down from median 7.6%/max 82%), 0 of 1,729 ISINs over a 5% threshold (down from 1,728). As a bonus, the real ta_atr also turned out to correctly handle an internal data gap that a separate hand-rolled pandas reference (qw._atr_ref, used as a stopgap while this was unresolved) did not — no extra workaround needed once the call site matched the 0.8.0 signature.

Closing — this was on my end, not quantwave's. Leaving the issue up for anyone else who upgrades past 0.8.0 without touching an old ta_atr(high, low, close)-shaped call site; the silent-wrong-value failure mode is worth being able to search for.

lavs9 avatar Sep 24 '26 07:09 lavs9