Build an NBA game model in Python and test it against closing lines
Fit a logistic regression for NBA home wins, score it on a held-out season against the market's no-vig closing probability, and compare log loss, Brier and calibration.
Every script run against the live API on December 4, 2026. One full run: 1,693 credits.
Most NBA model tutorials stop at accuracy on the games the model was built from. This one ends at a harder test: a season the model never saw, scored with log loss and the Brier score next to the market's own closing probability, with a calibration table for both.
You will pull three seasons of finished games, add our Elo ratings from the end of the prior season, fit a logistic regression for the home team's win probability on 2022-23 and 2023-24, and score it on 2024-25: 1,230 games. Then you pull each sportsbook's closing moneyline for those games, take the margin out, and compare.
Read the result as a measurement. The closing line is the market's final forecast, and doing better than it is hard: most models do not, and this one does not. Nothing here sizes a wager, works out a payout or recommends a bet. It forecasts games and measures how good the forecast is.
One full run costs 1,693 credits: 42 for the games, 6 for the ratings, 1,630 for a season of closing odds (10 a game day) and 15 for a check against the API's own probabilities. That fits a paid plan's monthly credits. The first two data steps cost 48 credits, so the 500 free credits cover them and about 45 game days of odds.
1. Install the client and set your key
The client has no required dependencies. This tutorial uses pandas for the tables and scikit-learn for the model. It needs Python 3.9 or newer, and the client reads your key from DUNKAPI_API_KEY.
pip install "dunkapi[pandas]" scikit-learn
export DUNKAPI_API_KEY=your_key_here2. Pull three seasons of games
list_games returns finished games with their final scores, 200 to a page and 2 credits a page. Seasons are named by the year they end, so 2025 is 2024-25. The loop follows next_offset until the season runs out. It pulls the regular season only (season_type="regular") and the 2023 and 2024 seasons are the training data, 2025 is the test. Each season is 1,230 games, so the three seasons are 21 calls and 42 credits.
The model uses the final score alone. Team box scores are one get_game call per game at 5 credits, 6,150 credits for a season, so the tutorial leaves them out; the last step says where they would go.
import pandas as pd
from dunkapi import Client
client = Client() # reads DUNKAPI_API_KEY
# Final regular-season games, 200 a page. Seasons are named by the year they end: 2025 = 2024-25.
rows = []
for season in (2023, 2024, 2025):
offset = 0
while offset is not None:
page = client.list_games(season=season, season_type="regular", status="final", limit=200, offset=offset)
rows += page["games"]
offset = page.get("next_offset")
games = pd.json_normalize(rows)
games = games.rename(columns={
"home.team_id": "home_id", "home.abbrev": "home", "home.score": "home_pts",
"away.team_id": "away_id", "away.abbrev": "away", "away.score": "away_pts",
})
games = games[["game_id", "season", "date", "home_id", "home", "home_pts", "away_id", "away", "away_pts"]]
games["home_win"] = (games["home_pts"] > games["away_pts"]).astype(int)
games.to_csv("games.csv", index=False)
print(games.groupby("season").agg(games=("game_id", "size"), home_win_rate=("home_win", "mean")).round(3).to_string())
print(games.head(3).to_string(index=False))
print("credits left:", client.last_credits_remaining)Output
games home_win_rate
season
2023 1230 0.580
2024 1230 0.543
2025 1230 0.544
game_id season date home_id home home_pts away_id away away_pts home_win
401469379 2023 2023-04-09 6 DAL 117 24 SA 138 0
401469380 2023 2023-04-09 16 MIN 113 3 NO 108 1
401469381 2023 2023-04-09 25 OKC 115 29 MEM 100 1
credits left: 1246Home teams won between 54% and 58% of games in these seasons. The last line is the credit balance of the key that ran it; yours will differ. A game's date is its US Eastern date, and game_id is what every other call takes.
3. Add each team's rating from the season before
get_ratings returns our Elo rating for every team as of the end of a season, playoffs included. A game in 2024-25 gets the ratings from the end of 2023-24, so the number is known before the first game is played and cannot leak the result. Three calls, 6 credits.
import pandas as pd
from dunkapi import Client
client = Client()
# Our Elo at the end of each season. A game in season S uses the ratings from the end of S-1,
# so the feature is known before the season starts.
rows = []
for season in (2022, 2023, 2024):
for r in client.get_ratings(season=season, limit=30)["ratings"]:
rows.append({"season": season + 1, "team_id": r["team_id"], "prior_elo": r["rating"]})
ratings = pd.DataFrame(rows)
ratings.to_csv("prior_ratings.csv", index=False)
print(ratings.groupby("season")["prior_elo"].agg(["count", "min", "max"]).round(1).to_string())Output
count min max
season
2023 30 1248.0 1707.6
2024 30 1266.1 1680.3
2025 30 1255.2 1747.4All 30 teams are in each season. 1500 is average, and a 100-point gap is about a 64% favorite on a neutral floor. Ratings regress a quarter of the way to the mean between seasons, which is why last season's rating is a prior and not the answer.
4. Pull the closing moneylines for the test season
get_odds with a date returns every game that day with each sportsbook's opening and closing moneyline, spread and total. A day costs 10 credits whatever the number of games, which is about 1.3 credits a game over this season; asking game by game would cost 5. home_close_prob and away_close_prob are each book's implied probabilities with its margin still in, so the pair adds to more than 1.
The script saves every day to odds_2025.json as it goes, so a rerun skips days you already paid for, and it waits between calls to stay under the 60 requests a minute limit. The 163 days take about three minutes. To try it on the free credits, shorten the list to days[:40]: 400 credits, and the later steps then score only the games you pulled.
import json
import os
import time
import pandas as pd
from dunkapi import Client
client = Client()
games = pd.read_csv("games.csv", dtype={"game_id": str})
days = sorted(games.loc[games["season"] == 2025, "date"].unique())
print(len(days), "game days in 2025 =", len(days) * 10, "credits")
# One call per day returns every game that day with each sportsbook's open and close.
# Saved as it goes, so a rerun skips days you already paid for.
cache = json.load(open("odds_2025.json")) if os.path.exists("odds_2025.json") else {}
for day in days:
if day not in cache:
cache[day] = client.get_odds(date=day)["games"]
json.dump(cache, open("odds_2025.json", "w"))
time.sleep(1.1) # the limit is 60 requests a minute
rows = []
for day_games in cache.values():
for g in day_games:
for b in g["books"]:
rows.append({"game_id": g["game_id"], "book": b["provider"],
"home_prob": b["home_close_prob"], "away_prob": b["away_close_prob"]})
books = pd.DataFrame(rows).dropna()
print(len(books), "closing moneylines from", books["book"].nunique(), "books,", books["game_id"].nunique(), "games")
print(books.groupby("game_id").size().describe()[["min", "50%", "max"]].to_string())Output
163 game days in 2025 = 1630 credits
9787 closing moneylines from 9 books, 1235 games
min 2.0
50% 8.0
max 8.0The 1,235 games are the 1,230 in step 1 plus five postponed games that carry prices but no result; the next steps keep only games with a result. A game has between 2 and 8 books, and the median game has 8.
5. Build features and fit the model
Everything the model sees is known before tip-off. For each team the script computes its average point margin over its last 10 games (shift(1) leaves out the game being predicted), its days of rest, and whether it played the day before. With the prior-season rating that is five numbers per game, each as home minus away where it makes sense.
A full net rating needs possessions, which come from box scores, so point margin stands in for it. The window runs across the season boundary, and the 79 games where either team had played fewer than five earlier games are dropped. The model is a standardized logistic regression fit on 2022-23 and 2023-24 and applied to 2024-25.
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
games = pd.read_csv("games.csv", dtype={"game_id": str, "home_id": str, "away_id": str})
games["date"] = pd.to_datetime(games["date"])
ratings = pd.read_csv("prior_ratings.csv", dtype={"team_id": str})
# One row per team per game, in date order.
home = games.assign(team=games["home_id"], margin=games["home_pts"] - games["away_pts"])
away = games.assign(team=games["away_id"], margin=games["away_pts"] - games["home_pts"])
tg = pd.concat([home, away]).sort_values(["team", "date", "game_id"])
by_team = tg.groupby("team")
# Everything below uses only games played before this one (shift(1) drops the current game).
tg["margin10"] = by_team["margin"].transform(lambda s: s.shift(1).rolling(10, min_periods=5).mean())
tg["rest"] = by_team["date"].diff().dt.days.clip(upper=7).fillna(7)
feat = tg[["game_id", "team", "margin10", "rest"]]
df = (games
.merge(feat.add_suffix("_h"), left_on=["game_id", "home_id"], right_on=["game_id_h", "team_h"])
.merge(feat.add_suffix("_a"), left_on=["game_id", "away_id"], right_on=["game_id_a", "team_a"])
.merge(ratings.rename(columns={"team_id": "home_id", "prior_elo": "elo_h"}), on=["season", "home_id"])
.merge(ratings.rename(columns={"team_id": "away_id", "prior_elo": "elo_a"}), on=["season", "away_id"]))
df["margin_diff"] = df["margin10_h"] - df["margin10_a"] # rolling point margin, home minus away
df["rest_diff"] = df["rest_h"] - df["rest_a"]
df["b2b_home"] = (df["rest_h"] == 1).astype(int) # played yesterday
df["b2b_away"] = (df["rest_a"] == 1).astype(int)
df["elo_diff"] = (df["elo_h"] - df["elo_a"]) / 100
FEATURES = ["margin_diff", "rest_diff", "b2b_home", "b2b_away", "elo_diff"]
df = df.dropna(subset=FEATURES)
train, test = df[df["season"] <= 2024], df[df["season"] == 2025]
model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(train[FEATURES], train["home_win"])
df.loc[test.index, "model_prob"] = model.predict_proba(test[FEATURES])[:, 1]
test = df.loc[test.index]
test.to_csv("test_predictions.csv", index=False)
print(len(train), "training games (2022-23 and 2023-24),", len(test), "test games (2024-25)")
coefs = model.named_steps["logisticregression"].coef_[0]
print(pd.Series(coefs, index=FEATURES).round(3).to_string())
print("intercept (home court, in log-odds):", round(model.named_steps["logisticregression"].intercept_[0], 3))Output
2381 training games (2022-23 and 2023-24), 1230 test games (2024-25)
margin_diff 0.469
rest_diff 0.021
b2b_home -0.079
b2b_away 0.141
elo_diff 0.341
intercept (home court, in log-odds): 0.272The features are standardized, so the sizes compare: recent margin (0.469) and prior rating (0.341) carry the model, and rest adds little. The intercept, 0.272 in log-odds, is the home-court term: with every feature at its training average the home team wins about 57% of the time. On a Mac with NumPy 2.0.2 we also saw RuntimeWarning lines about matmul during the fit; the coefficients and scores above came out finite.
6. Score it against the market, on games neither saw
Two proper scoring rules grade a probability forecast: log loss punishes confident misses hard, and the Brier score is the mean squared error of the probability. Lower is better on both. The market's probability is each book's closing pair with the margin removed proportionally, averaged across books, which is the method get_game_probabilities documents. A constant forecast of the training home-win rate is the floor any model has to clear.
The last two lines resample the games 2,000 times to put an interval on the log loss gap.
import json
import numpy as np
import pandas as pd
from sklearn.metrics import brier_score_loss, log_loss
test = pd.read_csv("test_predictions.csv", dtype={"game_id": str})
train_rate = pd.read_csv("games.csv").query("season <= 2024")["home_win"].mean()
# The market's probability: remove the margin from each book's pair of closing prices,
# then average across books, as get_game_probabilities does.
rows = []
for day_games in json.load(open("odds_2025.json")).values():
for g in day_games:
for b in g["books"]:
if b["home_close_prob"] and b["away_close_prob"]:
rows.append({"game_id": g["game_id"], "fair": b["home_close_prob"] / (b["home_close_prob"] + b["away_close_prob"])})
market = pd.DataFrame(rows).groupby("game_id")["fair"].agg(market_prob="mean", books="size").reset_index()
df = test.merge(market, on="game_id")
df["baseline_prob"] = train_rate
print(len(test), "test games,", len(df), "with closing moneylines; median", int(df["books"].median()), "books each")
def score(col):
return {"log_loss": log_loss(df["home_win"], df[col]), "brier": brier_score_loss(df["home_win"], df[col])}
table = pd.DataFrame({"home-win rate only": score("baseline_prob"), "our model": score("model_prob"), "market (no-vig close)": score("market_prob")}).T
print(table.round(4).to_string())
# How sure are we the gap is real? Resample games and compare per-game log loss.
def per_game(col):
p = df[col].clip(1e-6, 1 - 1e-6)
return -(df["home_win"] * np.log(p) + (1 - df["home_win"]) * np.log(1 - p)).to_numpy()
gap = per_game("model_prob") - per_game("market_prob")
rng = np.random.default_rng(0)
boot = [gap[rng.integers(0, len(gap), len(gap))].mean() for _ in range(2000)]
print("model minus market, log loss: %.4f (95%% interval %.4f to %.4f)" % (gap.mean(), *np.percentile(boot, [2.5, 97.5])))
df.to_csv("scored.csv", index=False)Output
1230 test games, 1230 with closing moneylines; median 8 books each
log_loss brier
home-win rate only 0.6899 0.2484
our model 0.6141 0.2131
market (no-vig close) 0.5811 0.1990
model minus market, log loss: 0.0331 (95% interval 0.0192 to 0.0468)How to read it:
- Against the floor: the model scores 0.6141 log loss against 0.6899 for the constant forecast, so the features carry real information.
- Against the market: the market scores 0.5811. The model is worse by 0.0331 per game, and the 95% interval (0.0192 to 0.0468) does not include zero, so on this season the gap is not noise.
- Why: the closing price is the books' final forecast after injuries, lineups, rest decisions and news, and after bettors have pushed it. Five slow public features cannot see those. Doing better than the closing line is hard, and most models do not manage it; this one does not either.
One held-out season is one draw. Rerun on another season before reading anything into a gap this size.
7. Check the market number against get_game_probabilities
The API computes the same margin-free probability for you with get_game_probabilities. It costs 5 credits a game, which is why the tutorial built the number from the day-level odds instead. This step spends 15 credits to confirm the two agree on three games.
import pandas as pd
from dunkapi import Client
client = Client()
df = pd.read_csv("scored.csv", dtype={"game_id": str})
# get_game_probabilities does the margin removal for you: 5 credits a game. Check three games against ours.
for _, g in df[df["books"] >= 7].sample(3, random_state=1).iterrows():
api = client.get_game_probabilities(g["game_id"])["moneyline"]["home"]["fair_prob"]
print(g["date"], g["away"], "at", g["home"], "| ours:", round(g["market_prob"], 3), "| API fair_prob:", api)Output
2025-03-29 BKN at WSH | ours: 0.544 | API fair_prob: 0.544
2025-03-31 BOS at MEM | ours: 0.388 | API fair_prob: 0.388
2025-01-10 GS at IND | ours: 0.808 | API fair_prob: 0.808The three games match to three decimals, so the number scored in step 6 is the one the API reports as fair_prob. The same call takes snapshot_type="opening" for the opening price.
8. Calibration: do 70% forecasts win 70% of the time?
Log loss mixes two things: whether the probabilities are honest (calibration) and how far from 50% they dare to go (sharpness). This table separates them by grouping the test games into probability bands for each forecaster and comparing the average forecast with how often the home team won.
import pandas as pd
df = pd.read_csv("scored.csv")
edges = [0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0]
out = []
for name, col in (("model", "model_prob"), ("market", "market_prob")):
band = pd.cut(df[col], edges)
t = df.groupby(band, observed=True).agg(games=("home_win", "size"), predicted=(col, "mean"), actual=("home_win", "mean"))
t.index = [f"{name} {i.left:.0%}-{i.right:.0%}" for i in t.index]
out.append(t)
print(pd.concat(out).round(3).to_string())Output
games predicted actual
model 0%-30% 114 0.236 0.202
model 30%-40% 134 0.355 0.343
model 40%-50% 210 0.454 0.410
model 50%-60% 237 0.549 0.540
model 60%-70% 227 0.650 0.648
model 70%-80% 190 0.745 0.726
model 80%-100% 118 0.852 0.856
market 0%-30% 181 0.207 0.199
market 30%-40% 172 0.350 0.337
market 40%-50% 152 0.448 0.434
market 50%-60% 162 0.552 0.580
market 60%-70% 195 0.650 0.595
market 70%-80% 179 0.746 0.765
market 80%-100% 189 0.853 0.857- Model
- Market
- Market average prediction
1,230 games. For each forecaster, games are grouped by the probability it gave the home team. The third line is the market's average prediction in the band, for reference. Bands hold 114 to 237 games each, so a point can sit 3 to 4 points from its true rate by chance.
What the table shows:
- Both are close to honest. The model's largest miss is the 40-50% band (45.4% predicted, 41.0% won, 210 games); the market's is 60-70% (65.0% against 59.5%, 195 games). With 200 games in a band the home win rate has a standard error of about 3.5 points, so misses of 4 to 5 points are close to noise.
- The difference is sharpness. The market gave 181 games under 30% and 189 above 80%, and it was right at those extremes (19.9% and 85.7% home wins). The model put 114 and 118 games there. The market is as honest as the model and says more.
9. Where the model and the market disagree
This is analysis, not a signal. The script takes the gap between the model's and the market's probability for each game, counts the games where they differ by 10 points or more, asks which forecast was closer to the result, and lists the eight largest gaps.
import pandas as pd
df = pd.read_csv("scored.csv")
df["gap"] = df["model_prob"] - df["market_prob"]
print("mean absolute gap: %.3f, largest: %.3f" % (df["gap"].abs().mean(), df["gap"].abs().max()))
big = df[df["gap"].abs() >= 0.10].copy()
model_err = (big["home_win"] - big["model_prob"]).abs()
market_err = (big["home_win"] - big["market_prob"]).abs()
print(len(big), "games where the two differ by 10 points or more;",
"the market was closer to the result in", int((market_err < model_err).sum()),
"and the model in", int((model_err < market_err).sum()))
cols = ["date", "away", "home", "model_prob", "market_prob", "gap", "home_win"]
print(df.reindex(df["gap"].abs().sort_values(ascending=False).index).head(8)[cols].round(3).to_string(index=False))Output
mean absolute gap: 0.091, largest: 0.489
464 games where the two differ by 10 points or more; the market was closer to the result in 311 and the model in 153
date away home model_prob market_prob gap home_win
2025-03-07 MEM DAL 0.701 0.212 0.489 0
2025-04-13 DET MIL 0.699 0.235 0.465 1
2025-03-09 MEM NO 0.623 0.208 0.415 0
2025-04-13 LAL POR 0.262 0.663 -0.400 1
2025-04-11 ATL PHI 0.562 0.167 0.394 0
2025-04-03 MEM MIA 0.727 0.336 0.392 0
2025-03-27 LAL CHI 0.768 0.381 0.386 1
2025-04-08 MEM CHA 0.495 0.123 0.372 0What the output shows:
- How often they differ: 464 of 1,230 games (38%) differ by 10 points or more, and the average gap is 9.1 points.
- Who was closer: in those games the market's probability was closer to the result in 311 (67%) and the model's in 153 (33%). Disagreeing with the market was not, on this season, a sign the model knew something.
- The biggest gaps: all eight are from March and April. In seven of them the market had the visiting team ahead, by 62% to 88%, while the model had the home team ahead in six of those seven and about level in the seventh. Memphis is the visitor in four. Recent margin and last year's rating said one thing and the market's price said another; this tutorial did not check why, and the injury report (see the injury recipe below) is the place to start.
Where to go next. Add pace and efficiency from team box scores, test a spread or total model against the closing line instead of the moneyline, score the opening price as well as the close, and keep a season held out every time you change a feature. If your model scores worse than the closing line, that is the usual result, not a bug.
Tools and credits
- list_games: 21 calls, 42 credits.
- get_ratings: 3 calls, 6 credits.
- get_odds: 163 calls, 1,630 credits (10 credits for every game day: a day's games cost 10, one game costs 5).
- get_game_probabilities: 3 calls, 15 credits.
One full run: 1,693 credits.
What you can do with the data
You may store these rows, train models and backtest on them, and build products that show your users what you derive. You may not redistribute the rows, or the prices as a raw feed, as a dataset or API of its own. Lines and prices are market information. This tutorial forecasts game results and measures the forecast; it does not size, price or recommend a wager.
Details: data timing and rights.
What to do next
Start with 500 free credits every month
No card. pip install dunkapi, REST or MCP.