API Reference¶
Auto-generated from source docstrings.
Core¶
Engine
¶
Engine(
feed,
strategy,
config=None,
*,
contract_specs=None,
market_impact_model=None,
commission_model=None,
slippage_model=None,
execution_limits=None,
funding_df=None,
settlement_events=None,
lifecycle_version=V1,
execution_policy=None,
target_intent_state=None,
holdings_sampling="none",
runtime=None,
benchmark=None,
)
Event-driven backtesting engine.
The Engine orchestrates the backtest by iterating through market data, managing the broker, and calling the strategy on each bar. Engine instances are single-use; create a new instance for each run.
Execution Flow
- Call on_start before any market bar is registered.
- Call on_prepare with the resolved config and no future feed data.
- For each accepted session bar, register data, process eligible deferred orders and risk, call the per-bar strategy callbacks, process configured current-bar orders, and record marked portfolio state.
- Call on_end after the final timestamp.
- Return closed trades plus marked open positions. The engine does not submit automatic end-of-data liquidation orders.
Attributes:
| Name | Type | Description |
|---|---|---|
feed |
DataFeed providing price and signal data |
|
strategy |
Strategy implementing trading logic |
|
broker |
Broker handling order execution and positions |
|
config |
BacktestConfig with all behavioral settings |
|
equity_curve |
list[tuple[datetime, float]]
|
List of (timestamp, equity) tuples |
Example
from ml4t.backtest import Engine, DataFeed, Strategy, BacktestConfig
class MyStrategy(Strategy): ... def on_data(self, timestamp, data, context, broker): ... for asset, bar in data.items(): ... if bar.get('signal', 0) > 0.5: ... broker.submit_order(asset, 100)
feed = DataFeed(prices_df=df) engine = Engine(feed=feed, strategy=MyStrategy()) result = engine.run() print(result['total_return'])
Source code in src/ml4t/backtest/engine.py
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 | |
run
¶
Run backtest and return structured results.
Returns:
| Type | Description |
|---|---|
BacktestResult
|
BacktestResult with trades, equity curve, metrics, and export methods. |
BacktestResult
|
Call .to_dict() for backward-compatible dictionary output. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a run was already started on this Engine instance. |
Source code in src/ml4t/backtest/engine.py
run_dict
¶
Run backtest and return dictionary (backward compatible).
This is equivalent to run().to_dict() but more explicit for code that requires dictionary output.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with metrics, trades, and equity curve. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a run was already started on this Engine instance. |
Source code in src/ml4t/backtest/engine.py
from_config
classmethod
¶
from_config(
feed,
strategy,
config,
*,
contract_specs=None,
market_impact_model=None,
commission_model=None,
slippage_model=None,
execution_limits=None,
funding_df=None,
settlement_events=None,
lifecycle_version=V1,
execution_policy=None,
target_intent_state=None,
holdings_sampling="none",
runtime=None,
benchmark=None,
)
Create an Engine instance from a BacktestConfig.
Equivalent to Engine(feed, strategy, config). Kept as a convenience
for code that reads more clearly with a named constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feed
|
DataFeed
|
DataFeed with price data |
required |
strategy
|
Strategy
|
Strategy to execute |
required |
config
|
BacktestConfig
|
BacktestConfig with all behavioral settings |
required |
contract_specs
|
dict[str, Any] | None
|
Per-asset contract specifications (futures multipliers, etc.) |
None
|
market_impact_model
|
Any | None
|
Market impact model for fill simulation |
None
|
commission_model
|
CommissionModel | None
|
Explicit native fee model overriding configured fee rates |
None
|
slippage_model
|
SlippageModel | None
|
Explicit native slippage model overriding configured rates |
None
|
execution_limits
|
Any | None
|
Execution limits (max order size, etc.) |
None
|
funding_df
|
DataFrame | None
|
Timestamped funding rates or amounts for named assets |
None
|
runtime
|
RuntimeServices | None
|
Optional causal market/history and callback services for this run |
None
|
Returns:
| Type | Description |
|---|---|
Engine
|
Configured Engine instance |
Source code in src/ml4t/backtest/engine.py
run_backtest
¶
run_backtest(
prices,
strategy,
signals=None,
context=None,
config=None,
*,
feed_spec=None,
contract=None,
contract_specs=None,
market_impact_model=None,
commission_model=None,
slippage_model=None,
execution_limits=None,
funding_df=None,
settlement_events=None,
capital_flows=None,
corporate_actions=None,
input_manifest=None,
lifecycle_version=V1,
execution_policy=None,
target_intent_state=None,
holdings_sampling="none",
runtime=None,
benchmark=None,
)
Run a backtest with minimal setup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
DataFrame | str
|
Price DataFrame or path to parquet file |
required |
strategy
|
Strategy
|
Strategy instance to execute |
required |
signals
|
DataFrame | str | None
|
Optional signals DataFrame or path |
None
|
context
|
DataFrame | str | None
|
Optional context DataFrame or path |
None
|
config
|
BacktestConfig | str | None
|
BacktestConfig instance, preset name (str), or None for defaults |
None
|
feed_spec
|
Any | None
|
Optional shared dataset contract for schema and temporal metadata |
None
|
contract
|
Any | None
|
Alias for feed_spec |
None
|
contract_specs
|
dict[str, Any] | None
|
Per-asset contract specifications (futures multipliers, etc.) |
None
|
market_impact_model
|
Any | None
|
Market impact model for fill simulation |
None
|
commission_model
|
CommissionModel | None
|
Explicit native fee model overriding configured fee rates |
None
|
slippage_model
|
SlippageModel | None
|
Explicit native slippage model overriding configured rates |
None
|
execution_limits
|
Any | None
|
Execution limits (max order size, etc.) |
None
|
funding_df
|
DataFrame | None
|
Timestamped funding rates or amounts for named assets |
None
|
runtime
|
RuntimeServices | None
|
Optional causal market/history and callback services for this run |
None
|
Returns:
| Type | Description |
|---|---|
BacktestResult
|
BacktestResult with metrics, trades, equity curve, and export methods. |
Example
Using config preset¶
result = run_backtest(prices_df, strategy, config="backtrader") print(result.metrics["sharpe"])
Using custom config¶
config = BacktestConfig.from_preset("backtrader") config.commission_rate = 0.002 result = run_backtest(prices_df, strategy, config=config)
Futures with contract specs¶
from ml4t.backtest import ContractSpec, AssetClass specs = {"ES": ContractSpec(symbol="ES", asset_class=AssetClass.FUTURE, multiplier=50.0)} result = run_backtest(prices_df, strategy, config=config, contract_specs=specs)
Source code in src/ml4t/backtest/engine.py
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 | |
Strategy
¶
Bases: ABC
Base strategy class.
on_prepare
¶
Called after on_start with causal configuration and no future feed data.
on_start
¶
Initialize strategy state before the first bar.
The broker is configured, but no market bar has been registered. Use this callback for position rules and state that does not require prices.
Source code in src/ml4t/backtest/strategy.py
on_data
abstractmethod
¶
Called for each timestamp with all available data.
Source code in src/ml4t/backtest/strategy.py
on_end
¶
Finalize strategy state after the final bar.
Open positions remain marked in the returned result; the engine does not submit automatic end-of-data closing orders before this callback.
Source code in src/ml4t/backtest/strategy.py
DataFeed
¶
DataFeed(
prices_path=None,
signals_path=None,
context_path=None,
prices_df=None,
signals_df=None,
context_df=None,
*,
feed_spec=None,
feature_spec=None,
contract=None,
entity_col=None,
timestamp_col=None,
price_col=None,
open_col=None,
high_col=None,
low_col=None,
close_col=None,
volume_col=None,
vwap_col=None,
bid_col=None,
ask_col=None,
mid_col=None,
bid_size_col=None,
ask_size_col=None,
session_col=None,
calendar=UNSET_CALENDAR,
capital_flows=None,
corporate_actions=None,
input_manifest=None,
)
Polars-based multi-asset data feed with signals and context.
Pre-indexes data by timestamp at initialization for O(1) lookups during
iteration. Public prices, signals, and context attributes are
normalized copies sorted by timestamp when needed. DataFrames are kept in
their native format and converted to dicts only for the active bar,
avoiding the large memory overhead of materializing one child DataFrame per
timestamp.
The resolved timestamp, entity, and reference-price columns are required. Open, high, low, and volume columns are optional. Missing OHLC values fall back to the configured close and missing volume becomes zero.
Usage
feed = DataFeed(prices_df=prices, signals_df=signals) for timestamp, assets_data, context in feed: # assets_data: {"AAPL": {"close": 150.0, "signals": {...}}, ...} process(timestamp, assets_data)
Source code in src/ml4t/backtest/datafeed.py
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 | |
input_provenance
property
¶
Verified source manifest and explicit table selections, defensively copied.
feature_metadata
property
¶
Original Engineer declaration and explicit decision-clock projection, defensively copied.
from_snapshot
classmethod
¶
from_snapshot(
path,
*,
prices_table="prices",
signals_table=None,
context_table=None,
corporate_actions_table=None,
capital_flows_table=None,
feature_spec=None,
calendar=UNSET_CALENDAR,
)
Verify an immutable Data snapshot before selecting explicitly named tables.
ML4T Data is optional and imported only for this route. Its public reader verifies every declared file. Preserve its effective prepared calendar, source manifest and selected table identities in the resulting run.
Source code in src/ml4t/backtest/datafeed.py
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 | |
verify_input_integrity
¶
Reject changed verified tables; direct caller frames have no snapshot attestation.
Source code in src/ml4t/backtest/datafeed.py
Configuration¶
BacktestConfig
dataclass
¶
BacktestConfig(
allow_short_selling=False,
allow_leverage=False,
initial_margin=0.5,
long_maintenance_margin=0.25,
short_maintenance_margin=0.3,
fixed_margin_schedule=None,
margin_pct_schedule=None,
short_cash_policy=CREDIT,
lock_notional_update_mode=POSITION_LEGS,
execution_price=OPEN,
mark_price=PRICE,
execution_mode=NEXT_BAR,
stop_fill_mode=STOP_PRICE,
stop_level_basis=FILL_PRICE,
trail_hwm_source=CLOSE,
trail_include_entry_bar_extremes=False,
initial_hwm_source=FILL_PRICE,
trail_stop_timing=LAGGED,
share_type=INTEGER,
share_rounding=NEAREST,
commission_type=NONE,
commission_rate=0.0,
commission_per_share=0.0,
commission_per_trade=0.0,
commission_minimum=0.0,
slippage_type=NONE,
slippage_rate=0.0,
slippage_fixed=0.0,
slippage_spread=0.0,
slippage_spread_by_asset=dict(),
slippage_spread_convention=FULL_SPREAD,
stop_slippage_rate=0.0,
initial_cash=100000.0,
cash_buffer_pct=0.0,
settlement_delay=0,
settlement_reduces_buying_power=True,
reject_on_insufficient_cash=True,
skip_cash_validation=False,
partial_fills_allowed=False,
fill_ordering=EXIT_FIRST,
entry_order_priority=SUBMISSION,
next_bar_submission_precheck=False,
next_bar_simple_cash_check=False,
buying_power_reservation=False,
next_bar_queue_shadow_validation=False,
immediate_fill=False,
rebalance_mode=INCREMENTAL,
rebalance_headroom_pct=1.0,
missing_price_policy=SKIP,
late_asset_policy=ALLOW,
late_asset_min_bars=1,
calendar=UNSET_CALENDAR,
timezone="UTC",
data_frequency=DAILY,
enforce_sessions=False,
preset_name=None,
feed_spec=None,
metadata=dict(),
retain_intent_history=False,
retain_lifecycle_history=False,
*,
next_bar_execution_price=None,
cancel_policy=NEVER,
corporate_action_policy="declared_terms",
conditional_order_mode=BAR_OHLC,
limit_slippage_policy=DEFER,
time_contract_version=2,
periods_per_year=None,
)
Complete configuration for backtesting behavior.
All behavioral differences between frameworks are captured here. Load presets to match specific frameworks exactly.
This is the single source of truth for all backtest settings. Broker and Engine are configured entirely from this dataclass.
from_preset
classmethod
¶
Load a predefined configuration preset.
Available presets: - "default": Sensible defaults for general use - "backtrader": Match Backtrader's default behavior - "vectorbt": Match VectorBT's default behavior - "zipline": Use the declared Zipline comparison profile with costs disabled - "lean": Match the frozen LEAN daily US-equity comparison protocol - "realistic": Conservative settings for realistic simulation - "ibkr_us_stocks_fixed": Interactive Brokers US stocks fixed pricing
Source code in src/ml4t/backtest/config.py
from_yaml
classmethod
¶
Load config from YAML file.
Source code in src/ml4t/backtest/config.py
from_dict
classmethod
¶
Create config from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Nested config dictionary |
required |
preset_name
|
str | None
|
Optional metadata label |
None
|
strict
|
bool
|
If True, reject unknown sections/keys |
True
|
Source code in src/ml4t/backtest/config.py
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 | |
to_yaml
¶
to_dict
¶
Convert config to dictionary for serialization.
Source code in src/ml4t/backtest/config.py
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 | |
validate
¶
Validate configuration and return warnings for edge cases.
Checks for configurations that may produce unexpected results or indicate potential issues. Returns a list of warning messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
warn
|
bool
|
If True, emit warnings via warnings.warn(). Default True. |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of warning message strings (empty if no issues found). |
Example
config = BacktestConfig(execution_mode=ExecutionMode.SAME_BAR) warnings = config.validate()
["SAME_BAR execution has look-ahead bias risk..."]¶
Source code in src/ml4t/backtest/config.py
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 | |
describe
¶
Return human-readable description of configuration.
Source code in src/ml4t/backtest/config.py
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 | |
profiles
¶
Centralized profile definitions for framework-aligned behavior.
get_profile_config
¶
Return a deep copy of nested config data for the named profile.
Source code in src/ml4t/backtest/profiles.py
Rebalancing¶
Use RebalanceConfig.rebalance_mode to select the executor mode. The
rebalancing guide explains sizing, eligible fills,
headroom and whole-share rounding.
RebalanceMode
¶
Bases: str, Enum
Sizing mode for TargetWeightExecutor.
Select this mode through RebalanceConfig.rebalance_mode. The separate
BacktestConfig.rebalance_mode field does not configure the executor.
SNAPSHOT
Use account value and current weights captured at the start of the call.
INCREMENTAL: Process eligible orders between submissions, then refresh account value and current weights for the next target. HYBRID: Process eligible orders between submissions while retaining the starting account value and weights for target sizing.
Execution timing and account rules still control fill eligibility. These modes do not guarantee batch fills or define another framework's defaults.
RebalanceConfig
dataclass
¶
RebalanceConfig(
min_trade_value=0.0,
min_weight_change=0.0,
allow_fractional=None,
round_lots=False,
lot_size=100,
allow_short=False,
max_single_weight=1.0,
max_gross_leverage=None,
cancel_before_rebalance=True,
account_for_pending=True,
rebalance_mode=SNAPSHOT,
share_rounding=NEAREST,
schedule=None,
calendar=UNSET_CALENDAR,
timezone=None,
session_start_time=None,
data_frequency=None,
timestamp_semantics=None,
)
Configuration for rebalancing behavior.
Attributes:
| Name | Type | Description |
|---|---|---|
min_trade_value |
float
|
Skip trades with absolute value smaller than this ($). Default 0.0 disables this filter. |
min_weight_change |
float
|
Skip if weight change is smaller than this (decimal). Default 0.0 disables this filter. |
allow_fractional |
bool | None
|
Allow fractional shares (default: False, whole shares only). |
round_lots |
bool
|
Round to lot_size increments (e.g., 100-share lots). |
lot_size |
int
|
Lot size for rounding (only used if round_lots=True). |
allow_short |
bool
|
Allow short positions via negative weights. |
max_single_weight |
float
|
Maximum absolute requested weight before share rounding. Long targets are capped at this value and short targets at its negation. Rounded position exposure can exceed the exact target weight. |
max_gross_leverage |
float | None
|
Maximum gross leverage (sum of abs weights). None means no cap — the gatekeeper's buying power check is the constraint. For cash accounts, the gatekeeper naturally prevents over-allocation. For margin accounts, set this as a risk guardrail (e.g., 5.0 for a CTA portfolio). |
cancel_before_rebalance |
bool
|
Cancel pending orders before rebalancing (safest). |
account_for_pending |
bool
|
Consider pending orders when calculating current weights. |
rebalance_mode |
RebalanceMode
|
How successive targets use account value and current weights. SNAPSHOT (default): Keep the starting value and weights for sizing. INCREMENTAL: Process eligible orders and refresh the sizing basis. HYBRID: Process eligible orders while keeping the starting sizing basis. Execution timing and account rules still determine which orders fill. |
schedule |
RebalanceSchedule | None
|
Optional event, session, weekly, month-end, or explicit schedule. |
calendar |
str | None | CalendarUnset
|
Exchange calendar used to identify session closes and period ends. Required for weekly and month-end schedules. |
timezone |
str | None
|
Timezone used to interpret naive feed timestamps. |
session_start_time |
str | None
|
Optional exchange-local session boundary in |
data_frequency |
DataFrequency | str | None
|
Feed frequency. Set this with |
timestamp_semantics |
TimestampSemantics | str | None
|
Whether timestamps are session labels, bar closes, or event times. Both metadata fields may be omitted only when each event is a daily session close. |
resolved_calendar
property
¶
Resolve omission to NYSE while preserving an explicit calendar disable.
TargetWeightExecutor
¶
Convert target portfolio weights to orders.
Handles the common pattern of rebalancing to target weights: - Computes required trades from current vs target positions - Accounts for pending orders to prevent double-allocation - Applies minimum trade thresholds - Handles lot rounding and fractional shares - Respects position limits
Example
executor = TargetWeightExecutor(config=RebalanceConfig( min_trade_value=500, round_lots=True, ))
In strategy:¶
target_weights = {'AAPL': 0.3, 'GOOG': 0.3, 'MSFT': 0.4} orders = executor.execute(target_weights, data, broker)
Initialize the executor with optional configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RebalanceConfig | None
|
Rebalancing configuration. Uses defaults if not provided. |
None
|
Source code in src/ml4t/backtest/execution/rebalancer.py
execute
¶
Execute rebalancing to target weights.
SNAPSHOT (default) sizes all targets from starting account value and
weights. INCREMENTAL processes eligible orders between submissions
and refreshes that sizing basis. HYBRID processes eligible orders
while retaining the starting basis. Broker execution and account rules
determine fill eligibility; the mode does not force an order to fill.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_weights
|
dict[str, float]
|
Dict of asset -> target weight. Negative weights
express shorts. Gross exposure may exceed 1.0 when leverage is
enabled; |
required |
data
|
dict[str, dict]
|
Current bar data (for prices). Format: {asset: {'close': price, ...}} |
required |
broker
|
Broker
|
Broker instance for order submission. |
required |
timestamp
|
datetime | None
|
Current event time, required when a schedule is configured. |
None
|
is_session_close
|
bool | None
|
Explicit boundary signal for intraday feeds without a calendar.
When a schedule is configured, call |
None
|
Returns:
| Type | Description |
|---|---|
list[Order]
|
List of submitted orders. |
Source code in src/ml4t/backtest/execution/rebalancer.py
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 | |
should_rebalance
¶
Evaluate one event in order; call this for every event when a schedule is set.
Source code in src/ml4t/backtest/execution/rebalancer.py
validate_completed_run
¶
Validate schedule alignment after the final event in a complete run.
reset
¶
Clear schedule state before reusing this executor for another run.
Broker¶
Broker
¶
Broker(
initial_cash=100000.0,
commission_model=None,
slippage_model=None,
stop_slippage_rate=0.0,
execution_mode=SAME_BAR,
execution_price=CLOSE,
mark_price=PRICE,
stop_fill_mode=STOP_PRICE,
stop_level_basis=FILL_PRICE,
trail_hwm_source=CLOSE,
trail_include_entry_bar_extremes=False,
initial_hwm_source=FILL_PRICE,
trail_stop_timing=LAGGED,
allow_short_selling=False,
allow_leverage=False,
initial_margin=0.5,
long_maintenance_margin=0.25,
short_maintenance_margin=0.3,
fixed_margin_schedule=None,
margin_pct_schedule=None,
short_cash_policy=CREDIT,
lock_notional_update_mode=POSITION_LEGS,
execution_limits=None,
market_impact_model=None,
contract_specs=None,
share_type=INTEGER,
fill_ordering=EXIT_FIRST,
entry_order_priority=SUBMISSION,
next_bar_submission_precheck=False,
next_bar_simple_cash_check=False,
buying_power_reservation=False,
next_bar_queue_shadow_validation=False,
immediate_fill=False,
reject_on_insufficient_cash=True,
skip_cash_validation=False,
cash_buffer_pct=0.0,
partial_fills_allowed=False,
rebalance_headroom_pct=1.0,
missing_price_policy=SKIP,
late_asset_policy=ALLOW,
late_asset_min_bars=1,
settlement_delay=0,
settlement_reduces_buying_power=True,
next_bar_execution_price=None,
cancel_policy=NEVER,
*,
conditional_order_mode=BAR_OHLC,
limit_slippage_policy=DEFER,
)
Broker interface - same for backtest and live trading.
Source code in src/ml4t/backtest/broker.py
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 | |
pending_orders
property
writable
¶
Return the pending-order collection owned by OrderState.
cash
property
writable
¶
Return the cash balance owned by the account ledger.
The value can be negative for a configured margin account. Assignment is retained for compatibility and updates the same account ledger.
last_rejection_reason
property
¶
Get reason for most recent order rejection.
Returns:
| Type | Description |
|---|---|
str | None
|
Rejection reason string, or None if no orders have been rejected |
from_config
classmethod
¶
from_config(
config,
execution_limits=None,
market_impact_model=None,
contract_specs=None,
commission_model=None,
slippage_model=None,
)
Create Broker from BacktestConfig.
Config supplies the execution and account settings. Explicit native fee, impact and execution-limit models override their configured counterparts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
BacktestConfig
|
BacktestConfig with all behavioral settings |
required |
execution_limits
|
ExecutionLimits | None
|
Optional execution limits (not in config) |
None
|
market_impact_model
|
MarketImpactModel | None
|
Optional market impact model (not in config) |
None
|
contract_specs
|
dict[str, ContractSpec] | None
|
Optional contract specifications (not in config) |
None
|
commission_model
|
CommissionModel | None
|
Explicit fee model overriding configured fee rates |
None
|
slippage_model
|
SlippageModel | None
|
Explicit slippage model overriding configured rates |
None
|
Returns:
| Type | Description |
|---|---|
Broker
|
Configured Broker instance |
Example
config = BacktestConfig.from_preset("backtrader") broker = Broker.from_config(config)
Source code in src/ml4t/backtest/broker.py
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 | |
submit_order
¶
submit_order(
asset,
quantity,
side=None,
order_type=MARKET,
limit_price=None,
stop_price=None,
trail_amount=None,
_options=None,
)
Submit a new order to the broker.
Creates and queues an order for execution. Orders are validated by the Gatekeeper before fills to ensure account constraints are met.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol (e.g., "AAPL", "BTC-USD") |
required |
quantity
|
float
|
Number of shares/units. Positive = buy, negative = sell (if side is not specified) |
required |
side
|
OrderSide | None
|
OrderSide.BUY or OrderSide.SELL. If None, inferred from quantity sign |
None
|
order_type
|
OrderType
|
Order type (MARKET, LIMIT, STOP, TRAILING_STOP) |
MARKET
|
limit_price
|
float | None
|
Limit price for LIMIT orders |
None
|
stop_price
|
float | None
|
Stop/trigger price for STOP orders |
None
|
trail_amount
|
float | None
|
Trail distance for TRAILING_STOP orders |
None
|
Returns:
| Type | Description |
|---|---|
Order | None
|
Order object if submitted successfully, None if rejected |
Order | None
|
(e.g., same-bar re-entry after stop exit in VBT Pro mode) |
Examples:
Market buy¶
order = broker.submit_order("AAPL", 100)
Market sell (using negative quantity)¶
order = broker.submit_order("AAPL", -100)
Limit buy¶
order = broker.submit_order("AAPL", 100, order_type=OrderType.LIMIT, limit_price=150.0)
Stop sell (stop-loss)¶
order = broker.submit_order("AAPL", -100, order_type=OrderType.STOP, stop_price=145.0)
Source code in src/ml4t/backtest/broker.py
submit_bracket
¶
submit_bracket(
asset,
quantity,
take_profit,
stop_loss,
entry_type=MARKET,
entry_limit=None,
validate_prices=True,
)
Submit entry with take-profit and stop-loss.
Creates a bracket order with entry, take-profit limit, and stop-loss orders. The exit side is automatically determined from the entry direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol to trade |
required |
quantity
|
float
|
Position size (positive for long, negative for short) |
required |
take_profit
|
float
|
Take-profit price level (LIMIT order) |
required |
stop_loss
|
float
|
Stop-loss price level (STOP order) |
required |
entry_type
|
OrderType
|
Entry order type (default MARKET) |
MARKET
|
entry_limit
|
float | None
|
Entry limit price (if entry_type is LIMIT) |
None
|
validate_prices
|
bool
|
If True, validate that TP/SL prices are sensible for the position direction (default True) |
True
|
Returns:
| Type | Description |
|---|---|
tuple[Order, Order, Order] | None
|
Tuple of (entry_order, take_profit_order, stop_loss_order) or None if any fails. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If validate_prices=True and prices are inverted for direction. |
Notes
For LONG entries (quantity > 0): - take_profit should be > reference_price (profit on up move) - stop_loss should be < reference_price (exit on down move)
For SHORT entries (quantity < 0): - take_profit should be < reference_price (profit on down move) - stop_loss should be > reference_price (exit on up move)
Reference price is entry_limit (if LIMIT order) or current market price.
Source code in src/ml4t/backtest/broker.py
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 | |
buy
¶
buy(
asset,
shares=None,
contracts=None,
amount=None,
dollars=None,
order_type=MARKET,
limit_price=None,
)
Buy an asset with explicit quantity specification.
Provides a clean API for buying with different quantity types: - shares: Number of shares (equities) - contracts: Number of contracts (futures) - amount: Base currency amount (crypto) - dollars: Dollar value to buy (any asset)
Exactly one quantity parameter must be provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol |
required |
shares
|
float | None
|
Number of shares to buy (equities) |
None
|
contracts
|
int | None
|
Number of contracts to buy (futures) |
None
|
amount
|
float | None
|
Base currency amount to buy (crypto) |
None
|
dollars
|
float | None
|
Dollar value to buy (converted to quantity at current price) |
None
|
order_type
|
OrderType
|
Order type (default MARKET) |
MARKET
|
limit_price
|
float | None
|
Limit price for LIMIT orders |
None
|
Returns:
| Type | Description |
|---|---|
Order | None
|
Order object if submitted, None if no current price or invalid params |
Raises:
| Type | Description |
|---|---|
ValueError
|
If zero or more than one quantity parameter is provided |
Example
Buy 100 shares of AAPL¶
broker.buy("AAPL", shares=100)
Buy 2 ES futures contracts¶
broker.buy("ES", contracts=2)
Buy $5000 worth of BTC¶
broker.buy("BTC", dollars=5000)
Buy 0.5 BTC¶
broker.buy("BTC", amount=0.5)
Source code in src/ml4t/backtest/broker.py
sell
¶
sell(
asset,
shares=None,
contracts=None,
amount=None,
dollars=None,
order_type=MARKET,
limit_price=None,
)
Sell an asset with explicit quantity specification.
Provides a clean API for selling with different quantity types: - shares: Number of shares (equities) - contracts: Number of contracts (futures) - amount: Base currency amount (crypto) - dollars: Dollar value to sell (any asset)
Exactly one quantity parameter must be provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol |
required |
shares
|
float | None
|
Number of shares to sell (equities) |
None
|
contracts
|
int | None
|
Number of contracts to sell (futures) |
None
|
amount
|
float | None
|
Base currency amount to sell (crypto) |
None
|
dollars
|
float | None
|
Dollar value to sell (converted to quantity at current price) |
None
|
order_type
|
OrderType
|
Order type (default MARKET) |
MARKET
|
limit_price
|
float | None
|
Limit price for LIMIT orders |
None
|
Returns:
| Type | Description |
|---|---|
Order | None
|
Order object if submitted, None if no current price or invalid params |
Raises:
| Type | Description |
|---|---|
ValueError
|
If zero or more than one quantity parameter is provided |
Example
Sell 50 shares of AAPL¶
broker.sell("AAPL", shares=50)
Sell 1 ES futures contract¶
broker.sell("ES", contracts=1)
Sell $2500 worth of position¶
broker.sell("BTC", dollars=2500)
Source code in src/ml4t/backtest/broker.py
close_position
¶
Close an open position for the given asset.
Submits an order to fully close the position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol to close |
required |
order_type
|
OrderType
|
Exit order type (default MARKET). Use |
MARKET
|
Returns:
| Type | Description |
|---|---|
Order | None
|
Order object if position exists and order submitted, None otherwise |
Example
Close AAPL position¶
order = broker.close_position("AAPL")
Flatten at the bar close¶
order = broker.close_position("AAPL", order_type=OrderType.MOC)
Source code in src/ml4t/backtest/broker.py
reduce_position
¶
Reduce an existing position by a fraction.
Sells (for long) or covers (for short) a percentage of the current position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol to reduce |
required |
fraction
|
float
|
Fraction to exit (0.5 = sell half, 0.25 = sell quarter) Must be between 0 and 1 (exclusive of 0, inclusive of 1) |
required |
order_type
|
OrderType
|
Order type (default MARKET) |
MARKET
|
limit_price
|
float | None
|
Limit price for LIMIT orders |
None
|
Returns:
| Type | Description |
|---|---|
Order | None
|
Order object if position exists and order submitted, None otherwise |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fraction is not in (0, 1] |
Example
Sell half of AAPL position¶
order = broker.reduce_position("AAPL", fraction=0.5)
Sell 25% of position with limit¶
order = broker.reduce_position("AAPL", fraction=0.25, order_type=OrderType.LIMIT, limit_price=155.0)
Source code in src/ml4t/backtest/broker.py
reduce_all_positions
¶
Cancel pending orders and reduce each open position atomically.
Source code in src/ml4t/backtest/broker.py
flatten_all_positions
¶
Cancel pending orders and submit exits for every open position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reason
|
str
|
Human-readable risk reason for the liquidation |
required |
order_type
|
OrderType
|
Exit order type to use for the flattening orders |
MARKET
|
Returns:
| Type | Description |
|---|---|
list[Order]
|
List of submitted exit orders |
Source code in src/ml4t/backtest/broker.py
order_target_percent
¶
Order to achieve target portfolio weight.
Calculates the order quantity needed to reach the target percentage of total portfolio value for this asset. Weights can exceed 1.0 for leveraged portfolios (e.g., futures, margin accounts). The gatekeeper validates whether the account has sufficient buying power.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol |
required |
target_percent
|
float
|
Target weight as decimal (0.10 = 10% of portfolio). Can exceed 1.0 for leveraged positions if allow_leverage=True. |
required |
order_type
|
OrderType
|
Order type (default MARKET) |
MARKET
|
limit_price
|
float | None
|
Limit price for LIMIT orders |
None
|
Returns:
| Type | Description |
|---|---|
Order | None
|
Submitted order, or None if no order needed or rejected |
Example
Target 10% of portfolio in AAPL¶
broker.order_target_percent("AAPL", 0.10)
Target 0% (close position)¶
broker.order_target_percent("AAPL", 0.0)
Leveraged: target 150% in ES futures (requires allow_leverage=True)¶
broker.order_target_percent("ES", 1.50)
Source code in src/ml4t/backtest/broker.py
order_target_value
¶
Order to achieve target position value.
Calculates the order quantity needed to reach the target dollar value for this position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol |
required |
target_value
|
float
|
Target position value in dollars (negative for short) |
required |
order_type
|
OrderType
|
Order type (default MARKET) |
MARKET
|
limit_price
|
float | None
|
Limit price for LIMIT orders |
None
|
Returns:
| Type | Description |
|---|---|
Order | None
|
Submitted order, or None if no order needed or rejected |
Example
Target $10,000 position in AAPL¶
broker.order_target_value("AAPL", 10000)
Target short $5,000¶
broker.order_target_value("AAPL", -5000)
Source code in src/ml4t/backtest/broker.py
rebalance_to_weights
¶
Rebalance portfolio to target weights.
Calculates orders needed to achieve target portfolio allocation. Processes sells before buys to free up capital.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_weights
|
dict[str, float]
|
Dict of {asset: weight} where weights are decimals (0.10 = 10%). Weights should sum to <= 1.0. |
required |
order_type
|
OrderType
|
Order type for all orders (default MARKET) |
MARKET
|
Returns:
| Type | Description |
|---|---|
list[Order]
|
List of submitted orders (may include None for rejected orders) |
Example
Equal weight three stocks¶
broker.rebalance_to_weights({ "AAPL": 0.33, "GOOGL": 0.33, "MSFT": 0.34, })
Source code in src/ml4t/backtest/broker.py
3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 | |
register_target_intent
¶
Register an idempotent target for a causal opening phase.
Source code in src/ml4t/backtest/broker.py
register_position_rule_policy
¶
Bind a position-rule implementation to a portable policy identity.
Source code in src/ml4t/backtest/broker.py
get_target_intents
¶
Return accepted canonical target intents.
get_child_order_intents
¶
Return canonical child intents derived from accepted targets.
Source code in src/ml4t/backtest/broker.py
get_intent_reconciliations
¶
Return retained child fill and remainder evidence.
Source code in src/ml4t/backtest/broker.py
get_target_rule_reconciliations
¶
Return retained per-target rule transition evidence.
Source code in src/ml4t/backtest/broker.py
export_target_intent_state
¶
Serialize accepted target, child, and reconciliation state.
restore_target_intent_state
¶
Restore target intent state before strategy initialization.
Source code in src/ml4t/backtest/broker.py
update_order
¶
Update pending order parameters.
Only the following fields can be updated: - quantity: Order size - limit_price: Limit price for LIMIT orders - stop_price: Stop/trigger price for STOP orders - trail_amount: Trail distance for TRAILING_STOP orders
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order_id
|
str
|
ID of the order to update |
required |
**kwargs
|
Unpack[OrderUpdate]
|
Fields to update |
{}
|
Returns:
| Type | Description |
|---|---|
bool
|
True if order was found and updated, False otherwise |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to update non-updatable fields |
Source code in src/ml4t/backtest/broker.py
cancel_order
¶
Cancel a pending order.
Returns True only when the identifier names a pending order. Filled, rejected, cancelled, and unknown orders return False.
Source code in src/ml4t/backtest/broker.py
get_order
¶
Return an order from the complete order history, or None when unknown.
get_pending_orders
¶
Return a copy of pending orders, optionally filtered by asset.
get_rejected_orders
¶
Get all rejected orders, optionally filtered by asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str | None
|
If provided, filter to only this asset's rejected orders |
None
|
Returns:
| Type | Description |
|---|---|
list[Order]
|
List of rejected Order objects with rejection_reason populated |
Source code in src/ml4t/backtest/broker.py
get_position
¶
Get the current position for an asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol |
required |
Returns:
| Type | Description |
|---|---|
Position | None
|
Position object if position exists, None otherwise |
Source code in src/ml4t/backtest/broker.py
get_positions
¶
Get all current positions.
Returns:
| Type | Description |
|---|---|
dict[str, Position]
|
Dictionary mapping asset symbols to Position objects |
get_cash
¶
Get current cash balance.
Returns:
| Type | Description |
|---|---|
float
|
Current cash balance (can be negative for margin accounts) |
equity
¶
get_account_value
¶
get_buying_power
¶
Get current buying power.
Returns:
| Type | Description |
|---|---|
float
|
Available buying power based on account policy: |
float
|
|
float
|
|
Source code in src/ml4t/backtest/broker.py
get_trades
¶
Get completed trades, optionally filtered.
Provides access to trade history during the backtest for stateful decision-making (e.g., adjusting position sizing based on recent wins/losses, implementing cooldown logic after stop-outs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str | None
|
Filter to only this asset's trades. If None, returns all trades. |
None
|
last_n
|
int | None
|
Return only the last N trades (after other filters) |
None
|
Returns:
| Type | Description |
|---|---|
list[Trade]
|
List of Trade objects matching the filters, ordered by exit time |
Example
Get all trades for BTC¶
btc_trades = broker.get_trades(asset="BTC")
Get last 5 trades overall¶
recent = broker.get_trades(last_n=5)
Get recent trades for cooldown logic¶
last_trade = broker.get_last_trade("AAPL") if last_trade and last_trade.exit_reason == "stop_loss": # Implement cooldown after stop-out pass
Source code in src/ml4t/backtest/broker.py
get_last_trade
¶
Get the most recent completed trade.
Convenience method for strategies that need to check the last trade (e.g., for cooldown logic after stop-outs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str | None
|
Filter to only this asset. If None, returns last trade overall. |
None
|
Returns:
| Type | Description |
|---|---|
Trade | None
|
Most recent Trade object, or None if no trades |
Example
last = broker.get_last_trade("AAPL") if last and last.exit_reason == "stop_loss": # Was stopped out - implement cooldown cooldown_bars = 5
Source code in src/ml4t/backtest/broker.py
set_position_rules
¶
Set position rules globally or per-asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rules
|
PositionRule | None
|
PositionRule or RuleChain to apply. |
required |
asset
|
str | None
|
If provided, apply only to this asset; otherwise global |
None
|
Source code in src/ml4t/backtest/broker.py
clear_position_rules
¶
update_position_context
¶
Update context data for a position (used by signal-based rules).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol |
required |
context
|
dict
|
Dict of signal/indicator values (e.g., {'exit_signal': -0.5, 'atr': 2.5}) |
required |
Source code in src/ml4t/backtest/broker.py
get_contract_spec
¶
Return a detached contract specification, or None when absent.
get_multiplier
¶
Get contract multiplier for an asset (1.0 for equities).
get_mark_price
¶
Resolve a finite configured mark, returning None when unavailable.
Source code in src/ml4t/backtest/broker.py
get_last_price
¶
get_price_for_source
¶
Resolve a configured price source with sensible OHLCV fallbacks.
Source code in src/ml4t/backtest/broker.py
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 | |
get_quote_mid
¶
Return explicit quote midpoint or derive it from bid/ask.
Source code in src/ml4t/backtest/broker.py
get_quote_context
¶
Return quote context for fills and trade summaries.
Source code in src/ml4t/backtest/broker.py
get_available_size
¶
Return side-aware quote size when available, otherwise bar volume.
Source code in src/ml4t/backtest/broker.py
configure_stats
¶
Configure trading statistics tracking.
Can either pass individual parameters or a StatsConfig object. Individual parameters override config values if both are provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recent_window_size
|
int | None
|
Number of recent trades to track (default 50) |
None
|
track_session_stats
|
bool | None
|
Whether to track per-session statistics |
None
|
enabled
|
bool | None
|
Whether stats tracking is enabled |
None
|
config
|
StatsConfig | None
|
StatsConfig object (alternative to individual params) |
None
|
Example
Using individual parameters¶
broker.configure_stats(recent_window_size=100)
Using StatsConfig¶
broker.configure_stats(config=StatsConfig( recent_window_size=100, track_session_stats=True, ))
Source code in src/ml4t/backtest/broker.py
get_asset_stats
¶
Get trading statistics for an asset.
Returns the AssetTradingStats object for the given asset, creating one if it doesn't exist. Stats are automatically updated when positions are closed or scaled down.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset
|
str
|
Asset symbol (e.g., "BTC", "AAPL") |
required |
Returns:
| Type | Description |
|---|---|
AssetTradingStats
|
AssetTradingStats object with all-time and recent statistics |
Example
stats = broker.get_asset_stats("BTC")
Check recent performance¶
if stats.recent_win_rate > 0.6: # Increase position size when winning size = base_size * 1.5 elif stats.recent_win_rate < 0.4: # Reduce size when losing size = base_size * 0.5
Check session performance (intraday)¶
if stats.session_trades > 3 and stats.session_win_rate < 0.25: # Stop trading this asset for today return
Source code in src/ml4t/backtest/broker.py
set_session_config
¶
Set session configuration for session-aware statistics.
When a session config is set, trading statistics are reset at session boundaries. This is useful for intraday strategies that want to track performance within each trading session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SessionConfig | None
|
SessionConfig object from ml4t.backtest.sessions, or None to disable session-aware statistics resets. |
required |
Example
from ml4t.backtest.sessions import SessionConfig
CME futures: sessions start 5pm CT previous day¶
session_config = SessionConfig( calendar="CME_Equity", timezone="America/Chicago", session_start_time="17:00", ) broker.set_session_config(session_config)
Source code in src/ml4t/backtest/broker.py
mark_account_positions
¶
Synchronize account position marks using configured price semantics.
Source code in src/ml4t/backtest/broker.py
evaluate_position_rules
¶
Evaluate position rules for all open positions.
Called by Engine before processing orders. Returns list of exit orders. Handles defer_fill=True by storing pending exits for next bar.
Source code in src/ml4t/backtest/broker.py
Domain Types¶
Order
dataclass
¶
Order(
asset,
side,
quantity,
order_type=MARKET,
limit_price=None,
stop_price=None,
trail_amount=None,
parent_id=None,
rebalance_id=None,
order_id="",
status=PENDING,
created_at=None,
filled_at=None,
filled_price=None,
filled_quantity=0.0,
rejection_reason=None,
requested_quantity=None,
target_intent_id=None,
child_intent_id=None,
intent_idempotency_key=None,
_rejection_code=None,
_created_bar_index=0,
_signal_price=None,
_priority_notional=None,
_risk_exit_reason=None,
_exit_reason=None,
_risk_fill_price=None,
*,
commission_paid=0.0,
action_adjusted_quantity=None,
cancelled_at=None,
cancellation_reason=None,
_submitted_session_date=None,
_eligible_from=None,
_eligible_on_boundary=True,
_stop_triggered=False,
_stop_triggered_at=None,
_trigger_price=None,
)
stop_triggered
property
¶
Whether a stop or stop-limit order has become eligible for execution.
stop_triggered_at
property
¶
Actual observed trigger instant, before any later partial fills.
rejection_code
property
¶
Return a stable machine-readable category for the rejection reason.
reject
¶
Move the order to a rejected state with a stable reason code.
Fill
dataclass
¶
Fill(
order_id,
asset,
side,
quantity,
price,
timestamp,
rebalance_id=None,
commission=0.0,
slippage=0.0,
order_type="",
limit_price=None,
stop_price=None,
price_source="",
reference_price=None,
quote_mid_price=None,
bid_price=None,
ask_price=None,
spread=None,
bid_size=None,
ask_size=None,
available_size=None,
exit_reason="",
exit_reason_detail=None,
target_intent_id=None,
child_intent_id=None,
intent_idempotency_key=None,
multiplier=None,
currency=None,
*,
stop_triggered_at=None,
trigger_price=None,
)
Trade
dataclass
¶
Trade(
symbol,
entry_time,
exit_time,
entry_price,
exit_price,
quantity,
pnl,
pnl_percent,
bars_held,
fees=0.0,
exit_slippage=0.0,
exit_reason="signal",
exit_reason_detail=None,
status="closed",
mfe=0.0,
mae=0.0,
entry_slippage=0.0,
multiplier=1.0,
entry_quote_mid_price=None,
entry_bid_price=None,
entry_ask_price=None,
entry_spread=None,
entry_available_size=None,
exit_quote_mid_price=None,
exit_bid_price=None,
exit_ask_price=None,
exit_spread=None,
exit_available_size=None,
metadata=None,
)
Realized exit leg or open position mark.
This dataclass is part of the cross-library API specification, designed to produce identical Parquet output across Python, Numba, and Rust implementations.
Fully closed positions use status="closed". Incremental reductions use
status="partial" so lifecycle analytics can exclude repeated position-level
excursion and holding-period values. Open positions use status="open" and
their exit fields represent end-of-backtest mark-to-market values.
Schema Alignment (v0.1.0a6): - symbol: Asset identifier (was 'asset' in earlier versions) - fees: Total transaction fees (was 'commission') - mfe/mae: Max favorable/adverse excursion (was 'max_favorable_excursion'/'max_adverse_excursion') - direction: Derived property from quantity sign
cost_drag
property
¶
Total cost as fraction of notional: (fees + total slippage cost) / notional.
Position
dataclass
¶
Position(
asset,
quantity,
entry_price,
entry_time,
current_price=None,
bars_held=0,
high_water_mark=None,
low_water_mark=None,
max_favorable_excursion=0.0,
max_adverse_excursion=0.0,
initial_quantity=None,
context=dict(),
multiplier=1.0,
entry_commission=0.0,
entry_slippage=0.0,
*,
_commission_adjusted_cost_basis=None,
variation_basis=None,
)
Unified position tracking for strategy and accounting.
Supports both long and short positions with: - Weighted average cost basis tracking - Mark-to-market price tracking - Risk metrics (MFE/MAE, water marks) - Contract multipliers for futures
Attributes:
| Name | Type | Description |
|---|---|---|
asset |
str
|
Asset identifier (e.g., "AAPL", "ES") |
quantity |
float
|
Position size (positive=long, negative=short) |
entry_price |
float
|
Weighted average entry price (cost basis) |
entry_time |
datetime
|
Timestamp when position was first opened |
current_price |
float | None
|
Latest mark-to-market price (updated each bar) |
bars_held |
int
|
Number of bars this position has been held |
Examples:
Long position: Position("AAPL", 100, 150.0, datetime.now()) -> quantity=100, unrealized_pnl depends on current_price
Short position: Position("AAPL", -100, 150.0, datetime.now()) -> quantity=-100, profit if price drops
commission_adjusted_cost_basis
property
¶
Reported price basis with each fill fee allocated over remaining signed units.
Reductions retain the prior price basis before their fee adjustment; reversals reset it to the fill price before allocating the entire reversal fee. This is a reporting convention and does not replace gross entry price or P&L costs.
market_value
property
¶
Current market value of the position.
For long positions: positive value (asset on balance sheet) For short positions: negative value (liability on balance sheet)
Returns:
| Type | Description |
|---|---|
float
|
Market value = quantity × current_price |
unrealized_pnl
¶
Calculate unrealized P&L including contract multiplier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_price
|
float | None
|
Price to calculate P&L at. If None, uses self.current_price. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Unrealized P&L = (current_price - entry_price) × quantity × multiplier |
Source code in src/ml4t/backtest/types.py
pnl_percent
¶
Calculate direction-aware percentage return on position.
For long positions: (price - entry) / entry For short positions: (entry - price) / entry
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_price
|
float | None
|
Price to calculate return at. If None, uses self.current_price. |
None
|
Source code in src/ml4t/backtest/types.py
notional_value
¶
Calculate notional value of position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_price
|
float | None
|
Price to calculate value at. If None, uses self.current_price. |
None
|
Source code in src/ml4t/backtest/types.py
update_water_marks
¶
update_water_marks(
current_price,
bar_high=None,
bar_low=None,
use_high_for_hwm=False,
use_low_for_lwm=False,
)
Update high/low water marks and excursion tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_price
|
float
|
Current bar's close price |
required |
bar_high
|
float | None
|
Bar's high price (used for HWM if use_high_for_hwm=True) |
None
|
bar_low
|
float | None
|
Bar's low price (used for LWM if use_low_for_lwm=True) |
None
|
use_high_for_hwm
|
bool
|
If True, use bar_high for HWM (VBT Pro OHLC mode). If False, use current_price (close) for HWM (default). |
False
|
use_low_for_lwm
|
bool
|
If True, use bar_low for LWM (VBT Pro OHLC mode). If False, use current_price (close) for LWM (default). |
False
|
Source code in src/ml4t/backtest/types.py
__repr__
¶
String representation for debugging.
Source code in src/ml4t/backtest/types.py
Enums¶
OrderType
¶
Bases: Enum
OrderSide
¶
Bases: Enum
ExecutionMode
¶
Bases: str, Enum
Order execution timing mode.
StopFillMode
¶
Bases: str, Enum
Stop/take-profit fill price mode.
Different frameworks handle stop order fills differently: - STOP_PRICE: Fill at exact stop/target price (standard model, default) Matches VectorBT Pro with OHLC and Backtrader behavior - CLOSE_PRICE: Fill at bar's close price when stop triggers Matches VectorBT Pro with close-only data - BAR_EXTREME: Fill at bar's low (stop-loss) or high (take-profit) Worst/best case model (conservative/optimistic) - NEXT_BAR_OPEN: Fill at next bar's open price when stop triggers Matches Zipline behavior (strategy-level stops)
CommissionType
¶
Bases: str, Enum
Commission calculation method.
SlippageType
¶
Bases: str, Enum
Slippage calculation method.
FillOrdering
¶
Bases: str, Enum
Order processing sequence within a single bar.
Controls how pending orders are sequenced during fill processing:
EXIT_FIRST (default): All exits → mark-to-market → all entries (with gatekeeper validation). Capital-efficient: exits free cash before entries need it. Matches engines that explicitly process reductions before additions.
FIFO
Orders process in submission order with sequential cash updates. Each order's gatekeeper check sees cash from all prior fills. Matches Backtrader's submission-order processing.
SEQUENTIAL
Orders process in submission order (typically alphabetical by asset) without exit/entry separation. Cash updates after each individual fill. Unlike EXIT_FIRST, exits do not pre-free cash for later entries. Matches LEAN's per-order sequential buying-power model.
PRIORITY
Sort all orders as one sequence using entry_order_priority. This preserves
combined reversal orders and matches portfolio simulators whose automatic call
sequence does not separate exits from entries.
Prediction-Market Fees¶
prediction_market_fees
¶
Trading-fee schedules for prediction-market venues.
Each venue has a vectorized function for research over arrays of fills and a
CommissionModel for the engine:
| Venue | Function | Model |
|---|---|---|
| Kalshi | kalshi_fee, kalshi_order_fees |
KalshiCommission |
| ForecastEx (via IBKR) | forecastex_fee |
ForecastExCommission |
| Polymarket US | polymarket_us_fee |
PolymarketUSCommission |
Prices are dollars per contract in [0, 1] and contracts pay 1.00 at
settlement. Buying NO at price q is a purchase at q; the quadratic
formulas use q * (1 - q), which is symmetric, so a fee needs no YES/NO flag.
Contracts are non-negative counts. side ("buy"/"sell") matters only
where a venue's rounding depends on the cash moved (Kalshi balance alignment).
liquidity is "taker" (the fill removed a resting order) or "maker"
(the fill executed a resting order).
The vectorized functions accept scalars, NumPy arrays, Python sequences and
Polars Series, broadcast them against each other and return a float64
numpy.ndarray of fees in dollars (0-d for all-scalar input).
Default coefficients preserve the schedules read on 2026-10-08. The Polymarket US taker-tier lookup separately models the November 2026 schedule.
KalshiCommission
¶
Kalshi trading fee as an engine CommissionModel.
Each calculate call is one fill and is treated as a one-fill order: the
per-order rebate of rounding overpayment (kalshi_order_fees) needs order
identity, which the protocol does not pass. A positive quantity is a buy, a
negative quantity a sell; buying NO is a buy at the NO price.
Formula, rounding modes and sources: see kalshi_fee.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
liquidity
|
Liquidity
|
|
'taker'
|
fee_type
|
KalshiFeeType
|
Series |
'quadratic'
|
fee_multiplier
|
float
|
Series |
1.0
|
rounding
|
KalshiRounding
|
|
'exact'
|
Source code in src/ml4t/backtest/prediction_market_fees.py
ForecastExCommission
¶
ForecastEx fee via IBKR as an engine CommissionModel.
Formula and sources: see forecastex_fee.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exchange_fee
|
float
|
Exchange fee per contract per side. |
FORECASTEX_EXCHANGE_FEE
|
broker_commission
|
float
|
Broker commission per contract per side. |
0.0
|
Source code in src/ml4t/backtest/prediction_market_fees.py
PolymarketUSCommission
¶
PolymarketUSCommission(
liquidity="taker",
fee_coefficient=POLYMARKET_US_TAKER_COEFFICIENT,
rounding="exact",
)
Polymarket US taker fee as an engine CommissionModel.
The engine charges only non-negative commissions, so a maker fill is
charged 0 and its rebate is left out, which
overstates maker costs. Use polymarket_us_fee where the rebate matters.
Formula, rounding and sources: see polymarket_us_fee.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
liquidity
|
Liquidity
|
|
'taker'
|
fee_coefficient
|
float
|
Fixed taker theta for the modeled account and period. |
POLYMARKET_US_TAKER_COEFFICIENT
|
rounding
|
PolymarketUSRounding
|
|
'exact'
|
Source code in src/ml4t/backtest/prediction_market_fees.py
kalshi_fee
¶
kalshi_fee(
price,
contracts,
*,
liquidity="taker",
side="buy",
fee_type="quadratic",
fee_multiplier=1.0,
rounding="exact",
)
Kalshi trading fee per fill, with each fill treated as its own order.
Taker fee: round_up(M * 0.07 * C * P * (1 - P)) with C contracts at
price P and M the series fee_multiplier. A maker fill pays a
multiple of the taker formula set by the series fee_type: 0 for
quadratic, 0.25 for quadratic_with_maker_fees and 0.5 for
quadratic_with_combo_maker_fees. Both fee_type and fee_multiplier
are on the series record of Kalshi's API (an event may override them).
Kalshi does not publish the flat formula in machine-readable form; that
type raises ValueError.
Rounding:
"exact": the trade fee, rounded up to 0.000001. 100 contracts at 0.50 pay 1.75; 1 contract at 0.50 pays 0.0175."cent": what a non-direct (FCM-cleared, retail) member is charged. The balance change (cash for the contracts minus the trade fee) is aligned down to 0.01, and the difference is added to the fee. 1 contract at 0.50 pays 0.02. Kalshi rebates accumulated overpayment across the fills of one order; this function treats every row as a one-fill order, where no rebate can arise. Usekalshi_order_feesfor the fills of one multi-fill order."direct": as"cent"with the direct-member precision 0.0001.
side changes the result only under "cent" and "direct", where a
sub-cent notional is part of the alignment.
Sources: Kalshi fee schedule, "Fee Schedule for July 2026 - 7.7.26 Update"
(https://kalshi.com/docs/kalshi-fee-schedule.pdf); maker multipliers from
the FeeType description in https://docs.kalshi.com/openapi.yaml;
rounding from https://docs.kalshi.com/getting_started/fee_rounding. All read
2026-10-08.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price
|
ArrayInput
|
Execution price in dollars per contract, in |
required |
contracts
|
ArrayInput
|
Contracts filled, non-negative. |
required |
liquidity
|
ArrayInput
|
|
'taker'
|
side
|
ArrayInput
|
|
'buy'
|
fee_type
|
ArrayInput
|
Series fee type, scalar or per fill. |
'quadratic'
|
fee_multiplier
|
ArrayInput
|
Series fee multiplier |
1.0
|
rounding
|
KalshiRounding
|
|
'exact'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Fee in dollars per fill. |
Source code in src/ml4t/backtest/prediction_market_fees.py
kalshi_order_fees
¶
kalshi_order_fees(
price,
contracts,
*,
liquidity="taker",
side="buy",
fee_type="quadratic",
fee_multiplier=1.0,
rounding="cent",
)
Net Kalshi fee per fill for the fills of one order, in execution order.
Each fill pays its trade fee plus a rounding fee that aligns the balance to
the member's precision (see kalshi_fee). The rounding fees accumulate per
order, across taker and maker fills alike. Whenever the accumulator holds at
least one precision step, whole steps are rebated on that fill, capped so
the fill's net fee stays non-negative. Three fills that each overpay 0.004
pay 0.004, 0.004, and on the third fill 0.010 less (accumulator 0.012,
0.002 carried forward).
Source: https://docs.kalshi.com/getting_started/fee_rounding (read 2026-10-08).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price
|
ArrayInput
|
Execution price per fill, in |
required |
contracts
|
ArrayInput
|
Contracts per fill, non-negative. |
required |
liquidity
|
ArrayInput
|
|
'taker'
|
side
|
ArrayInput
|
|
'buy'
|
fee_type
|
ArrayInput
|
Series fee type. |
'quadratic'
|
fee_multiplier
|
ArrayInput
|
Series fee multiplier |
1.0
|
rounding
|
KalshiRounding
|
|
'cent'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
One-dimensional array of net fees in dollars, one per fill. |
Source code in src/ml4t/backtest/prediction_market_fees.py
forecastex_fee
¶
ForecastEx fee per fill: a flat amount per contract per side.
ForecastEx charges 0.01 per contract per side at execution, "independent of contract resolution, netting, or settlement"; IBKR charges no commission on ForecastEx contracts. The fee does not depend on price or liquidity; price is validated so that the inputs match the other venues.
Before 2026-03-31 the fee was embedded in prices (a YES and a NO paired at
1.01) instead of charged explicitly. Prices recorded before that date
already contain it; pass exchange_fee=0.0 for them. Block trades are
exempt from 2026-09-22 to 2026-12-01; pass exchange_fee=0.0 for those
too.
Sources: ForecastEx fee schedule, CFTC filing https://www.cftc.gov/filings/orgrules/rules09082624298.pdf; change of model, https://www.cftc.gov/filings/orgrules/rules03022640231.pdf; IBKR commission, https://www.interactivebrokers.com/en/pricing/commissions-events.php. All read 2026-10-08.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price
|
ArrayInput
|
Execution price in |
required |
contracts
|
ArrayInput
|
Contracts filled, non-negative. |
required |
exchange_fee
|
ArrayInput
|
Exchange fee per contract. |
FORECASTEX_EXCHANGE_FEE
|
broker_commission
|
ArrayInput
|
Broker commission per contract. |
0.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Fee in dollars per fill. |
Source code in src/ml4t/backtest/prediction_market_fees.py
polymarket_us_fee
¶
polymarket_us_fee(
price,
contracts,
*,
liquidity="taker",
fee_coefficient=POLYMARKET_US_TAKER_COEFFICIENT,
maker_rebate_coefficient=POLYMARKET_US_MAKER_REBATE_COEFFICIENT,
rounding="exact",
)
Polymarket US fee per fill; a maker rebate is a negative fee.
Taker: theta * C * p * (1 - p). The default theta (0.0695) and
default maker rebate magnitude (0.0125) preserve the October 2026 schedule.
Under the November 2026 schedule, pass the account's coefficient at order
insertion. Use polymarket_us_taker_coefficient for a standard taker tier
or pass the venue-assigned rate explicitly when it differs. A market's
feeCoefficient is insufficient to determine an account's rate.
Rounding: "exact" returns the formula value; "cent" rounds each fill
to 0.01 with round-half-to-even, as the venue charges it, so small fees can
round to 0. The venue also caps the sum over one aggressive order's fills
at the rounded cumulative fee; per-fill rounding can exceed that cap by up
to 0.005 per fill.
Combo fees and weekly taker rebates are outside this per-fill function. To calculate a current maker rebate, pass its coefficient explicitly (including zero when the account has no rebate).
Source: Polymarket US fee schedule, https://docs.polymarket.us/fees.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price
|
ArrayInput
|
Execution price in |
required |
contracts
|
ArrayInput
|
Contracts filled, non-negative. |
required |
liquidity
|
ArrayInput
|
|
'taker'
|
fee_coefficient
|
ArrayInput
|
Taker theta, scalar or per fill. |
POLYMARKET_US_TAKER_COEFFICIENT
|
maker_rebate_coefficient
|
ArrayInput
|
Maker rebate magnitude, scalar or per fill. |
POLYMARKET_US_MAKER_REBATE_COEFFICIENT
|
rounding
|
PolymarketUSRounding
|
|
'exact'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Signed fee in dollars per fill: positive is paid, negative is received. |
Source code in src/ml4t/backtest/prediction_market_fees.py
polymarket_us_taker_coefficient
¶
Select the standard Polymarket US taker coefficient by qualifying USD volume.
Uses the exchange-wide schedule effective November 14, 2026. The input is the account's qualifying volume at order insertion. Normally this is the sum over the preceding 30 completed Eastern Time calendar days, excluding the current day. The lookup does not compute the volume, handle onboarding or manual overrides, or derive a rate from market metadata.
Use the returned coefficient with polymarket_us_fee or pass a single value
to PolymarketUSCommission for a backtest with a fixed known account tier.
Source code in src/ml4t/backtest/prediction_market_fees.py
Results¶
BacktestResult
dataclass
¶
BacktestResult(
trades,
equity_curve,
fills,
metrics,
predictions=None,
config=None,
equity=None,
trade_analyzer=None,
portfolio_state=list(),
rejected_orders=list(),
funding_payments=list(),
artifact_diagnostics=tuple(),
initial_capital=None,
holdings=None,
holdings_sampling="none",
capital_changes=list(),
returns_include_commissions=None,
observation_metadata=list(),
recorded_variables=None,
account_method=None,
benchmark=None,
benchmark_metadata=None,
corporate_actions=None,
corporate_entitlements=None,
corporate_receivables=None,
instrument_accounting=None,
accounting_observations=None,
futures_settlements=None,
futures_rolls=None,
input_provenance=None,
_trades_df=None,
_equity_df=None,
_fills_df=None,
_portfolio_state_df=None,
_rejected_orders_df=None,
)
Structured backtest result with export capabilities.
This class wraps the raw output from Engine.run() and provides: - DataFrame conversion methods (trades, equity, daily P&L) - Parquet export/import for persistence - Integration with ml4t.diagnostic library - Backward-compatible dict export
Attributes:
| Name | Type | Description |
|---|---|---|
trades |
list[Trade]
|
List of completed Trade objects |
equity_curve |
list[tuple[datetime, float]]
|
List of (timestamp, portfolio_value) tuples |
fills |
list[Fill]
|
List of Fill objects (all order fills) |
funding_payments |
list[FundingPayment]
|
Timestamped cash flows separate from trades and fills |
rejected_orders |
list[Order]
|
Orders that reached the rejected terminal state. Orders cancelled under permissive insufficient-cash handling are not included. |
predictions |
DataFrame | None
|
Raw prediction DataFrame passed into the backtest (optional) |
metrics |
dict[str, Any]
|
Dictionary of computed performance metrics |
config |
BacktestConfig | None
|
BacktestConfig used for the backtest (optional) |
equity |
EquityCurve | None
|
EquityCurve analytics object |
trade_analyzer |
TradeAnalyzer | None
|
TradeAnalyzer analytics object |
artifact_diagnostics |
tuple[ArtifactDiagnostic, ...]
|
Structured omissions and recovery actions. Empty for artifacts loaded successfully in strict mode. |
from_parquet
classmethod
¶
Load a validated result artifact.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Directory containing files written by :meth: |
required |
recovery
|
bool
|
Permit manifest-free beta artifacts and omit unreadable components.
Every omission is reported through |
False
|
Returns:
| Type | Description |
|---|---|
BacktestResult
|
BacktestResult instance. |
Raises:
| Type | Description |
|---|---|
ArtifactError
|
If strict validation or component decoding fails. |
Source code in src/ml4t/backtest/result.py
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 | |
to_trades_dataframe
¶
Convert trades to Polars DataFrame.
Returns DataFrame with columns
symbol, entry_time, exit_time, entry_price, exit_price, quantity, direction, pnl, pnl_percent, bars_held, fees, exit_slippage, mfe, mae, entry_slippage, multiplier, gross_pnl, net_return, total_slippage_cost, cost_drag, exit_reason, exit_reason_detail, status
Cost decomposition columns
gross_pnl: Price-move P&L before fees net_return: Direction-aware net return including fees total_slippage_cost: Entry + exit slippage in dollars cost_drag: Total cost as fraction of notional
The status column indicates "closed" (flat-to-flat completion), "partial" (realized reduction), or "open" (mark-to-market at end of backtest).
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with one row per trade |
Source code in src/ml4t/backtest/result.py
to_fills_dataframe
¶
Convert every execution fill to a stable Polars DataFrame.
The result includes order identity, quantity, execution costs, price source, nullable quote context, available size, and exit-reason fields. An empty result retains the same typed schema.
Source code in src/ml4t/backtest/result.py
to_funding_dataframe
¶
Return timestamped funding cash flows separately from trades and fills.
Source code in src/ml4t/backtest/result.py
to_rejected_orders_dataframe
¶
Convert rejected orders to a stable, machine-readable DataFrame.
Source code in src/ml4t/backtest/result.py
to_portfolio_state_dataframe
¶
Return ordered account observations and explicit holdings completeness.
Source code in src/ml4t/backtest/result.py
to_predictions_dataframe
¶
Return the raw prediction DataFrame used as backtest input.
to_equity_dataframe
¶
Convert equity curve to Polars DataFrame.
Returns DataFrame with columns
timestamp, equity, return, cumulative_return, drawdown, high_water_mark
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with one row per bar, sorted by timestamp |
Source code in src/ml4t/backtest/result.py
to_daily_pnl
¶
Get daily P&L DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_aligned
|
bool
|
If True and session config is available, align P&L to trading sessions (e.g., CME 5pm-4pm CT). If False, use calendar day boundaries. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: date, open_equity, close_equity, high_equity, low_equity, pnl, return_pct, cumulative_return, num_bars |
Source code in src/ml4t/backtest/result.py
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 | |
to_daily_returns
¶
Get daily returns as Polars Series for ml4t-diagnostic integration.
Omission or a named calendar aggregates bar-level equity to daily returns. Explicit None instead retains observation-level returns; use the matching declared annualization scale for downstream metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
calendar
|
str | None | CalendarUnset
|
Trading calendar for context. If provided and known, enables session-aware aggregation. Common values: - "crypto": 365 days/year (24/7) - "NYSE", "NASDAQ": 252 days/year - "CME_Equity", etc: Uses pandas_market_calendars Omission resolves the feed calendar, then NYSE. Explicit None returns one return per observation without daily aggregation. |
UNSET_CALENDAR
|
session_aligned
|
bool | None
|
If True, align to trading sessions (e.g., CME 5pm CT). If None, auto-detect from calendar (True for CME, False for crypto). If False, use calendar day boundaries. |
None
|
Returns:
| Type | Description |
|---|---|
Series
|
Series of daily returns (percentage, e.g., 0.01 = 1%) |
Example
result = engine.run() daily_returns = result.to_daily_returns(calendar="NYSE")
Use with ml4t-diagnostic¶
from ml4t.diagnostic.evaluation.metrics.risk_adjusted import sharpe_ratio sharpe = sharpe_ratio(daily_returns.to_numpy(), annualization_factor=252)
Source code in src/ml4t/backtest/result.py
to_returns_series
¶
Get period returns as Polars Series.
Note: This returns BAR-LEVEL returns, not daily returns. For risk metrics like Sharpe ratio, use to_daily_returns() instead.
Returns:
| Type | Description |
|---|---|
Series
|
Series of period returns (one per bar) |
Source code in src/ml4t/backtest/result.py
to_trade_records
¶
Convert trades to ml4t.diagnostic TradeRecord format.
Returns list of dictionaries matching the TradeRecord schema from ml4t.diagnostic.integration.
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of trade record dictionaries |
Source code in src/ml4t/backtest/result.py
to_dict
¶
Export as dictionary (backward compatible with Engine.run()).
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with all metrics and raw data |
Source code in src/ml4t/backtest/result.py
to_spec_dict
¶
Export a resolved runtime spec for reproducibility.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing the fully resolved config, library version, |
dict[str, Any]
|
and realized run window. The nested |
dict[str, Any]
|
compatible with |
Source code in src/ml4t/backtest/result.py
to_parquet
¶
Export backtest result to Parquet files.
Creates directory structure
{path}/ trades.parquet fills.parquet funding.parquet rejected_orders.parquet predictions.parquet equity.parquet portfolio_state.parquet daily_pnl.parquet metrics.json config.yaml (if config available) spec.yaml (if config available) manifest.json
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Directory path to write files |
required |
include
|
list[str] | None
|
Components to include. Default: all. Options: ["trades", "fills", "funding", "rejected_orders", "predictions", "equity", "portfolio_state", "daily_pnl", "metrics", "config", "spec"] |
None
|
compression
|
Literal['lz4', 'uncompressed', 'snappy', 'gzip', 'brotli', 'zstd']
|
Parquet compression codec (default: "zstd") |
'zstd'
|
Returns:
| Type | Description |
|---|---|
dict[str, Path]
|
Dict mapping requested component names to file paths. The always-written |
dict[str, Path]
|
manifest is returned under the additional |
dict[str, Path]
|
a selectable component. |
Raises:
| Type | Description |
|---|---|
ArtifactWriteError
|
If a requested component is unavailable or cannot be written. |
Source code in src/ml4t/backtest/result.py
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 | |
__getitem__
¶
get
¶
keys
¶
Execution: Market Impact¶
LinearImpact
dataclass
¶
Bases: MarketImpactModel
Linear market impact model.
Impact = coefficient * (quantity / volume) * price
Simple model where impact scales linearly with participation rate. Appropriate for liquid markets with moderate order sizes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coefficient
|
float
|
Impact scaling factor (default 0.1) Higher values = more impact per unit participation |
0.1
|
The impact this returns is entirely temporary: calculate sees one order
and holds no reference to earlier slices of the same parent, so there is
nothing for a permanent component to persist into. A permanent_fraction
field was accepted and documented here until 0.1.7 and was never read; it is
removed rather than defaulted so that asking for a permanent component
raises instead of silently returning a fully temporary one.
calculate
¶
Calculate linear impact.
Source code in src/ml4t/backtest/execution/impact.py
SquareRootImpact
dataclass
¶
Bases: MarketImpactModel
Square root market impact model (Almgren-Chriss style).
Impact = coefficient * sigma * sqrt(quantity / ADV) * price
Based on academic market microstructure research. Impact scales with the square root of order size, which matches empirical observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coefficient
|
float
|
Scaling factor (default 0.5, typical range 0.1-1.0) |
0.5
|
volatility
|
float
|
Daily volatility (sigma, default 0.02 = 2%) |
0.02
|
adv_factor
|
float
|
Average daily volume as multiple of bar volume (default 1.0 for daily bars, 390 for minute bars) |
1.0
|
Example
model = SquareRootImpact(coefficient=0.5, volatility=0.02)
For order = 1% of ADV at 2% vol, $100 price:¶
Impact = 0.5 * 0.02 * sqrt(0.01) * 100 = $0.10¶
calculate
¶
Calculate square root impact.
Source code in src/ml4t/backtest/execution/impact.py
PowerLawImpact
dataclass
¶
Bases: MarketImpactModel
Generalized power law impact model.
Impact = coefficient * (quantity / volume)^exponent * price
Flexible model that can represent various impact regimes. - exponent = 1.0: Linear (like LinearImpact) - exponent = 0.5: Square root (like SquareRootImpact) - exponent < 0.5: Concave (impact flattens for large orders) - exponent > 1.0: Convex (impact accelerates for large orders)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coefficient
|
float
|
Scaling factor (default 0.1) |
0.1
|
exponent
|
float
|
Power law exponent (default 0.5) |
0.5
|
min_impact
|
float
|
Minimum impact per trade (fixed cost, default 0) |
0.0
|
Example
model = PowerLawImpact(coefficient=0.1, exponent=0.6)
calculate
¶
Calculate power law impact.
Source code in src/ml4t/backtest/execution/impact.py
Risk: Position Rules¶
StopLoss
dataclass
¶
Exit when stop price is breached during the bar.
Stop orders trigger when the bar's price range touches the stop level. Fill price depends on StopFillMode configuration: - STOP_PRICE: Fill at exact stop price (standard model, default) - BAR_EXTREME: Fill at bar's low (matches VectorBT Pro behavior)
For long positions: stop triggers if bar_low <= stop_price For short positions: stop triggers if bar_high >= stop_price
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct
|
float
|
Maximum loss as decimal (0.05 = 5% loss triggers exit) |
required |
Example
rule = StopLoss(pct=0.05) # Exit at -5%
evaluate
¶
Exit if stop price was breached during the bar.
Source code in src/ml4t/backtest/risk/position/static.py
TakeProfit
dataclass
¶
Exit when target price is reached during the bar.
Take-profit orders trigger when the bar's price range touches the target. Fill price depends on StopFillMode configuration: - STOP_PRICE: Fill at exact target price (standard model, default) - BAR_EXTREME: Fill at bar's high (matches VectorBT Pro behavior)
For long positions: triggers if bar_high >= target_price For short positions: triggers if bar_low <= target_price
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct
|
float
|
Target profit as decimal (0.10 = 10% profit triggers exit) |
required |
Example
rule = TakeProfit(pct=0.10) # Exit at +10%
evaluate
¶
Exit if target price was reached during the bar.
Source code in src/ml4t/backtest/risk/position/static.py
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 | |
TimeExit
dataclass
¶
Exit after holding for a specified number of bars.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_bars
|
int
|
Maximum bars to hold position |
required |
Example
rule = TimeExit(max_bars=20) # Exit after 20 bars
evaluate
¶
Exit if held too long.
Source code in src/ml4t/backtest/risk/position/static.py
TrailingStop
dataclass
¶
Exit when price retraces from high water mark.
For longs: Exit if price drops X% from highest price since entry For shorts: Exit if price rises X% from lowest price since entry
Fill price depends on StopFillMode configuration: - STOP_PRICE: Fill at exact trail level (default) - CLOSE_PRICE: Fill at bar's close price (VBT Pro behavior)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct
|
float
|
Trail percentage as decimal (0.05 = 5% trail) |
required |
Example
rule = TrailingStop(pct=0.05) # 5% trailing stop
evaluate
¶
Exit if price retraces beyond trail.
Uses bar_low/bar_high for intrabar trigger detection. Handles gap-through: if bar opens beyond stop level, fill at open.
Fill price depends on StopFillMode configuration: - STOP_PRICE: Fill at exact trail level (default) - CLOSE_PRICE: Fill at bar's close price - BAR_EXTREME: Fill at bar's low (long) or high (short)
Water mark timing depends on TrailStopTiming configuration: - LAGGED: Use water mark from PREVIOUS bar (default, 1-bar lag) - INTRABAR: Compute "live" water mark using current bar's extreme, then check. VBT Pro compatible: respects StopFillMode for fill price.
Gap-through handling: When bar opens beyond the stop level (gap down for longs, gap up for shorts), the fill is at the open price regardless of StopFillMode. This matches VBT Pro behavior.
Source code in src/ml4t/backtest/risk/position/dynamic.py
RuleChain
dataclass
¶
Evaluate rules in order, first non-HOLD action wins.
This is the most common composition pattern - rules are checked in priority order and the first rule to trigger takes effect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rules
|
list[PositionRule]
|
List of rules to evaluate in order |
required |
Example
chain = RuleChain([ StopLoss(pct=0.05), # Highest priority ScaledExit([(0.10, 0.5)]), # Second priority TighteningTrailingStop([...]), # Third priority TimeExit(bars=20), # Lowest priority ])
evaluate
¶
Evaluate rules in order, return first non-HOLD action.
Source code in src/ml4t/backtest/risk/position/composite.py
AllOf
dataclass
¶
All rules must return non-HOLD for the action to trigger.
Useful for requiring multiple conditions to be true before exiting. Returns the first rule's action details (pct, stop_price, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rules
|
list[PositionRule]
|
List of rules that must all agree |
required |
Example
Exit only if both profitable AND held long enough¶
rule = AllOf([ TakeProfit(pct=0.0), # Must be profitable TimeExit(bars=5), # Must have held 5+ bars ])
evaluate
¶
Return action only if ALL rules return non-HOLD.
Source code in src/ml4t/backtest/risk/position/composite.py
AnyOf
dataclass
¶
First rule to return non-HOLD wins (alias for RuleChain).
Semantically equivalent to RuleChain but named for clarity when composing complex rule logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rules
|
list[PositionRule]
|
List of rules where any can trigger |
required |
Example
Exit on stop-loss OR signal¶
rule = AnyOf([ StopLoss(pct=0.05), SignalExit(threshold=0.5), ])
evaluate
¶
Return first non-HOLD action (same as RuleChain).
Source code in src/ml4t/backtest/risk/position/composite.py
Risk: Portfolio Limits¶
MaxDrawdownLimit
dataclass
¶
Bases: PortfolioLimit
Liquidate or halt when drawdown exceeds threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_drawdown
|
float
|
Maximum allowed drawdown (0.0-1.0) Default 0.20 = 20% max drawdown |
0.2
|
action
|
str
|
Action when breached ("warn", "reduce", "halt", "liquidate") Default "liquidate" - flatten positions and stop new trades |
'liquidate'
|
warn_threshold
|
float | None
|
Optional earlier threshold for warnings |
None
|
reduction_pct
|
float
|
Required fraction in (0, 1] when action is "reduce" |
0.0
|
Example
limit = MaxDrawdownLimit(max_drawdown=0.20, warn_threshold=0.15)
Warns at 15% drawdown, liquidates at 20%¶
MaxPositionsLimit
dataclass
¶
Bases: PortfolioLimit
Limit maximum number of open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_positions
|
int
|
Maximum number of simultaneous positions |
10
|
action
|
str
|
Action when breached ("warn", "halt") |
'halt'
|
MaxExposureLimit
dataclass
¶
Bases: PortfolioLimit
Limit maximum exposure to a single asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_exposure_pct
|
float
|
Maximum position size as % of equity (0.0-1.0) Default 0.10 = 10% max per asset |
0.1
|
action
|
str
|
Action when breached |
'warn'
|
Example
limit = MaxExposureLimit(max_exposure_pct=0.10)
No single position can be > 10% of portfolio¶
DailyLossLimit
dataclass
¶
Bases: PortfolioLimit
Liquidate or halt when daily loss exceeds threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_daily_loss_pct
|
float
|
Maximum daily loss as % of equity (0.0-1.0) Default 0.02 = 2% max daily loss |
0.02
|
action
|
str
|
Action when breached ("warn", "halt", "liquidate") |
'liquidate'
|
Strategy Templates¶
SignalFollowingStrategy
¶
Bases: Strategy
Template for strategies that follow pre-computed signals.
Use this when you have ML predictions, technical indicators, or any pre-computed signal column in your DataFrame.
Class Attributes
signal_column: Name of the signal column in data (default: "signal") position_size: Fraction of equity per position (default: 0.10) allow_shorts: Whether to allow short positions (default: False)
Example
class MyMLStrategy(SignalFollowingStrategy): ... signal_column = "rf_prediction" ... position_size = 0.05 ... ... def should_enter_long(self, signal): ... return signal > 0.7 ... ... def should_exit(self, signal): ... return signal < 0.3
should_enter_long
abstractmethod
¶
Return True to open a long position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
float
|
Current signal value for the asset |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if should enter long position |
should_exit
abstractmethod
¶
Return True to close current position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
float
|
Current signal value for the asset |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if should exit position |
should_enter_short
¶
Return True to open a short position.
Override this method for short strategies. Default returns False.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
float
|
Current signal value for the asset |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if should enter short position |
Source code in src/ml4t/backtest/strategies/templates.py
on_data
¶
Process each bar and generate orders based on signals.
Source code in src/ml4t/backtest/strategies/templates.py
MomentumStrategy
¶
Bases: Strategy
Template for momentum/trend-following strategies.
Enters long when asset has positive momentum over lookback period, exits when momentum turns negative.
Class Attributes
lookback: Number of bars for momentum calculation (default: 20) entry_threshold: Minimum return to enter (default: 0.05 = 5%) exit_threshold: Return level to exit (default: -0.02 = -2%) position_size: Fraction of equity per position (default: 0.10)
Example
class MyMomentum(MomentumStrategy): ... lookback = 60 # 60-day momentum ... entry_threshold = 0.10 # Enter on 10% gain ... exit_threshold = 0.0 # Exit when momentum turns negative
Source code in src/ml4t/backtest/strategies/templates.py
calculate_momentum
¶
Calculate momentum as return over lookback period.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
list[float]
|
List of prices (most recent last) |
required |
Returns:
| Type | Description |
|---|---|
float
|
Return from first to last price |
Source code in src/ml4t/backtest/strategies/templates.py
on_data
¶
Process each bar and trade based on momentum.
Source code in src/ml4t/backtest/strategies/templates.py
MeanReversionStrategy
¶
Bases: Strategy
Template for mean-reversion strategies.
Buys when price is below moving average by a threshold, sells when price reverts to the mean.
Class Attributes
lookback: Number of bars for mean calculation (default: 20) entry_zscore: Z-score threshold to enter (default: -2.0) exit_zscore: Z-score threshold to exit (default: 0.0) position_size: Fraction of equity per position (default: 0.10)
Example
class MyMeanReversion(MeanReversionStrategy): ... lookback = 30 ... entry_zscore = -2.5 # More extreme entry ... exit_zscore = 0.5 # Take profit above mean
Source code in src/ml4t/backtest/strategies/templates.py
calculate_zscore
¶
Calculate z-score of current price vs historical distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
list[float]
|
Historical prices |
required |
current
|
float
|
Current price |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
Z-score or None if insufficient data |
Source code in src/ml4t/backtest/strategies/templates.py
on_data
¶
Process each bar and trade based on mean reversion.
Source code in src/ml4t/backtest/strategies/templates.py
LongShortStrategy
¶
Bases: Strategy
Template for long/short equity strategies.
Ranks assets by a signal and goes long top N, short bottom N.
Class Attributes
signal_column: Column to rank assets by (default: "signal") long_count: Number of assets to go long (default: 5) short_count: Number of assets to go short (default: 5) position_size: Fraction of equity per position (default: 0.05) rebalance_frequency: Bars between rebalancing (default: 20)
Example
class MyLongShort(LongShortStrategy): ... signal_column = "momentum_score" ... long_count = 10 ... short_count = 10 ... rebalance_frequency = 21 # Monthly
Source code in src/ml4t/backtest/strategies/templates.py
on_prepare
¶
Retain causal calendar metadata for online schedule evaluation.
Source code in src/ml4t/backtest/strategies/templates.py
rank_assets
¶
Rank assets by signal and return long/short lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, dict]
|
Current bar data for all assets |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[str], list[str]]
|
Tuple of (long_assets, short_assets) |
Source code in src/ml4t/backtest/strategies/templates.py
on_data
¶
Rebalance portfolio periodically based on rankings.