Skip to content

fix(analytics): indicators on gaps and chains, point-in-time factors, costs, attribution, certification analytics (sweep 11-25) - #8

Merged
chris-cpz merged 7 commits into
mainfrom
fix/sweep1125-quant-analytics
Nov 29, 2026
Merged

chris-cpz merged 7 commits into
mainfrom
fix/sweep1125-quant-analytics

Conversation

@chris-cpz

@chris-cpz chris-cpz commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Bug sweep 11-25, group quant-analytics: indicators, factor models, costs, attribution and certification analytics. 19 issues filed in CPZ-Lab/cpzai (from the in-app bug reporter) against cpz-quant 1.2.0. Every one was reproduced on origin/main before any change; each FIXED issue has a test that fails on origin/main and passes here (checked by running the new test files against a clean git archive origin/main).

Review follow-ups (commit 9b81c24)

An independent review asked for these; each has a test that fails on the reviewed head (419f26b) and passes now:

  1. #3177: a fraction equal to analytics.max_drawdown raises at any size (a wipe-out's -1.0 read as "1.0%"), and a magnitude of 1 or less needs the analytics to confirm it as a percent.
  2. NaN in a window no longer becomes a made-up number in CCI, z-scores, ROC, momentum, STC, MFI, OBV, Williams %R, stochastic, Fisher, ADX, KAMA and regression R-squared. Flat prices give NaN in MFI, Ultimate Oscillator, fast stochastic and Williams %R (as RSI).
  3. #3039: single-number caps require caps_at_start=True; today's caps as single numbers had shown a value premium in noise.
  4. Invented liquidity removed: turnover_analysis raises for traded symbols with no ADV (or no volatility for sqrt/Almgren-Chriss); sqrt_impact no longer uses a volatility of 1.0 (163 bps vs 8.16); linear and Almgren-Chriss impact raise without ADV/volatility; no cost model means None, not 0.
  5. CHANGELOG has a "Changed (may break callers)" section.
  6. Short wiped-out curves report the total loss (NumPy and Rust); regimes count a wipe-out; momentum pickles and documents the indicator; NumPy SMA is O(n); factor_attribution returns None, not NaN; the #3072 commit trailer now says Refs (history rewritten with --force-with-lease, tree unchanged).

Re-review leftovers (commit 6b0ba23): CMO, CMF, Aroon, NVI/PVI and rolling correlation/beta also keep a missing bar NaN instead of a finite wrong number; sqrt_impact without volatility raises a clear ValueError; certify raises when the metrics drawdown contradicts the analytics drawdown. Each has a test that fails on 9b81c24. Without analytics, a metrics drawdown above 1 in magnitude (for example -1.5) is still read as a percent: it cannot be told apart from a real 1.5% drawdown.

Cross-PR fix (commit b6c94fa): a zero notional or a zero impact coefficient (and gamma = eta = 0 for Almgren-Chriss) has zero impact and needs no ADV or volatility, so a spread-and-commission-only CostModel(impact_coefficient=0) works again in #9's alpha_risk_cost_optimize (which calls estimate(0.0, 0.0, 0.0)). turnover_analysis only asks for ADV and volatility when impact is priced; priced impact still raises without them. Tests fail on 6b0ba23 and pass now. Combined tree (#7 4bd1475 + #8 b6c94fa + #9 3a880ea, CHANGELOG hand-merged in a scratch worktree): 1829 passed, 6 skipped, ruff and mypy clean.

Ship order: cpzai create-strategy-repo/content-generators.ts (around line 2398) computes adv and vol but never passes them to turnover_analysis. With this release that call raises, so the one-line cpzai change (pass adv=adv, volatility=vol) must ship BEFORE cpz-quant 1.3.0 is published (routed to strategy-lab). cpz-ai (cpz-py) atr_size needs an isfinite guard, since atr is NaN after one null high.

Per-issue verdicts

Issue Verdict Verified real by (on origin/main) Fix
cpzai#3039 HIGH momentum premium in noise FIXED 60 random-walk stocks x 504 days: momentum t = 5.41 / 4.98 / 4.81 (3 seeds); size t = -8.1 with end-of-sample caps fundamental_factors regresses day t on exposures known at t-1 (momentum t-252..t-21, caps rolled forward from a start-of-sample snapshot or given as a time series). 40-seed check: momentum t mean 0.22, sd 1.01. Missing caps/book values raise instead of defaulting to 1 / 0. New start_index, momentum_skip.
cpzai#3040 HIGH stale value after a missing bar FIXED One NaN close 60 bars back: sma(20) 45.52 vs true 45.04 (pandas); ema, macd, atr returned pre-gap values where TA-Lib gives NaN Scalar = value at the latest bar, never the last non-NaN one; NaN latest value warns. SMA is a true trailing window (blanks only windows holding the gap, like pandas); EMA family/MACD/RSI/ATR go NaN like TA-Lib; true range propagates NaN.
cpzai#3052 indicators of indicators FIXED sma/ema/dema/tema/bollinger/macd of rsi(9) and sma(atr): 0 non-NaN values; rsi(sma(30)) 44 zeros, up to 4.67 off TA-Lib; stochastic %D warm-up filled with 50 Smoothers skip a leading NaN warm-up. Now equal to TA-Lib SMA(RSI), BBANDS(RSI), RSI(SMA), RSI(WMA), STOCHF fastd (1e-9).
cpzai#3053 RSI 0 on flat, 0 on empty FIXED rsi(40 bars at 25.00) = 0.0; rsi/williams_r/stochastic/sma/cci(empty frame) = 0.0, ema/atr/macd IndexError RSI 0/0 is NaN (NumPy and Rust kernel). Empty input raises ValueError("no bars ...") in scalar form. Note: TA-Lib 0.8.0 itself returns 0 on flat (the reporter quoted 50); NaN is the undefined value, not a signal.
cpzai#3054 Hurst 0.63 on random walks FIXED 10 random walks of 750 bars: mean 0.635 (0.587 to 0.667); too-short input returned a made-up 0.5 Anis-Lloyd-Peters bias-corrected R/S (Weron 2002), default min_lag 10. 20 random walks: mean within 0.03 of 0.5; fGn with H=0.4 reads below 0.45. Too short gives NaN; non-positive prices raise.
cpzai#3071 Ichimoku d=0, Supertrend lag, EMA seed docs FIXED ichimoku(displacement=0) span at t changes when later bars are removed (100.66 vs NaN); Supertrend crash-bar test still on the long band Displacement < 1 raises. Supertrend follows pandas-ta: flips on the bar that closes through the band. ema/macd docstrings state the first-value seed and how it differs from TA-Lib/apo().
cpzai#3072 pandas frames, trading days, Rust GK FIXED (partial), Refs pandas frame: realized_vol 111.5 vs 0.271, donchian upper = volume, hurst 0.087 vs 0.671; obv(numpy) = 0; global TRADING_DAYS_PER_YEAR = 365 changes nothing pandas DataFrame/Series supported in every indicator (duck-typed, pandas still not imported); 2-D arrays, derived source on a bare series and obv() without volume raise. Rust Garman-Klass only used with annualize=True, trading_days=252; Rust kernels only on complete data. Partial: the trading-days constant is now documented as a default, not a global setting (CONTRIBUTING: no global state); pass trading_days= per call.
cpzai#3073 momentum() broken after rsi() FIXED ci.rsi(c); ci.momentum(c, 10) -> TypeError: 'module' object is not callable The momentum submodule is made callable as the indicator, so ind.momentum(bars, 10) and import cpz_quant.indicators.momentum as mo both work in any order.
cpzai#3045 turnover cost 30-100x high FIXED $50M book, 3% swap: 9.899 bps reported vs $1,484.85 = 0.297 bps by hand estimated_cost_bps = sum(
cpzai#3070 cost model one leg / settings / sells FIXED permanent_fraction 0/0.5/1 identical; Almgren-Chriss coefficient 0.1 vs 1.0 identical; "Sqrt" silently 2.5 bps; linear sell -22.5 bps; sqrt sell (2.5+3.16j) estimate documented as one leg (the number was right for per-trade sums, the docstring said round trip); breakdown() splits impact by permanent_fraction; unknown model raises; Almgren-Chriss refuses impact_coefficient/impact_exponent/permanent_fraction it does not use; all impact models use abs(notional).
cpzai#3050 capacity ignores shorts FIXED 50/50 long-short with the short in a $3M-ADV name: capacity $1,000,000,000 (short dropped) vs $600,000 by hand Uses abs(weight) for both limits; positions without ADV raise instead of being dropped.
cpzai#3132 attribution drops unmapped holdings FIXED TSLA unmapped: active 0.35% vs 1.70% actual; net-short Health sector: 4.10% vs 6.10% Unmapped holdings or missing returns raise; sector return defined for net-short sectors; a zero-net sector that still contributes raises.
cpzai#3029 IR, factor split, max drawdown, time under water FIXED IR +0.369 vs active/TE -0.817; per-factor parts 0.040242 vs factor variance 0.042882; maxdd(-3%,-4%) 4.0% vs 6.88%; time under water 200 vs 30 IR = mean active return / tracking error (also in rolling_attribution); Euler per-factor split in factor_risk_decomposition and risk_attribution; drawdown peak includes the starting value; flat days at a high are not under water (NumPy and Rust).
cpzai#3047 capture, worst month, wipe-outs FIXED 2x leveraged fund: up capture 403 vs about 2; June 2 crash: worst month 0.0 vs -10%; curve to 0: max drawdown -17.96%, Sharpe -0.49 Morningstar geometric per-period capture; month-end to month-end months; an equity value at or below 0 ends the curve as a total loss (-100%). Rust kernel updated, cargo tests added, Python/Rust parity checked on 30 curves including wipe-outs.
cpzai#3048 regime look-ahead FIXED Random walk vs itself: bull Sharpe +3.1, bear -2.8 Each day labelled from trailing vol of the days before it and the previous benchmark close vs its MA. 30 seeds: bull/bear means 0.04/0.09.
cpzai#3069 missing inputs score better, numpy types FIXED beta 0.8 -> 69.4 (C), no beta -> 74.7 (B); capacity missing 40 vs $20,000 -> 10; np.int64 trades -> provisional; np.float32 / np.bool_ -> Not Certified Missing beta/capacity score the lowest band; numbers.Real and np.bool_ accepted.
cpzai#3177 62% drawdown read as 0.6% FIXED max_drawdown=-0.62 -> "Max drawdown 0.6%", risk 65, grade B CertMetrics.max_drawdown documented as percent; a value with magnitude below 1 raises unless analytics= confirms a genuine sub-1% drawdown.
cpzai#3145 absurd alpha stats on exact fits FIXED 50/30/20 factor copy: R2 1.0, alpha 0, t -5.87, idiosyncratic Sharpe -4.36 Exact fit (residual SS below 1e-20 of the return scale) gives NaN t-stats and idiosyncratic Sharpe; non-exact fits unchanged.
cpzai#3006 docs example stops at validation FIXED (package) Docs example with a Polars frame: cross_validate -> AttributeError: 'DataFrame' object has no attribute 'keys' cross_validate and grid_search accept Polars and pandas frames like the allocators; the docs example now runs to the end (OOS Sharpe and stability printed). Docs text: OTHER GROUP (docs-legal-search), only if they want to note the minimum cpz-quant version once this is published; the example itself needs no change.

Fixes CPZ-Lab/cpzai#3006
Fixes CPZ-Lab/cpzai#3029
Fixes CPZ-Lab/cpzai#3039
Fixes CPZ-Lab/cpzai#3040
Fixes CPZ-Lab/cpzai#3045
Fixes CPZ-Lab/cpzai#3047
Fixes CPZ-Lab/cpzai#3048
Fixes CPZ-Lab/cpzai#3050
Fixes CPZ-Lab/cpzai#3052
Fixes CPZ-Lab/cpzai#3053
Fixes CPZ-Lab/cpzai#3054
Fixes CPZ-Lab/cpzai#3069
Fixes CPZ-Lab/cpzai#3070
Fixes CPZ-Lab/cpzai#3071
Fixes CPZ-Lab/cpzai#3073
Fixes CPZ-Lab/cpzai#3132
Fixes CPZ-Lab/cpzai#3145
Fixes CPZ-Lab/cpzai#3177
Refs CPZ-Lab/cpzai#3072 (partial: global trading-days setting documented, not added)

Tests

  • 1698 passed, 6 skipped (was 1563 + 6 on origin/main); 135 new tests (92 in the first round, 43 after the reviews) in tests/test_indicators_gaps_and_inputs.py, tests/test_costs_attribution_factors.py, tests/test_certification_fixes.py. Of those, 81 fail on origin/main; the other 11 are guards (clean data raises no warning, pandas already worked in cross_validate, percent drawdowns still score as before, and so on).
  • Reference values: TA-Lib 0.8.0 (SMA/BBANDS/RSI of RSI/SMA/WMA, STOCHF, EMA/MACD/ATR NaN), hand computations written in the tests (turnover dollars, one-leg cost, 600k participation cap, Brinson totals, Euler split, 6.88% drawdown, Morningstar capture, month-end returns), Anis-Lloyd-Peters expected R/S with fractional Gaussian noise.
  • Also passing with the Rust extension built (maturin develop --release); Python and Rust analytics agree on 40 random curves including short and below-zero wipe-outs; cargo test 9 passed (4 new). Coverage 84.3%. ruff check clean; mypy cpz_quant clean (with mypy 2.4 and numpy 2.4 it reports 10 errors on origin/main, in the old fundamental_factors and rsi_series code replaced here and two in adx_series, now cast to float).

Behaviour changes worth knowing (also in CHANGELOG "Changed (may break callers)")

  • Scalar indicator calls on an empty input now raise ValueError; on a NaN latest value they return NaN with a RuntimeWarning.
  • hurst() default min_lag is 10 (was 2) and values are lower by about 0.13 for the same series (bias removed).
  • fundamental_factors with momentum regresses only days from momentum_window on; factor_returns lists are shorter (see start_index), factor_loadings are the end-of-sample exposures.
  • alpha_decay_capacity, brinson_fachler, fundamental_factors and certify raise on inputs they used to drop or guess.
  • Python certification analytics and grading now differ from the cpzai edge engine (see follow-ups).

Shared modules

cpz_quant/portfolio/risk_measures.py is also being edited by the quant-optim sweep (optimizer input handling). This PR only changes _drawdowns (lines 61-73), which does not overlap their hunks.

PR #7 (sweep 11-25 sdk-options) changes grid_search. This PR leaves the grid_search body alone (frames reach it through cross_validate), so the only expected conflict is the [Unreleased] list in CHANGELOG.md, where both PRs add entries: keep both.

Follow-ups (not in this PR)

  • cpzai platform parity (owner of certification on the platform, likely strategy-lab): supabase/functions/_shared/risk-analytics.ts has the same compounding capture (lines 139-145), first-to-last month returns (line 172) and drops equity at or below zero (line 56); supabase/functions/_shared/certification.ts gives a missing beta 50 and a missing capacity 40 (lines 542-550, 570-578). Until those change, SDK and hosted grades differ for these cases.
  • slow stochastic and stoch_rsi keep TA-Lib's zero-range rule (0), which the TA-Lib parity suite checks.

Release note for Chris

Ship #7, #8 (and #9) together as cpz-quant 1.3.0, after the cpzai content-generators change above (minor version: new methods and fields such as CostModel.breakdown, TurnoverResult.estimated_cost_usd, FundFactorModel.start_index, momentum_skip, caps_at_start; several inputs now raise). Not bumped here: version, CHANGELOG release header and the publish are yours; the entries sit under [Unreleased]. After publishing, raise the cpz-quant floor in cpz-ai (cpz-py) so cpz.indicators, cpz.portfolio and cpz.certification pick it up. Anyone running the optional Rust extension should rebuild it (cd rust && maturin develop --release).

Simons added 4 commits November 25, 2026 11:17
… definition fixes

- The scalar form returns the value at the latest bar. A missing bar no
  longer yields a value from before the gap: SMA blanks only the windows
  holding it (as pandas), recursive smoothers turn NaN (as TA-Lib) and a
  NaN latest value warns. Empty input raises instead of returning 0.
- SMA, EMA, DEMA, TEMA, MACD, Bollinger, KAMA and Wilder smoothing skip a
  leading NaN warm-up, so indicators of indicators match TA-Lib; RSI of an
  SMA no longer counts the warm-up as flat bars; stochastic %D no longer
  fills the %K warm-up with 50.
- RSI of an unmoving price is NaN (0/0) instead of 0, in NumPy and Rust.
- momentum() stays callable after other momentum indicators import the
  submodule of the same name.
- pandas DataFrames and Series work everywhere; 2-D arrays, derived sources
  on a bare series and obv() without volume raise. Rust kernels only run
  on complete data, Rust Garman-Klass only with its fixed 252-day setting.
- Ichimoku refuses displacement < 1, Supertrend flips on the crossing bar
  (pandas-ta), EMA and MACD document their seed, Hurst uses the
  bias-corrected Anis-Lloyd-Peters rescaled range.

Fixes CPZ-Lab/cpzai#3040
Fixes CPZ-Lab/cpzai#3052
Fixes CPZ-Lab/cpzai#3053
Fixes CPZ-Lab/cpzai#3054
Fixes CPZ-Lab/cpzai#3071
Refs CPZ-Lab/cpzai#3072 (partial: the global trading-days setting is documented, not added)
Fixes CPZ-Lab/cpzai#3073
…shorts, attribution

- fundamental_factors builds exposures from data known before each day
  (momentum t-252..t-21, size from the previous close's cap); noise no
  longer shows a momentum premium. Missing caps or book values raise.
- turnover_analysis reports the rebalance cost in bps of the book and in
  dollars instead of summing per-trade bps.
- CostModel: estimate documented as one leg, breakdown() applies
  permanent_fraction, unknown models raise, Almgren-Chriss refuses settings
  it ignores, sells cost the same as buys in every impact model.
- alpha_decay_capacity counts short legs and refuses positions without ADV.
- brinson_fachler raises on unmapped holdings and counts net-short sectors.
- Information ratio is active return over tracking error; per-factor risk
  uses the Euler split; drawdowns count a loss on the first return.
- cross_validate and grid_search accept Polars and pandas frames.

Fixes CPZ-Lab/cpzai#3006
Fixes CPZ-Lab/cpzai#3029
Fixes CPZ-Lab/cpzai#3039
Fixes CPZ-Lab/cpzai#3045
Fixes CPZ-Lab/cpzai#3050
Fixes CPZ-Lab/cpzai#3070
Fixes CPZ-Lab/cpzai#3132
…, exact fits

- Time under water counts only days below the peak; up/down capture use
  Morningstar's geometric per-period ratio; worst/best month run month-end
  to month-end; an equity value at or below zero ends the curve as a total
  loss. The Rust kernel matches (cargo tests added).
- Regime breakdown labels each day from trailing volatility and the
  previous benchmark close, not from the day's own move.
- certify: a missing beta or capacity scores the lowest band, NumPy numbers
  and booleans are accepted, a fractional max_drawdown raises.
- factor_attribution: an exact fit reports NaN alpha t-stat and
  idiosyncratic Sharpe instead of rounding noise.

Fixes CPZ-Lab/cpzai#3029
Fixes CPZ-Lab/cpzai#3047
Fixes CPZ-Lab/cpzai#3048
Fixes CPZ-Lab/cpzai#3069
Fixes CPZ-Lab/cpzai#3145
Fixes CPZ-Lab/cpzai#3177
…_search

grid_search passes returns straight to cross_validate, which now accepts
Polars and pandas frames, so it needs no conversion of its own. Keeps the
grid_search body untouched next to the open grid_search fix (PR #7).
…p inputs, invented liquidity

- certify: a max_drawdown equal to analytics.max_drawdown (a fraction,
  including -1.0 for a wipe-out) raises at any size, and a magnitude of 1
  or less needs the analytics to confirm it as a percent.
- Indicators: scalar guards are NaN-aware (a NaN in the window gives NaN,
  not 0, 50, -50 or 0.5) in CCI, z-scores, ROC, momentum, STC, MFI, OBV,
  Williams %R, stochastic, Fisher, ADX, KAMA and the regression R-squared.
  Flat prices give NaN in MFI, the Ultimate Oscillator, fast stochastic and
  Williams %R, as in RSI.
- fundamental_factors: single-number caps need caps_at_start=True; caps
  given as series stay point in time.
- turnover_analysis, sqrt/linear/Almgren-Chriss impact and capacity raise on
  a missing or non-positive ADV or volatility instead of using 1% of the
  book, 2% a day or a volatility of 1.0; without a cost model the cost is
  None, not 0.
- A wiped-out curve too short for statistics still reports the total loss
  (NumPy and Rust); the regime breakdown counts a wipe-out.
- momentum module pickles by name and carries the indicator docstring; the
  NumPy SMA is O(n); factor_attribution returns None, not NaN, for
  undefined statistics.
- CHANGELOG: "Changed (may break callers)" section.

Refs CPZ-Lab/cpzai#3177
Refs CPZ-Lab/cpzai#3039
Refs CPZ-Lab/cpzai#3045
Refs CPZ-Lab/cpzai#3047
@chris-cpz
chris-cpz force-pushed the fix/sweep1125-quant-analytics branch from 419f26b to 9b81c24 Compare November 25, 2026 17:21
Simons added 2 commits November 25, 2026 12:33
… corr/beta; impact and drawdown checks

- CMO keeps a missing change NaN instead of a flat bar; CMF gives NaN for a
  missing high, low, close or volume instead of 0; Aroon gives NaN for a
  window holding a missing bar (argmax took the NaN as the extreme);
  NVI/PVI stay NaN after a missing bar instead of absorbing it; rolling
  correlation and beta give NaN instead of 0.
- sqrt_impact and Almgren-Chriss raise a clear ValueError when volatility
  is omitted (was a TypeError from float(None)).
- certify raises when the metrics drawdown contradicts the analytics one
  (for example -15 against -0.62); the tail-penalty test now passes the
  analytics drawdown so only the analytics differ.

Refs CPZ-Lab/cpzai#3040
Refs CPZ-Lab/cpzai#3045
Refs CPZ-Lab/cpzai#3177
…r volatility

sqrt, linear and Almgren-Chriss impact raised on a missing ADV even when
nothing was traded or impact was not priced (impact_coefficient=0, or
gamma = eta = 0). A spread-and-commission-only CostModel (as the
alpha-risk-cost optimizer in PR #9 uses with estimate(0.0, 0.0, 0.0)) then
failed. Those cases have zero impact and need no market inputs;
turnover_analysis only asks for ADV and volatility when impact is priced.
Priced impact still raises without them.

Refs CPZ-Lab/cpzai#3045
Refs CPZ-Lab/cpzai#3070
@chris-cpz
chris-cpz merged commit 66dd40a into main Nov 29, 2026
0 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant