quantwave icon indicating copy to clipboard operation
quantwave copied to clipboard

A single NaN input poisons EMA/beta forever and is hidden by supertrend

Open lavs9 opened this issue 3 weeks ago • 1 comments

Found while moving the trade_backtest 9-EMA Bounce backtest onto quantwave 0.9.0 (PyPI wheel, Python 3.12, macOS arm64). Every repro below was rerun and reproduces.

import numpy as np, quantwave as q
q.ema(3, np.array([1,2,3,np.nan,5,6,7.]))
# -> [1.0, 1.5, 2.25, nan, nan, nan, nan]   NaN forever

c = np.array([1,2,3,np.nan,5,6,7.])
[(r.value, r.direction) for r in q.supertrend(3, 2.0, c+1, c-1, c)]
# -> [(-3,1), (-2,1), (-1,1), (-1,1), (-1,1), (-1,1), (-1,1)]   stale, no NaN

rng = np.random.default_rng(3)
m = 100*np.exp(np.cumsum(rng.normal(0,.02,200)))
s = 100*np.exp(np.cumsum(rng.normal(0,.02,200)))
s[100] = np.nan
q.beta(52, m, s)   # finite on 52..99, then NaN for all 100 later bars

Expected: the docs say NaN propagates "for the duration of the rolling window". In practice:

  • EMA and the running-sum beta never recover from a single NaN;
  • supertrend swallows the NaN and keeps emitting the last value, so it disagrees with its own ATR.

Ask: pick one NaN policy, apply it to all indicators and document it. For example: skip and recover after the window, or raise on NaN. supertrend must not emit stale finite values.

lavs9 avatar Nov 11 '26 03:11 lavs9

Resolved in v0.10.0 (commits 080efe0c and df25c2cf).

  • EMA NaN Recovery: EMA::next guards against NaN by returning f64::NAN immediately without poisoning self.current_ema. When valid values resume, recursion continues cleanly.
  • Beta Self-Healing: TaBETA uses ring buffers to store history and cleanly self-heals running accumulators once the transient NaN ages out of the rolling window.
  • SuperTrend NaN State: SuperTrend now emits (f64::NAN, self.direction) immediately on NaN input or while ATR is NaN, rather than outputting stale finite values.
  • Volatility & Rolling Guards: TaATR, TrueRange, RollingMax, and RollingMin handle NaN inputs defensively without state corruption.
  • Regression tests verified in tests/python/test_dogfood_fixes.py::test_gh56_ema_nan_recovery, test_gh56_supertrend_nan_not_stale, and test_gh56_beta_nan_recovery.

lavs9 avatar Nov 11 '26 05:11 lavs9