Skip to content
Back to skills

Backtesting

ASecurity

Use when the user asks whether a sports model or system would have worked in the past, for any sport, in plain wording: 'does my model actually work', 'test it on the last three seasons', 'did it beat the closing line', 'is it still as accurate as it used to be', 'what is the confidence interval on my hit rate', 'how would this have done in 2023', 'run it against past odds', 'is this edge real or luck', 'how should I split seasons to test it'. Use this whenever historical performance, fold de...

  • 6 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 25, 2026
ai-agentspythongotestingapiperformance

Works with

  • cli
  • api
  • mcp

Security analysis

A100/100

Scanned December 4, 2026

npx -y skills add sports-data-hq/sportsdatahq-skills --skill backtesting --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Backtesting?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Backtesting
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/sports-data-hq-backtesting/badge)](https://www.skillsdirectory.com/skills/sports-data-hq-backtesting)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: backtesting
description: "Use when the user asks whether a sports model or system would have worked in the past, for any sport, in plain wording: 'does my model actually work', 'test it on the last three seasons', 'did it beat the closing line', 'is it still as accurate as it used to be', 'what is the confidence interval on my hit rate', 'how would this have done in 2023', 'run it against past odds', 'is this edge real or luck', 'how should I split seasons to test it'. Use this whenever historical performance, fold design, sample size or an interval is the question. Load this skill first, before calling any data tool; it says which tools to call. Walk-forward only; refuses k-fold and in-sample testing; reports sample size, an interval and a per-season breakdown. Not for logging live predictions as games finish (see prediction-tracker), tonight's gap to the market (see market-vs-model) or training (see model-building)."
metadata:
  version: 2.3.0
  author: SportsDataHQ
---

# Backtesting

Odds are information only. This skill measures how good a model's probabilities were on games it had not seen, and how they compare with the market's no-margin (fair) probabilities. It does not recommend actions based on a result.

You are a skeptical auditor. The job is to try to falsify a claim that a model is good, not to confirm it.

## Data

Call your sport's SportsDataHQ MCP tools. Examples: get_schedule or list_games for results, get_odds or get_game_probabilities for the market's closing prices and no-margin probabilities, get_line_movement for opening vs closing. Hockey, football, basketball, baseball, soccer, tennis, golf, UFC and cricket servers all expose results and odds in this shape; tool names differ slightly, so read the tool list first.

Where a server offers get_prop_backtest, prefer it for "how often did this kind of prop hit against the market". It returns the sample size, an interval and a by_season breakdown. Report all three and never present a past result as a pick.

Own data (CSV or JSON): required columns are game_id, game_date, model_prob, market_prob (no-margin), actual_result. Dates ISO 8601, sorted ascending before anything else.

## Rules for numbers

- Call the tools. Never answer a historical figure from memory.
- Cite which tool call produced each number (tool name plus its arguments, such as get_game_probabilities for one date range).
- State the sample size (games, not seasons) and the season convention the server uses (for example 2025 = 2024-25 in basketball, the year the season starts in football and soccer).
- If the sample is too small to support a conclusion, write "not enough data" and say how many games would be needed. Do not guess.
- Always check the cost of a large pull with the user before running it.

## Step 0: refuse in-sample testing

If the model was trained or calibrated on the games being tested, stop. Results from the training period reflect what the model already saw and look better than reality.

Walk-forward only: train on period A, test on period B, then retrain on A+B and test on C. If the user insists on the same period, explain why it is invalid and propose a split.

## Walk-forward fold design

Use this part alone when the user asks how to split their data.

### Why k-fold fails on sports data

K-fold randomly partitions data into folds. On time-series sports data, this means:

- A game from January appears in both training and test folds
- Features for that January game include rolling stats from December
- But the December games appear in a different fold: potentially the "test" fold
- The model trains on December data it would never have had access to in production

**Measured inflation:** In our hockey game-prediction tests, k-fold overstated walk-forward accuracy by 7-12 percentage points. A model appearing to reach 65% via k-fold scored 58% on walk-forward. That gap is the difference between a real signal and noise. Treat these figures as an illustration from one project, and measure the gap on your own data.

**The fundamental issue:** K-fold assumes i.i.d. (independent, identically distributed) data. Sports games are not i.i.d.: they are time-ordered, with yesterday's game affecting tomorrow's features. K-fold's assumption is violated at the data level.

### Fold structure

Choose between two walk-forward approaches:

**Expanding window (recommended for most sports models):**
- Fold 1: Train on Season 1, Test on Season 2
- Fold 2: Train on Seasons 1-2, Test on Season 3
- Fold 3: Train on Seasons 1-3, Test on Season 4
- Train set grows with each fold

**Sliding window (use when older data degrades model):**
- Fold 1: Train on Seasons 1-3, Test on Season 4
- Fold 2: Train on Seasons 2-4, Test on Season 5
- Fold 3: Train on Seasons 3-5, Test on Season 6
- Train window stays fixed size

**Use expanding window as default.** Switch to sliding only if you have evidence that adding older seasons hurts performance (test this explicitly).

Minimum viable: 3 folds. More is better. Never evaluate on a single train/test split.

### Within-fold discipline

Within each fold, features must still be computed correctly:

- Sort data ascending by date within each fold
- `.shift(1)` before rolling windows applies within the training fold
- Test fold features computed using ONLY training fold data: no peeking at test-fold stats
- SOS, cumulative stats, and season-level features rebuilt per fold from training data only

If you join external stats (standings, Elo) into the test fold, those stats must be as-of the test period start date: not end-of-season values.

### Train and predict per fold

```python
results = []
seasons = sorted(df['season'].unique())

for test_idx in range(1, len(seasons)):
    train_seasons = seasons[:test_idx]       # expanding window
    test_season = seasons[test_idx]

    train = df[df['season'].isin(train_seasons)]
    test = df[df['season'] == test_season]

    # Features computed from training data only
    model.fit(train[features], train[target])
    preds = model.predict_proba(test[features])[:, 1]

    results.append({
        'fold': test_idx,
        'test_season': test_season,
        'n_games': len(test),
        'accuracy': accuracy_score(test[target], preds > 0.5),
        'log_loss': log_loss(test[target], preds),
        'brier': brier_score_loss(test[target], preds)
    })
```

### Games needed before an accuracy gap is real

**Minimum sample sizes for significance at p < 0.05:**

| Accuracy vs 55% Baseline | Games Required |
|--------------------------|----------------|
| 58% (3pp above baseline) | ~750 games |
| 60% (5pp above baseline) | ~280 games |
| 63% (8pp above baseline) | ~120 games |
| 65% (10pp above baseline) | ~80 games |

**One full hockey regular season is about 1,230 games (other sports differ).** A single season of walk-forward test data is typically sufficient for 60%+ accuracy claims. Two seasons is better.

### Report per fold

```
Fold 1 (test: 2021-22): 59.1% acc, log loss 0.672, Brier 0.238 (n=1,230)
Fold 2 (test: 2022-23): 61.3% acc, log loss 0.658, Brier 0.231 (n=1,230)
Fold 3 (test: 2023-24): 58.7% acc, log loss 0.680, Brier 0.241 (n=1,230)
Mean:                    59.7% acc, log loss 0.670, Brier 0.237
Std:                     +/-1.1pp (consistent, not a single lucky season)
```

If accuracy varies wildly across folds (e.g., 65% in fold 1, 52% in fold 2), the model is unstable. Investigate feature leakage or overfitting.

## Step 1: prepare data

Sort ascending by date. Join model predictions to results and to the market's pre-game probabilities on game_id. Predictions must use only information available before each game; if features were rebuilt with full-season data, flag leakage and send the user to feature-engineering.

```python
df = df.sort_values('game_date').reset_index(drop=True)
```

## Step 2: score the model

Report, on test data only:

| Metric | Formula | Reading |
|--------|---------|---------|
| Log loss | -mean(y*log(p) + (1-y)*log(1-p)) | Lower is better |
| Brier score | mean((p - y)^2) | Lower is better; coin flip is 0.25 |
| Accuracy | correct / games | Context only; needs the base rate |
| Calibration error | gap between predicted and actual rate per bin | See probability-calibration |

## Step 3: model vs market comparison

The market's no-margin probability is a strong benchmark. Compare the same games on the same metrics:

```python
model_ll  = log_loss(y, df['model_prob'])
market_ll = log_loss(y, df['market_prob'])
gap = market_ll - model_ll   # positive: model probabilities scored better
```

Frame this as how our probability differs from the market's and which was closer to what happened. It is a measure of model quality, not an instruction to wager.

Closing-line comparison: if the model moves toward the closing probability before the game (use opening and closing from get_line_movement or get_odds), the model is picking up information the market later agreed with. Report the average difference between model probability and closing probability, and how often the closing probability moved toward the model. Treat this as a diagnostic.

## Step 4: intervals

A single number is not a result. Bootstrap by game:

```python
import numpy as np
rng = np.random.default_rng(0)
vals = []
for _ in range(1000):
    s = df.sample(len(df), replace=True, random_state=int(rng.integers(1e9)))
    vals.append(log_loss(s['actual_result'], s['market_prob']) - log_loss(s['actual_result'], s['model_prob']))
lo, hi = np.percentile(vals, [2.5, 97.5])
```

Report "model beat market by 0.004 log loss (95% interval -0.003 to 0.011, n = 1,230 games)". An interval that crosses zero means the difference is not established. Say so plainly.

## Step 5: per-season breakdown

Always show each season separately, not only the pooled figure. A pooled result driven by one season is fragile.

| Season | Games | Model log loss | Market log loss | Gap | Interval |
|--------|-------|----------------|-----------------|-----|----------|

Check for compression: compare the first and second half of each season, and early vs late seasons. A gap that shrinks over time suggests the market absorbed the information the model uses, which calls for new features rather than more tuning.

## Step 6: drift audit

- Accuracy and log loss over trailing 30, 60 and 90 days.
- Calibration by probability bin (0.50-0.55, 0.55-0.60 and so on): predicted vs actual rate.
- Feature drift: did the inputs' distributions shift (rule changes, new venues, roster turnover)?

Recommendation guide: calibration error under 2 points, keep; 2 to 5, recalibrate (probability-calibration); over 5 or a 60-day decline, retrain (model-building).

## Step 7: naive baselines

A model must beat simple references on the same test set: always-home rate, last season's win percentage, and the market's no-margin probability. If it does not beat the first two, stop and look at features before anything else.

## Anti-patterns

| Claim | Why it is wrong | Do instead |
|-------|-----------------|------------|
| "Backtest shows 58% accuracy" | Over how many games, and against what base rate? | Give n, interval and baseline |
| "Tested on the full dataset" | In-sample | Walk-forward only |
| "Gap to market is just variance" | Maybe, so test it | Bootstrap interval, per-season table |
| "Last month was great" | 30 games is noise | Need hundreds of games before drawing a conclusion |
| "Beats the market this season" | One season can be luck | Report every season in the table |
| "Better on one data provider's line" | Closing lines differ across books | Report the average and the range across books |

## Output format

```
BACKTEST REPORT: [model] [date range]

SAMPLE
Games: X (test period only). Season convention: [..]. Tool calls: [..]

MODEL SCORES
Log loss: X.XXX  Brier: X.XXX  Accuracy: X.X% (base rate X.X%)

MODEL VS MARKET (no-margin closing probability)
Log loss gap: X.XXX (95% interval X.XXX to X.XXX)
Closing-line check: closing probability moved toward model in X.X% of games

BY SEASON
[table]

DRIFT
Calibration error: X.X pp. Trend: [stable / compressing / improving]
Recommendation: [keep / recalibrate / retrain / not enough data]
```

## What to do next

| Finding | Next | Skill |
|---------|------|-------|
| Results hold up | Log live predictions and grade them | `prediction-tracker` |
| Gap shrinking or negative | Retrain or add features | `model-building` |
| Calibration drifted | Recalibrate | `probability-calibration` |
| Want today's gap to the market | Compare today's probabilities | `market-vs-model` |

## Credits

- Sequences (last 5, recent form, a run of results) are quoted in the order the tool returns them, with dates; never retell them from memory. Lists in the answer must match the tool rows.
- Out of credits: if a call is refused for credits, pass on the API's message as it comes (it says when free credits refill and how to add more), and stop; don't retry or switch tools to get around it.
- No key, or the server is not connected: say so once and give the free key (no card): https://app.sportsdatahq.com/signup?utm_source=skills&utm_medium=sports-analytics-core&utm_campaign=backtesting

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.