quantwave icon indicating copy to clipboard operation
quantwave copied to clipboard

hmm_bull_bear returns constant state 1 on price input (unusable as regime filter); undocumented {1,2} states on returns

Open lavs9 opened this issue 4 months ago • 1 comments

Summary

pl.col(...).ta.hmm_bull_bear() returns a constant 1 for every bar when fed a price series, regardless of the underlying trend — an all-up series and an all-down series both classify as 100% state 1. The indicator only produces varying output when fed returns, and even then emits states labelled {1, 2} rather than the 0/1 (bear/bull) a caller would expect. This makes it unusable as a regime filter on price data without undocumented preprocessing.

Environment

  • quantwave 0.7.0
  • polars 1.40.1
  • Python 3.12, macOS (arm64)

Minimal reproduction

import polars as pl, quantwave, numpy as np
np.random.seed(1)

def series(drift, n=400, vol=0.01, p0=100.0):
    p = [p0]
    for _ in range(n): p.append(p[-1] * (1 + np.random.normal(drift, vol)))
    return p

def counts(vals):
    v = np.asarray(vals, float); v = v[~np.isnan(v)]
    u, c = np.unique(v, return_counts=True); return dict(zip(u.astype(int).tolist(), c.tolist()))

def hmm(x):
    return (pl.DataFrame({"c": [float(v) for v in x]})
            .select(pl.col("c").ta.hmm_bull_bear().alias("r")).to_series().to_numpy())

up, dn = series(0.004), series(-0.004)
print("PRICE  uptrend  ->", counts(hmm(up)))
print("PRICE  downtrend->", counts(hmm(dn)))
print("RETURN uptrend  ->", counts(hmm(np.diff(np.log(up)))))
print("RETURN downtrend->", counts(hmm(np.diff(np.log(dn)))))

Actual output

PRICE  uptrend  -> {1: 401}
PRICE  downtrend-> {1: 401}
RETURN uptrend  -> {1: 398, 2: 2}
RETURN downtrend-> {1: 361, 2: 39}

Same behaviour on real data: run against ~4,100 daily closes of the NIFTY 50 index, hmm_bull_bear returned 1 for all 4,106 bars.

Expected

  • On a price series with a clear regime change, the classifier should switch states (bull vs bear), not return a single constant state.
  • State labels should be documented and ideally normalised (e.g. 0 = bear, 1 = bull). The current {1, 2} labelling (only on returns input) is undocumented and easy to misread.

Observations / questions

  1. Input expectation is undocumented. It appears the indicator wants returns, not price levels — but .ta accessors generally take price/close. If returns are required, that should be stated (and price input should probably error or be internally differenced rather than silently collapsing to a constant).
  2. State semantics. On returns input it emits {1, 2}, with 2 appearing far more often in the downtrend (39 vs 2), suggesting 2 ≈ bear — but this isn't documented.
  3. Look-ahead. If the HMM is fit in batch over the whole series, the classification at bar t uses future data. Given the library's "bit-identical streaming & batch" guarantee, it would help to confirm hmm_bull_bear is causal (streaming-safe) for backtesting use.

Impact

Discovered while dogfooding quantwave as the compute layer for a momentum backtest, using hmm_bull_bear as a market-regime gate on NIFTY 50. Because it returned a constant on price input, the gate never triggered defensively; when coerced via returns it fired on ~8% of days and degraded every backtest metric — consistent with an unreliable/constant signal rather than a working regime classifier.

Minor, likely-by-design (noting for docs)

  • stddev(N) uses population std (ddof=0); pandas .std() defaults to ddof=1. TA-Lib convention, but a documented note would prevent parity surprises.
  • roc(N) is scaled ×100 (TA-Lib convention); rocp(N) gives the raw price/price_N - 1 ratio.

lavs9 avatar Jul 24 '26 05:07 lavs9

All three concerns here are already addressed on main/PyPI (v0.8.0+, currently v0.8.1) — filed independently as quantwave-wrz0 from a degenerate-input audit, so this issue and that fix crossed paths without a cross-link. Confirmed by rerunning your exact repro against the published 0.8.1 wheel:

1. Silent constant on price input → now raises, doesn't silently degrade.

PRICE uptrend raised: ComputeError the plugin failed with message:
hmm_bull_bear: input looks like price, not returns — 401 of 401 bars
underflowed both Gaussian emissions (bull_bear() assumes daily returns
near zero: means=[0.001, -0.002], stds=[0.01, 0.02]). Pass a returns
series (e.g. pl.col("close").pct_change() / .ta.rocp()) instead of raw
price.

The plugin now detects the majority-degenerate-emission case (both Gaussians underflowing on most bars — the exact signature of feeding it price instead of returns) and raises a clear, actionable ComputeError instead of returning a plausible-looking constant 1 for every bar.

2. State-label semantics — now documented explicitly. From the regime detection guide:

State labels are {1, 2}, not {0, 1}. 0 is reserved for "no regime decided yet" — Bull is 1, Bear is 2.

Plus an explicit input-contract callout ("pass returns, not price") with the exact hardcoded emission means/stds that make it returns-scale-only, and an edge-case table entry describing exactly the failure mode you hit.

3. Look-ahead / causality — confirmed causal, and a prior doc error was corrected. hmm_bull_bear decodes with online Viterbi, one bar at a time — no batch fit, no look-ahead. It's safe for backtesting. (Worth noting: an earlier version of this project's own internal docs incorrectly claimed the opposite — that it batch-fits and is lookahead-contaminated — which has since been corrected; if you saw that claim anywhere, it was wrong.)

The unreliable-signal degradation you saw dogfooding this against NIFTY 50 was very likely the constant-1-on-price-input bug specifically (a regime gate that's always "bull" never triggers defensively, exactly matching your "gate never triggered defensively" observation) — feeding it pct_change()/.ta.rocp() returns instead of raw price should behave as expected now.

Your two "minor, likely-by-design" notes (stddev ddof=0, roc vs rocp scaling) are also already documented with explicit !!! danger callouts on the relevant indicator pages, for the same reason — thanks for flagging them independently, good confirmation they were worth calling out.

Closing since this needs no further code change — upgrade to quantwave>=0.8.0 and switch the regime gate to a returns column. Reopen if you still see a constant/degenerate output after that.

lavs9 avatar Sep 27 '26 02:09 lavs9