Repository navigation
fix(portfolio): allocators, optimisers and covariance estimators match their published methods (sweep 11-25) - #9
Merged
Conversation
…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.
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.
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 intests/fixtures/allocator_reference.npz, regenerated bytests/reference/generate_allocator_fixture.py).Every issue was reproduced on
origin/mainfirst (scripts on seeded ETF-like returns, then the new tests: 106 of the 114 new tests fail onorigin/main; the other 8 are guards that hold on both).Per-issue verdicts
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.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_investedfail on main.argsortthe 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).test_qhrp_*fail on main.covCor.m,covMarket.m, sklearn for identity) andsingle_factoris now actually the single-index target (it was a copy of constant correlation); every estimator raises on a missing value.covCor.m0.0201; one NaN gave 91/100 NaN entries. Branch matches sklearn/PyPortfolioOpt/LdP code to ~1e-15.mean_cvaris an exact Rockafellar-Uryasev LP (HiGHS).mean_cvar,robust_mvo,max_diversification,min_tracking_error,turnover_penalized,alpha_risk_cost_optimizeenforce the gross cap, reject unsupported limits, raise on failed or infeasible solves.mean_risk_optimizegetsmax_risk(required formax_return) and raises instead of returning equal weights.entropy_poolingpreconditions views and only reportsconvergedwhen they hold (max_view_erroradded).robust_mvo30.2x gross andturnover_penalized31.3x under a 1.0 cap; 60% CVaR target returned 27.2% with no error;max_returnput 100% in one asset; a 1e-4 daily view missed by 7.9% withconverged=True.t * cost_model.estimate(t * portfolio_value, adv, vol) / 1e4per asset tradedt(newportfolio_value,adv,daily_volatility; size-dependent impact without them raises);cost_model=Noneis 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-pycpz/alpha/analysis.py:341transfer_coefficientuses the samecorr(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.Nonecharged 10 bps; TC up to 5.66 across 30 seeds.252 * cov / T(cov and mu annualised); kappa=1 is one standard error of the annualised mean.test_robust_penalty_is_one_standard_error_of_the_annual_meanfails on main.synthetic_returns,pseudo_observationsand the pre-selection filters raise on missing values (constant series too);select_complete_assetscounts blanks as missing and returns the kept assets on their common complete window.drop_zero_variancekept none of 10; top-3 Sharpe and lowest-vol picks wrong.NotImplementedErroron sector, factor and tracking-error limits (Constraintscarries no sector map, loadings or benchmark), same as the core optimisers;max_net_exposure< 1 raises; a positivemin_weightnow applies withlong_only=True(cardinality raises on it and points tomin_position).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 reachOptResult.sigma_TLT/(sigma_SPY+sigma_TLT)to 1e-9; 5-asset weights match riskfolio-lib to 1e-5.ValueErrorwhen the cluster-level problem has no fully invested tangency portfolio (1'C^-1 m <= 0for the cluster portfolios), where normalising returns the lowest-Sharpe mix. A single cluster with a negative1'Sigma^-1 mudoes 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).test_nco_max_sharpe_refuses_when_no_tangency_portfolio_existsfails on main.g = (n_c - n_d) / (T - n_nn)(Gerber et al. 2021, PSD), population sd, inclusive thresholds; vectorised. Equals riskfolio-libgerber_cov_stat1exactly.asset_idsstill names array columns.TypeError.min_periods.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_coefficientstill open)Behaviour changes callers will see
mean_risk_optimize(objective="max_return")withoutmax_risk; a size-dependent cost model withoutportfolio_value/adv/daily_volatility; a partialrisk_paritybudget; out-of-range HERCn_clusters;denoise_mpwith T <= N.Constraints()gross cap of 2.0 inrobust_mvo,mean_cvar,turnover_penalizedandalpha_risk_cost_optimize.sample_cov,factor_model_covanddetone_covreturn 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
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 testsclean.mypy cpz_quant: only the 10 errors already onorigin/main(indicators/momentum.py, portfolio/factors.py).mainrun failed in 4 s with "The job was not started because your account is locked due to a billing issue."Notes
optimization.py,convex.py,covariance.py,risk_measures.pymean-risk part,entropy_pooling.py,copula.py,preselection.py).costs.pyis untouched; the ARC integration validatesCostModel.impact_modelitself becauseCostModel.estimatesilently prices an unknown model as zero impact andsqrt_impactassumes 100% daily volatility when given 0.rust/crate'sledoit_wolf,ewma_cov,denoise_mp,risk_parity_weightsandhrp_weightsare not called by the Python package and still implement the old formulas. README,docs/index.mdandrust/README.mdnow say so; the Rust code itself is unchanged.mean_cvarnamestarget_returnand 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
UnreleasedCHANGELOG entry under## [1.3.0], tag, and letpublish.ymlpush to PyPI (CI billing lock needs clearing first).