Guide

NHL expected goals: feature engineering from shot data

Short answer: an expected goals model gives each shot a probability of scoring. With PuckAPI's get_shot_map you can build one from distance, angle, shot type, strength and a rebound flag, then fit a logistic regression. On 57,310 attempts it reached AUC 0.750 and log loss 0.2331 against 0.2610 for the baseline.

What the data gives you, and what it does not

get_shot_map returns every shot attempt with rink coordinates, shot type, strength, shooter and goalie. A page holds up to 2,000 shots and costs 10 credits, and next_offset points to the next page. One team's 2025-26 regular season came back as three pages (2,000, 2,000 and 356 shots) on December 6, 2026.

Each row looks like this:

{"type": "shot-on-goal", "x_coord": -55, "y_coord": 4, "shot_type": "wrist",
 "strength": "5v5", "team": "TOR", "shooter": 8476931, "goalie": 8478470,
 "game_id": "2025020004", "period": 1, "seconds_elapsed": 27}

There is no per-shot xG field. PuckAPI exposes team-level expected goals in get_standings, and shot-level location, type and strength in get_shot_map, and that is all. The value you want is a model, and this guide builds it. Three facts about the coordinates matter. The frame is the rink: x runs from -100 to 100 along the length and y from -42 to 42 across. The attacking end flips between periods. The goal lines sit at x = plus or minus 89 feet.

The public repo sports-data-hq/nhl-xg-model holds a small runnable version of the pipeline below. It is MIT licensed.

Step 1: pull the shots

This script follows next_offset to the end of a team's season and writes a CSV. Set PUCKAPI_API_KEY first. A free key has 500 credits a month, enough for about 16 pages.

import json, os, urllib.request, pandas as pd

KEY = os.environ["PUCKAPI_API_KEY"]
URL = "https://mcp.puckapi.com/v1/get_shot_map"

def post(body):
    req = urllib.request.Request(URL, data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json", "x-api-key": KEY})
    with urllib.request.urlopen(req, timeout=60) as r:
        return r.status, json.load(r)["data"]

rows, offset = [], 0
while offset is not None:
    status, page = post({"season": "20252026", "team": "TOR", "limit": 2000, "offset": offset})
    print("HTTP", status, "rows", len(page["shots"]), "next_offset", page.get("next_offset"))
    rows += page["shots"]
    offset = page.get("next_offset")
pd.DataFrame(rows).to_csv("tor.csv", index=False)
print(len(rows))

It printed three HTTP 200 pages and 4,356 rows, of which 3,274 were unblocked attempts.

Step 2: build features

Start with the features that carry most of the signal and cost nothing to compute.

Distance and angle. Mirror every shot onto one end of the rink by taking the absolute value of x. Distance is the straight line from the shot to the goal center, and angle is how far off the goal line's axis the shot is. Close, central shots score far more often than long, wide ones.

Shot type and strength. Wrist, slap, snap, tip-in, backhand and wrap-around shots convert at different rates. Strength (5v5, 5v4, 4v5) captures power-play and penalty-kill context. Encode both as dummy columns.

Rebound and quick follow-up. A shot taken within three seconds of a previous attempt from close range is a rebound, and rebounds convert more often. The shot map has game_id, period and seconds_elapsed, so you can compute the gap to the previous attempt inside a game without calling another endpoint. In our team sample, rebounds scored 11.9 percent of the time against 7.5 percent for other attempts, on 176 rebound attempts.

What this shot map cannot give you. It does not hold the pass before the shot, defender positions or goalie position. Rush flags and royal-road passes need tracking data or play-by-play context from get_plays, and screens are not recorded. Anything you read into those from this table is a guess.

import numpy as np, pandas as pd

GOAL_X = 89.0

def build(shots: pd.DataFrame) -> pd.DataFrame:
    df = shots[shots["type"].isin(["goal", "shot-on-goal", "missed-shot"])].copy()
    df = df.dropna(subset=["x_coord", "y_coord"])
    df["game_id"] = df["game_id"].astype(str)
    df["clock"] = (df["period"] - 1) * 1200 + df["seconds_elapsed"]
    df = df.sort_values(["game_id", "clock"]).reset_index(drop=True)

    x, y = df["x_coord"].abs().astype(float), df["y_coord"].astype(float)
    df["distance"] = np.hypot(GOAL_X - x, y)
    df["angle"] = np.degrees(np.arctan2(y.abs(), (GOAL_X - x).clip(lower=0.1)))

    g = df.groupby("game_id")
    df["gap"] = (df["clock"] - g["clock"].shift(1)).fillna(999)
    df["prev_dist"] = g["distance"].shift(1)
    df["rebound"] = ((df["gap"] <= 3) & (df["prev_dist"] < 30)).astype(int)
    df["quick_follow"] = (df["gap"] <= 10).astype(int)
    df["log_dist"] = np.log1p(df["distance"])
    df["goal"] = (df["type"] == "goal").astype(int)
    return df

BASE = ["distance", "angle"]
FULL = ["distance", "angle", "log_dist", "rebound", "quick_follow"]

def design(df, cols, dummies=("shot_type", "strength")):
    X = df[cols].astype(float)
    return pd.concat([X, pd.get_dummies(df[list(dummies)].fillna("unknown"), dtype=float)], axis=1)

Note that the previous attempt comes from the same team, because the pull above is filtered to one team. Pull by game_id instead if you want both teams' attempts in the gap calculation.

Step 3: fit, and split by time

Fit a logistic regression and score it with log loss and AUC. Split by time, not at random. Shots from one game are correlated, and a random split puts a game's shots on both sides of the divide. The walk-forward validation guide covers that in full.

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, roc_auc_score

df = build(pd.read_csv("tor.csv"))
games = sorted(df["game_id"].unique())
cut = games[int(len(games) * 0.75)]
tr, te = df[df["game_id"] < cut], df[df["game_id"] >= cut]

for name, cols in [("distance+angle", BASE), ("plus rebound", FULL)]:
    Xtr = design(tr, cols)
    Xte = design(te, cols).reindex(columns=Xtr.columns, fill_value=0.0)
    p = LogisticRegression(max_iter=3000).fit(Xtr, tr["goal"]).predict_proba(Xte)[:, 1]
    print(name, "log loss", round(log_loss(te["goal"], p), 4), "AUC", round(roc_auc_score(te["goal"], p), 3))

base = np.full(len(te), tr["goal"].mean())
print("league-rate log loss", round(log_loss(te["goal"], base), 4), "n test", len(te))

What we measured

On one team's season, 3,274 unblocked attempts and 252 goals (7.7 percent), with the first 75 percent of games for training and the last 25 percent (767 attempts) for testing:

ModelLog lossAUC
League-average rate0.2680n/a
Distance and angle, shot type, strength0.24000.754
Plus rebound and quick follow-up0.24160.744

The extra features did not help on this sample. That is a finding, not a bug: 767 test shots and about 60 goals are too few to separate models that differ by 0.002 in log loss, and the rebound flag applies to only 5 percent of attempts. A bigger sample is what settles it. The public repo's December 6 run used 16 teams and 57,310 attempts and reached AUC 0.750 and log loss 0.2331, against 0.2610 for the league-average rate. Those are the repo's figures. We did not rerun all 16 teams for this page, and the two runs use different splits, so do not compare them as if they were one test.

Check calibration, not only ranking

AUC rewards ordering shots correctly. An xG number is used as a probability, so it must also be calibrated. Bin the predictions by distance and compare the average prediction to the actual goal rate in each bin. A model with good AUC and poor calibration will quietly overstate long shots. Also check each strength state separately, since a pooled model can be right on average and wrong on the power play.

Ideas that tend to pay off

When not to use this

Get a free key

Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.