Guide
NHL expected goals model in Python from shot locations
Short answer: an expected goals model turns each shot's location into a probability of scoring. With PuckAPI's get_shot_map you can fit one from just distance and angle in about forty lines. On 2,148 held-out 5v5 attempts it scored a log loss of 0.2152 and an AUC of 0.710, against 0.2302 for a constant goal rate.
This guide is deliberately the small version. The earlier guide on NHL expected goals feature engineering adds shot type, strength and rebound flags. Here the goal is the plainest model that works, an honest test of it, and a clear view of where it breaks. None of this is advice about wagering. It is a modelling exercise.
This guide builds the location-only baseline. For richer inputs (rebounds, rush shots, shot type and game state), see NHL expected goals: feature engineering.
What a location-only model is
Every shot attempt has a place on the ice. Shots from the slot go in far more often than shots from the blue line, and shots from a sharp angle go in less often than shots from straight on. A location-only xG model captures exactly that and nothing else. It sees the point where the puck was released. It does not see who passed it, how many defenders stood in the lane, whether a goalie was moving, or whether the attempt was a rebound.
That narrow view is the point of building it first. A location model is easy to explain, fast to fit and hard to overfit with a few thousand shots. It also sets a floor. If a richer model cannot beat it on held-out games, the extra features are not earning their place.
Step 1: pull the shots
get_shot_map returns every shot attempt with x_coord, y_coord, type, shot_type, strength, team, shooter and goalie. A page holds up to 2,000 attempts and costs 10 credits. With a season and a team it follows next_offset until the season ends. There is no xG column, so the target is simply whether the attempt was a goal.
The script below pulls three clubs for the 2025-26 regular season: Toronto, Boston and Colorado. Set PUCKAPI_API_KEY first. It backs off on HTTP 429, which one of our runs needed in a different guide, so the retry is cheap insurance. Nine calls returned 14,824 attempts: 6,326 shots on goal, 3,932 blocked, 3,748 missed and 818 goals. That cost 90 credits.
import json, os, time, urllib.error, urllib.request
import pandas as pd
KEY = os.environ["PUCKAPI_API_KEY"]
def post(tool, body):
req = urllib.request.Request(f"https://mcp.puckapi.com/v1/{tool}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "x-api-key": KEY})
for wait in (2, 5, 10, 20):
try:
with urllib.request.urlopen(req, timeout=90) as r:
return json.load(r)["data"]
except urllib.error.HTTPError as e:
if e.code != 429:
raise
time.sleep(wait)
rows = []
for team in ["TOR", "BOS", "COL"]: # three clubs, 2025-26 regular season
offset = 0
while offset is not None:
page = post("get_shot_map", {"season": "20252026", "team": team, "limit": 2000, "offset": offset})
rows += page["shots"]
offset = page.get("next_offset")
shots = pd.DataFrame(rows)
shots.to_csv("nhl_shots.csv", index=False)
print(len(shots), "attempts;", shots.type.value_counts().to_dict())The coordinates are the rink frame. The x axis runs from -100 to 100 along the length and y runs from -42 to 42 across it. The response note says the attacking end flips between periods. The goal lines sit near 89 feet from centre ice, and the goal itself is at y = 0.
If you want to confirm the frame on one event, get_plays returns the same coordinates for the same moment. For game 2025020004, the Toronto goal at 1:00 of the first period is a tip-in at x = -71, y = 2 in get_plays, and the matching row in get_shot_map carries the same pair. Because get_plays also reports zone and the home team's defending side, it is the better tool when you need to resolve direction exactly. For a location model that only needs a distance, folding the ends together is enough.
Step 2: clean the data and build two features
Three decisions shape the training set.
Drop blocked shots. A blocked attempt is recorded where the shooter released it, but it never reached the net and so cannot score. Standard practice is to model unblocked attempts. That leaves shots on goal, misses and goals.
Keep one game state. The model below uses 5v5 only. Power plays, empty-net situations and three-on-three change the chance of any given shot, and mixing them in would blur a location-only model. An empty-net shot from 80 feet scores at a rate no distance feature can explain. After the filters, 8,500 attempts remain.
Fold the rink. Take the absolute value of x, then measure from the goal line at 89 feet. Distance is the straight line to the goal centre. Angle is the angle off the centre line, in degrees, where 0 means straight on and 90 means level with the goal line.
The split is by time, not at random. Within each team, the earliest 75 percent of games train the model and the final 25 percent test it. A random split of shots would let the model see other shots from the same game, which flatters it. Splitting by game, in date order, is the version that matches how a model is used: fit on the past, score the future.
Step 3: fit three models and a lookup table
The next script reads the saved CSV, builds the features and fits four things on the training games.
- A constant rate, the average goal rate, which is the floor every model must beat.
- Logistic regression on distance alone.
- Logistic regression on distance and angle.
- A lookup table, with ten-foot distance bands by fifteen-degree angle bands, each cell's goal rate shrunk toward the overall rate with a prior worth 40 shots. The shrinkage keeps thin cells from producing a rate of zero or one.
import warnings
warnings.filterwarnings("ignore")
import numpy as np, pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, roc_auc_score
df = pd.read_csv("nhl_shots.csv")
df = df[(df.strength == "5v5") & (df.type != "blocked-shot")].copy() # unblocked 5v5 attempts
df["goal"] = (df.type == "goal").astype(int)
# The attacking end flips each period, so fold both ends onto one goal at x = 89.
df["dx"] = 89 - df.x_coord.abs()
df["dist"] = np.hypot(df.dx, df.y_coord)
df["angle"] = np.degrees(np.arctan2(df.y_coord.abs(), df.dx.clip(lower=0.5))) # 0 = straight on
df = df[df.dist < 90]
# Time split by game: earliest 75 percent of each team's games train, the rest test.
df = df.sort_values(["team", "game_id"])
rank = df.groupby("team").game_id.rank(method="dense")
cut = df.groupby("team").game_id.transform(lambda s: s.nunique()) * 0.75
train, test = df[rank <= cut], df[rank > cut]
print(len(train), len(test), "goal rate", round(train.goal.mean(), 4), round(test.goal.mean(), 4))
def fit(cols):
m = LogisticRegression(C=10, max_iter=1000).fit(train[cols], train.goal)
return m, m.predict_proba(test[cols])[:, 1]
base = np.full(len(test), train.goal.mean())
m1, p1 = fit(["dist"])
m2, p2 = fit(["dist", "angle"])
# Lookup-table model: 10 ft distance bands by 15 degree angle bands, shrunk toward the overall rate.
def band(d):
return pd.DataFrame({"d": (d.dist // 10).clip(upper=7), "a": (d.angle // 15).clip(upper=5)})
tb = band(train).assign(goal=train.goal.values)
cell = tb.groupby(["d", "a"]).goal.agg(["sum", "count"])
k, mu = 40, train.goal.mean() # prior worth 40 shots
cell["rate"] = (cell["sum"] + k * mu) / (cell["count"] + k)
tt = band(test)
p3 = tt.join(cell["rate"], on=["d", "a"])["rate"].fillna(mu).values
print(f"{'model':<22}{'log loss':>9}{'AUC':>7}")
for name, p in [("constant rate", base), ("distance", p1), ("distance + angle", p2), ("lookup table", p3)]:
auc = roc_auc_score(test.goal, p) if name != "constant rate" else 0.5
print(f"{name:<22}{log_loss(test.goal, p):>9.4f}{auc:>7.3f}")
# Calibration of the distance + angle model on the test set.
test = test.assign(xg=p2)
test["bin"] = pd.cut(test.xg, [0, .03, .06, .10, .15, 1])
print(test.groupby("bin", observed=True).agg(shots=("goal", "size"), mean_xg=("xg", "mean"), goal_rate=("goal", "mean")).round(3))
# Team totals on the test set.
print(test.groupby("team").agg(shots=("goal", "size"), goals=("goal", "sum"), xg=("xg", "sum")).round(1))
print("coef", m2.coef_.round(4), m2.intercept_.round(3))
for dist, ang in [(10, 0), (10, 45), (30, 0), (50, 20)]:
print(dist, ang, round(m2.predict_proba(pd.DataFrame([[dist, ang]], columns=["dist", "angle"]))[0, 1], 3))The training set holds 6,352 attempts with a 6.94 percent goal rate. The test set holds 2,148 with a 6.10 percent rate. Rates move between periods of a season, and a held-out set reflects that.
What the numbers say
| Model | Log loss | AUC |
|---|---|---|
| Constant rate | 0.2302 | 0.500 |
| Distance only | 0.2165 | 0.694 |
| Distance and angle | 0.2152 | 0.710 |
| Lookup table | 0.2150 | 0.708 |
Distance does most of the work. Adding angle improves log loss by about 0.0013, a small gain that still shows up in the AUC. The lookup table, which assumes nothing about the shape of the relationship, lands at the same place as the logistic regression. That agreement is reassuring. It suggests the smooth model is not hiding structure, and that a location-only ceiling sits near 0.215 on this much data.
The fitted coefficients explain the shape. Each extra foot of distance cuts the log odds by 0.0435, and each extra degree of angle cuts them by 0.0134. The intercept is -0.933. In plain terms the model gives a shot from 10 feet, straight on, a 20.3 percent chance. The same shot from a 45 degree angle drops to 12.3 percent. From 30 feet straight on it is 9.6 percent, and from 50 feet at 20 degrees it is 3.3 percent.
Check calibration, not only the totals
A good log loss can hide a model that is wrong in one corner. Group the test shots by predicted probability and compare the mean forecast with the actual goal rate.
| Predicted range | Shots | Mean xG | Goal rate |
|---|---|---|---|
| Up to 0.03 | 569 | 0.020 | 0.014 |
| 0.03 to 0.06 | 616 | 0.044 | 0.036 |
| 0.06 to 0.10 | 406 | 0.078 | 0.086 |
| 0.10 to 0.15 | 324 | 0.122 | 0.127 |
| Above 0.15 | 233 | 0.180 | 0.107 |
The model is close in the middle and too generous at both ends. The top bin is the clear problem: 233 shots forecast at 0.180 went in 10.7 percent of the time. With 233 shots the standard error is about 0.02, so a gap of 0.07 is not noise. The cause is the straight-line link between distance and log odds. Real shots from the doorstep include tips and scrambles at close range that are hard to convert. A model that only sees location cannot tell a tip from a clean look, and it averages them.
Team totals on the test games show the same mild over-prediction: Boston 49.9 expected against 48 scored, Colorado 59.9 against 45, Toronto 42.2 against 38. With 38 to 48 goals per team in the sample, those gaps are within what a single team's finishing luck can produce. They are not evidence about any club.
Using the model
Once fitted, scoring a new shot is a single call, m2.predict_proba, with a distance and an angle. Sum the probabilities over a game or a season for a team's expected goals. Because the model has no information about defenders or passes, treat team totals as a description of shot quality by location, not a forecast of results.
Two upgrades are worth trying in order. First, add the shot type and the rebound flag, as the feature engineering guide does, and check that the held-out log loss improves. Second, fit on more clubs. Three clubs gave 8,500 usable attempts. All 32 would take roughly 80 pages and 800 credits, and the top-bin calibration would tighten considerably.
Limits
- Three clubs, one season. The sample is 14,824 attempts, 8,500 of them 5v5 and unblocked. The held-out set is 2,148 shots. Results on other clubs or seasons will differ.
- Location only. No passes, screens, goalie position, rebounds or rush context. The model's AUC of 0.710 is what location alone can do.
- Folding the rink assumes shooters attack the near goal. A long shot from a team's own end gets measured as if it were at the opposite goal's distance. It is rare, and
get_playswith the home team's defending side resolves it when it matters. - Over-confident near the crease. The top calibration bin is off by 0.07. Fix it with shot-type features or a monotone model, not by trusting the output.
- Block rates differ by team. Dropping blocked attempts removes information about shot suppression. Models of defence need them.
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.