abaquant.portfolio.optimization¶
Import path: abaquant.portfolio.optimization
Domain: Portfolio construction, optimization, backtesting, risk metrics, and stress testing.
Purpose¶
Static portfolio allocation strategies.
When to use it¶
Use this package to transform return histories and covariance estimates into weights, then evaluate those weights out of sample and under explicit scenarios.
Public objects¶
class:
PortfolioScenarioAnalysis— One-period portfolio shock scenario analysis. *PortfolioScenarioAnalysis.as_frame— Return asset-level shock, weight, and contribution rows. *PortfolioScenarioAnalysis.as_dict— Return a serialization-friendly portfolio scenario mapping. *PortfolioScenarioAnalysis.scenario_analysis— Evaluate a one-period asset-shock scenario for a portfolio. *PortfolioScenarioAnalysis.backtest— Run a deterministic periodically rebalanced portfolio backtest. *PortfolioScenarioAnalysis.visualize— Return a figure for this portfolio scenario analysis.class:
PortfolioComputation— Static in-sample allocation model for a panel of periodic asset returns. *PortfolioComputation.equal_weight— Construct or evaluate an equally weighted fully invested portfolio. *PortfolioComputation.max_sharpe— Construct a bounded maximum-Sharpe-ratio portfolio. *PortfolioComputation.min_variance— Compute the result defined by ‘’min_variance’’ under this module’s documented convention. *PortfolioComputation.risk_parity— Compute an equal-risk-contribution portfolio allocation. *PortfolioComputation.inverse_volatility— Compute weights inversely proportional to asset volatility. *PortfolioComputation.inverse_variance— Compute weights inversely proportional to asset variance. *PortfolioComputation.max_diversification— Optimize the diversification ratio under the configured constraints. *PortfolioComputation.min_cvar— Optimize a portfolio for minimum historical conditional value at risk. *PortfolioComputation.max_sortino— Optimize a portfolio for maximum Sortino ratio. *PortfolioComputation.max_calmar— Optimize a portfolio for maximum Calmar ratio. *PortfolioComputation.hrp— Compute Hierarchical Risk Parity weights from the optimizer return data. *PortfolioComputation.max_decorrelation— Optimize an allocation that minimizes average portfolio correlation. *PortfolioComputation.min_cdar— Optimize a portfolio for minimum conditional drawdown at risk. *PortfolioComputation.target_volatility— Find an allocation whose volatility is close to the requested target. *PortfolioComputation.max_return— Maximize estimated portfolio return under configured constraints. *PortfolioComputation.min_neg_skewness— Optimize a portfolio to reduce negative skewness exposure. *PortfolioComputation.kelly_fraction— Optimize the implemented expected-log-growth Kelly criterion. *PortfolioComputation.black_litterman— Compute the implemented equilibrium-prior Black–Litterman allocation without investor views. *PortfolioComputation.min_tail_kurtosis— Optimize a portfolio to reduce downside-tail kurtosis. *PortfolioComputation.max_omega— Optimize the Omega ratio relative to the supplied periodic threshold. *PortfolioComputation.max_entropy— Optimize diversified weights using the implemented entropy–variance objective. *PortfolioComputation.optimize— Run the named portfolio-allocation strategy. *PortfolioComputation.available_strategies— Return the allocation strategy names accepted by optimize. *PortfolioComputation.weights_to_series— Return a weight vector indexed by the optimizer asset labels.class:
PortfolioEstimationContext— Validated in-sample returns, moments, and constraints for allocation methods.class:
MeanVarianceAllocator— Mean–variance and full-investment allocation methods. *MeanVarianceAllocator.equal_weight— Return equal fully invested asset weights. *MeanVarianceAllocator.maximum_sharpe— Return the in-sample maximum-Sharpe allocation. *MeanVarianceAllocator.minimum_variance— Return the constrained global minimum-variance allocation. *MeanVarianceAllocator.maximum_return— Return the constrained maximum-return allocation.class:
RiskBasedAllocator— Risk-budget, diversification, hierarchy, and concentration allocation methods. *RiskBasedAllocator.risk_parity— Return equal-risk-contribution weights. *RiskBasedAllocator.inverse_volatility— Return weights inversely proportional to asset volatility. *RiskBasedAllocator.inverse_variance— Return weights inversely proportional to asset variance. *RiskBasedAllocator.maximum_diversification— Return the maximum-diversification allocation. *RiskBasedAllocator.maximum_decorrelation— Return the maximum-decorrelation allocation. *RiskBasedAllocator.hierarchical_risk_parity— Return hierarchical risk-parity weights. *RiskBasedAllocator.maximum_entropy— Return the maximum-entropy allocation.class:
DownsideRiskAllocator— Tail-loss and downside-performance allocation methods. *DownsideRiskAllocator.minimum_cvar— Return the allocation minimizing conditional value at risk. *DownsideRiskAllocator.minimum_cdar— Return the allocation minimizing conditional drawdown at risk. *DownsideRiskAllocator.maximum_sortino— Return the in-sample maximum-Sortino allocation. *DownsideRiskAllocator.maximum_calmar— Return the in-sample maximum-Calmar allocation. *DownsideRiskAllocator.minimum_tail_kurtosis— Return the allocation minimizing tail kurtosis. *DownsideRiskAllocator.maximum_omega— Return the allocation maximizing the Omega ratio.class:
PortfolioAllocator— Facade that composes specialized static portfolio allocation families. *PortfolioAllocator.allocate— Run one explicitly selected allocation-family method. *PortfolioAllocator.weights_to_series— Index an allocation vector by the context asset order. *PortfolioAllocator.scenario_analysis— Evaluate a one-period asset-shock scenario for a portfolio. *PortfolioAllocator.backtest— Run a deterministic periodically rebalanced portfolio backtest. *PortfolioAllocator.report— Return an exportable report for this portfolio allocator. *PortfolioAllocator.visualize— Return a figure for weights, cumulative return, or correlation.
Detailed reference¶
Static portfolio allocation strategies.
Purpose¶
The module implements a collection of fully invested allocation and optimization rules, including mean–variance, risk-parity, downside-risk, entropy, and Black–Litterman-style routines.
Conventions¶
Input returns are periodic simple returns. The periods argument annualizes selected statistics. Unless allow_short is true, allocations are constrained to non-negative weights that sum to one.
Scope and limitations¶
Most strategies are in-sample optimizations. Solver success, covariance conditioning, and objective non-convexity may affect results.
References
[ 1 ] Markowitz, H. (1952), “Portfolio Selection”. [ 2 ] Sharpe, W. F. (1966), “Mutual Fund Performance”. [ 3 ] Rockafellar, R. T., and S. Uryasev (2000), “Optimization of Conditional Value-at-Risk”. [ 4 ] Lopez de Prado, M. (2016), “Building Diversified Portfolios that Outperform Out of Sample”.
- class abaquant.portfolio.optimization.PortfolioScenarioAnalysis(shocks, weights, contributions, portfolio_return, base_value=1.0, ending_value=1.0, provenance=None)¶
Bases:
objectOne-period portfolio shock scenario analysis.
- Parameters:
shocks (Mapping[str, float]) – Asset-level shock returns in decimal units, keyed by asset symbol.
weights (pd.Series) – Portfolio weights aligned to the optimizer asset order.
contributions (pd.Series) – Asset-level contribution to portfolio return, equal to weight times shock return.
portfolio_return (float) – Total one-period shocked portfolio return.
base_value (float) – Starting portfolio value used to compute
ending_value.ending_value (float) – Portfolio value after applying the one-period shocked return.
provenance (DataProvenance | None)
- as_frame()¶
Return asset-level shock, weight, and contribution rows.
- Return type:
DataFrame
- as_dict()¶
Return a serialization-friendly portfolio scenario mapping.
- Return type:
dict[str, object]
- scenario_analysis(shocks, *, weights=None, base_value=1.0)¶
Evaluate a one-period asset-shock scenario for a portfolio.
- Parameters:
shocks (Mapping[str, float]) – Asset-level shock returns in decimal units, keyed by asset symbol. Missing symbols receive a zero shock; unknown symbols are rejected.
weights (sequence, pandas.Series, mapping, optional) – Allocation to evaluate. Equal weights are used when omitted.
base_value (float, default=1.0) – Starting portfolio value used to compute the ending value.
- Returns:
Asset-level shocks, weights, return contributions, total portfolio return, and ending value.
- Return type:
- backtest(*, weights='equal_weight', rebalance='monthly', transaction_cost_bps=0.0, slippage_bps=0.0, fixed_transaction_cost=0.0, initial_capital=1.0, benchmark='equal_weight', lookback=63, min_history=2)¶
Run a deterministic periodically rebalanced portfolio backtest.
- Parameters:
weights (str or sequence or pandas.Series or mapping, default="equal_weight") – Target allocation policy. Supported string policies include
"equal_weight","buy_and_hold", and"inverse_volatility". Mappings are keyed by asset symbol; sequences are interpreted in optimizer asset order.rebalance ({"none", "daily", "weekly", "monthly", "quarterly", "annual"}, default="monthly") – Calendar rebalance schedule.
transaction_cost_bps (float, default=0.0) – One-way transaction cost in basis points of turnover.
slippage_bps (float, default=0.0) – Additional one-way slippage in basis points of turnover.
fixed_transaction_cost (float, default=0.0) – Fixed cost charged whenever a non-zero rebalance occurs.
initial_capital (float, default=1.0) – Starting portfolio value.
benchmark (str or sequence or pandas.Series or mapping or None, default="equal_weight") – Benchmark used for active-return diagnostics. A pandas Series is interpreted as precomputed benchmark returns.
lookback (int, default=63) – Historical window used by dynamic policies such as
"inverse_volatility".min_history (int, default=2) – Minimum observations required before dynamic policy estimates are used.
- Returns:
Simulated equity curve, drawdowns, returns, weights, trades, turnover, transaction costs, benchmark diagnostics, and summaries.
- Return type:
- visualize(*, chart='contributions', backend=None, theme=None, save_path=None, filename=None)¶
Return a figure for this portfolio scenario analysis.
- Parameters:
chart ({"contributions", "shocks", "waterfall"}, default="contributions") – Scenario diagnostic to visualize.
backend ({"matplotlib", "plotly"}, optional) – Figure backend override.
theme (VisualizationTheme, optional) – Per-call style override.
save_path (str or pathlib.Path, optional) – Explicit export path.
filename (str, optional) – Filename relative to the active theme’s save directory.
- class abaquant.portfolio.optimization.PortfolioComputation(periodic_returns, annual_risk_free_rate=0.0, allow_short_positions=False, periods_per_year=TRADING_DAYS)¶
Bases:
objectStatic in-sample allocation model for a panel of periodic asset returns.
- Parameters:
periodic_returns (pandas.DataFrame) – Periodic simple returns with observations in rows and assets in columns.
annual_risk_free_rate (float, default=0.0) – Annual risk-free rate in decimal units used by excess-return objectives.
allow_short_positions (bool, default=False) – Whether allocation optimizers may use negative asset weights.
periods_per_year (int, default=252) – Number of periodic observations used to annualize return and covariance estimates.
- periodic_returns¶
Complete-case periodic return observations used by the optimizer.
- Type:
pandas.DataFrame
- asset_symbols¶
Asset labels in optimizer-vector order.
- Type:
list[str]
- annualized_mean_returns¶
Arithmetic mean periodic returns multiplied by
periods_per_year.- Type:
pandas.Series
- annualized_covariance_matrix¶
Sample covariance matrix multiplied by
periods_per_year.- Type:
pandas.DataFrame
Initialize a static portfolio optimizer from periodic return observations.
- Parameters:
periodic_returns (pandas.DataFrame) – Periodic simple returns with observations in rows and assets in columns.
annual_risk_free_rate (float, default=0.0) – Annual risk-free rate in decimal units used by excess-return objectives.
allow_short_positions (bool, default=False) – Whether allocation optimizers may use negative asset weights.
periods_per_year (int, default=252) – Number of periodic observations used to annualize return and covariance estimates.
- equal_weight()¶
Construct or evaluate an equally weighted fully invested portfolio.
- Returns:
Numeric array ordered consistently with the supplied strikes, time grid, assets, or state labels.
- Return type:
numpy.ndarray
- max_sharpe()¶
Construct a bounded maximum-Sharpe-ratio portfolio.
- Returns:
Result of the max sharpe calculation.
- Return type:
np.ndarray
Notes
This is an analytical in-sample calculation. It does not by itself model transaction costs, execution effects, taxes, or future return uncertainty.
- min_variance()¶
Compute the result defined by
min_varianceunder this module’s documented convention.- Returns:
Result of the min variance calculation.
- Return type:
np.ndarray
Notes
This is an analytical in-sample calculation. It does not by itself model transaction costs, execution effects, taxes, or future return uncertainty.
- risk_parity()¶
Compute an equal-risk-contribution portfolio allocation.
- Returns:
Result of the risk parity calculation.
- Return type:
np.ndarray
Notes
This is an analytical in-sample calculation. It does not by itself model transaction costs, execution effects, taxes, or future return uncertainty.
- inverse_volatility()¶
Compute weights inversely proportional to asset volatility.
- Returns:
Result of the inverse volatility calculation.
- Return type:
np.ndarray
- inverse_variance()¶
Compute weights inversely proportional to asset variance.
- Returns:
Result of the inverse variance calculation.
- Return type:
np.ndarray
Notes
This is an analytical in-sample calculation. It does not by itself model transaction costs, execution effects, taxes, or future return uncertainty.
- max_diversification()¶
Optimize the diversification ratio under the configured constraints.
- Returns:
Result of the max diversification calculation.
- Return type:
np.ndarray
- min_cvar(alpha=0.05)¶
Optimize a portfolio for minimum historical conditional value at risk.
- Parameters:
alpha (float, default=0.05) – Model-specific alpha parameter; consult the module convention.
- Returns:
Result of the min cvar calculation.
- Return type:
np.ndarray
- max_sortino()¶
Optimize a portfolio for maximum Sortino ratio.
- Returns:
Result of the max sortino calculation.
- Return type:
np.ndarray
- max_calmar()¶
Optimize a portfolio for maximum Calmar ratio.
- Returns:
Result of the max calmar calculation.
- Return type:
np.ndarray
- hrp()¶
Compute Hierarchical Risk Parity weights from the optimizer return data.
- Returns:
Result of the hrp calculation.
- Return type:
np.ndarray
- max_decorrelation()¶
Optimize an allocation that minimizes average portfolio correlation.
- Returns:
Result of the max decorrelation calculation.
- Return type:
np.ndarray
- min_cdar(alpha=0.05)¶
Optimize a portfolio for minimum conditional drawdown at risk.
- Parameters:
alpha (float, default=0.05) – Model-specific alpha parameter; consult the module convention.
- Returns:
Result of the min cdar calculation.
- Return type:
np.ndarray
- target_volatility(target_vol=0.10)¶
Find an allocation whose volatility is close to the requested target.
- Parameters:
target_vol (float, default=0.1) – Target annualized portfolio volatility in decimal units.
- Returns:
Result of the target volatility calculation.
- Return type:
np.ndarray
- max_return()¶
Maximize estimated portfolio return under configured constraints.
- Returns:
Result of the max return calculation.
- Return type:
np.ndarray
- min_neg_skewness()¶
Optimize a portfolio to reduce negative skewness exposure.
- Returns:
Result of the min neg skewness calculation.
- Return type:
np.ndarray
- kelly_fraction()¶
Optimize the implemented expected-log-growth Kelly criterion.
- Returns:
Result of the kelly fraction calculation.
- Return type:
np.ndarray
- black_litterman()¶
Compute the implemented equilibrium-prior Black–Litterman allocation without investor views.
- Returns:
Result of the black litterman calculation.
- Return type:
np.ndarray
- min_tail_kurtosis()¶
Optimize a portfolio to reduce downside-tail kurtosis.
- Returns:
Result of the min tail kurtosis calculation.
- Return type:
np.ndarray
- max_omega(threshold=None)¶
Optimize the Omega ratio relative to the supplied periodic threshold.
- Parameters:
threshold (float | None, default=None) – Periodic return threshold used by the Omega-ratio objective.
- Returns:
Result of the max omega calculation.
- Return type:
np.ndarray
- max_entropy()¶
Optimize diversified weights using the implemented entropy–variance objective.
- Returns:
Result of the max entropy calculation.
- Return type:
np.ndarray
- optimize(strategy, **kwargs)¶
Run the named portfolio-allocation strategy.
- Parameters:
strategy (str) – Name of the portfolio-allocation strategy to execute.
kwargs (float or array-like) – Additional keyword arguments forwarded to the selected strategy.
- Returns:
Result of the optimize calculation.
- Return type:
np.ndarray
Notes
This is an analytical in-sample calculation. It does not by itself model transaction costs, execution effects, taxes, or future return uncertainty.
- available_strategies()¶
Return the allocation strategy names accepted by optimize.
- Returns:
Available labels in the order supplied by the provider or defined by the implementation.
- Return type:
list[str]
- weights_to_series(w)¶
Return a weight vector indexed by the optimizer asset labels.
- Parameters:
w (np.ndarray) – Numeric portfolio-weight vector in the established asset order.
- Returns:
Portfolio weights indexed by the optimizer asset labels.
- Return type:
pandas.Series
- class abaquant.portfolio.optimization.PortfolioEstimationContext(periodic_returns, annual_risk_free_rate=0.0, allow_short_positions=False, periods_per_year=TRADING_DAYS)¶
Bases:
PortfolioComputationValidated in-sample returns, moments, and constraints for allocation methods.
Initialize a static portfolio optimizer from periodic return observations.
- Parameters:
periodic_returns (pandas.DataFrame) – Periodic simple returns with observations in rows and assets in columns.
annual_risk_free_rate (float, default=0.0) – Annual risk-free rate in decimal units used by excess-return objectives.
allow_short_positions (bool, default=False) – Whether allocation optimizers may use negative asset weights.
periods_per_year (int, default=252) – Number of periodic observations used to annualize return and covariance estimates.
- class abaquant.portfolio.optimization.MeanVarianceAllocator(context)¶
Bases:
_AllocationFamilyMean–variance and full-investment allocation methods.
- Parameters:
context (PortfolioEstimationContext)
- equal_weight()¶
Return equal fully invested asset weights.
- Return type:
ndarray
- maximum_sharpe()¶
Return the in-sample maximum-Sharpe allocation.
- Return type:
ndarray
- minimum_variance()¶
Return the constrained global minimum-variance allocation.
- Return type:
ndarray
- maximum_return()¶
Return the constrained maximum-return allocation.
- Return type:
ndarray
- class abaquant.portfolio.optimization.RiskBasedAllocator(context)¶
Bases:
_AllocationFamilyRisk-budget, diversification, hierarchy, and concentration allocation methods.
- Parameters:
context (PortfolioEstimationContext)
- risk_parity()¶
Return equal-risk-contribution weights.
- Return type:
ndarray
- inverse_volatility()¶
Return weights inversely proportional to asset volatility.
- Return type:
ndarray
- inverse_variance()¶
Return weights inversely proportional to asset variance.
- Return type:
ndarray
- maximum_diversification()¶
Return the maximum-diversification allocation.
- Return type:
ndarray
- maximum_decorrelation()¶
Return the maximum-decorrelation allocation.
- Return type:
ndarray
- hierarchical_risk_parity()¶
Return hierarchical risk-parity weights.
- Return type:
ndarray
- maximum_entropy()¶
Return the maximum-entropy allocation.
- Return type:
ndarray
- class abaquant.portfolio.optimization.DownsideRiskAllocator(context)¶
Bases:
_AllocationFamilyTail-loss and downside-performance allocation methods.
- Parameters:
context (PortfolioEstimationContext)
- minimum_cvar(alpha=0.05)¶
Return the allocation minimizing conditional value at risk.
- Parameters:
alpha (float)
- Return type:
ndarray
- minimum_cdar(alpha=0.05)¶
Return the allocation minimizing conditional drawdown at risk.
- Parameters:
alpha (float)
- Return type:
ndarray
- maximum_sortino()¶
Return the in-sample maximum-Sortino allocation.
- Return type:
ndarray
- maximum_calmar()¶
Return the in-sample maximum-Calmar allocation.
- Return type:
ndarray
- minimum_tail_kurtosis()¶
Return the allocation minimizing tail kurtosis.
- Return type:
ndarray
- maximum_omega(threshold=None)¶
Return the allocation maximizing the Omega ratio.
- Parameters:
threshold (float | None)
- Return type:
ndarray
- class abaquant.portfolio.optimization.PortfolioAllocator(periodic_returns, annual_risk_free_rate=0.0, allow_short_positions=False, periods_per_year=TRADING_DAYS)¶
Bases:
objectFacade that composes specialized static portfolio allocation families.
Public allocation methods are intentionally namespaced:
mean_variance,risk_based, anddownside_risk. This prevents one class from accumulating unrelated optimization responsibilities.- Parameters:
periodic_returns (pd.DataFrame)
annual_risk_free_rate (float)
allow_short_positions (bool)
periods_per_year (int)
- allocate(family, method, **kwargs)¶
Run one explicitly selected allocation-family method.
- Parameters:
family (str)
method (str)
- Return type:
ndarray
- weights_to_series(weights)¶
Index an allocation vector by the context asset order.
- Parameters:
weights (ndarray)
- Return type:
Series
- scenario_analysis(shocks, *, weights=None, base_value=1.0)¶
Evaluate a one-period asset-shock scenario for a portfolio.
- Parameters:
shocks (Mapping[str, float]) – Asset-level shock returns in decimal units, keyed by asset symbol. Missing symbols receive a zero shock; unknown symbols are rejected.
weights (sequence, pandas.Series, mapping, optional) – Allocation to evaluate. Equal weights are used when omitted.
base_value (float, default=1.0) – Starting portfolio value used to compute the ending value.
- Returns:
Asset-level shocks, weights, return contributions, total portfolio return, and ending value.
- Return type:
- backtest(*, weights='equal_weight', rebalance='monthly', transaction_cost_bps=0.0, slippage_bps=0.0, fixed_transaction_cost=0.0, initial_capital=1.0, benchmark='equal_weight', lookback=63, min_history=2)¶
Run a deterministic periodically rebalanced portfolio backtest.
- Parameters:
weights (str or sequence or pandas.Series or mapping, default="equal_weight") – Target allocation policy. Supported string policies include
"equal_weight","buy_and_hold", and"inverse_volatility". Mappings are keyed by asset symbol; sequences are interpreted in optimizer asset order.rebalance ({"none", "daily", "weekly", "monthly", "quarterly", "annual"}, default="monthly") – Calendar rebalance schedule.
transaction_cost_bps (float, default=0.0) – One-way transaction cost in basis points of turnover.
slippage_bps (float, default=0.0) – Additional one-way slippage in basis points of turnover.
fixed_transaction_cost (float, default=0.0) – Fixed cost charged whenever a non-zero rebalance occurs.
initial_capital (float, default=1.0) – Starting portfolio value.
benchmark (str or sequence or pandas.Series or mapping or None, default="equal_weight") – Benchmark used for active-return diagnostics. A pandas Series is interpreted as precomputed benchmark returns.
lookback (int, default=63) – Historical window used by dynamic policies such as
"inverse_volatility".min_history (int, default=2) – Minimum observations required before dynamic policy estimates are used.
- Returns:
Simulated equity curve, drawdowns, returns, weights, trades, turnover, transaction costs, benchmark diagnostics, and summaries.
- Return type:
- report(*, backtest_kwargs=None)¶
Return an exportable report for this portfolio allocator.
- Parameters:
backtest_kwargs (Mapping[str, object], optional) – Keyword arguments forwarded to
backtest()when producing the default report backtest summary.- Returns:
Report object with Markdown, HTML, and PDF export methods.
- Return type:
- visualize(*, weights=None, chart='cumulative_returns', backend=None, theme=None, save_path=None, filename=None)¶
Return a figure for weights, cumulative return, or correlation.
- Parameters:
weights (array-like or pandas.Series, optional) – Allocation vector for weight-dependent plots. Equal weights are used when omitted.
chart ({"weights", "cumulative_returns", "correlation"}, default="cumulative_returns") – Portfolio diagnostic to visualize.
backend ({"matplotlib", "plotly"}, default="matplotlib") – Figure backend; the method never calls
show().