A strategy is any object with on_bar(ctx, bar) (one bar at a time) or on_bars(ctx, bars) (every symbol’s bar for a period at once), and optionally on_stop(ctx). ctx.target(symbol, quantity) states how many shares to hold; the order fills at the next bar’s open. With fill="decision-close" it fills at the symbol’s last close when the target was set instead, the convention of backtests that trade on the close; that is optimistic, since a real order cannot trade at a close already seen. With fill="next-close" it fills at the next bar’s close instead; that prices daily or shorter bars, and an order that would fill on a weekly or longer bar halts the replay.
import numpy as npimport pandas as pdimport pyatlrng = np.random.default_rng(7)days = pd.bdate_range("2024-01-02", periods=250)close = np.round(50_000* np.exp(np.cumsum(rng.normal(0, 0.01, len(days)))), -2)frame = pd.DataFrame( {"open": close, "high": close, "low": close, "close": close, "volume": 1_000_000.0}, index=days,)class Crossover:"""Holds 100 shares while the 5-day mean is above the 20-day mean."""def__init__(self, fast=5, slow=20):self.fast, self.slow, self.closes = fast, slow, []def on_bar(self, ctx, bar):self.closes.append(bar.close)iflen(self.closes) <self.slow:return fast =sum(self.closes[-self.fast:]) /self.fast slow =sum(self.closes[-self.slow:]) /self.slow ctx.target(bar.symbol, 100if fast > slow else0)result = pyatl.backtest( Crossover(), {"005930": frame}, commission=0.00015, sell_tax=0.002)print(f"{result.bars} bars, {len(result.fills['time'])} fills")print(f"equity {result.opening_equity} -> {result.closing_equity}")print(f"total return {result.total_return:.2%}")
backtest() replays the bars you give it in time order. A Replay takes them in as many calls as you like, in the order you define, and is finished once.
feed_bars takes one long block (a symbol, a time and the prices per row), which is the fastest way to feed a sequence you generate. Each feed is checked before any of it runs: a symbol’s bars must move forward in time, and no bar may end before the bar fed before it.