Starter project
NBA backtesting starter with Python and DuckDB
This starter loads one NBA season of games and closing lines from DunkAPI into DuckDB, runs a walk-forward Elo rating model, and scores it against the market's closing probabilities with log loss, Brier score and margin error. Five short files, one command each, no wagering logic.
What you will build
A small pipeline in three steps. pull.py calls DunkAPI and writes two tables into a local DuckDB file: games (final scores for the warm-up season and the evaluation season) and books (each book's closing moneyline, spread and total for every game in the evaluation season). evaluate.py walks through every game in date order, keeps an Elo rating for each team, records the model's pre-game probability and expected margin, and then joins those predictions to the market's closing numbers with plain SQL.
Sample output from a real run on the 2025 season (1,230 regular season games, 9,811 book rows):
games 1230
model_logloss 0.6124
market_logloss 0.5811
model_brier 0.2124
market_brier 0.199
model_margin_mae 11.1
market_margin_mae 10.52
calibration of the model (decile of predicted home win probability)
# columns: decile, games, predicted, actual, market average
(5, 187, 0.551, 0.529, 0.519)
(6, 230, 0.649, 0.6, 0.6)
(7, 211, 0.749, 0.659, 0.709)
(8, 157, 0.844, 0.847, 0.813)In text form, the result reads like this: the market's closing probabilities beat a results-only Elo model on every measure, by about 0.03 in log loss and about half a point in margin error. The model is also a little overconfident in the 70 to 80 percent range, where it said 75 percent and home teams won 66 percent of the time.
Prerequisites
- Python 3.9 or newer (the run below used 3.9.6).
- A DunkAPI key. A full season uses about 1,700 credits, so check your balance first and start with the capped test run.
- Nothing else. DuckDB is an in-process database, so there is no server to install.
Keep the key in an environment variable. Never paste it into a file you commit.
The project
nba-backtest/
requirements.txt
dunk.py API client with retry on rate limits
pull.py loads games and closing lines into nba.duckdb
evaluate.py walk-forward Elo, then SQL scoring against the marketrequirements.txt
duckdb>=1.0
requests>=2.31dunk.py
"""Tiny DunkAPI client. Key comes from the DUNKAPI_KEY environment variable."""
import os
import time
import requests
BASE = os.environ.get("DUNKAPI_BASE", "https://mcp.dunkapi.com/v1")
def call(tool: str, **params):
for attempt in range(8):
resp = requests.post(
f"{BASE}/{tool}",
headers={"x-api-key": os.environ["DUNKAPI_KEY"], "Content-Type": "application/json"},
json=params,
timeout=60,
)
if resp.status_code == 429: # rate limited: wait and retry
time.sleep(float(resp.headers.get("Retry-After", 2 ** attempt)))
continue
resp.raise_for_status()
body = resp.json()
return body.get("data", body) # responses may arrive wrapped as {"data": ...}
raise RuntimeError(f"still rate limited after retries: {tool}")pull.py
"""Load games and closing lines into DuckDB.
usage: python pull.py [EVAL_SEASON] [MAX_DAYS]
Warm-up season (EVAL_SEASON - 1) loads scores only (2 credits per 50 games).
Eval season loads scores plus every book's closing line (10 credits per game day).
"""
import sys
import duckdb
from dunk import call
EVAL = int(sys.argv[1]) if len(sys.argv) > 1 else 2025
MAX_DAYS = int(sys.argv[2]) if len(sys.argv) > 2 else None # cap game days while testing
con = duckdb.connect("nba.duckdb")
con.execute("""
CREATE OR REPLACE TABLE games (
game_id VARCHAR, season INT, season_type VARCHAR, game_date DATE, starts_at TIMESTAMPTZ,
home VARCHAR, away VARCHAR, home_score INT, away_score INT);
CREATE OR REPLACE TABLE books (
game_id VARCHAR, provider VARCHAR, home_ml_close INT, away_ml_close INT,
home_spread_close DOUBLE, total_close DOUBLE);
""")
def load_games(season):
offset, n = 0, 0
while offset is not None:
page = call("list_games", season=season, season_type="regular",
status="final", limit=50, offset=offset)
for g in page["games"]:
con.execute("INSERT INTO games VALUES (?,?,?,?,?,?,?,?,?)", [
g["game_id"], g["season"], g["season_type"], g["date"], g["starts_at"],
g["home"]["abbrev"], g["away"]["abbrev"], g["home"]["score"], g["away"]["score"]])
n += 1
offset = page.get("next_offset") if page["games"] else None
return n
print("warm-up games:", load_games(EVAL - 1))
print("eval games:", load_games(EVAL))
days = [r[0] for r in con.execute(
"SELECT DISTINCT game_date FROM games WHERE season = ? ORDER BY 1", [EVAL]).fetchall()]
if MAX_DAYS:
days = days[:MAX_DAYS]
for d in days:
for g in call("get_odds", date=str(d))["games"]:
for b in g.get("books", []):
con.execute("INSERT INTO books VALUES (?,?,?,?,?,?)", [
g["game_id"], b["provider"], b["home_ml_close"], b["away_ml_close"],
b["home_spread_close"], b["total_close"]])
print("book rows:", con.execute("SELECT count(*) FROM books").fetchone()[0])evaluate.py
"""Walk-forward Elo ratings, then score the model against the market's closing lines.
Metrics are model evaluation only: log loss, Brier score, margin error, calibration.
"""
import duckdb
K, HFA, REGRESS = 20.0, 70.0, 0.25
con = duckdb.connect("nba.duckdb")
EVAL = con.execute("SELECT max(season) FROM games").fetchone()[0]
rows = con.execute("""SELECT game_id, season, home, away, home_score, away_score
FROM games ORDER BY starts_at, game_id""").fetchall()
ratings, last_season, preds = {}, None, []
for gid, season, home, away, hs, as_ in rows:
if last_season is not None and season != last_season: # new season: pull toward 1500
ratings = {t: r + REGRESS * (1500 - r) for t, r in ratings.items()}
last_season = season
rh, ra = ratings.get(home, 1500.0), ratings.get(away, 1500.0)
diff = rh - ra + HFA
p_home = 1 / (1 + 10 ** (-diff / 400))
if season == EVAL: # predictions use pre-game ratings only
preds.append((gid, p_home, diff / 28.0)) # ~28 Elo points per point of margin
margin = hs - as_
winner_diff = diff if margin > 0 else -diff
mult = ((abs(margin) + 3) ** 0.8) / (7.5 + 0.006 * winner_diff)
delta = K * mult * ((1 if margin > 0 else 0) - p_home)
ratings[home], ratings[away] = rh + delta, ra - delta
con.execute("CREATE OR REPLACE TABLE preds (game_id VARCHAR, model_p_home DOUBLE, model_margin DOUBLE)")
con.executemany("INSERT INTO preds VALUES (?,?,?)", preds)
con.execute("""
CREATE OR REPLACE VIEW market AS
WITH imp AS (
SELECT game_id, home_spread_close,
CASE WHEN home_ml_close < 0 THEN -home_ml_close / (-home_ml_close + 100.0) ELSE 100.0 / (home_ml_close + 100.0) END AS ph,
CASE WHEN away_ml_close < 0 THEN -away_ml_close / (-away_ml_close + 100.0) ELSE 100.0 / (away_ml_close + 100.0) END AS pa
FROM books WHERE home_ml_close IS NOT NULL AND away_ml_close IS NOT NULL)
SELECT game_id, count(*) AS n_books,
avg(ph / (ph + pa)) AS market_p_home, -- margin removed per book, then averaged
median(home_spread_close) AS median_spread
FROM imp GROUP BY game_id""")
con.execute("""
CREATE OR REPLACE VIEW scored AS
SELECT g.game_id, g.game_date, p.model_p_home, m.market_p_home,
p.model_margin, -m.median_spread AS market_margin,
(g.home_score - g.away_score) AS actual_margin,
(g.home_score > g.away_score)::INT AS home_won
FROM games g JOIN preds p USING (game_id) JOIN market m USING (game_id)
WHERE m.median_spread IS NOT NULL""")
cols = ["games", "model_logloss", "market_logloss", "model_brier", "market_brier",
"model_margin_mae", "market_margin_mae"]
row = con.execute("""
SELECT count(*),
round(-avg(home_won*ln(model_p_home) + (1-home_won)*ln(1-model_p_home)), 4),
round(-avg(home_won*ln(market_p_home) + (1-home_won)*ln(1-market_p_home)), 4),
round(avg(pow(model_p_home-home_won,2)), 4),
round(avg(pow(market_p_home-home_won,2)), 4),
round(avg(abs(model_margin-actual_margin)), 2),
round(avg(abs(market_margin-actual_margin)), 2)
FROM scored""").fetchone()
for c, v in zip(cols, row):
print(f"{c:18} {v}")
print("\ncalibration of the model (decile of predicted home win probability)")
for r in con.execute("""
SELECT least(floor(model_p_home*10), 9)::INT AS decile, count(*) AS n,
round(avg(model_p_home),3) AS predicted, round(avg(home_won),3) AS actual,
round(avg(market_p_home),3) AS market
FROM scored GROUP BY 1 ORDER BY 1""").fetchall():
print(r)How to run it
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
export DUNKAPI_KEY="your-key-here"
python pull.py 2025 5 # test run: 5 game days of lines, about 100 credits
python pull.py 2025 # full season, about 1,700 credits, several minutes
python evaluate.pyThe first argument is the evaluation season, named by the year it ends (2025 means 2024-25). The previous season is loaded as a warm-up so the ratings are settled before the first scored game. The optional second argument caps the number of game days of lines, which is the cheap way to confirm everything works before a full pull.
How it works
The client. dunk.py posts JSON to /v1/<tool> with an x-api-key header. Responses may arrive wrapped in a data object, so the client unwraps it. If the API answers 429 (too many requests), it waits and retries, which matters because the day-by-day pull makes a few hundred calls in a row. The base URL comes from DUNKAPI_BASE, so you can point the same code at another host without editing it.
The pull. Two tools do the work. list_games returns final scores a page at a time (2 credits a page, 50 games per page), and the script follows next_offset until the pages run out. get_odds with a date returns every game that day along with each book's opening and closing price (10 credits per day). The script keeps only the closing moneyline, closing home spread and closing total for each book, because those are the numbers the market had settled on at the start of the game. Dates are US Eastern, the same convention the API uses.
The model. The rating model is classic Elo with three choices worth knowing. Every team starts at 1500. After each game the winner gains points in proportion to how surprising the result was, scaled by the margin of victory so that blowouts move ratings more than one-point finishes. Between seasons each rating moves a quarter of the way back to 1500, because rosters change. Home teams get a 70 point bump when the win probability is computed. The expected margin is the rating gap divided by 28, a rough conversion from rating points to game points. None of these constants are tuned. They are a sensible starting point so you have something to beat.
A detail that matters: the prediction for a game is stored before that game updates the ratings. If you move the preds.append line below the update, the model sees the answer it is meant to predict and the scores look better than they are. Leakage like this is the most common reason a backtest looks too good, so it is worth reading that loop once with that in mind.
The market view. DuckDB does the comparison. The market view converts each book's closing moneylines to implied probabilities, removes the book's margin by rescaling the two sides so they sum to one, and averages the result across books. It also takes the median closing spread. The scored view joins those to the model's predictions and the actual final margin. Because both the model and the market are reduced to a home win probability and an expected home margin, the same two metrics apply to both.
The metrics. Log loss and Brier score both reward probabilities that are close to what happened and punish confident misses. Lower is better for both. Margin error is the average gap between the expected margin and the real one, in points. The calibration table groups games by the model's predicted probability and compares it with how often the home team actually won, and shows the market's average in the same group. A well-calibrated model has predicted and actual columns that match.
Ways to extend it
- Add rest and travel. Join a table of days of rest per team and add a small adjustment to the rating gap. Check whether the margin error moves, and whether the gap to the market narrows in the calibration deciles where the model is weakest.
- Tune the constants honestly. Fit K, home advantage and the season regression on the warm-up season only, then freeze them and score the evaluation season once. Tuning on the games you score is the second most common source of a flattering backtest.
- Score totals as well as sides. The
bookstable already holds the closing total. Build a simple pace and efficiency model for expected points and compare its error with the market total's error. - Add a second season of evaluation. Pull 2024 lines too and report metrics per season. A model that only wins in one season is telling you something about that season.
Limits and when not to use this
- This is a model evaluation harness, not a forecasting product. A model that scores well on past games has not shown that it will keep doing so.
- The Elo model sees results only. It knows nothing about injuries, rest, lineups or trades, which is exactly what closing prices include. Expect it to trail the market.
- Closing lines are the final pre-game numbers. For some books the capture time is unknown, and the API says so in
captured_at_note. Treat them as closing numbers, not as prices you could have seen at a specific moment. - One season is about 1,230 games. Differences of a few thousandths in log loss are inside the noise, so report a sample size next to every metric.
- Stored data is for your own analysis and for products that show your users what you derive. You may not redistribute the raw data as a dataset or feed. See the terms in the DunkAPI documentation.
FAQ
Does this project place or size wagers? No. It only evaluates a rating model: log loss, Brier score, margin error and calibration. It has no stakes, payouts or profit figures, and nothing in it tells you what to do with a price.
How many credits does one season cost? About 1,700. Scores for two seasons cost roughly 100 credits (2 per page of 50 games), and the closing lines cost 10 credits per game day, about 165 days. Pass a day cap to pull.py to test cheaply first.
Why did the Elo model score worse than the market? That is the expected result and the useful one. Closing prices absorb injuries, rest and lineup news that a results-only rating cannot see. The gap is your baseline: a new feature earns its place only if it narrows it.
Live from the API
Free to embed on your own site, with no key needed. Get the embed code.
Get a free key Or download whole seasons as Parquet
Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.