API reference¶
Everything on this page is public API, covered by the stability policy. The most used names import from the package itself:
# Running backtests
from trading import BacktestConfig, BacktestEngine, BacktestResult
# Writing strategies
from trading import HOLD, Direction, MarketDataEvent, PortfolioStrategy, Signal, Strategy
Backtesting¶
BacktestEngine
¶
BacktestEngine(
config: BacktestConfig | None = None,
*,
feeds: Sequence[Feed] | None = None,
feed: Feed | None = None,
strategy: AnyStrategy | None = None,
warmup_until: datetime | None = None,
run_id: str | None = None,
)
Builds every component from a BacktestConfig and runs the simulation.
The event loop. Feeds are merged into chronological time slices (every bar sharing a timestamp). For each slice the engine:
- publishes the slice's
MarketDataEvents and drains the bus, which lets the whole cascade settle: fills for earlier orders, new signals, orders and risk decisions; then - publishes an
EndOfBarEventand drains again, which triggers the portfolio's mark-to-market snapshot and cross-sectional strategies.
Only then is the next slice read. Every component therefore sees a strictly causal stream, and orders placed on slice t trade on a later slice.
Warm-up. Slices before warmup_until are shown only to the
strategy and the shared market state (indicators, ATR), never to the
portfolio, risk, metrics or persistence. Walk-forward testing uses this
so a test window starts with warmed-up indicators. When trading starts,
each symbol's last warm-up signal is replayed (see
WarmupSignals), so the strategy starts in its current position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
BacktestConfig | None
|
Run configuration. |
None
|
feeds
|
Sequence[Feed] | None
|
Optional feed overrides, one per symbol (defaults to config). |
None
|
feed
|
Feed | None
|
Shorthand for a single feed. |
None
|
strategy
|
AnyStrategy | None
|
Optional strategy override, e.g. a custom |
None
|
warmup_until
|
datetime | None
|
First timestamp that counts. Earlier slices only warm up. |
None
|
run_id
|
str | None
|
Identifier for the run (random by default). |
None
|
BacktestResult
dataclass
¶
BacktestResult(
run_id: str,
config: BacktestConfig,
strategy: str,
symbols: tuple[str, ...],
report: PerformanceReport,
equity_curve: PriceSeries,
prices: Mapping[str, PriceSeries],
fills: tuple[FillEvent, ...],
trades: tuple[Trade, ...],
symbol_stats: tuple[SymbolStats, ...] = (),
benchmark_curve: tuple[float, ...] = (),
confidence: ConfidenceIntervals | None = None,
)
Everything a run produced: the report plus the series needed to analyse or plot it.
BacktestConfig
dataclass
¶
BacktestConfig(
simulation: SimulationConfig = SimulationConfig(),
strategy: StrategyConfig = StrategyConfig(),
order_manager: OrderManagerConfig = OrderManagerConfig(),
execution: ExecutionConfig = ExecutionConfig(),
risk: RiskConfig = RiskConfig(),
exits: ExitsConfig = ExitsConfig(),
portfolio: PortfolioConfig = PortfolioConfig(),
metrics: MetricsConfig = MetricsConfig(),
persistence: PersistenceConfig = PersistenceConfig(),
visualization: VisualizationConfig = VisualizationConfig(),
paper: PaperConfig = PaperConfig(),
)
from_dict
classmethod
¶
from_dict(data: dict[str, Any] | None) -> BacktestConfig
Build a config from a nested mapping (e.g. parsed YAML), validating everything.
with_overrides
¶
with_overrides(
overrides: Mapping[str, Any], *, skip_none: bool = True
) -> BacktestConfig
Return a copy with dotted-key overrides applied, e.g. {"strategy.type": "rsi"}.
By default None values are ignored so callers can pass optional CLI
arguments directly. With skip_none=False they are applied, which
disables optional limits such as risk.max_position.
Each section of the config is a dataclass of its own; the configuration reference lists every field.
Strategies¶
Strategy
¶
Bases: ABC
Turns bars into signals. Subclasses implement only on_bar.
The base class subscribes to MarketDataEvent and publishes exactly
one SignalEvent per bar, with strength clamped to [0, 1].
Strategies see each bar after it closes; any order they trigger executes
on a later bar.
A minimal strategy:
class AlwaysLong(Strategy):
name = "always_long"
def on_bar(self, bar: MarketDataEvent) -> Signal:
return Direction.BUY, 1.0
Keep per-symbol state in dicts keyed by bar.symbol so the same
instance can trade several symbols.
on_bar
abstractmethod
¶
on_bar(bar: MarketDataEvent) -> Signal
Return the signal for bar, using only this and earlier bars.
PortfolioStrategy
¶
Bases: ABC
Cross-sectional strategy: decides for every symbol once per time slice.
The base class collects the bars of each slice and, on the engine's
EndOfBarEvent, calls on_slice with all of them. It then
publishes one SignalEvent for every symbol in the slice, using
HOLD for symbols the strategy did not mention.
A minimal strategy:
class LongTheLeader(PortfolioStrategy):
name = "leader"
def on_slice(self, timestamp, bars):
best = max(bars, key=lambda s: bars[s].close)
return {s: (Direction.BUY if s == best else Direction.EXIT, 1.0)
for s in bars}
on_slice
abstractmethod
¶
on_slice(
timestamp: datetime, bars: Mapping[str, MarketDataEvent]
) -> Mapping[str, Signal]
Return signals for any of the symbols in bars (the bars of this slice).
Signal
module-attribute
¶
Signal = tuple[Direction, float]
A strategy decision: direction plus a strength in [0, 1].
STRATEGIES
module-attribute
¶
STRATEGIES: dict[str, StrategyFactory] = {
"ma_crossover": lambda cfg, _seed, _syms: (
MACrossoverStrategy(
cfg.fast_period, cfg.slow_period
)
),
"rsi": lambda cfg, _seed, _syms: RSIStrategy(
cfg.period, cfg.overbought, cfg.oversold
),
"random": lambda _cfg, seed, _syms: RandomStrategy(
seed
),
"buy_and_hold": lambda _cfg, _seed, _syms: (
BuyAndHoldStrategy()
),
"momentum_rotation": lambda cfg, _seed, _syms: (
MomentumRotationStrategy(
cfg.lookback, cfg.top_k, cfg.rebalance_every
)
),
"pairs": lambda cfg, _seed, syms: PairsStrategy(
syms[0],
syms[1],
cfg.lookback,
cfg.entry_z,
cfg.exit_z,
),
}
Strategy names and the factories that build them from config, seed and symbols.
Add an entry at module level to use a strategy of your own by name, in config files, sweeps (whose worker processes import that module too) and studies:
STRATEGIES["breakout"] = lambda cfg, seed, symbols: Breakout()
indicators
¶
Incremental technical indicators.
Each update() consumes one value and returns None until the indicator has warmed up.
RSI
¶
Relative Strength Index with Wilder's smoothing (the standard definition).
The first value is produced after period + 1 prices, seeded with the
simple average gain/loss over the first period changes. Subsequent
values use Wilder's recursive average:
avg = (prev_avg * (period - 1) + current) / period
RSI = 100 - 100 / (1 + avg_gain / avg_loss)
A window with no movement at all reads as a neutral 50.
ATR
¶
Average True Range with Wilder's smoothing.
True range is max(high - low, |high - prev_close|, |low - prev_close|)
(just high - low for the first bar). The first ATR is the simple mean
of the first period true ranges; later values use Wilder's recursion.
Events¶
types
¶
Typed, immutable event definitions for the trading pipeline.
Every component communicates exclusively through these events. They are frozen, slotted, keyword-only dataclasses: cheap to create, impossible to mutate once published, and robust to field reordering.
Lifecycle of an order:
SignalEvent ─► OrderEvent ─► ApprovedOrderEvent ─► FillEvent (one or more)
│ │
▼ ├─► OrderCancelledEvent (expired / cancelled /
RiskVetoEvent │ rejected, possibly after partial fills)
◄── CancelOrderEvent (a cancel request)
Direction
¶
Bases: Enum
Trade direction, also used by signals.
EXIT is a signal-only value meaning "go flat"; orders and fills are
always BUY or SELL.
MarketDataEvent
dataclass
¶
SignalEvent
dataclass
¶
SignalEvent(
*,
timestamp: datetime,
symbol: str,
direction: Direction,
strength: float,
)
OrderEvent
dataclass
¶
OrderEvent(
*,
timestamp: datetime,
symbol: str,
order_id: str,
order_type: OrderType,
direction: Direction,
quantity: int,
price: float,
limit_price: float | None = None,
stop_price: float | None = None,
time_in_force: TimeInForce = GTC,
reduce_only: bool = False,
tag: str = "signal",
)
Bases: Event
An order request, before risk checks.
Attributes:
| Name | Type | Description |
|---|---|---|
price |
float
|
Reference price (the last close) used for sizing and risk. |
limit_price |
float | None
|
Required for |
stop_price |
float | None
|
Required for |
reduce_only |
bool
|
The order may only shrink an existing position; any part that would open or increase exposure is cancelled. |
tag |
str
|
Free-form origin label ( |
ApprovedOrderEvent
dataclass
¶
ApprovedOrderEvent(
*,
timestamp: datetime,
symbol: str,
order_id: str,
order_type: OrderType,
direction: Direction,
quantity: int,
price: float,
limit_price: float | None = None,
stop_price: float | None = None,
time_in_force: TimeInForce = GTC,
reduce_only: bool = False,
tag: str = "signal",
)
Bases: OrderEvent
An order that passed every risk check and may be sent to execution.
It carries exactly the fields of the OrderEvent it approves. The
bus dispatches on exact type, so subscribers of OrderEvent never see it.
RiskVetoEvent
dataclass
¶
CancelOrderEvent
dataclass
¶
OrderCancelledEvent
dataclass
¶
OrderCancelledEvent(
*,
timestamp: datetime,
symbol: str,
order_id: str,
unfilled_quantity: int,
reason: str,
)
Bases: Event
An order left the book without filling completely.
Published by execution when an order is cancelled on request, expires
(DAY orders), loses its reduce-only basis, or is rejected by a broker.
FillEvent
dataclass
¶
FillEvent(
*,
timestamp: datetime,
symbol: str,
fill_id: str,
order_id: str,
direction: Direction,
quantity: int,
fill_price: float,
commission: float,
)
Bases: Event
A (possibly partial) execution. timestamp is the bar the fill happened on.
A resumed paper session opens with one fill per position it carries over,
with order_id CARRIED and the position's average cost as the
price. It sets up every component as if the position had just been
bought, but nothing traded: metrics leave it out of fills and turnover.
CashFlowEvent
dataclass
¶
Bases: Event
Interest or a borrow fee, paid into or out of the account's cash.
The portfolio publishes them when a bar closes, for the time since the
previous bar: interest on the cash balance (earned on cash, charged
on a negative balance) and a borrow_fee for each short position.
TargetEvent
dataclass
¶
Bases: Event
The order manager's target position for symbol was set or ended.
target is the signed position the last actionable signal asked for,
or None once something else (a protective exit) moved the position
and the symbol waits for its next signal. Stored, so a resumed paper
session can finish what the previous one was doing.
PositionSnapshot
dataclass
¶
PositionSnapshot(
*,
symbol: str,
quantity: int,
avg_cost: float,
mark: float,
realized_pnl: float,
unrealized_pnl: float,
)
One symbol's position inside a PortfolioUpdateEvent.
PortfolioUpdateEvent
dataclass
¶
PortfolioUpdateEvent(
*,
timestamp: datetime,
cash: float,
equity: float,
realized_pnl: float,
unrealized_pnl: float,
positions: tuple[PositionSnapshot, ...] = (),
)
Bases: Event
Mark-to-market portfolio snapshot, published once per bar (time slice).
EndOfBarEvent
dataclass
¶
Bases: Event
Clock event published by the engine once a time slice's events have settled.
Every bar sharing timestamp has been dispatched (one per symbol that
traded), and so has everything those bars triggered. Components that need
a consistent cross-symbol view act on this: the portfolio's mark-to-market
snapshot and cross-sectional strategies.
Market data¶
Feed
¶
Bases: Protocol
A source of bars for one symbol, iterated in chronological order.
Feeds do not touch the bus: the backtest engine pulls one bar at a time and lets the full event cascade settle before requesting the next. That is what keeps the simulation causal.
SyntheticFeed
¶
SyntheticFeed(
symbol: str,
n_bars: int = TRADING_DAYS_PER_YEAR,
seed: int | None = None,
start_price: float = 150.0,
annual_drift: float = 0.08,
annual_volatility: float = 0.25,
start: datetime = datetime(2024, 1, 2),
correlation: float = 0.0,
market_seed: int | None = None,
calendar: str = "nyse",
)
Daily OHLCV bars from a geometric Brownian motion.
Prices follow dS/S = mu dt + sigma dW sampled once per trading day,
with a small overnight gap between the previous close and the next open.
By default the trading days are the New York Stock Exchange's: no bars
on its holidays, and on its early-close days a session of 3.5 hours
instead of 6.5, with drift, variance and volume to match.
Fully deterministic for a given seed, which makes it ideal for tests and
reproducible demos. It is not a model of any real instrument.
Several feeds built with the same market_seed and a positive
correlation share a common market factor: each day's shock is
sqrt(rho) * market + sqrt(1 - rho) * idiosyncratic, so any two such
feeds have return correlation rho.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Ticker to tag bars with. |
required |
n_bars
|
int
|
Number of bars to generate. |
TRADING_DAYS_PER_YEAR
|
seed
|
int | None
|
RNG seed ( |
None
|
start_price
|
float
|
Price before the first bar. |
150.0
|
annual_drift
|
float
|
Expected annual log-return |
0.08
|
annual_volatility
|
float
|
Annualised volatility |
0.25
|
start
|
datetime
|
Date of the first bar (rolled forward to a trading day). |
datetime(2024, 1, 2)
|
correlation
|
float
|
Weight of the shared market factor, in |
0.0
|
market_seed
|
int | None
|
Seed of the shared market factor. |
None
|
calendar
|
str
|
|
'nyse'
|
MemoryFeed
¶
MemoryFeed(symbol: str, bars: Sequence[MarketDataEvent])
A feed over bars already in memory.
Research tools load data once (possibly from the network) and replay it
many times; window cuts a time range without copying the source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Ticker the bars belong to. |
required |
bars
|
Sequence[MarketDataEvent]
|
Bars in ascending time order. |
required |
window
¶
window(
start: datetime | None = None,
end: datetime | None = None,
) -> MemoryFeed
Bars with start <= timestamp < end (either bound may be open).
CSVFeed
¶
Yields one MarketDataEvent per row of a CSV file.
The file needs a header row with (case-insensitive) columns
date, open, high, low, close, volume; extra columns are ignored. Rows
must be in strictly ascending date order. A feed that silently reorders or
deduplicates data hides problems, so out-of-order rows raise instead.
Date formats accepted: YYYY-MM-DD, YYYY-MM-DD HH:MM:SS,
YYYY-MM-DDTHH:MM:SS and MM/DD/YYYY.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the CSV file. |
required |
symbol
|
str
|
Ticker symbol to tag events with. |
required |
Raises:
| Type | Description |
|---|---|
DataError
|
on a missing file, missing columns, unparseable values or out-of-order rows (raised during iteration). |
YFinanceFeed
¶
YFinanceFeed(
symbol: str,
start: str,
end: str,
interval: str = "1d",
*,
cache: BarCache | None = None,
)
Downloads split/dividend-adjusted bars from Yahoo Finance via yfinance.
Data is fetched lazily on first iteration. Rows with missing values are dropped.
With a cache, bars already downloaded for the same symbol, interval and dates are read from it instead, checked against their checksum, and a download is stored in it once its date range is over (its end, which is exclusive, is no later than today in New York), so that no bar in it can still change.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Ticker symbol (e.g. |
required |
start
|
str
|
First date, |
required |
end
|
str
|
Last date, |
required |
interval
|
str
|
Bar interval accepted by |
'1d'
|
cache
|
BarCache | None
|
Where downloads are kept, or |
None
|
Raises:
| Type | Description |
|---|---|
MissingDependencyError
|
if |
DataError
|
if the download returns no data. |
BarCache
¶
Downloaded bars kept as CSV files, each checked against a SHA-256 checksum.
Each download is stored as one CSV named after the request,
{symbol}_{interval}_{start}_{end}.csv, in the format CSVFeed
reads, with floats written exactly. Beside it, {name}.csv.sha256 holds its
checksum as sha256sum writes it, so shasum -a 256 -c *.sha256 in
the directory checks the whole cache.
A cached file is used only if it still matches its checksum. One that
does not, or has no checksum, raises DataError rather than
being downloaded again, since data that changes under a study should be
noticed, not replaced. Delete the file to download it again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Where the files go; created when the first is stored. |
required |
path
¶
The file the bars for this request are, or would be, cached in.
load
¶
load(
symbol: str, interval: str, start: str, end: str
) -> list[MarketDataEvent] | None
The cached bars for this request, or None if there are none.
Raises:
| Type | Description |
|---|---|
DataError
|
if the cached file has no checksum or does not match it. |
store
¶
store(
symbol: str,
interval: str,
start: str,
end: str,
bars: Sequence[MarketDataEvent],
) -> Path
Cache bars for this request; the file they are in.
The CSV is written under a temporary name and renamed into place after its checksum, so an interrupted write never leaves a cached file without one.
Research¶
ParamGrid
¶
The Cartesian product of named value lists.
Iterates as dicts of dotted config keys, ready for
BacktestConfig.with_overrides:
grid = ParamGrid({"strategy.fast_period": [5, 10], "strategy.slow_period": [20, 50]})
len(grid) # 4
list(grid) # [{"strategy.fast_period": 5, "strategy.slow_period": 20}, ...]
run_sweep
¶
run_sweep(
config: BacktestConfig,
grid: ParamGrid,
*,
metric: str = "sharpe_ratio",
jobs: int = 1,
feeds: Sequence[MemoryFeed] | None = None,
progress: Progress | None = None,
) -> SweepResult
Backtest every point of grid on the same data and rank the results.
Combinations the config rejects (e.g. fast_period >= slow_period)
are recorded as skipped rather than aborting the sweep.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
BacktestConfig
|
Base configuration; grid values override it. |
required |
grid
|
ParamGrid
|
Parameters to vary. |
required |
metric
|
str
|
|
'sharpe_ratio'
|
jobs
|
int
|
Worker processes (1 = run in this process). |
1
|
feeds
|
Sequence[MemoryFeed] | None
|
Preloaded data (defaults to loading |
None
|
progress
|
Progress | None
|
Called with |
None
|
SweepResult
dataclass
¶
SweepResult(
metric: str,
grid: dict[str, list[Any]],
runs: tuple[SweepRun, ...],
periods_per_year: float = 252.0,
)
Every run of a sweep, ranked by metric.
deflated_sharpe
property
¶
deflated_sharpe: DeflatedSharpe | None
How likely the best run's true Sharpe ratio is above zero, given how many were tried.
Every completed run counts as a trial. Similar parameter values make correlated trials, fewer in effect than counted, so the correction errs on the strict side.
SweepRun
dataclass
¶
SweepRun(
params: dict[str, Scalar],
report: PerformanceReport | None,
error: str | None = None,
)
One grid point: its parameters and either a report or why it did not run.
DeflatedSharpe
dataclass
¶
The deflated Sharpe ratio of a sweep's best run (Bailey and López de Prado, 2014).
run_walk_forward
¶
run_walk_forward(
config: BacktestConfig,
grid: ParamGrid,
*,
train_bars: int,
test_bars: int,
anchored: bool = False,
metric: str = "sharpe_ratio",
jobs: int = 1,
feeds: Sequence[MemoryFeed] | None = None,
progress: Progress | None = None,
) -> WalkForwardResult
Walk-forward optimisation.
For each fold, every grid point is backtested on the training window and the best by metric is run once on the following test window. Test runs replay the training window first as warm-up, so indicators start warm but no trade happens before the test window. The test windows are then chained into one out-of-sample equity curve.
Raises:
| Type | Description |
|---|---|
ConfigError
|
if the data is too short for a single fold. |
WalkForwardResult
dataclass
¶
WalkForwardResult(
metric: str,
grid: dict[str, list[Any]],
train_bars: int,
test_bars: int,
anchored: bool,
folds: tuple[Fold, ...],
oos_equity: tuple[tuple[datetime, float], ...],
oos_report: PerformanceReport,
efficiency: float,
oos_confidence: ConfidenceIntervals | None = None,
)
Every fold plus the stitched out-of-sample performance.
Fold
dataclass
¶
Fold(
index: int,
train_start: datetime,
train_end: datetime,
test_start: datetime,
test_end: datetime,
best_params: dict[str, Scalar] | None,
train_report: PerformanceReport | None,
test_report: PerformanceReport | None,
candidates: int,
)
One train/test split and what happened in it.
StudySpec
dataclass
¶
StudySpec(
title: str,
arms: tuple[Arm, ...],
train_bars: int,
test_bars: int,
metric: str = "sharpe_ratio",
anchored: bool = False,
source: str | None = None,
)
run_study
¶
run_study(
spec: StudySpec,
*,
jobs: int = 1,
progress: Progress | None = None,
) -> Study
Walk every strategy of spec forward, and sweep it over the whole period.
write_report
¶
Write README.md (and equity.png with matplotlib) to out_dir; the README.
Metrics¶
PerformanceReport
dataclass
¶
PerformanceReport(
starting_equity: float,
final_equity: float,
n_bars: int,
total_return_pct: float,
cagr_pct: float,
annual_volatility_pct: float,
sharpe_ratio: float,
sortino_ratio: float,
max_drawdown_pct: float,
max_drawdown_bars: int,
calmar_ratio: float,
benchmark_return_pct: float,
total_trades: int,
win_rate_pct: float,
profit_factor: float,
avg_trade_pnl: float,
total_fills: int,
total_commission: float,
exposure_pct: float,
turnover: float,
risk_vetoes: int,
cancelled_orders: int,
interest: float = 0.0,
borrow_fees: float = 0.0,
alpha_pct: float = 0.0,
beta: float = 0.0,
information_ratio: float = 0.0,
tracking_error_pct: float = 0.0,
skewness: float = 0.0,
kurtosis: float = 3.0,
)
Summary statistics for one backtest. *_pct fields are percentages.
to_dict
¶
JSON-safe dict (non-finite values become None).
from_dict
classmethod
¶
from_dict(
data: dict[str, float | int | None],
) -> PerformanceReport
Inverse of to_dict (None ratios become inf).
bootstrap
¶
Bootstrap confidence intervals for the Sharpe ratio and the total return.
A backtest's Sharpe ratio is one draw from a noisy process: the same strategy on another stretch of similar data would score differently. Resampling the per-bar returns shows how differently. Returns are resampled in blocks (the stationary bootstrap of Politis and Romano, 1994) so that volatility clustering and other short-range dependence survive the resampling, which plain resampling of single bars would destroy, understating the uncertainty.
ConfidenceIntervals
dataclass
¶
ConfidenceIntervals(
confidence: float,
resamples: int,
block: int,
sharpe_ratio: Interval,
total_return_pct: Interval,
)
Percentile intervals from a stationary bootstrap of per-bar returns.
bootstrap
¶
bootstrap(
equity: Sequence[float],
periods_per_year: float,
risk_free_rate: float = 0.0,
*,
resamples: int = DEFAULT_RESAMPLES,
confidence: float = 0.95,
block: int | None = None,
seed: int = 0,
) -> ConfidenceIntervals
Confidence intervals for the Sharpe ratio and total return of equity.
Each resample draws as many per-bar returns as the curve has, in blocks
of random length averaging block bars (n ** (1/3) by default, the
usual rate for block bootstraps), and the interval is the central
confidence share of the resampled statistics. The same curve and seed
always give the same intervals.
Raises:
| Type | Description |
|---|---|
ValueError
|
on fewer than 1 resample, a confidence outside (0, 1) or a block shorter than 1 bar. |
default_block
¶
Mean block length for n returns: n ** (1/3), at least 1.
resample
¶
A stationary-bootstrap resample of returns, of the same length.
Blocks start at random bars and run for a geometric number of bars with mean block, wrapping from the last bar to the first.
quantile
¶
The q quantile of values, interpolating linearly between order statistics.
stats
¶
Pure performance statistics over equity curves and return series.
All functions take plain sequences, have no side effects, and return
fractions (0.05 == 5 %) unless the name says otherwise. Undefined ratios
(e.g. Sharpe of a flat curve) return 0.0; unbounded ones (e.g. Calmar
with zero drawdown) return math.inf.
simple_returns
¶
Period-over-period simple returns: e[i] / e[i-1] - 1.
cagr
¶
Compound annual growth rate, treating each step of equity as one period.
sharpe_ratio
¶
sharpe_ratio(
returns: Sequence[float],
periods_per_year: float,
risk_free_rate: float = 0.0,
) -> float
Annualised Sharpe ratio (sample standard deviation).
risk_free_rate is an annual rate, de-annualised per period.
sortino_ratio
¶
sortino_ratio(
returns: Sequence[float],
periods_per_year: float,
risk_free_rate: float = 0.0,
) -> float
Annualised Sortino ratio: like Sharpe, but penalising only downside deviation.
drawdown_series
¶
Drawdown from the running peak at each point, as a non-negative fraction.
max_drawdown
¶
Deepest peak-to-trough decline and the longest time spent below a peak.
Returns:
| Type | Description |
|---|---|
float
|
|
int
|
longest run of consecutive periods with equity below its prior peak. |
beta
¶
How much returns move with benchmark: cov / var (0 for a flat benchmark).
alpha
¶
alpha(
returns: Sequence[float],
benchmark: Sequence[float],
periods_per_year: float,
risk_free_rate: float = 0.0,
) -> float
Jensen's alpha, annualised: the mean excess return that beta does not explain.
mean(r - rf) - beta × mean(b - rf) per period, times periods_per_year.
tracking_error
¶
tracking_error(
returns: Sequence[float],
benchmark: Sequence[float],
periods_per_year: float,
) -> float
Annualised standard deviation of the returns in excess of the benchmark's.
information_ratio
¶
information_ratio(
returns: Sequence[float],
benchmark: Sequence[float],
periods_per_year: float,
) -> float
Annualised mean return in excess of the benchmark's, per unit of tracking error.
skewness
¶
Skewness of returns (third standardised moment; 0 when undefined).
kurtosis
¶
Kurtosis of returns, not excess: 3 for a normal distribution, and when undefined.
probabilistic_sharpe_ratio
¶
probabilistic_sharpe_ratio(
sharpe: float,
n_returns: int,
skew: float,
kurt: float,
benchmark: float = 0.0,
) -> float
Probability that the true Sharpe ratio exceeds benchmark (Bailey and López de Prado).
Sharpe ratios here are per period, not annualised. The estimate's standard
error grows with negative skew and fat tails, so the same Sharpe ratio is
less convincing from returns that have them. nan when undefined.
expected_max_sharpe
¶
The best Sharpe ratio that many trials of zero true skill would be expected to reach.
From the spread of the trials' Sharpe ratios (per period) and their
number: sd × ((1 − γ) Φ⁻¹(1 − 1/N) + γ Φ⁻¹(1 − 1/(N e))), with γ the
Euler-Mascheroni constant. 0 for fewer than two trials.
deflated_sharpe_ratio
¶
deflated_sharpe_ratio(
sharpe: float,
n_returns: int,
skew: float,
kurt: float,
trial_sharpes: Sequence[float],
) -> float
Probability that the best of trial_sharpes has a true Sharpe ratio above zero.
The probabilistic Sharpe ratio of the selected trial, measured against
expected_max_sharpe rather than zero, which corrects for picking
the best of many (Bailey and López de Prado, 2014). Per-period ratios.
Paper trading¶
PaperTrader
¶
PaperTrader(
config: BacktestConfig,
broker: PaperBroker,
*,
timeframe: str | None = None,
warmup_bars: int | None = None,
poll_seconds: float | None = None,
settle_seconds: float | None = None,
dry_run: bool = False,
resume: bool | None = None,
max_iterations: int | None = None,
clock: Callable[[], datetime] | None = None,
sleep: Callable[[float], None] = sleep,
strategy: AnyStrategy | None = None,
run_id: str | None = None,
alerts: Alerter | None = None,
)
Run the backtest pipeline on live bars, sending orders to an Alpaca paper account.
The pipeline is the one the backtester uses (strategy, order manager,
exits, risk, portfolio, metrics, persistence) with
BrokerExecution in place of the simulator. Each loop it:
- polls the broker for fills and cancellations of working orders;
- fetches bars that have completed since the last loop and feeds them through the pipeline slice by slice, exactly like a backtest;
- sleeps
poll_seconds, or until just before the next open once the market has closed (seetrading.market_data.calendar).
Stopping. SIGTERM or SIGINT (Ctrl-C) lets the current step finish,
or cuts a sleep short, then winds the session down as below. A second
signal stops at once, as an unhandled Ctrl-C would. Signals are only
handled when run is called from the main thread.
Safety limits halt the trader: it winds down as on a stop signal and
reports halted. While the paper.kill_switch file exists it
refuses to start, and it halts before the next step once the file
appears. paper.max_orders_per_day caps the orders sent to the
broker in the traded symbols per trading day, counting those sent
earlier that day, so a restart does not reset it; the trader refuses to
start once the cap is reached and halts when it is reached (see
BrokerExecution). Refusing to start raises
SafetyLimitError, logged as a warning rather than an error, so a
supervisor that keeps restarting a halted trader does not repeat the
halt's alert. A dry run sends nothing and ignores both limits.
risk.max_daily_loss_pct only refuses new exposure for the day (see
RiskManager).
Before trading it replays the most recent warmup_bars completed bars
through the strategy only, so indicators start warm. Each symbol's last
warm-up signal is then carried into trading (see WarmupSignals),
so the strategy takes its current position straight away instead of
waiting for its next signal.
The strategy trades a virtual account of portfolio.starting_cash
inside the paper account. To keep the two in step, a new session refuses
to start while the paper account holds positions or open orders in the
traded symbols. On exit (max_iterations reached, a stop signal or an
error) it cancels its open orders but leaves protective exits resting at
the broker, because positions are left as they are.
Resuming (resume, paper.resume) continues the latest session
stored for the same symbols instead (see trading.live.resume):
its virtual cash and positions are rebuilt from the broker's fills and
must match the paper account, its open orders are cancelled, and the
new session starts holding its positions. Their protective exits are
placed again (ATR stops keep their level), and the order manager takes
up the targets the previous session was still working towards, ordering
any shortfall an interrupted order left. Only warm-up signals from bars
the previous session never saw are carried into trading. With no
earlier session, it starts a new one.
Heartbeat. Every paper.heartbeat_seconds, while it trades and
while it sleeps, the trader logs its status (see TraderStatus)
and rewrites paper.heartbeat_file with it, if set. A last beat
reports how the session ended. See Heartbeat.
Alerts. Given an Alerter, the trader sends the kinds it
was built for: fill for every fill, error for every ERROR it
logs (a halt, or the error that ended the session), and session
when the session starts trading and when it ends.
With dry_run the bars are live but fills come from the execution
simulator, and nothing is sent to the broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
BacktestConfig
|
Strategy, sizing, exits, risk, persistence and |
required |
broker
|
PaperBroker
|
Alpaca client (or a compatible fake). |
required |
timeframe
|
str | None
|
Overrides |
None
|
warmup_bars
|
int | None
|
Overrides |
None
|
poll_seconds
|
float | None
|
Overrides |
None
|
settle_seconds
|
float | None
|
Overrides |
None
|
dry_run
|
bool
|
Simulate fills instead of sending orders. |
False
|
resume
|
bool | None
|
Overrides |
None
|
max_iterations
|
int | None
|
Stop after this many loops (default: run until interrupted). |
None
|
clock
|
Callable[[], datetime] | None
|
Current time, timezone-aware (injectable for tests). |
None
|
sleep
|
Callable[[float], None]
|
Sleep function (injectable for tests). |
sleep
|
strategy
|
AnyStrategy | None
|
Optional strategy instance instead of |
None
|
run_id
|
str | None
|
Session identifier (random by default). |
None
|
alerts
|
Alerter | None
|
Where to send alerts (see |
None
|
PaperResult
dataclass
¶
PaperResult(
run_id: str,
strategy: str,
symbols: tuple[str, ...],
timeframe: str,
dry_run: bool,
warmup_bars: int,
bars: int,
report: PerformanceReport | None,
positions: Mapping[str, int],
resumed_from: str | None = None,
stopped_by: str | None = None,
halted: bool = False,
)
Summary of a paper-trading session.
AlpacaClient
¶
AlpacaClient(
credentials: Credentials,
*,
transport: Transport | None = None,
data_feed: str = "iex",
retries: int = 3,
backoff: float = 1.0,
sleep: Callable[[float], None] = sleep,
page_limit: int = 10000,
)
Alpaca paper-trading and market-data REST API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
Credentials
|
API key pair (see |
required |
transport
|
Transport | None
|
HTTP function, replaceable in tests (default: |
None
|
data_feed
|
str
|
|
'iex'
|
retries
|
int
|
Retries for network errors, rate limits and 5xx responses. |
3
|
backoff
|
float
|
First retry delay in seconds; doubles on each retry. |
1.0
|
sleep
|
Callable[[float], None]
|
Sleep function used between retries. |
sleep
|
page_limit
|
int
|
Bars requested per page of market data. |
10000
|
The event bus¶
EventBus
¶
FIFO publish/subscribe dispatcher.
publish enqueues an event; run drains the queue, including
any events that handlers publish while it runs.
Dispatch guarantees:
- Breadth-first. Every handler for an event runs before any event those handlers published is delivered.
- Deterministic. Handlers for one event type run in subscription order.
- Fail-fast. Handler exceptions propagate out of
run. A backtest that silently skips a broken component is worse than one that stops.
Usage:
bus = EventBus()
bus.subscribe(MarketDataEvent, strategy.on_bar)
bus.publish(bar)
bus.run()
subscribe
¶
Call handler for every published event whose type is exactly event_type.
run
¶
Dispatch queued events until the queue is empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_events
|
int | None
|
Stop after dispatching this many events. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The number of events dispatched. |
Errors¶
errors
¶
Exception hierarchy: everything the package raises on purpose is a TradingError.
TradingError
¶
Bases: Exception
Base class for all errors raised by this package.
ConfigError
¶
Bases: TradingError, ValueError
Invalid or inconsistent configuration.
DataError
¶
Bases: TradingError
Market data is missing, malformed, or could not be fetched.
MissingDependencyError
¶
Bases: TradingError, ImportError
An optional dependency needed for the requested feature is not installed.
SafetyLimitError
¶
Bases: TradingError
A safety limit, such as the kill switch, stops the paper trader from starting.
BrokerError
¶
Bases: TradingError
A broker API request failed or was rejected.
status is the HTTP status code, or None when no response arrived.