Build an NHL expected goals model in Python from shot coordinates
Pull NHL shot coordinates from the API, fit a logistic regression for xG, test it on the next season, then work out goals saved above expected (GSAx) for goalies.
Every script run against the live API on December 4, 2026. One full run: 1,208 credits.
An expected goals (xG) model gives every shot a probability of scoring from where and how it was taken. This tutorial builds one from the shot coordinates in the PuckAPI shot data API: it pulls two seasons of NHL shot attempts, builds distance, angle, shot type, rebound and strength features, fits a logistic regression on 2023-24 and scores it on 2024-25, a season the model never saw, with log loss, AUC and a calibration table.
Then it turns the model into goals saved above expected (GSAx) for every goalie, the number behind most goalie rankings: the xG of the shots a goalie faced minus the goals he allowed. You will compare both the team and goalie results with the expected goals the API serves.
The model trains on 8 teams' 2023-24 shots and tests on all 32 teams' 2024-25 shots: 111,304 unblocked attempts in 1,312 games. One full run costs 1,208 credits: 1 for the team list, 1,200 for 120 shot map calls (24 for the training season, 96 for the test season), 2 for the standings and 5 for the goalie leaderboard. The 500 free credits do not cover all of it. They cover 49 shot map calls, which is about 16 team-seasons at the 3 calls a team seen here. To run the whole tutorial on them, cut both team lists to 8 teams, for example TEAMS[:8] (about 48 calls, 480 credits); the team, standings and goalie checks still run, but the goalie numbers then cover only the shots those teams took, so ignore the comparison with the served GSAx.
1. Install the client and set your key
The client has no required dependencies. This tutorial uses pandas and scikit-learn for the model and matplotlib for the charts. It needs Python 3.9 or newer, and the client reads your key from PUCKAPI_API_KEY.
pip install "puckapi[pandas]" scikit-learn matplotlib
export PUCKAPI_API_KEY=your_key_here2. Pull two seasons of shots
get_shot_map is the cheapest route that is also correct for this job. It returns shot attempts only, up to 2,000 a page. get_plays returns every event type, at most 1,000 a page: the 156,114 attempts of the test season would take at least 157 calls and 1,570 credits there, against 96 calls and 960 credits here. Use get_plays when you need the other events, such as penalties or faceoffs.
The shot map needs a team or a player with the season, because a whole league's season is not one map, so the script loops over the 32 teams and follows next_offset until it is empty. A team's rows are that team's own attempts, so no shot is counted twice. The script waits 1.1 seconds between calls to stay under the 60 requests a minute limit.
For the test season it takes all 32 teams. For the training season it takes 8 (BOS, CAR, COL, EDM, NYR, TBL, TOR and VGK): 24 calls, 240 credits, where all 32 teams would cost about what the test season did, 960. The training pull is 41,477 attempts.
import time
import pandas as pd
from puckapi import Client, to_dataframe
client = Client() # reads PUCKAPI_API_KEY
TEAMS = [t["abbrev"] for t in client.list_teams()["teams"]]
TRAIN_TEAMS = ["BOS", "CAR", "COL", "EDM", "NYR", "TBL", "TOR", "VGK"]
start = client.last_credits_remaining + client.last_credits_used # the balance before the team list call
def pull(season, teams):
frames, calls = [], 0
for team in teams:
offset = 0
while offset is not None:
page = client.get_shot_map(season=season, team=team, limit=2000, offset=offset)
frames.append(to_dataframe(page, key="shots"))
offset = page["next_offset"]
calls += 1
time.sleep(1.1) # the limit is 60 requests a minute
return pd.concat(frames, ignore_index=True), calls
train, n1 = pull("20232024", TRAIN_TEAMS)
test, n2 = pull("20242025", TEAMS)
train.to_csv("shots_train_2023_24.csv", index=False)
test.to_csv("shots_test_2024_25.csv", index=False)
print("train:", len(train), "attempts from", n1, "calls;", "test:", len(test), "attempts from", n2, "calls")
print("credits spent:", start - client.last_credits_remaining, "left:", client.last_credits_remaining)Output
train: 41477 attempts from 24 calls; test: 156114 attempts from 96 calls
credits spent: 1201 left: 1173| Column | Meaning |
|---|---|
| type | goal, shot-on-goal, missed-shot or blocked-shot |
| x_coord, y_coord | Rink coordinates in feet: x from -100 to 100 along the length, y from -42 to 42 across; the nets are near x = 89 and x = -89 |
| shot_type | wrist, snap, slap, backhand, tip-in, deflected and a few rare types; empty on blocked attempts |
| strength | Skaters a side from the shooter's view, such as 5v5 or 5v4 |
| team, shooter, goalie | The shooting team, the shooter's player id and the goalie in net (empty on blocked attempts and empty nets) |
| game_id, period, seconds_elapsed | The game, the period and seconds since the start of the game |
credits spent counts from the balance before the team list call: 1 credit for the list and 1,200 for the 120 shot map calls. The balance on the last line is the key that ran it; yours will differ. The two files are written to disk, so the later steps cost nothing.
3. Build features: distance, angle, shot type, rebound and strength
The script turns the raw rows into model features:
- Rebound. The team's previous attempt was a shot on goal 3 seconds or less earlier. It is worked out before blocked attempts are dropped.
- Unblocked attempts at a goalie. Goals, shots on goal and misses stay. Blocked attempts are dropped, and so are empty-net attempts, which are a different kind of shot.
- Distance and angle. The shot map does not say which way a team is attacking, so each attempt is turned to face the net at x = +89 using the side of the rink that team's own attempts came from in that game and period. Distance is in feet to the net's centre, and angle is degrees off the line straight out from it.
- Strength.
5v5,power_play,short_handed,extra_attacker(a team with six skaters) andeven_other(4v4 and 3v3). - Shot type. The seven common types, with the rest in
other.
import numpy as np
import pandas as pd
def build_features(path):
shots = pd.read_csv(path, dtype={"game_id": str})
shots = shots.sort_values(["game_id", "team", "seconds_elapsed"], kind="stable").reset_index(drop=True)
# Rebound: the team's previous attempt was a shot on goal 3 seconds or less earlier.
prev = shots.groupby(["game_id", "team"])
gap = shots["seconds_elapsed"] - prev["seconds_elapsed"].shift()
shots["rebound"] = ((gap <= 3) & (prev["type"].shift() == "shot-on-goal")).astype(int)
# Unblocked attempts at a goalie in net: goals, shots on goal and misses.
shots = shots[shots["type"].isin(["goal", "shot-on-goal", "missed-shot"]) & shots["goalie"].notna()].copy()
shots["goal"] = (shots["type"] == "goal").astype(int)
# Teams swap ends each period. Face every attempt toward the net at x = +89 by the side
# of the rink the team's own attempts came from in that game and period.
side = np.sign(shots.groupby(["game_id", "team", "period"])["x_coord"].transform("median"))
dx = 89 - shots["x_coord"] * side.replace(0, 1)
shots["distance"] = np.hypot(dx, shots["y_coord"])
shots["angle"] = np.degrees(np.arctan2(shots["y_coord"].abs(), dx))
# Strength is "own skaters v opposing skaters" from the shooting team's side.
own, opp = shots["strength"].str.split("v", expand=True).astype(int).T.values
shots["state"] = np.select(
[(own == 5) & (opp == 5), own == opp, own == 6, own > opp],
["5v5", "even_other", "extra_attacker", "power_play"],
default="short_handed",
)
common = ["wrist", "snap", "slap", "backhand", "tip-in", "deflected", "wrap-around"]
shots["shot_type"] = shots["shot_type"].where(shots["shot_type"].isin(common), "other")
return shots
train = build_features("shots_train_2023_24.csv")
test = build_features("shots_test_2024_25.csv")
train.to_csv("features_train.csv", index=False)
test.to_csv("features_test.csv", index=False)
for name, df in (("train 2023-24", train), ("test 2024-25", test)):
print(f"{name}: {len(df)} unblocked attempts, {df['goal'].sum()} goals, goal rate {df['goal'].mean():.4f}")
print(test.groupby(pd.cut(test["distance"], [0, 10, 20, 30, 45, 60, 200]), observed=True)["goal"].agg(["size", "mean"]).round(3).to_string())
print(test.groupby("rebound")["goal"].agg(["size", "mean"]).round(3).to_string())
print(test.groupby("state")["goal"].agg(["size", "mean"]).round(3).to_string())Output
train 2023-24: 29727 unblocked attempts, 2125 goals, goal rate 0.0715
test 2024-25: 111304 unblocked attempts, 7377 goals, goal rate 0.0663
size mean
distance
(0, 10] 14351 0.139
(10, 20] 18192 0.108
(20, 30] 17069 0.089
(30, 45] 28331 0.049
(45, 60] 19109 0.020
(60, 200] 14250 0.009
size mean
rebound
0 104582 0.063
1 6722 0.118
size mean
state
5v5 89180 0.059
even_other 2281 0.110
extra_attacker 2776 0.077
power_play 14651 0.103
short_handed 2416 0.074Before any model, the 2024-25 table already shows the shape of the problem: the goal rate falls from 13.9% for attempts within 10 feet to 0.9% beyond 60. Rebounds score at 11.8% against 6.3% for other attempts, and a power play attempt scores at 10.3% against 5.9% at 5v5.
The training season's goal rate (7.15%) is higher than the test season's (6.63%). That is the usual trouble with a held-out season: the game moves, and a model fit on one year meets another.
4. Fit the model on 2023-24, score it on 2024-25
The model is a logistic regression on distance, angle, the rebound flag, and one column per shot type and strength state. Every test shot is from a season the model never saw. Two simpler forecasts set the bar: the training season's goal rate for every shot, and a model that sees distance alone.
Log loss punishes confident misses and lower is better. AUC is the chance the model gives a goal a higher xG than a non-goal, where 0.5 is a coin flip.
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, roc_auc_score
train = pd.read_csv("features_train.csv")
test = pd.read_csv("features_test.csv")
def design(df):
return pd.concat([
df[["distance", "angle", "rebound"]],
pd.get_dummies(df["shot_type"], dtype=float),
pd.get_dummies(df["state"], dtype=float),
], axis=1)
X_train = design(train)
X_test = design(test).reindex(columns=X_train.columns, fill_value=0)
model = LogisticRegression(max_iter=2000).fit(X_train, train["goal"])
test["xg"] = model.predict_proba(X_test)[:, 1]
test.to_csv("xg_test.csv", index=False)
# Two things to beat: the goal rate of the training season, and distance alone.
dist_only = LogisticRegression().fit(train[["distance"]], train["goal"])
scores = {
"training goal rate": [train["goal"].mean()] * len(test),
"distance only": dist_only.predict_proba(test[["distance"]])[:, 1],
"full model": test["xg"],
}
rows = {name: {"log_loss": log_loss(test["goal"], p), "auc": roc_auc_score(test["goal"], p)} for name, p in scores.items()}
print(pd.DataFrame(rows).T.round(4).to_string())
print("test goals:", int(test["goal"].sum()), "| sum of xG:", round(test["xg"].sum(), 1))Output
log_loss auc
training goal rate 0.2441 0.5000
distance only 0.2264 0.7083
full model 0.2190 0.7519
test goals: 7377 | sum of xG: 7759.8- Against the bar: the full model scores 0.2190 log loss, against 0.2441 for the constant forecast and 0.2264 for distance alone. Angle, rebounds, shot type and strength add real information on top of distance, and the AUC rises from 0.708 to 0.752.
- In total: the model expects 7,759.8 goals and 7,377 were scored, so it runs about 5% high on this season. That is the 2023-24 goal rate showing through.
- What it cannot see: defenders, screens, the pass before the shot and the shooter's skill. An AUC of 0.752 is a modest model, which is what a location-and-type model is.
5. Check calibration
A model is calibrated when shots it gives a 10% chance score about 10% of the time. This groups the test attempts into seven bands of xG and compares each band's average xG with the share that scored. The chart plots the same table; the dashed line is perfect calibration.
import pandas as pd
import matplotlib.pyplot as plt
test = pd.read_csv("xg_test.csv")
bands = pd.cut(test["xg"], [0, 0.02, 0.04, 0.06, 0.10, 0.15, 0.25, 1])
cal = test.groupby(bands, observed=True).agg(shots=("goal", "size"), mean_xg=("xg", "mean"), goal_rate=("goal", "mean"))
print(cal.round(3).to_string())
ax = cal.plot(x="mean_xg", y="goal_rate", marker="o", figsize=(5, 5), legend=False)
ax.plot([0, 0.32], [0, 0.32], linestyle="--", color="grey")
ax.set_xlabel("Average xG in the band")
ax.set_ylabel("Share that scored")
plt.tight_layout()
plt.savefig("xg_calibration.png", dpi=150)Output
shots mean_xg goal_rate
xg
(0.0, 0.02] 25563 0.011 0.010
(0.02, 0.04] 21167 0.029 0.024
(0.04, 0.06] 16587 0.050 0.051
(0.06, 0.1] 22023 0.078 0.080
(0.1, 0.15] 13523 0.122 0.126
(0.15, 0.25] 9594 0.189 0.181
(0.25, 1.0] 2847 0.306 0.205- Average xG
- Share that scored
111,304 unblocked attempts, from the table above. A band on the diagonal is calibrated: the average xG equals the share that scored.
- Most of the range is close. The three middle bands (4% to 15%, 52,133 attempts) are within half a point of their average xG.
- The top band is not. The 2,847 closest, most central attempts were given an average 30.6% and 20.5% scored. A straight line in log-odds cannot bend where the goal rate flattens near the net. Distance bands, an interaction between distance and angle, or a gradient-boosted model are the places to go next; this tutorial does not test them.
- The bottom bands run a little high, in line with the 5% overall miss.
6. Compare with the expected goals the API serves
The NHL shot map has no xG column, so there is no value per shot to compare. The API does serve expected goals for teams and goalies. get_standings returns each team's 5v5 expected goals for and against, which is the first comparison: our 5v5 xG summed by team, and by the team across the ice, against the served numbers. It costs 2 credits.
import pandas as pd
from puckapi import Client, to_dataframe
client = Client() # reads PUCKAPI_API_KEY
test = pd.read_csv("xg_test.csv", dtype={"game_id": str})
# Our 5v5 xG for and against, by team: sum the model's xG over each team's 5v5 attempts.
five = test[test["state"] == "5v5"]
ours = five.groupby(["game_id", "team"])["xg"].sum().rename("xgf").reset_index()
ours["xga"] = ours.groupby("game_id")["xgf"].transform("sum") - ours["xgf"] # the other team's xG in the game
ours = ours.groupby("team")[["xgf", "xga"]].sum()
# The API serves its own 5v5 expected goals for and against in the standings.
served = to_dataframe(client.get_standings(season="20242025"), key="standings").set_index("teamAbbrev")
both = ours.join(served[["expectedGoalsFor", "expectedGoalsAgainst"]])
print(len(both), "teams")
print("xG for: correlation %.3f, ours %.1f a team, served %.1f" % (both["xgf"].corr(both["expectedGoalsFor"]), both["xgf"].mean(), both["expectedGoalsFor"].mean()))
print("xG against: correlation %.3f, ours %.1f a team, served %.1f" % (both["xga"].corr(both["expectedGoalsAgainst"]), both["xga"].mean(), both["expectedGoalsAgainst"].mean()))
print("credits left:", client.last_credits_remaining)Output
32 teams
xG for: correlation 0.975, ours 169.7 a team, served 163.3
xG against: correlation 0.970, ours 169.7 a team, served 163.3
credits left: 1147The 32 teams line up closely: the correlation is 0.975 for expected goals for and 0.970 against. The levels differ. Our teams average 169.7 and the served ones 163.3, about 4% lower than ours, which is close to the 5% by which our model ran high on this season. Both averages are the same for and against in our numbers because every shot is one team's for and the other's against.
7. Goals saved above expected for every goalie
A goalie only faces shots on goal, so the model for GSAx is refit on goals and saves alone. It now answers the question a goalie cares about: of the shots that reach the net, how likely is this one to score? A goalie's GSAx is the xG of the shots he faced minus the goals he allowed, and a positive number means he stopped more than the average goalie would have behind the same shots.
get_goalie_stats with sort_by="gsax" returns the API's own goalie GSAx, the second comparison. min_games=40 returns the 30 goalies with 40 or more games in 2024-25, which fits one call of up to 50. It costs 5 credits.
import pandas as pd
from puckapi import Client, to_dataframe
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, roc_auc_score
train = pd.read_csv("features_train.csv")
test = pd.read_csv("features_test.csv")
def design(df):
return pd.concat([
df[["distance", "angle", "rebound"]],
pd.get_dummies(df["shot_type"], dtype=float),
pd.get_dummies(df["state"], dtype=float),
], axis=1)
# A goalie only faces shots on goal, so refit the same features on goals and saves alone:
# the model now answers "of the shots that reach the net, how likely is this one to score?"
train_on = train[train["type"].isin(["goal", "shot-on-goal"])]
faced = test[test["type"].isin(["goal", "shot-on-goal"])].copy()
X_train = design(train_on)
model = LogisticRegression(max_iter=2000).fit(X_train, train_on["goal"])
faced["xg"] = model.predict_proba(design(faced).reindex(columns=X_train.columns, fill_value=0))[:, 1]
print(f"{len(faced)} shots on goal, {faced['goal'].sum()} goals, xG {faced['xg'].sum():.1f}")
print(f"log loss {log_loss(faced['goal'], faced['xg']):.4f} (constant {log_loss(faced['goal'], [train_on['goal'].mean()] * len(faced)):.4f}), AUC {roc_auc_score(faced['goal'], faced['xg']):.3f}")
# Per goalie: the shots he faced, the goals he allowed and the xG of those shots.
by_goalie = faced.groupby("goalie").agg(shots=("goal", "size"), goals=("goal", "sum"), xg=("xg", "sum"))
client = Client()
served = to_dataframe(client.get_goalie_stats(season="20242025", min_games=40, sort_by="gsax", limit=50), key="goalies")
table = served.set_index("playerId").join(by_goalie, how="inner")
table = table.rename(columns={"playerName": "goalie", "gsax": "served_gsax"})
# Goals saved above expected (GSAx) = the xG of the shots he faced minus the goals he allowed.
table["our_gsax"] = table["xg"] - table["goals"]
table.to_csv("gsax_2024_25.csv")
print(len(served), "goalies with 40+ games;", len(table), "matched to shots")
print(table.sort_values("our_gsax", ascending=False).head(10)[["goalie", "team", "gamesPlayed", "shots", "goals", "xg", "our_gsax", "served_gsax"]].round(1).to_string(index=False))
print("correlation %.3f, rank correlation %.3f, average gap %.1f goals" % (
table["our_gsax"].corr(table["served_gsax"]),
table["our_gsax"].corr(table["served_gsax"], method="spearman"),
(table["our_gsax"] - table["served_gsax"]).abs().mean(),
))
top_ours = set(table.nlargest(10, "our_gsax")["goalie"])
top_served = set(table.nlargest(10, "served_gsax")["goalie"])
print(len(top_ours & top_served), "of the top 10 are the same goalies in both lists")
gap = (table["our_gsax"] - table["served_gsax"]).abs()
widest = table.loc[gap.idxmax()]
print("widest gap: %s, ours %.1f, served %.1f" % (widest["goalie"], widest["our_gsax"], widest["served_gsax"]))
print("credits left:", client.last_credits_remaining)Output
73692 shots on goal, 7377 goals, xG 7472.0
log loss 0.2905 (constant 0.3254), AUC 0.746
30 goalies with 40+ games; 30 matched to shots
goalie team gamesPlayed shots goals xg our_gsax served_gsax
Andrei Vasilevskiy TBL 63 1717 136 168.4 32.4 23.7
Connor Hellebuyck WPG 63 1664 125 155.0 30.0 38.8
Samuel Montembeault MTL 62 1679 166 195.8 29.8 19.4
Darcy Kuemper LAK 50 1268 100 129.4 29.4 25.4
Igor Shesterkin NYR 61 1751 167 191.6 24.6 19.9
Logan Thompson WSH 43 1172 105 128.9 23.9 21.5
Karel Vejmelka UTA 58 1509 145 168.7 23.7 9.5
Mackenzie Blackwood COL 56 1550 137 156.8 19.8 17.8
Dustin Wolf CGY 53 1549 140 158.8 18.8 14.2
Lukas Dostal ANA 54 1625 158 173.8 15.8 14.5
correlation 0.938, rank correlation 0.946, average gap 4.4 goals
9 of the top 10 are the same goalies in both lists
widest gap: Karel Vejmelka, ours 23.7, served 9.5
credits left: 1137- The model: on the 73,692 shots on goal it scores 0.2905 log loss against 0.3254 for the constant forecast and 0.746 AUC, and it expects 7,472.0 goals against 7,377 scored.
- The two GSAx lists agree. The correlation is 0.938, the rank correlation 0.946, and 9 of the top 10 goalies are the same in both. The average gap is 4.4 goals.
- They are not the same number. Vasilevskiy is first on ours and third on the served list; Hellebuyck is first there. The widest gap is Karel Vejmelka at 23.7 against 9.5. Two models of shot quality built on location and shot type will disagree about a goalie at the margin, so quote a GSAx with the model that produced it.
8. Plot the top goalies
The bars put the two measures side by side for our top 10, and the script lists the three goalies with the lowest GSAx on our model.
import pandas as pd
import matplotlib.pyplot as plt
table = pd.read_csv("gsax_2024_25.csv")
top = table.sort_values("our_gsax", ascending=False).head(10)
ax = top.plot.barh(x="goalie", y=["our_gsax", "served_gsax"], figsize=(8, 5))
ax.invert_yaxis()
ax.set_xlabel("Goals saved above expected, 2024-25")
plt.tight_layout()
plt.savefig("gsax_top10.png", dpi=150)
worst = table.sort_values("our_gsax").head(3)
print(worst[["goalie", "team", "shots", "goals", "xg", "our_gsax", "served_gsax"]].round(1).to_string(index=False))Output
goalie team shots goals xg our_gsax served_gsax
Samuel Ersson PHI 1162 136 114.9 -21.1 -23.8
Ukko-Pekka Luukkonen BUF 1490 169 148.6 -20.4 -16.2
Alexandar Georgiev SJS 1317 165 147.4 -17.6 -24.5- Our GSAx
- Served GSAx
Our GSAx from the model above and the GSAx served by get_goalie_stats, for goalies with 40 or more games.
Where to go next. Train on all 32 teams, or on two seasons, and test on a third. Add the previous event (a rush, a pass across the middle) from get_plays, and score by shooter to see who finishes above the model. Keep a season held out every time you change a feature, and read a goalie's GSAx as one season's evidence: the goalies in the table faced about 1,200 to 1,750 shots each, and team defense and luck move it. To score one game, get_shot_map takes a game_id, and the recipes below cover the shot map, the goalie leaderboard and play-by-play one call at a time.
Tools and credits
- list_teams: 1 call, 1 credit.
- get_shot_map: 120 calls, 1,200 credits (24 calls for 8 teams in the training season, 96 for 32 teams in the test season; each team's season took 3 pages of up to 2,000 attempts).
- get_standings: 1 call, 2 credits.
- get_goalie_stats: 1 call, 5 credits.
One full run: 1,208 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 as a dataset or API of its own. xG from a model you fit is your estimate, not a record of what happened.
Details: data timing and rights.
What to do next
Start with 500 free credits every month
No card. pip install puckapi, REST or MCP.