Skip to Content
While25SDK docs
ExamplesBacktests

SPY / QQQ pair: two instruments in one backtest

Trades the spread between SPY and QQQ: when the log price ratio is more than two standard deviations from its 60-day mean, sells the rich one and buys the cheap one in equal dollar amounts, and closes both when the ratio is back within half a deviation. Both legs fill at the next day's open. Costs are a flat custom figure per order, stated in the block.

Trades the spread between SPY and QQQ: when the log price ratio is more than two standard deviations from its 60-day mean, sells the rich one and buys the cheap one in equal dollar amounts, and closes both when the ratio is back within half a deviation. Both legs fill at the next day's open. Costs are a flat custom figure per order, stated in the block.

Shows: two history_span() answers in one backtest, aligning bars by trading date, short trades (side "sell"), backtest.assume(costs="custom", custom_flat=, custom_pct=), ui.backtest_block(data=[id1, id2]).

View on GitHub

backtests/pairs_spy_qqq.py
"""SPY / QQQ pair: two instruments in one backtest

Trades the spread between SPY and QQQ: when the log price ratio is more than
two standard deviations from its 60-day mean, sells the rich one and buys the
cheap one in equal dollar amounts, and closes both when the ratio is back
within half a deviation. Both legs fill at the next day's open. Costs are a
flat custom figure per order, stated in the block.

Shows: two history_span() answers in one backtest, aligning bars by trading date, short trades (side "sell"), backtest.assume(costs="custom", custom_flat=, custom_pct=), ui.backtest_block(data=[id1, id2]).
"""
import math
from decimal import ROUND_FLOOR, Decimal

import while25
from while25 import App, backtest, ui

A, B = "EQ:US:SPY", "EQ:US:QQQ"
START, END = "2018-01-02", "2025-12-31"

ui.panel("bt_pairs", "SPY / QQQ pair backtest")
ui.layout(ui.view("main"))


def align(bars_a, bars_b):
    """[(bar_a, bar_b)] for the trading dates both lines have, in order."""
    by_date = {b["date"]: b for b in bars_b}
    return [(a, by_date[a["date"]]) for a in bars_a if a["date"] in by_date]


def zscore(values, n):
    if len(values) < n:
        return None
    w = values[-n:]
    m = sum(w) / n
    sd = math.sqrt(sum((x - m) ** 2 for x in w) / n)
    return None if sd == 0 else (w[-1] - m) / sd


def shares(notional, price, step):
    step = step or Decimal(1)
    raw = Decimal(str(notional)) / Decimal(str(price))
    return (raw / step).to_integral_value(rounding=ROUND_FLOOR) * step


def pair_trades(pairs, inst_a, inst_b, a, *, window=60, entry_z=2.0, exit_z=0.5,
                notional=50_000):
    """Round trips of both legs. The decision on day i reads ratios up to i;
    both legs fill at day i+1's open."""
    ratios, trades, open_ = [], [], None
    for i, (ba, bb) in enumerate(pairs[:-1]):
        ratios.append(math.log(ba["close"] / bb["close"]))
        z = zscore(ratios, window)
        if z is None:
            continue
        na, nb = pairs[i + 1]
        if open_ is None and abs(z) >= entry_z:
            side_a = "sell" if z > 0 else "buy"          # A rich against B: sell A
            side_b = "buy" if side_a == "sell" else "sell"
            open_ = [(inst_a, side_a, shares(notional, na["open"], inst_a.step),
                      backtest.fill(na, side_a, "open", instrument=inst_a, assume=a)),
                     (inst_b, side_b, shares(notional, nb["open"], inst_b.step),
                      backtest.fill(nb, side_b, "open", instrument=inst_b, assume=a))]
        elif open_ is not None and abs(z) <= exit_z:
            trades += close_legs(open_, (na, nb), "open", a)
            open_ = None
    if open_ is not None:
        trades += close_legs(open_, pairs[-1], "close", a)
    return trades


def close_legs(legs, bars, how, a):
    out = []
    for (inst, side, qty, entry), bar in zip(legs, bars):
        exit_ = backtest.fill(bar, "sell" if side == "buy" else "buy", how, instrument=inst, assume=a)
        product = "intraday" if entry.date == exit_.date else "delivery"
        out.append(backtest.trade(inst, side, qty, entry, exit_, product=product, assume=a))
    return out


class PairsBacktest(App):
    id = "bt_pairs_spy_qqq"
    label = "SPY / QQQ pair backtest"

    def run(self, ctx):
        span_a = while25.history_span(A, "1D", START, END)
        span_b = while25.history_span(B, "1D", START, END)
        inst_a, inst_b = while25.data.instrument(A), while25.data.instrument(B)
        a = backtest.assume(costs="custom", custom_flat=1.0, custom_pct=0)
        trades = pair_trades(align(span_a["bars"], span_b["bars"]), inst_a, inst_b, a)
        while25.ui.push("main", {"blocks": [ui.backtest_block(
            trades, data=[span_a["id"], span_b["id"]], capital=100_000, assume=a,
            title="SPY / QQQ ratio reversion", subtitle=f"{START} to {END}, $50,000 a leg",
            logic={"Signal": "log(SPY / QQQ) z-score over 60 days",
                   "Entry": "|z| >= 2: sell the rich leg, buy the cheap one, equal dollars",
                   "Exit": "|z| <= 0.5, both legs; fills at the next open"},
            notes="Costs: $1 per order, stated. Short sales assume shares were available to borrow.")]})