Guide

Walk-forward validation for sports models, without leakage

Short answer: train only on games that finished before the game you predict. Walk forward through time: fit on everything before a cutoff, score the next block, move the cutoff and repeat. Build each feature from data available at prediction time. Shuffled folds and whole-season features leak the future and inflate scores.

What leakage is

Leakage means information from the time you are predicting reached the model during training or feature building. In sports it comes in four forms:

  1. Shuffled splits. A random split puts some of a game's shots in training and the rest in testing. The model has effectively seen the game.
  2. Whole-sample features. A shooter's season goal rate, a team's season rating or a z-score computed over all rows includes the test rows.
  3. Same-game information. A column joined by game_id, such as a game total or a final score, carries the outcome into a row that happened earlier in the game.
  4. Late-arriving data. A record corrected after the game, or a line captured after the start, is not what you would have had in time.

Every one of these makes the model look better on paper and worse in use. The fix is structural: make the split respect time, and make every feature a function of the past.

The walk-forward loop

Walk-forward validation, also called an expanding-window backtest, runs in four steps. Pick a first cutoff after enough history. Train on every row before the cutoff. Score the next block of games. Move the cutoff forward by one block and retrain. The out-of-sample predictions from every block, joined together, are your score.

This version has no external dependencies and generates its own sample data so you can run it anywhere. It checks that no training row is later than any test row in every split:

import numpy as np, pandas as pd

def walk_forward_splits(game_nums, first_test_game, block):
    """Yield (train_mask, test_mask) pairs. Training is everything before the block."""
    last = int(game_nums.max())
    for start in range(first_test_game, last + 1, block):
        train = game_nums < start
        test = (game_nums >= start) & (game_nums < start + block)
        if test.any():
            yield train, test

rng = np.random.default_rng(7)
games = pd.DataFrame({"gnum": np.repeat(np.arange(82), 25)})      # 82 games, 25 shots each
for train, test in walk_forward_splits(games["gnum"], first_test_game=30, block=10):
    assert games.loc[train, "gnum"].max() < games.loc[test, "gnum"].min()
    print("train games 0 to", games.loc[train, "gnum"].max(), "| test games",
          games.loc[test, "gnum"].min(), "to", games.loc[test, "gnum"].max())

It printed six splits, from train games 0 to 29 | test games 30 to 39 through the last block of 80 to 81.

If your model uses a lagging window, such as a 10-game rolling average, add a gap of at least that window between train and test, so no training row's feature window touches a test row. This gap is sometimes called an embargo.

Build features from the past only

Every feature obeys one rule. For the row at time t, use only information that existed before t. Three habits make that automatic.

A demonstration on real shots

We pulled one team's 2025-26 regular season from get_shot_map through PuckAPI (3,274 unblocked attempts, shown in the expected goals guide) and scored the same logistic regression four ways: with shuffled five-fold cross-validation and with walk-forward blocks of ten games, starting at game 30. The walk-forward predictions cover 2,070 attempts. The leaky feature below is built on purpose.

import numpy as np, pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
from sklearn.model_selection import KFold
# build, design and BASE are defined in the expected goals guide.

df = build(pd.read_csv("tor.csv"))
games = sorted(df["game_id"].unique())          # ids rise through the season
df["gnum"] = df["game_id"].map({g: i for i, g in enumerate(games)})
prior = df["goal"].mean()

# Shooter history, two ways.
df["sh_leaky"] = df.groupby("shooter")["goal"].transform("mean")          # includes test games
per = df.groupby(["shooter", "gnum"])["goal"].agg(["sum", "count"]).reset_index().sort_values(["shooter", "gnum"])
per["cg"] = per.groupby("shooter")["sum"].cumsum() - per["sum"]            # goals before this game
per["ca"] = per.groupby("shooter")["count"].cumsum() - per["count"]        # attempts before this game
df = df.merge(per[["shooter", "gnum", "cg", "ca"]], on=["shooter", "gnum"])
df["sh_past"] = (df["cg"] + 20 * prior) / (df["ca"] + 20)                  # shrunk toward league rate

# Game-level feature that peeks at the same game's outcomes, and an honest version.
df["game_goal_rate"] = df.groupby("game_id")["goal"].transform("mean")     # leak
g = df.groupby("gnum")["goal"].mean()
df["prev3_rate"] = df["gnum"].map(g.shift(1).rolling(3, min_periods=1).mean()).fillna(prior)

def fit_score(train, test, cols):
    Xtr = design(train, cols)
    Xte = design(test, cols).reindex(columns=Xtr.columns, fill_value=0.0)
    return LogisticRegression(max_iter=3000).fit(Xtr, train["goal"]).predict_proba(Xte)[:, 1]

def walk_forward(df, cols, block=10, min_train=30):
    preds = []
    for start in range(min_train, df["gnum"].max() + 1, block):
        tr = df[df["gnum"] < start]
        te = df[(df["gnum"] >= start) & (df["gnum"] < start + block)]
        if len(te):
            preds.append(pd.Series(fit_score(tr, te, cols), index=te.index))
    p = pd.concat(preds)
    return log_loss(df.loc[p.index, "goal"], p)

def shuffled_kfold(df, cols):
    out = pd.Series(index=df.index, dtype=float)
    for tr, te in KFold(5, shuffle=True, random_state=7).split(df):
        out.iloc[te] = fit_score(df.iloc[tr], df.iloc[te], cols)
    return log_loss(df["goal"], out)

for label, cols in [("distance + angle", BASE),
                    ("+ shooter rate, whole season", BASE + ["sh_leaky"]),
                    ("+ shooter rate, past only", BASE + ["sh_past"]),
                    ("+ same-game goal rate", BASE + ["game_goal_rate"]),
                    ("+ previous 3 games rate", BASE + ["prev3_rate"])]:
    print(f"{label:30s} shuffled {shuffled_kfold(df, cols):.4f}   walk-forward {walk_forward(df, cols):.4f}")

Log loss, lower is better:

FeaturesShuffled 5-foldWalk-forward
Distance and angle0.24410.2361
Plus shooter rate, whole season (leaky)0.24360.2357
Plus shooter rate, past only0.24420.2362
Plus same-game goal rate (leaky)0.23940.2319
Plus previous 3 games rate0.24420.2362

Read it carefully, because the result is mixed. The shooter-rate leak barely moved the score, because one team's shooters have too few attempts for a season rate to carry much. That feature also made no difference when built honestly. The same-game rate is a plain leak, and it "improved" log loss by 0.0042 in both schemes. The honest feature from the previous three games added nothing, and the apparent gain disappeared the moment the feature was computed from the past. That is the pattern to watch for: a feature that helps only when it contains the future.

Also notice that the two schemes disagree by about 0.008 on the same baseline model. Walk-forward scores a later part of the season and retrains on a smaller early sample, so the numbers are not interchangeable, and you should never compare a walk-forward score to a shuffled one.

A checklist before you trust a score

  1. Is every train row earlier than every test row, with a gap for rolling windows?
  2. Is each feature a function of data before the row's time? Shift, then aggregate.
  3. Do any columns join on a game id, season or final result?
  4. Were hyperparameters tuned on the test blocks? If so, hold out a final block you touch once.
  5. Is the score reported per block, so you can see drift, and not only as one pooled number?
  6. Does the baseline use the same split? Compare to a league-average rate on the same blocks.
  7. Could the data you used have been revised after the fact?

When not to use this

Get a free key

Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.