Examples¶
Runnable scripts in examples/.
Each runs on synthetic data in about a second, except the paper trader, which needs Alpaca
paper keys. The tests run all four, so they stay in step with the code.
A strategy of your own¶
A Donchian breakout, backtested on three correlated symbols against buy and hold.
"""Write your own strategy and backtest it against buy and hold.
A Donchian breakout: buy when the close makes a new N-bar high, exit when it
makes a new M-bar low. Run it with::
python examples/custom_strategy.py
"""
from __future__ import annotations
from collections import defaultdict, deque
from trading import (
HOLD,
BacktestConfig,
BacktestEngine,
Direction,
MarketDataEvent,
Signal,
Strategy,
)
class Breakout(Strategy):
"""Long on a close above the highest high of the last *entry* bars; flat below the
lowest low of the last *exit* bars."""
name = "breakout"
def __init__(self, entry: int = 55, exit: int = 20) -> None:
super().__init__()
self.entry, self.exit = entry, exit
# One history per symbol, so a single instance can trade several symbols.
self._bars: defaultdict[str, deque[MarketDataEvent]] = defaultdict(
lambda: deque(maxlen=max(entry, exit))
)
def on_bar(self, bar: MarketDataEvent) -> Signal:
history = self._bars[bar.symbol] # earlier bars only: this one is added at the end
try:
if len(history) < (history.maxlen or 0):
return HOLD # warming up
if bar.close > max(b.high for b in list(history)[-self.entry :]):
return Direction.BUY, 1.0
if bar.close < min(b.low for b in list(history)[-self.exit :]):
return Direction.EXIT, 1.0
return HOLD
finally:
history.append(bar)
def main() -> None:
config = BacktestConfig().with_overrides(
{
"simulation.symbols": ["AAA", "BBB", "CCC"],
"simulation.n_bars": 756, # three years of synthetic daily bars
"simulation.correlation": 0.4,
"order_manager.sizing": "percent",
"order_manager.percent_equity": 30.0,
"risk.max_position": None,
"persistence.enabled": False, # keep the example out of trading.db
}
)
breakout = BacktestEngine(config, strategy=Breakout(entry=55, exit=20)).run()
held = BacktestEngine(config.with_overrides({"strategy.type": "buy_and_hold"})).run()
print(breakout.report)
print(f"{'':<14}{'return %':>10}{'Sharpe':>9}{'max dd %':>10}")
for name, result in (("breakout", breakout), ("buy and hold", held)):
r = result.report
print(f"{name:<14}{r.total_return_pct:>+10.2f}{r.sharpe_ratio:>9.2f}"
f"{r.max_drawdown_pct:>10.2f}") # fmt: skip
if __name__ == "__main__":
main()
A parameter sweep¶
Every combination on the same bars, in parallel, and the deflated Sharpe ratio of the winner: the chance that its true Sharpe ratio is above zero, given how many combinations were tried.
"""Sweep a strategy's parameters, then ask how much the winner can be trusted.
Every combination is backtested on the same bars, in parallel. The deflated
Sharpe ratio corrects the best Sharpe ratio for the number of combinations
tried: with enough tries, one looks good by chance. Run it with::
python examples/sweep.py
The same sweep from the command line::
trading sweep --symbols AAA --bars 1000 \\
--param strategy.fast_period=5:30:5 --param strategy.slow_period=40,60,100
"""
from __future__ import annotations
from trading import BacktestConfig
from trading.research import ParamGrid, run_sweep
def main() -> None:
config = BacktestConfig().with_overrides(
{"simulation.n_bars": 1000, "persistence.enabled": False}
)
grid = ParamGrid(
{
"strategy.fast_period": [5, 10, 15, 20, 25, 30],
"strategy.slow_period": [40, 60, 100],
}
)
result = run_sweep(config, grid, metric="sharpe_ratio", jobs=2)
print(result.table(top=5))
best, deflated = result.best, result.deflated_sharpe
if best is None or deflated is None:
print("no combination completed")
return
print(f"\nbest of {deflated.trials}: {best.params}")
print(
f"in-sample Sharpe ratio {deflated.sharpe_ratio:.2f}; "
f"the best of {deflated.trials} random tries would average {deflated.expected_max:.2f}"
)
print(f"probability the true Sharpe ratio is above zero: {deflated.probability:.2f}")
if __name__ == "__main__":
main() # the guard matters: worker processes import this module
Walk-forward validation¶
Tune on one window, trade the next with the chosen parameters, repeat. The chained test windows are the honest estimate, with a bootstrap interval for their Sharpe ratio.
"""Walk-forward validation: tune on one window, score on the next, repeat.
The out-of-sample result chains only the test windows, each traded with
parameters chosen before it began, so it is the honest estimate of what the
tuning process would have delivered. Run it with::
python examples/walk_forward.py
"""
from __future__ import annotations
from trading import BacktestConfig
from trading.research import ParamGrid, run_walk_forward
def main() -> None:
config = BacktestConfig().with_overrides(
{
"strategy.type": "rsi",
"simulation.n_bars": 1260, # five years of synthetic daily bars
"metrics.bootstrap": 1000, # a confidence interval for the out-of-sample Sharpe
"persistence.enabled": False,
}
)
grid = ParamGrid({"strategy.period": [7, 14], "strategy.oversold": [20, 30]})
result = run_walk_forward(config, grid, train_bars=504, test_bars=126, jobs=2)
print(result.table())
print(result.oos_report)
if result.oos_confidence is not None:
print(result.oos_confidence)
print(f"walk-forward efficiency (OOS CAGR / mean IS CAGR): {result.efficiency:.2f}")
if __name__ == "__main__":
main()
Paper trading¶
A custom strategy on live bars against an Alpaca paper account: a dry run that logs the
orders it would send, unless given --send.
"""Run a strategy on live bars against an Alpaca paper account.
The pipeline is the backtest's, with the broker in place of the simulator.
You need free paper-trading keys from https://alpaca.markets::
export APCA_API_KEY_ID=... APCA_API_SECRET_KEY=...
python examples/paper_trading.py # dry run: logs orders, sends none
python examples/paper_trading.py --send # places orders in the paper account
It runs until Ctrl-C (or a few loops with --iterations N), then prints the
session's report. ``PaperTrader`` takes any strategy instance, such as the
breakout in ``custom_strategy.py``; this one fades three-bar losing streaks.
The same with a built-in strategy, from the command line::
trading paper --config config/paper.yaml --dry-run
"""
from __future__ import annotations
import argparse
import sys
from collections import defaultdict, deque
from trading import HOLD, BacktestConfig, Direction, MarketDataEvent, Signal, Strategy
from trading.errors import ConfigError
from trading.live import AlpacaClient, PaperTrader
class FadeLosingStreaks(Strategy):
"""Buy after *streak* lower closes in a row; exit on the first higher close."""
name = "fade_streaks"
def __init__(self, streak: int = 3) -> None:
super().__init__()
self._closes: defaultdict[str, deque[float]] = defaultdict(lambda: deque(maxlen=streak + 1))
def on_bar(self, bar: MarketDataEvent) -> Signal:
closes = self._closes[bar.symbol]
closes.append(bar.close)
if len(closes) < (closes.maxlen or 0):
return HOLD
steps = [b - a for a, b in zip(list(closes), list(closes)[1:], strict=False)]
if all(step < 0 for step in steps):
return Direction.BUY, 1.0
if steps[-1] > 0:
return Direction.EXIT, 1.0
return HOLD
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--send", action="store_true", help="send orders (default: dry run)")
parser.add_argument("--iterations", type=int, help="stop after this many loops")
args = parser.parse_args(argv)
config = BacktestConfig().with_overrides(
{
"simulation.symbols": ["SPY", "QQQ"],
"paper.timeframe": "1Day",
"paper.warmup_bars": 20, # replayed through the strategy before trading
"order_manager.sizing": "percent",
"order_manager.percent_equity": 20.0,
"risk.max_position": None,
"paper.max_orders_per_day": 20,
"persistence.db_path": "paper.db",
}
)
try:
broker = AlpacaClient.from_env(data_feed=config.paper.feed)
except ConfigError as exc:
print(exc, file=sys.stderr)
return 2
trader = PaperTrader(
config,
broker,
strategy=FadeLosingStreaks(streak=3),
dry_run=not args.send,
max_iterations=args.iterations,
)
print(trader.run())
return 0
if __name__ == "__main__":
sys.exit(main())