Skip to Content
While25SDK docs
ExamplesBacktests

Moving-average crossover on AAPL, with real costs and slippage

The simplest honest backtest: daily AAPL bars for a fixed window, a fast and a slow average, decided on each close and filled at the next bar's open, costed on the connected broker's real fee schedule with a few basis points of slippage against every fill. The platform re-derives every trade from the bars and seals the result, or refuses it naming the rule broken.

The simplest honest backtest: daily AAPL bars for a fixed window, a fast and a slow average, decided on each close and filled at the next bar's open, costed on the connected broker's real fee schedule with a few basis points of slippage against every fill. The platform re-derives every trade from the bars and seals the result, or refuses it naming the rule broken.

Shows: App with run(ctx), history_span(), data.instrument(), backtest.assume(costs="real", slippage=Slippage.bps()), backtest.fill(how="open"/"close"), backtest.trade(product=), ui.backtest_block(data=, capital=, assume=, logic=, notes=).

View on GitHub

backtests/sma_crossover_costs.py
"""Moving-average crossover on AAPL, with real costs and slippage

The simplest honest backtest: daily AAPL bars for a fixed window, a fast and
a slow average, decided on each close and filled at the next bar's open,
costed on the connected broker's real fee schedule with a few basis points of
slippage against every fill. The platform re-derives every trade from the
bars and seals the result, or refuses it naming the rule broken.

Shows: App with run(ctx), history_span(), data.instrument(), backtest.assume(costs="real", slippage=Slippage.bps()), backtest.fill(how="open"/"close"), backtest.trade(product=), ui.backtest_block(data=, capital=, assume=, logic=, notes=).
"""
import while25
from while25 import App, backtest, ui
from while25.backtest import Slippage

KEY = "EQ:US:AAPL"
START, END = "2019-01-02", "2025-12-31"

ui.panel("bt_sma_crossover", "AAPL SMA crossover backtest")
ui.layout(ui.view("main"))


def sma(values, n):
    return None if len(values) < n else sum(values[-n:]) / n


def crossover_trades(bars, inst, a, *, fast=20, slow=100, qty=100):
    """Every round trip of the rule on `bars` (a history_span's bars), as
    backtest.trade() dicts. The decision on bar i reads closes up to i only;
    the order fills at bar i+1's open. A position still open at the end is
    closed at the last bar's close, so the block has no open trade."""
    closes, trades, entry = [], [], None
    for i, bar in enumerate(bars[:-1]):
        closes.append(bar["close"])
        f, s = sma(closes, fast), sma(closes, slow)
        pf, ps = sma(closes[:-1], fast), sma(closes[:-1], slow)
        if None in (f, s, pf, ps):
            continue
        nxt = bars[i + 1]
        if entry is None and pf <= ps and f > s:
            entry = backtest.fill(nxt, "buy", "open", instrument=inst, assume=a)
        elif entry is not None and pf >= ps and f < s:
            out = backtest.fill(nxt, "sell", "open", instrument=inst, assume=a)
            trades.append(close_trade(inst, qty, entry, out, a))
            entry = None
    if entry is not None:
        out = backtest.fill(bars[-1], "sell", "close", instrument=inst, assume=a)
        trades.append(close_trade(inst, qty, entry, out, a))
    return trades


def close_trade(inst, qty, entry, out, a):
    product = "intraday" if entry.date == out.date else "delivery"
    return backtest.trade(inst, "buy", qty, entry, out, product=product, assume=a)


class SmaCrossoverBacktest(App):
    id = "bt_sma_crossover"
    label = "AAPL SMA crossover backtest"

    def run(self, ctx):
        span = while25.history_span(KEY, "1D", START, END)
        if span["missing_days"]:
            while25.log(f"{len(span['missing_days'])} trading days have no bar", "warn")
        inst = while25.data.instrument(KEY)
        a = backtest.assume(costs="real", slippage=Slippage.bps(2))
        trades = crossover_trades(span["bars"], inst, a)
        while25.ui.push("main", {"blocks": [ui.backtest_block(
            trades, data=[span["id"]], capital=100_000, assume=a,
            title="AAPL 20/100-day crossover", subtitle=f"{START} to {END}, 100 shares",
            logic={"Entry": "20-day average crosses above the 100-day, on the close",
                   "Exit": "20-day average crosses below the 100-day, on the close",
                   "Fills": "next bar's open; a position open at the end closes on the last close"},
            notes="Costs from the connected broker's schedule; 2 bps slippage on every fill.")]})