Skip to content

fix(portfolio): allocators, optimisers and covariance estimators match their published methods (sweep 11-25) - #9

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

chris-cpz merged 3 commits into
mainfrom
fix/sweep1125-quant-optim

Conversation

@chris-cpz

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

Copy link
Copy Markdown
Contributor

Allocators, optimisers and covariance estimators now match the methods they are named after, enforce the limits they accept, and raise instead of returning numbers built from a failed solve or a missing return. Reference values come from the papers' published code (Ledoit-Wolf covCor.m/covMarket.m, Lopez de Prado's MLAM snippets), scikit-learn (live in the tests), and PyPortfolioOpt / riskfolio-lib (frozen in tests/fixtures/allocator_reference.npz, regenerated by tests/reference/generate_allocator_fixture.py).

Every issue was reproduced on origin/main first (scripts on seeded ETF-like returns, then the new tests: 106 of the 114 new tests fail on origin/main; the other 8 are guards that hold on both).

Per-issue verdicts

Issue Verdict What changed Verified real by
CPZ-Lab/cpzai#3016 HRP / HERC weights FIXED HRP splits by inverse variance (1 - V1/(V1+V2)), one asset returns 100%. HERC walks the dendrogram down to K clusters with summed cluster variances (riskfolio-lib's HERC). Schur and QHRP use the same split. main: HRP 27 points off PyPortfolioOpt on SHY, one-asset HRP raised scipy ValueError; HERC 21/29/36 points off riskfolio at k=3/4/5. test_hrp_matches_pyportfolioopt, test_herc_follows_the_dendrogram_like_riskfolio, test_hrp_single_asset_is_fully_invested fail on main.
CPZ-Lab/cpzai#3017 QHRP ordering FIXED Exact and QUBO modes now argsort the solved positions (they used positions as an order). Default heuristic is spectral seriation (Fiedler vector of the similarity Laplacian) plus pairwise-swap refinement; RCM left dense matrices unsorted. Brute force vectorised (9 assets: 30 s to 0.3 s). main, 9 assets in 3 groups: brute-force order W=222.9 vs optimum 52.0; heuristic = columns reversed (W=199.3); weights moved 35 points under column shuffles. Branch: both reach W=52.0, shuffle change 0.000. test_qhrp_* fail on main.
CPZ-Lab/cpzai#3019 covariance estimators FIXED OAS = Chen et al. Eq. 23 as sklearn implements it; EWMA normalises weights, exact half-life; MP = Lopez de Prado constant residual eigenvalue method with KDE-fitted noise variance, variances preserved; Ledoit-Wolf uses each paper's intensity (covCor.m, covMarket.m, sklearn for identity) and single_factor is now actually the single-index target (it was a copy of constant correlation); every estimator raises on a missing value. main: OAS largest eigenvalue 6.3e10 vs sklearn 0.0028 (30 assets x 20 days); EWMA 60-day eq-weight vol 7.68% vs normalised 10.84%; MP moved variances 3-4%; LW constant-correlation 0.0268 vs covCor.m 0.0201; one NaN gave 91/100 NaN entries. Branch matches sklearn/PyPortfolioOpt/LdP code to ~1e-15.
CPZ-Lab/cpzai#3020 exposure caps, failed solves, max_return, entropy pooling FIXED mean_cvar is an exact Rockafellar-Uryasev LP (HiGHS). mean_cvar, robust_mvo, max_diversification, min_tracking_error, turnover_penalized, alpha_risk_cost_optimize enforce the gross cap, reject unsupported limits, raise on failed or infeasible solves. mean_risk_optimize gets max_risk (required for max_return) and raises instead of returning equal weights. entropy_pooling preconditions views and only reports converged when they hold (max_view_error added). main: robust_mvo 30.2x gross and turnover_penalized 31.3x under a 1.0 cap; 60% CVaR target returned 27.2% with no error; max_return put 100% in one asset; a 1e-4 daily view missed by 7.9% with converged=True.
CPZ-Lab/cpzai#3046 alpha-risk-cost costs and TC FIXED (partial) Cost is t * cost_model.estimate(t * portfolio_value, adv, vol) / 1e4 per asset traded t (new portfolio_value, adv, daily_volatility; size-dependent impact without them raises); cost_model=None is zero cost; transfer_coefficient = alpha'w / (sqrt(alpha' Sigma^-1 alpha) sqrt(w' Sigma w)), in [-1, 1]. Weights match cvxpy to 2e-5 at 0, 2.5 and 200 bps. Not fixed here: cpz-py cpz/alpha/analysis.py:341 transfer_coefficient uses the same corr(a, w*a) ratio (returns 1.0 for an all-cash book); that is CPZ-Lab/cpz-py, OTHER GROUP. The "long-only ranks above looser" sub-claim is not a property the correct TC guarantees under a fully invested budget, so no test asserts it. main: default and 300+50 bps models gave identical weights (turnover 1.0 vs cvxpy 0.359 at 200 bps); None charged 10 bps; TC up to 5.66 across 30 seeds.
CPZ-Lab/cpzai#3049 robust MV uncertainty scale FIXED Estimation-error covariance is 252 * cov / T (cov and mu annualised); kappa=1 is one standard error of the annualised mean. main: penalty 0.0104 vs hand-computed SE 0.1653 (ratio 15.9 = sqrt(252)). Branch ratio 1.0. test_robust_penalty_is_one_standard_error_of_the_annual_mean fails on main.
CPZ-Lab/cpzai#3051 copulas / pre-selection with blanks FIXED Copula fits, synthetic_returns, pseudo_observations and the pre-selection filters raise on missing values (constant series too); select_complete_assets counts blanks as missing and returns the kept assets on their common complete window. main: one NaN turned a 0.907 copula correlation into 0.000; pct-change frame gave an identity matrix; drop_zero_variance kept none of 10; top-3 Sharpe and lowest-vol picks wrong.
CPZ-Lab/cpzai#3079 cvxpy optimisers drop limits FIXED All four cvxpy optimisers raise NotImplementedError on sector, factor and tracking-error limits (Constraints carries no sector map, loadings or benchmark), same as the core optimisers; max_net_exposure < 1 raises; a positive min_weight now applies with long_only=True (cardinality raises on it and points to min_position). main: weights identical to the no-limit run for all three limits.
CPZ-Lab/cpzai#3124 risk parity NaN (HIGH) FIXED Cyclical coordinate descent on 0.5 x'Sx - sum b ln x (Spinu 2013; Griveau-Billion, Richard & Roncalli 2013); raises if it does not converge; NaN weights can no longer reach OptResult. main: SPY/TLT at rho=-0.6 gave NaN/NaN with Sharpe 0.0. Branch: closed form sigma_TLT/(sigma_SPY+sigma_TLT) to 1e-9; 5-asset weights match riskfolio-lib to 1e-5.
CPZ-Lab/cpzai#3126 min variance at gross cap 1.0 FIXED A long-only book already has gross exposure 1, so the cap is not passed to SLSQP (its gradient duplicated the budget row and SLSQP stopped early); when shorts are allowed the cap uses smooth epigraph variables. main: 2.51% vol vs cvxpy 1.44%, 0 of 20 column orders reached the minimum. Branch: 20 of 20.
CPZ-Lab/cpzai#3131 NCO max Sharpe in a falling market FIXED Raises ValueError when the cluster-level problem has no fully invested tangency portfolio (1'C^-1 m <= 0 for the cluster portfolios), where normalising returns the lowest-Sharpe mix. A single cluster with a negative 1'Sigma^-1 mu does not raise: the cluster-level step weights it negatively, which flips it back. Raises rather than the equal-weight fallback the report suggests (fail-loudly rule). main: Sharpe -4.04 vs equal weight -1.76 on a falling-market sample. test_nco_max_sharpe_refuses_when_no_tangency_portfolio_exists fails on main.
CPZ-Lab/cpzai#3137 Gerber not PSD FIXED g = (n_c - n_d) / (T - n_nn) (Gerber et al. 2021, PSD), population sd, inclusive thresholds; vectorised. Equals riskfolio-lib gerber_cov_stat1 exactly. main: not PSD in 130 of 130 rolling 90-day windows (riskfolio: 0); SPY-QQQ read 1.000.
CPZ-Lab/cpzai#3144 mean-risk only takes NumPy FIXED Accepts Polars, pandas and dicts, keeps the column names; asset_ids still names array columns. main: Polars, pandas and dict all raised TypeError.
CPZ-Lab/cpzai#3146 LW units, EWMA min_periods FIXED LW intensity is unit-invariant (no absolute floor); EWMA raises below min_periods. main: LW intensity 0.0268 at scale 1 vs 0.0095 at 0.01; one day of EWMA returned an all-zero matrix.

Fixes CPZ-Lab/cpzai#3016
Fixes CPZ-Lab/cpzai#3017
Fixes CPZ-Lab/cpzai#3019
Fixes CPZ-Lab/cpzai#3020
Fixes CPZ-Lab/cpzai#3049
Fixes CPZ-Lab/cpzai#3051
Fixes CPZ-Lab/cpzai#3079
Fixes CPZ-Lab/cpzai#3124
Fixes CPZ-Lab/cpzai#3126
Fixes CPZ-Lab/cpzai#3131
Fixes CPZ-Lab/cpzai#3137
Fixes CPZ-Lab/cpzai#3144
Fixes CPZ-Lab/cpzai#3146
Refs CPZ-Lab/cpzai#3046 (cpz-quant part fixed; cpz-py alpha.transfer_coefficient still open)

Behaviour changes callers will see

  • These now raise where they used to return numbers: missing or non-finite returns in any covariance estimator, copula or pre-selection filter; unsupported limits and failed or infeasible solves in the native and cvxpy optimisers listed above; NCO max-Sharpe without a tangency portfolio; mean_risk_optimize(objective="max_return") without max_risk; a size-dependent cost model without portfolio_value/adv/daily_volatility; a partial risk_parity budget; out-of-range HERC n_clusters; denoise_mp with T <= N.
  • Defaults that were silently ignored now bind, for example the default Constraints() gross cap of 2.0 in robust_mvo, mean_cvar, turnover_penalized and alpha_risk_cost_optimize.
  • HRP, HERC, Schur, QHRP and every covariance estimator except sample_cov, factor_model_cov and detone_cov return different numbers (the corrected ones). Ledoit-Wolf and OAS now use the maximum-likelihood sample covariance (divide by T), as the papers and sklearn do.

Tests

  • Python 3.11 (numpy 2.4.6, scipy 1.17.1, cvxpy 1.9.3): 881 passed, 722 skipped (the TA-Lib suite; TA-Lib is not installed locally). Coverage 76.70% (floor 55%).
  • Python 3.9 (numpy 2.0.2, scipy 1.13.1, cvxpy 1.7.5), portfolio suites: 264 passed, 5 skipped.
  • cpz-py's suite against this branch: 2165 passed, 53 skipped, 2 failed. One is its zero-drift copy of test_max_sharpe_runs (that sample has no tangency portfolio; 1.2.0 returned the lowest-Sharpe mix), updated in CPZ-Lab/cpz-py#82, which should merge before 1.3.0 is published (it also updates the certification test copy that cpz-quant#8 breaks). The other, test_health_decay.py::test_rolling_sharpe_zero_variance_window_is_none_not_fabricated, also fails against cpz-quant origin/main.
  • ruff check cpz_quant tests clean. mypy cpz_quant: only the 10 errors already on origin/main (indicators/momentum.py, portfolio/factors.py).
  • GitHub Actions does not run on this repo right now: every recent main run failed in 4 s with "The job was not started because your account is locked due to a billing issue."

Notes

  • Stayed in allocator, optimiser and covariance modules (optimization.py, convex.py, covariance.py, risk_measures.py mean-risk part, entropy_pooling.py, copula.py, preselection.py). costs.py is untouched; the ARC integration validates CostModel.impact_model itself because CostModel.estimate silently prices an unknown model as zero impact and sqrt_impact assumes 100% daily volatility when given 0.
  • The rust/ crate's ledoit_wolf, ewma_cov, denoise_mp, risk_parity_weights and hrp_weights are not called by the Python package and still implement the old formulas. README, docs/index.md and rust/README.md now say so; the Rust code itself is unchanged.
  • mean_cvar names target_return and the highest attainable return when the target is out of reach. The QHRP split search uses a 2D prefix sum (identical splits on 30 test universes; 500 assets went from 6.5 s to 0.7 s); exactly tied splits go to the first one, independent of summation rounding.

Release note for Chris

Nothing published. Merge CPZ-Lab/cpz-py#82 first (cpz-ai takes any cpz-quant >= 1.1.0). To ship: bump cpz-quant to 1.3.0 (behaviour fixes plus new keyword arguments; several calls now raise instead of returning wrong numbers), move the Unreleased CHANGELOG entry under ## [1.3.0], tag, and let publish.yml push to PyPI (CI billing lock needs clearing first).

…h their published methods

- HRP splits by inverse variance (Lopez de Prado 2016, PyPortfolioOpt) and
  handles one asset; HERC follows the dendrogram (Raffinot 2018, riskfolio-lib).
- Quantum-inspired HRP reads solved positions the right way round; the
  heuristic is spectral seriation with swap refinement.
- Risk parity uses cyclical coordinate descent (no NaN for stock-bond pairs).
- NCO max-Sharpe raises when no tangency portfolio exists.
- mean_cvar is an exact LP; native optimisers enforce gross caps through
  smooth epigraph variables, reject unsupported limits and raise on failed
  solves; a redundant long-only gross cap no longer stalls SLSQP.
- alpha_risk_cost_optimize prices trades per unit traded and reports the
  Clarke, de Silva & Thorley transfer coefficient.
- cvxpy optimisers raise on sector, factor and tracking-error limits; robust
  mean-variance uses the standard error of the annualised mean.
- mean_risk_optimize accepts frames, needs max_risk for max_return.
- entropy_pooling verifies its views.
- OAS, Ledoit-Wolf (all targets), EWMA, Marchenko-Pastur and Gerber match
  sklearn, the authors' published code and riskfolio-lib; estimators,
  copulas and pre-selection raise on missing returns.

Refs CPZ-Lab/cpzai#3016 #3017 #3019 #3020 #3046 #3049 #3051 #3079 #3124
#3126 #3131 #3137 #3144 #3146
- NCO max-Sharpe checks for a tangency portfolio only in the cluster-level
  problem. A cluster with a negative 1'Sigma^-1 mu is weighted negatively
  there, which flips it back, so it no longer raises; the error names NCO and
  the clusters and suggests only objective='min_variance'.
- select_complete_assets returns the kept assets on their common complete
  window, so its output feeds the next step.
- cvxpy optimisers apply a positive min_weight when long_only=True;
  cardinality_constrained_cvx raises on one and points to min_position.
- mean_cvar names target_return and the highest attainable return when the
  target is out of reach.
- QHRP split search uses a 2D prefix sum (same splits, 10x faster at 500
  assets).
- README, docs and rust/README.md stop claiming the Rust crate accelerates
  Ledoit-Wolf, EWMA, Marchenko-Pastur or HRP; CHANGELOG lists the new errors.
chris-cpz pushed a commit that referenced this pull request Nov 25, 2026
…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
The prefix-sum split search compared costs that tie in exact arithmetic but
differ by summation rounding, so tied splits were broken by rounding (an
equal-similarity block of 28 picked 21 where the loop picked 8). Take the
first split within a relative 1e-9 of the minimum instead, and test it.
@chris-cpz
chris-cpz merged commit 224a3d5 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