Repository navigation
fix(analytics): indicators on gaps and chains, point-in-time factors, costs, attribution, certification analytics (sweep 11-25) - #8
Merged
Conversation
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
force-pushed
the
fix/sweep1125-quant-analytics
branch
from
November 25, 2026 17:21
419f26b to
9b81c24
Compare
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
This was referenced Nov 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/mainbefore any change; each FIXED issue has a test that fails onorigin/mainand passes here (checked by running the new test files against a cleangit 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:
analytics.max_drawdownraises 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.caps_at_start=True; today's caps as single numbers had shown a value premium in noise.turnover_analysisraises for traded symbols with no ADV (or no volatility for sqrt/Almgren-Chriss);sqrt_impactno longer uses a volatility of 1.0 (163 bps vs 8.16); linear and Almgren-Chriss impact raise without ADV/volatility; no cost model meansNone, not 0.momentumpickles and documents the indicator; NumPy SMA is O(n);factor_attributionreturnsNone, 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_impactwithout volatility raises a clearValueError;certifyraises 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'salpha_risk_cost_optimize(which callsestimate(0.0, 0.0, 0.0)).turnover_analysisonly 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) computesadvandvolbut never passes them toturnover_analysis. With this release that call raises, so the one-line cpzai change (passadv=adv, volatility=vol) must ship BEFORE cpz-quant 1.3.0 is published (routed to strategy-lab). cpz-ai (cpz-py)atr_sizeneeds anisfiniteguard, sinceatris NaN after one null high.Per-issue verdicts
fundamental_factorsregresses 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. Newstart_index,momentum_skip.sma(20)45.52 vs true 45.04 (pandas);ema,macd,atrreturned pre-gap values where TA-Lib gives NaNsma/ema/dema/tema/bollinger/macdofrsi(9)andsma(atr): 0 non-NaN values;rsi(sma(30))44 zeros, up to 4.67 off TA-Lib; stochastic %D warm-up filled with 50SMA(RSI),BBANDS(RSI),RSI(SMA),RSI(WMA),STOCHFfastd (1e-9).rsi(40 bars at 25.00)= 0.0;rsi/williams_r/stochastic/sma/cci(empty frame)= 0.0,ema/atr/macdIndexErrorValueError("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.min_lag10. 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.ichimoku(displacement=0)span at t changes when later bars are removed (100.66 vs NaN); Supertrend crash-bar test still on the long bandema/macddocstrings state the first-value seed and how it differs from TA-Lib/apo().realized_vol111.5 vs 0.271,donchianupper = volume,hurst0.087 vs 0.671;obv(numpy)= 0; globalTRADING_DAYS_PER_YEAR = 365changes nothingsourceon a bare series andobv()without volume raise. Rust Garman-Klass only used withannualize=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); passtrading_days=per call.momentum()broken afterrsi()ci.rsi(c); ci.momentum(c, 10)->TypeError: 'module' object is not callablemomentumsubmodule is made callable as the indicator, soind.momentum(bars, 10)andimport cpz_quant.indicators.momentum as moboth work in any order.estimated_cost_bps= sum(permanent_fraction0/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)estimatedocumented as one leg (the number was right for per-trade sums, the docstring said round trip);breakdown()splits impact bypermanent_fraction; unknown model raises; Almgren-Chriss refusesimpact_coefficient/impact_exponent/permanent_fractionit does not use; all impact models use abs(notional).rolling_attribution); Euler per-factor split infactor_risk_decompositionandrisk_attribution; drawdown peak includes the starting value; flat days at a high are not under water (NumPy and Rust).np.int64trades -> provisional;np.float32/np.bool_-> Not Certifiednumbers.Realandnp.bool_accepted.max_drawdown=-0.62-> "Max drawdown 0.6%", risk 65, grade BCertMetrics.max_drawdowndocumented as percent; a value with magnitude below 1 raises unlessanalytics=confirms a genuine sub-1% drawdown.cross_validate->AttributeError: 'DataFrame' object has no attribute 'keys'cross_validateandgrid_searchaccept 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
origin/main); 135 new tests (92 in the first round, 43 after the reviews) intests/test_indicators_gaps_and_inputs.py,tests/test_costs_attribution_factors.py,tests/test_certification_fixes.py. Of those, 81 fail onorigin/main; the other 11 are guards (clean data raises no warning, pandas already worked incross_validate, percent drawdowns still score as before, and so on).maturin develop --release); Python and Rust analytics agree on 40 random curves including short and below-zero wipe-outs;cargo test9 passed (4 new). Coverage 84.3%.ruff checkclean;mypy cpz_quantclean (with mypy 2.4 and numpy 2.4 it reports 10 errors onorigin/main, in the oldfundamental_factorsandrsi_seriescode replaced here and two inadx_series, now cast to float).Behaviour changes worth knowing (also in CHANGELOG "Changed (may break callers)")
ValueError; on a NaN latest value they return NaN with aRuntimeWarning.hurst()defaultmin_lagis 10 (was 2) and values are lower by about 0.13 for the same series (bias removed).fundamental_factorswith momentum regresses only days frommomentum_windowon;factor_returnslists are shorter (seestart_index),factor_loadingsare the end-of-sample exposures.alpha_decay_capacity,brinson_fachler,fundamental_factorsandcertifyraise on inputs they used to drop or guess.Shared modules
cpz_quant/portfolio/risk_measures.pyis 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 thegrid_searchbody alone (frames reach it throughcross_validate), so the only expected conflict is the[Unreleased]list inCHANGELOG.md, where both PRs add entries: keep both.Follow-ups (not in this PR)
supabase/functions/_shared/risk-analytics.tshas 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.tsgives 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 stochasticandstoch_rsikeep 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 thecpz-quantfloor in cpz-ai (cpz-py) socpz.indicators,cpz.portfolioandcpz.certificationpick it up. Anyone running the optional Rust extension should rebuild it (cd rust && maturin develop --release).