Backtesting API Reference¶
The backtesting package provides the backtesting engine, transaction modeling, and performance analysis.
Overview¶
The backtesting package contains:
- Engine - Core backtesting simulation engine
- Transactions - Transaction cost modeling
- Performance - Performance analytics and metrics
- Models - Data models for backtesting
Backtesting Package¶
portfolio_management.backtesting
¶
Backtesting framework for portfolio strategies.
This package provides historical simulation capabilities, including: - Transaction cost modeling (commissions, slippage, bid-ask spread) - Rebalancing logic (scheduled, opportunistic, forced) - Performance metrics calculation (Sharpe, Sortino, drawdown, etc.) - Portfolio evolution tracking with cash management - Point-in-time eligibility filtering to avoid look-ahead bias
BacktestEngine
¶
Historical portfolio backtesting engine.
Simulates the performance of a portfolio strategy over a historical period, incorporating realistic constraints like transaction costs, rebalancing schedules, and point-in-time data eligibility.
The engine iterates day by day through the historical price data, tracks the portfolio's value, and triggers rebalancing events based on the configured frequency. At each rebalance, it uses the provided strategy to determine a new target portfolio and executes the necessary trades.
Workflow
- Initialize with configuration, strategy, and historical data.
- Iterate through each day in the backtest period.
- On each day, update the total portfolio equity value.
- Check if a scheduled rebalancing is due.
- On a rebalancing day: a. Determine the universe of eligible assets (PIT eligibility). b. Apply preselection and membership policies to get candidate assets. c. Call the portfolio strategy to get target weights. d. Calculate required trades (buys/sells). e. Compute and deduct transaction costs. f. Update cash and holdings.
- After the simulation, calculate final performance metrics.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
BacktestConfig
|
The configuration settings for the backtest. |
strategy |
PortfolioStrategy
|
The portfolio construction strategy to be tested. |
prices |
DataFrame
|
DataFrame of historical prices. |
returns |
DataFrame
|
DataFrame of historical returns. |
classifications |
dict[str, str] | None
|
Asset class mappings for constraints. |
preselection |
Optional preselection filter for asset screening. |
|
membership_policy |
Optional policy to control portfolio turnover. |
|
cache |
Optional cache for factors and eligibility data to improve performance. |
|
cost_model |
TransactionCostModel
|
The model for calculating trade costs. |
holdings |
dict[str, int]
|
The current number of shares held for each asset. |
cash |
Decimal
|
The current cash balance in the portfolio. |
rebalance_events |
list[RebalanceEvent]
|
A log of all rebalancing events. |
equity_curve |
list[tuple[date, float]]
|
A daily log of portfolio equity. |
Example
from portfolio_management.backtesting.models import BacktestConfig from portfolio_management.portfolio.strategy import EqualWeightStrategy from portfolio_management.utils.testing import create_dummy_data
start_date = datetime.date(2022, 1, 1) end_date = datetime.date(2023, 12, 31) prices, returns = create_dummy_data(['AAPL', 'MSFT'], start_date, end_date)
config = BacktestConfig( ... start_date=start_date, ... end_date=end_date, ... initial_capital=Decimal("100000.00"), ... rebalance_frequency=RebalanceFrequency.QUARTERLY, ... commission_pct=Decimal("0.001") ... ) strategy = EqualWeightStrategy(min_history_periods=60)
engine = BacktestEngine(config, strategy, prices, returns) equity_curve, metrics, events = engine.run()
print(f"Backtest finished with {len(events)} rebalances.") print(f"Final portfolio value: ${metrics.final_value:,.2f}") print(f"Annualized Return: {metrics.annualized_return:.2%}") print(f"Sharpe Ratio: {metrics.sharpe_ratio:.2f}")
Source code in src/portfolio_management/backtesting/engine/backtest.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 | |
run()
¶
Execute the backtest simulation.
This is the main entry point to start the backtest. It iterates through the specified time period, manages the portfolio, and calculates results.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A tuple containing: |
PerformanceMetrics
|
|
list[RebalanceEvent]
|
|
tuple[DataFrame, PerformanceMetrics, list[RebalanceEvent]]
|
|
Raises:
| Type | Description |
|---|---|
InsufficientHistoryError
|
If the provided data does not cover the configured backtest period. |
RebalanceError
|
If a fatal error occurs during a rebalancing attempt. |
Source code in src/portfolio_management/backtesting/engine/backtest.py
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
BacktestConfig
dataclass
¶
Configuration for a backtest run.
This dataclass holds all the parameters needed to define a backtest simulation. It is immutable to ensure that the configuration cannot be changed during a run.
Attributes:
| Name | Type | Description |
|---|---|---|
start_date |
date
|
The first date of the backtest period. |
end_date |
date
|
The last date of the backtest period. |
initial_capital |
Decimal
|
The starting portfolio value. |
rebalance_frequency |
RebalanceFrequency
|
How often to rebalance. |
rebalance_threshold |
float
|
The weight drift threshold for opportunistic rebalancing. |
commission_pct |
float
|
Commission as a percentage of trade value. |
commission_min |
float
|
Minimum commission fee per trade. |
slippage_bps |
float
|
Slippage cost in basis points. |
cash_reserve_pct |
float
|
The minimum percentage of the portfolio to hold as cash. |
lookback_periods |
int
|
The rolling window size for parameter estimation (e.g., returns). |
use_pit_eligibility |
bool
|
If True, enables point-in-time eligibility filtering. |
min_history_days |
int
|
The minimum calendar days of history for PIT eligibility. |
min_price_rows |
int
|
The minimum number of price observations for PIT eligibility. |
Source code in src/portfolio_management/backtesting/models.py
PerformanceMetrics
dataclass
¶
A container for the performance metrics of a backtest run.
This dataclass holds all the key statistics calculated from a backtest's equity curve, providing a comprehensive summary of the strategy's performance and risk characteristics.
Attributes:
| Name | Type | Description |
|---|---|---|
total_return |
float
|
The cumulative return over the entire backtest period. |
annualized_return |
float
|
The annualized geometric mean return (CAGR). |
annualized_volatility |
float
|
The annualized standard deviation of daily returns. |
sharpe_ratio |
float
|
The risk-adjusted return (assumes a 0% risk-free rate). |
sortino_ratio |
float
|
The downside risk-adjusted return. |
max_drawdown |
float
|
The largest peak-to-trough decline in portfolio value. |
calmar_ratio |
float
|
The annualized return divided by the max drawdown. |
expected_shortfall_95 |
float
|
The average loss on the worst 5% of days (CVaR). |
win_rate |
float
|
The percentage of days with positive returns. |
avg_win |
float
|
The average return on days with positive returns. |
avg_loss |
float
|
The average return on days with negative returns. |
turnover |
float
|
The average portfolio turnover per rebalancing period. |
total_costs |
Decimal
|
The sum of all transaction costs incurred. |
num_rebalances |
int
|
The total number of rebalancing events. |
Source code in src/portfolio_management/backtesting/models.py
RebalanceEvent
dataclass
¶
A detailed record of a single portfolio rebalancing event.
This dataclass captures the state of the portfolio immediately before and after a rebalance, along with details of the trades executed and costs incurred.
Attributes:
| Name | Type | Description |
|---|---|---|
date |
date
|
The date on which the rebalance occurred. |
trigger |
RebalanceTrigger
|
The reason for the rebalance (e.g., scheduled, forced). |
trades |
dict[str, int]
|
A mapping of asset tickers to the number of shares traded. Positive values are buys, negative values are sells. |
costs |
Decimal
|
The total transaction costs (commission + slippage) for the event. |
pre_rebalance_value |
Decimal
|
The total portfolio value before rebalancing. |
post_rebalance_value |
Decimal
|
The total portfolio value after rebalancing. |
cash_before |
Decimal
|
The cash balance before the rebalance. |
cash_after |
Decimal
|
The cash balance after executing trades and paying costs. |
Source code in src/portfolio_management/backtesting/models.py
RebalanceFrequency
¶
Bases: Enum
Enumeration for supported rebalancing frequencies.
Source code in src/portfolio_management/backtesting/models.py
RebalanceTrigger
¶
Bases: Enum
Enumeration for the cause of a rebalance event.
Source code in src/portfolio_management/backtesting/models.py
TransactionCostModel
dataclass
¶
Model for calculating realistic transaction costs.
This class combines multiple cost components (commission, slippage) to provide a total cost for a given trade.
Attributes:
| Name | Type | Description |
|---|---|---|
commission_pct |
float
|
The commission charged as a percentage of the total trade value. E.g., 0.001 for 0.1%. |
commission_min |
float
|
The minimum flat fee for a commission. The actual
commission will be |
slippage_bps |
float
|
The estimated slippage cost in basis points (1/100th of a percent). E.g., 5.0 bps means a cost of 0.05% of the trade value. |
Example
model = TransactionCostModel(commission_pct=0.001, slippage_bps=10) cost = model.calculate_cost("MSFT", shares=50, price=300.0, is_buy=True)
Commission = 50 * 300 * 0.001 = 15.0¶
Slippage = 50 * 300 * (10 / 10000) = 15.0¶
Total = 15.0 + 15.0 = 30.0¶
print(cost) 30.00
Source code in src/portfolio_management/backtesting/transactions/costs.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
calculate_cost(ticker, shares, price, is_buy)
¶
Calculate the total transaction cost for a single trade.
The total cost is the sum of the commission and slippage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The symbol of the asset being traded. |
required |
shares
|
int
|
The absolute number of shares being traded. |
required |
price
|
float
|
The execution price per share. |
required |
is_buy
|
bool
|
True if the trade is a buy, False for a sell. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Decimal |
Decimal
|
The total calculated cost for the trade, always positive. |
Raises:
| Type | Description |
|---|---|
DataValidationError
|
If input |
Source code in src/portfolio_management/backtesting/transactions/costs.py
calculate_batch_cost(trades)
¶
Calculate costs for a batch of multiple trades.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trades
|
dict[str, tuple[int, float]]
|
A dictionary mapping a ticker to a tuple of (shares, price). A positive number of shares indicates a buy, and a negative number indicates a sell. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Decimal]
|
dict[str, Decimal]: A dictionary mapping each ticker to its |
dict[str, Decimal]
|
calculated transaction cost. |
Source code in src/portfolio_management/backtesting/transactions/costs.py
compute_pit_eligibility(returns, date, min_history_days=252, min_price_rows=252)
¶
Compute a point-in-time eligibility mask for assets at a given date.
This function prevents lookahead bias by ensuring that only assets with a sufficiently long and dense history of data are considered for inclusion in the portfolio on a given rebalancing date.
An asset is considered eligible if it meets two criteria:
1. The time since its first valid data point is at least min_history_days.
2. The number of non-missing data points up to the given date is at
least min_price_rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
DataFrame
|
A DataFrame of historical returns, with dates as the index and asset tickers as columns. |
required |
date
|
date
|
The rebalancing date for which to compute eligibility. |
required |
min_history_days
|
int
|
The minimum number of calendar days of history required for an asset to be eligible. Defaults to 252. |
252
|
min_price_rows
|
int
|
The minimum number of non-missing return data points required. Defaults to 252. |
252
|
Returns:
| Type | Description |
|---|---|
Series
|
pd.Series: A boolean Series where the index is the asset tickers and the |
Series
|
values indicate eligibility (True if eligible, False otherwise). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input |
Source code in src/portfolio_management/backtesting/eligibility.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
detect_delistings(returns, current_date, lookforward_days=30)
¶
Detect assets that have been or will soon be delisted.
This utility identifies assets whose last available data point occurs at or
before the current_date, and for which no new data appears within the
lookforward_days window. It is used to gracefully liquidate positions
in assets that are no longer trading.
Note
This function involves a small degree of lookahead, which is a pragmatic choice for handling delistings in a backtest. In a live trading environment, delisting information would be received from a data provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
DataFrame
|
The entire historical returns DataFrame. |
required |
current_date
|
date
|
The current date in the backtest simulation. |
required |
lookforward_days
|
int
|
The number of days to look ahead to confirm that an asset has truly been delisted. Defaults to 30. |
30
|
Returns:
| Type | Description |
|---|---|
dict[str, date]
|
dict[str, datetime.date]: A dictionary mapping the ticker of each |
dict[str, date]
|
delisted asset to its last known date with valid data. |
Source code in src/portfolio_management/backtesting/eligibility.py
get_asset_history_stats(returns, date)
¶
Get detailed history statistics for each asset up to a given date.
This function computes comprehensive statistics about data availability for each asset, which is useful for debugging eligibility filters and understanding the data quality of the universe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
DataFrame
|
The historical returns DataFrame. |
required |
date
|
date
|
The date up to which statistics should be computed. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: A DataFrame where each row corresponds to an asset and |
DataFrame
|
columns include 'ticker', 'first_valid_date', 'last_valid_date', |
DataFrame
|
'days_since_first', 'total_rows', and 'coverage_pct'. |
Source code in src/portfolio_management/backtesting/eligibility.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
calculate_metrics(equity_df, rebalance_events)
¶
Calculate performance metrics from an equity curve and rebalance events.
This function takes the results of a backtest and computes a wide range of standard performance and risk metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
equity_df
|
DataFrame
|
A DataFrame with a 'equity' column containing the portfolio's total value, indexed by date. |
required |
rebalance_events
|
list[RebalanceEvent]
|
A list of all rebalancing events that occurred during the backtest, used for cost and turnover calculations. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PerformanceMetrics |
PerformanceMetrics
|
A dataclass containing all calculated statistics. Returns a zeroed-out metrics object if the equity curve has insufficient data (< 2 periods). |
Source code in src/portfolio_management/backtesting/performance/metrics.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
options: show_root_heading: true show_source: false members_order: source group_by_category: true show_category_heading: true