Skip to Content
While25SDK docs
ExamplesBacktests

Walk-forward logistic regression on SPY, numpy only

Fits a small logistic regression (five price features, L2 penalty, plain gradient descent) to say whether SPY's next session closes above its open, and trades that session open-to-close when the model is confident. It walks forward: fit on a training window, trade the next window, move both along. Every scaling figure and weight comes from bars before the test window, and no training label reaches into it; only test-window trades are sealed.

Fits a small logistic regression (five price features, L2 penalty, plain gradient descent) to say whether SPY's next session closes above its open, and trades that session open-to-close when the model is confident. It walks forward: fit on a training window, trade the next window, move both along. Every scaling figure and weight comes from bars before the test window, and no training label reaches into it; only test-window trades are sealed.

Shows: a model in a backtest with numpy only, walk-forward windows, features scaled on the training window alone, labels that end before the test window, open-to-close intraday fills on one bar, backtest.assume(costs="zero") stated in the block.

View on GitHub

backtests/walk_forward_logistic.py
"""Walk-forward logistic regression on SPY, numpy only

Fits a small logistic regression (five price features, L2 penalty, plain
gradient descent) to say whether SPY's next session closes above its open,
and trades that session open-to-close when the model is confident. It walks
forward: fit on a training window, trade the next window, move both along.
Every scaling figure and weight comes from bars before the test window, and
no training label reaches into it; only test-window trades are sealed.

Shows: a model in a backtest with numpy only, walk-forward windows, features scaled on the training window alone, labels that end before the test window, open-to-close intraday fills on one bar, backtest.assume(costs="zero") stated in the block.
"""
import numpy as np

import while25
from while25 import App, backtest, ui

KEY = "EQ:US:SPY"
START, END = "2015-01-02", "2025-12-31"

ui.panel("bt_walk_forward", "SPY walk-forward logistic backtest")
ui.layout(ui.view("main"))


def features(bars):
    """One row per bar, from that bar's close and earlier only:
    1-, 5- and 20-day log returns, 20-day volatility, distance from the
    50-day average. NaN where the history is too short."""
    c = np.array([b["close"] for b in bars], dtype=float)
    lr = np.diff(np.log(c), prepend=np.nan)
    out = np.full((len(c), 5), np.nan)
    for i in range(len(c)):
        if i >= 50:
            out[i] = [lr[i], np.log(c[i] / c[i - 5]), np.log(c[i] / c[i - 20]),
                      np.std(lr[i - 19:i + 1]), c[i] / c[i - 49:i + 1].mean() - 1]
    return out


def labels(bars):
    """y[i] = 1 when bar i+1 closes above its open (the trade the decision on
    bar i takes); NaN for the last bar, which has no next session."""
    y = np.full(len(bars), np.nan)
    for i in range(len(bars) - 1):
        y[i] = 1.0 if bars[i + 1]["close"] > bars[i + 1]["open"] else 0.0
    return y


def fit(X, y, *, l2=1.0, lr=0.1, steps=500):
    """Logistic regression weights (bias first) by gradient descent."""
    Xb = np.hstack([np.ones((len(X), 1)), X])
    w = np.zeros(Xb.shape[1])
    for _ in range(steps):
        p = 1 / (1 + np.exp(-Xb @ w))
        grad = Xb.T @ (p - y) / len(y) + l2 * np.r_[0, w[1:]] / len(y)
        w -= lr * grad
    return w


def predict(w, X):
    return 1 / (1 + np.exp(-np.hstack([np.ones((len(X), 1)), X]) @ w))


def windows(n, train, test):
    """(train_start, train_end, test_end) index triples: train on
    [train_start, train_end), decide on [train_end, test_end)."""
    out, start = [], 0
    while start + train + test <= n:
        out.append((start, start + train, start + train + test))
        start += test
    return out


def walk_forward(bars, *, train=500, test=60, threshold=0.55):
    """For each bar index decided on in a test window, the model's
    probability; nothing for training bars. {decision index: p}."""
    X, y = features(bars), labels(bars)
    probs = {}
    for t0, t1, t2 in windows(len(bars) - 1, train, test):
        # A training row i is labelled by bar i+1: keep only rows whose label
        # bar is before the test window starts (i + 1 < t1).
        idx = [i for i in range(t0, t1 - 1) if not np.isnan(X[i]).any() and not np.isnan(y[i])]
        if len(idx) < 100:
            continue
        mu, sd = X[idx].mean(axis=0), X[idx].std(axis=0)
        sd[sd == 0] = 1
        w = fit((X[idx] - mu) / sd, y[idx])
        test_idx = [i for i in range(t1, t2) if not np.isnan(X[i]).any()]
        if test_idx:
            for i, p in zip(test_idx, predict(w, (X[test_idx] - mu) / sd)):
                probs[i] = float(p)
    return {i: p for i, p in probs.items() if p >= threshold}


def model_trades(bars, inst, a, *, qty=100, **kw):
    """Buy the next session's open, sell its close, for each confident decision."""
    trades = []
    for i in sorted(walk_forward(bars, **kw)):
        nxt = bars[i + 1]
        entry = backtest.fill(nxt, "buy", "open", instrument=inst, assume=a)
        out = backtest.fill(nxt, "sell", "close", instrument=inst, assume=a)
        trades.append(backtest.trade(inst, "buy", qty, entry, out, product="intraday", assume=a))
    return trades


class WalkForwardLogistic(App):
    id = "bt_walk_forward_logistic"
    label = "SPY walk-forward logistic backtest"

    def run(self, ctx):
        span = while25.history_span(KEY, "1D", START, END)
        inst = while25.data.instrument(KEY)
        a = backtest.assume(costs="zero")
        trades = model_trades(span["bars"], inst, a)
        while25.ui.push("main", {"blocks": [ui.backtest_block(
            trades, data=[span["id"]], capital=100_000, assume=a,
            title="SPY open-to-close, walk-forward logistic model",
            logic={"Model": ["logistic regression, L2, 5 price features",
                             "refit every 60 sessions on the 500 before"],
                   "Entry": "probability of an up session >= 0.55: buy the open",
                   "Exit": "the same session's close"},
            notes="Zero costs, stated, to show the model's edge before costs. "
                  "Features are scaled on each training window only.")]})