abaquant.portfolio.backtesting¶
Import path: abaquant.portfolio.backtesting
Domain: Portfolio construction, optimization, backtesting, risk metrics, and stress testing.
Purpose¶
Deterministic portfolio backtesting with transparent periodic rebalancing.
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:
PortfolioBacktestResult— Result of a deterministic periodically rebalanced portfolio backtest. *PortfolioBacktestResult.equity_curve— Return the simulated portfolio value path. *PortfolioBacktestResult.returns— Return realized periodic portfolio returns after transaction costs. *PortfolioBacktestResult.drawdowns— Return realized portfolio drawdowns. *PortfolioBacktestResult.benchmark_returns— Return benchmark returns when a benchmark was supplied. *PortfolioBacktestResult.benchmark_equity_curve— Return the benchmark value path when a benchmark was supplied. *PortfolioBacktestResult.active_returns— Return strategy returns minus benchmark returns when available. *PortfolioBacktestResult.summary— Return scalar performance, risk, benchmark, turnover, and cost diagnostics. *PortfolioBacktestResult.benchmark_summary— Return benchmark-relative statistics when a benchmark is available. *PortfolioBacktestResult.rolling_metrics— Return rolling annualized return, volatility, Sharpe, Sortino, and drawdown metrics. *PortfolioBacktestResult.monthly_returns— Return calendar-month compounded strategy returns. *PortfolioBacktestResult.annual_returns— Return calendar-year compounded strategy returns. *PortfolioBacktestResult.return_table— Return a year-by-month table of compounded strategy returns. *PortfolioBacktestResult.drawdown_events— Return the largest drawdown episodes sorted by trough drawdown. *PortfolioBacktestResult.contribution_summary— Return asset-level cumulative contribution and share diagnostics. *PortfolioBacktestResult.trade_summary— Return rebalance-date turnover, cost, and largest-trade diagnostics. *PortfolioBacktestResult.cost_summary— Return transaction-cost totals and averages. *PortfolioBacktestResult.as_frame— Return a compact tabular summary of the simulated path. *PortfolioBacktestResult.to_frame— Alias for :meth:’as_frame’ for pandas-style workflows. *PortfolioBacktestResult.report— Return an exportable report for this portfolio backtest result. *PortfolioBacktestResult.visualize— Return a figure for a backtest diagnostic.function:
rebalance_dates— Select the first available observation in each rebalance period.function:
coerce_backtest_weights— Validate and align a target-weight specification.function:
inverse_volatility_weights— Return inverse-volatility weights estimated from a historical return window.function:
run_rebalanced_backtest— Run a deterministic periodically rebalanced portfolio backtest.function:
run_backtest— Run the legacy dictionary backtest wrapper with English labels.
Detailed reference¶
Deterministic portfolio backtesting with transparent periodic rebalancing.
Purpose¶
This module implements a compact but useful portfolio backtesting layer. It applies transparent target-weight policies to a historical return panel, rebalances on explicit calendar dates, records transaction costs, compares a benchmark when supplied, and produces common performance, risk, turnover, drawdown, rolling, and contribution diagnostics.
Conventions¶
Input data are periodic simple returns with observations on a date-like index
and assets on columns. Rebalance schedules are calendar labels such as
"none", "daily", "weekly", "monthly", "quarterly", or
"annual". Transaction costs and slippage are expressed in basis points of
one-way turnover. payoff style path values are not annualized; summary
statistics use periods_per_year.
Scope and limitations¶
The backtest is deterministic and close-to-close. It does not model intraday execution, market impact beyond explicit slippage, taxes, cash interest, borrowing costs, dividends outside the supplied return series, survivorship bias, or point-in-time index membership.
References
- [1] Bailey, D. H., Borwein, J. M., Lopez de Prado, M., and Zhu, Q. J. (2014),
“Pseudo-Mathematics and Financial Charlatanism”.
- class abaquant.portfolio.backtesting.PortfolioBacktestResult(equity_curve_series, periodic_return_series, drawdown_series, weights_history, turnover_series, transaction_cost_series, asset_contribution_frame, trade_weight_frame, drifted_weight_frame, target_weight_frame, benchmark_return_series, benchmark_equity_series, transaction_cost_bps, slippage_bps, fixed_transaction_cost, periods_per_year, annual_risk_free_rate, initial_capital, rebalance, weight_policy, provenance=None)¶
Bases:
objectResult of a deterministic periodically rebalanced portfolio backtest.
- Parameters:
equity_curve_series (pandas.Series) – Portfolio value after each return observation. The first value is the initial portfolio value before the first period return.
periodic_return_series (pandas.Series) – Realized portfolio simple returns after transaction costs. The index matches the simulated return dates.
drawdown_series (pandas.Series) – Portfolio drawdown series, calculated as value divided by running peak minus one.
weights_history (pandas.DataFrame) – Portfolio weights after each rebalance date. Rows are rebalance dates and columns are asset labels.
turnover_series (pandas.Series) – One-way turnover at each rebalance date. The initial allocation records zero turnover by convention.
transaction_cost_series (pandas.Series) – Currency cost paid at each rebalance date.
asset_contribution_frame (pandas.DataFrame) – Periodic asset-level return contributions to portfolio return.
trade_weight_frame (pandas.DataFrame) – Weight trades at each rebalance date, target weight minus pre-trade drifted weight.
drifted_weight_frame (pandas.DataFrame) – Pre-trade drifted weights observed at each rebalance date.
target_weight_frame (pandas.DataFrame) – Target weights selected at each rebalance date.
benchmark_return_series (pandas.Series, optional) – Realized periodic benchmark returns aligned to the backtest returns.
benchmark_equity_series (pandas.Series, optional) – Benchmark value path scaled to the same initial capital.
transaction_cost_bps (float) – Transaction cost in basis points of one-way turnover.
slippage_bps (float) – Slippage in basis points of one-way turnover.
fixed_transaction_cost (float) – Fixed currency cost charged whenever a non-zero rebalance trade occurs.
periods_per_year (int) – Number of return observations interpreted as one year.
annual_risk_free_rate (float) – Annualized risk-free rate in decimal units.
initial_capital (float) – Initial portfolio value.
rebalance (str) – Rebalance-frequency label used for the simulation.
weight_policy (str) – Human-readable weight policy label.
provenance (DataProvenance | None)
- equity_curve()¶
Return the simulated portfolio value path.
- Return type:
Series
- returns()¶
Return realized periodic portfolio returns after transaction costs.
- Return type:
Series
- drawdowns()¶
Return realized portfolio drawdowns.
- Return type:
Series
- benchmark_returns()¶
Return benchmark returns when a benchmark was supplied.
- Return type:
Series | None
- benchmark_equity_curve()¶
Return the benchmark value path when a benchmark was supplied.
- Return type:
Series | None
- active_returns()¶
Return strategy returns minus benchmark returns when available.
- Return type:
Series | None
- summary()¶
Return scalar performance, risk, benchmark, turnover, and cost diagnostics.
- Return type:
dict[str, float]
- benchmark_summary()¶
Return benchmark-relative statistics when a benchmark is available.
- Return type:
dict[str, float]
- rolling_metrics(window=63)¶
Return rolling annualized return, volatility, Sharpe, Sortino, and drawdown metrics.
- Parameters:
window (int)
- Return type:
DataFrame
- monthly_returns()¶
Return calendar-month compounded strategy returns.
- Return type:
Series
- annual_returns()¶
Return calendar-year compounded strategy returns.
- Return type:
Series
- return_table()¶
Return a year-by-month table of compounded strategy returns.
- Return type:
DataFrame
- drawdown_events(top=5)¶
Return the largest drawdown episodes sorted by trough drawdown.
- Parameters:
top (int)
- Return type:
DataFrame
- contribution_summary()¶
Return asset-level cumulative contribution and share diagnostics.
- Return type:
DataFrame
- trade_summary()¶
Return rebalance-date turnover, cost, and largest-trade diagnostics.
- Return type:
DataFrame
- cost_summary()¶
Return transaction-cost totals and averages.
- Return type:
dict[str, float]
- as_frame()¶
Return a compact tabular summary of the simulated path.
- Return type:
DataFrame
- to_frame()¶
Alias for
as_frame()for pandas-style workflows.- Return type:
DataFrame
- report()¶
Return an exportable report for this portfolio backtest result.
- Returns:
Report object with Markdown, HTML, and PDF export methods.
- Return type:
- visualize(*, chart='equity_curve', backend=None, theme=None, save_path=None, filename=None, rolling_window=63)¶
Return a figure for a backtest diagnostic.
- Parameters:
chart (str, default="equity_curve") – Diagnostic to visualize. Supported values are
"equity_curve","benchmark","drawdown","weights","turnover","transaction_costs","rolling_sharpe","rolling_volatility","return_heatmap","contributions", and"trade_weights".backend ({"matplotlib", "plotly"}, optional) – Visualization 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.
rolling_window (int, default=63) – Rolling window used by rolling-metric charts.
- Returns:
Backend-native figure object.
- Return type:
matplotlib.figure.Figure or plotly.graph_objects.Figure
- abaquant.portfolio.backtesting.coerce_backtest_weights(weights, asset_symbols, *, allow_short=False)¶
Validate and align a target-weight specification.
- Parameters:
weights (Literal['equal_weight', 'buy_and_hold', 'inverse_volatility'] | ~collections.abc.Mapping[str, float] | ~collections.abc.Sequence[float] | ~pandas.Series)
asset_symbols (Sequence[str])
allow_short (bool)
- Return type:
Series
- abaquant.portfolio.backtesting.rebalance_dates(dates, rebalance)¶
Select the first available observation in each rebalance period.
- Parameters:
dates (DatetimeIndex)
rebalance (str)
- Return type:
list[Timestamp]
- abaquant.portfolio.backtesting.run_backtest(prices, strategy_name='equal_weight', rebalance_freq='monthly', lookback_days=252, rf=0.0, allow_short=False, initial_capital=10_000.0, cvar_alpha=0.05, target_vol=0.10)¶
Run the legacy dictionary backtest wrapper with English labels.
- Parameters:
prices (DataFrame)
strategy_name (str)
rebalance_freq (str)
lookback_days (int)
rf (float)
allow_short (bool)
initial_capital (float)
cvar_alpha (float)
target_vol (float)
- Return type:
dict | None
- abaquant.portfolio.backtesting.run_rebalanced_backtest(periodic_returns, *, weights='equal_weight', rebalance='monthly', transaction_cost_bps=0.0, slippage_bps=0.0, fixed_transaction_cost=0.0, initial_capital=1.0, annual_risk_free_rate=0.0, periods_per_year=252, benchmark='equal_weight', lookback=63, min_history=2, allow_short=False)¶
Run a deterministic periodically rebalanced portfolio backtest.
- Parameters:
periodic_returns (pandas.DataFrame) – Periodic simple asset returns with observations in rows and assets in columns. Missing rows are removed by complete-case filtering.
weights (DynamicWeightSpec, default="equal_weight") – Target allocation applied at each rebalance date. Supported string policies are
"equal_weight","buy_and_hold", and"inverse_volatility". A callable may return any static weight spec from historical returns and the current rebalance date.rebalance ({"none", "daily", "weekly", "monthly", "quarterly", "annual"}, default="monthly") – Calendar rebalance frequency.
"none"applies the initial allocation and lets weights drift.transaction_cost_bps (float, default=0.0) – One-way transaction cost in basis points of turnover.
slippage_bps (float, default=0.0) – Additional slippage in basis points of turnover.
fixed_transaction_cost (float, default=0.0) – Fixed currency cost charged whenever a non-zero rebalance trade occurs.
initial_capital (float, default=1.0) – Starting portfolio value.
annual_risk_free_rate (float, default=0.0) – Annualized risk-free rate in decimal units used by performance ratios.
periods_per_year (int, default=252) – Number of return observations interpreted as one year.
benchmark (BenchmarkSpec, default="equal_weight") – Benchmark return specification. A pandas Series is interpreted as precomputed benchmark returns. Other weight specs are applied to the asset return panel.
lookback (int, default=63) – Historical window for dynamic policies such as
"inverse_volatility".min_history (int, default=2) – Minimum observations before dynamic policy estimates are used.
allow_short (bool, default=False) – Whether negative weights are permitted.
- Returns:
Simulated portfolio path, returns, drawdowns, weights, costs, turnover, benchmark diagnostics, and summary statistics.
- Return type: