NHL — additional Python functions — Analytics
expected_goals
expected_goals(adj_xgf_home: 'float', adj_xga_home: 'float', adj_xgf_away: 'float', adj_xga_away: 'float', neutral: 'bool', *, league: 'str' = 'nhl') -> 'tuple[float, float]'
Per-team expected goals, blending own offense with opponent defense.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
adj_xgf_home | float | home team's opponent-adjusted xG-for rate. | |
adj_xga_home | float | home team's opponent-adjusted xG-against rate. | |
adj_xgf_away | float | away team's opponent-adjusted xG-for rate. | |
adj_xga_away | float | away team's opponent-adjusted xG-against rate. | |
neutral | bool | whether the game is at a neutral site (drops HFA). | |
league | str | 'nhl' | resolves hfa via get_constants. |
Returns
A (eg_home, eg_away) tuple of expected goals.
Example
from sportsdataverse.nhl.nhl_market import expected_goals
expected_goals(2.8, 2.2, 2.5, 2.4, False)
in_game_features
in_game_features(pbp: 'pl.DataFrame', pregame_home_prob: 'float') -> 'pl.DataFrame'
Per-play in-game win-probability features from game state.
Reads the load_nhl_pbp_full schema (home_score/away_score,
game_seconds_remaining, home_skaters/away_skaters,
home_goalie_in/away_goalie_in). A live feed can populate the same
five features via a documented column map from
sportsdataverse.nhl.nhl_api_web_parsers.parse_nhl_web_pbp
(homeScore/awayScore/timeRemaining/situationCode).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | a play-by-play frame shaped like load_nhl_pbp_full. | |
pregame_home_prob | float | the model (2) pregame home win probability (e.g. from win_prob_from_margin), converted to a logit and carried as a constant per-play anchor feature. |
Returns
A polars DataFrame, one row per play. |col_name |type | |:-------------------|:------| |score_diff |Int32 | |sec_remaining |Float64| |sqrt_sec_remaining |Float64| |strength_diff |Int32 | |home_goalie_pulled |Int8 | |away_goalie_pulled |Int8 | |pregame_logit |Float64|
| col_name | type | description |
|---|---|---|
score_diff | Int64 | |
sec_remaining | Float64 | |
sqrt_sec_remaining | Float64 | |
strength_diff | Int64 | |
home_goalie_pulled | Int64 | |
away_goalie_pulled | Int64 | |
pregame_logit | Float64 |
Example
from sportsdataverse.nhl.nhl_market import in_game_features, win_prob_from_margin
pregame_p = win_prob_from_margin(0.3)
feats = in_game_features(pbp, pregame_home_prob=pregame_p)
nhl_edge_skating_value
nhl_edge_skating_value(*, season: 'int', league: 'str' = 'nhl', detail_frames: 'pl.DataFrame | None' = None, method: "Literal['zscore', 'percentile']" = 'zscore', include_zone_balance: 'bool' = False, return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Per-skater EDGE skating-value composite (z-score or percentile blend).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
season | int | Season end-year (e.g. 2024 for 2023-24). | |
league | str | 'nhl' | "nhl" or "pwhl". PWHL short-circuits to a zero-row frame (no EDGE feed) BEFORE any network access. |
detail_frames | DataFrame | None | None | Pre-parsed EDGE aggregate (one row per skater with the _COMPONENTS columns) for offline use. When None on the NHL path, the live per-skater nhl_edge_skater_*_detail fetch would run -- not implemented offline; supply detail_frames. |
method | Literal['zscore', 'percentile'] | 'zscore' | "zscore" (default, original composite) or "percentile" -- see the module docstring's flesh-out note. |
include_zone_balance | bool | False | add the derived oz_dz_time_balance component when dz_time_pct is present in detail_frames (default False -- preserves the original 4-component output). |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
Per-skater frame: player_id, season, top_speed, distance_km, speed_bursts_20, oz_time_pct, skating_value, skating_value_rank (1 = fastest composite), plus oz_dz_time_balance when include_zone_balance=True and derivable. PWHL (or empty/absent input) returns a zero-row frame with the base schema.
| col_name | type | description |
|---|---|---|
player_id | Int64 | Unique player identifier. |
season | Int64 | Season year (echoed from arg). |
top_speed | Float64 | |
distance_km | Float64 | |
speed_bursts_20 | Float64 | |
oz_time_pct | Float64 | |
skating_value | Float64 | |
skating_value_rank | Int64 |
Example
from sportsdataverse.nhl.nhl_edge_value import nhl_edge_skating_value
out = nhl_edge_skating_value(season=2024, detail_frames=edge_df)
# Percentile composite + zone-balance component
out = nhl_edge_skating_value(
season=2024, detail_frames=edge_df, method="percentile", include_zone_balance=True
)
nhl_faceoff_value
nhl_faceoff_value(pbp: 'pl.DataFrame', *, league: 'str' = 'nhl', return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Per-player context-adjusted faceoff-win value.
Fits fit_faceoff_context on the taker-perspective expansion of
every faceoff in pbp, then aggregates each player's win rate above
the context expectation and a zone-weighted faceoff_value using
get_constants(league).faceoff_zone_weights.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | Parsed pbp frame (Task-0.1 contract). | |
league | str | 'nhl' | League key for ~sportsdataverse.nhl.nhl_microstat_constants.get_constants ("nhl" or "pwhl"). |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
Per-player frame: player_id, faceoffs_taken, faceoffs_won, fo_win_pct, fo_win_pct_above_exp, faceoff_value. Zero-row input returns a zero-row frame with this schema.
| col_name | type | description |
|---|---|---|
player_id | String | Unique player identifier. |
faceoffs_taken | Int64 | Faceoffs taken in the season. |
faceoffs_won | Int64 | Faceoffs won in the season. |
fo_win_pct | Float64 | |
fo_win_pct_above_exp | Float64 | |
faceoff_value | Float64 |
Example
from sportsdataverse.nhl.nhl_faceoff_value import nhl_faceoff_value
out = nhl_faceoff_value(pbp)
# PWHL
out_pwhl = nhl_faceoff_value(pwhl_pbp, league="pwhl")
nhl_game_story
nhl_game_story(pbp: 'pl.DataFrame', schedule: 'pl.DataFrame', skater_box: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> 'dict[str, pl.DataFrame] | dict[str, pd.DataFrame]'
How the winner won it, for one or many NHL games: edges in goals, the moment, periods, runs, performers.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | load_nhl_pbp_full plays (with its xg), one or many games. | |
schedule | DataFrame | load_nhl_schedules rows (game_id, home_score, away_score): the official finals, a shootout's goal included. | |
skater_box | DataFrame | load_nhl_skater_boxscores rows: each side's team id and the players' points. | |
return_as_pandas | bool | False | Return pandas frames instead of polars. |
Returns
{"summary", "edges", "moment", "periods", "runs", "performers"}, the frames of ~sportsdataverse._common.game_story.GAME_STORY_SCHEMAS. Edges are the goals by situation (which add up to the margin exactly, the shootout's goal included) and the expected-goals splits, in goals and ranked. Periods are P1-P3, OT (OT2 ... in the playoffs) and SO. A game needs its schedule row and both skater-box sides. Rows of any frame without a game_id are dropped with a UserWarning.
summary:
| col_name | type | description |
|---|---|---|
game_id | Int64 | The game's NHL game id (e.g. 2024020001). |
home_team_id | Int64 | Home team's NHL team id. |
away_team_id | Int64 | Away team's NHL team id. |
home_score | Int64 | Home team's official final score. |
away_score | Int64 | Away team's official final score. |
winner_team_id | Int64 | Winning team's id; null on a tie. |
loser_team_id | Int64 | Losing team's id; null on a tie. |
margin | Int64 | Winner's final score less the loser's; 0 on a tie. |
decided | Boolean | True when the game has a winner (false on a tie). |
periods_agree | Boolean | True when the period sums (from the play-by-play's running score) equal the official final; false flags a source whose plays end on another score. |
n_periods | Int64 | Periods played, overtimes included. |
overtime | Boolean | True when the game went past regulation. |
edges:
| col_name | type | description |
|---|---|---|
game_id | Int64 | The game's NHL game id (e.g. 2024020001). |
winner_team_id | Int64 | Winning team's id (null on a tie, where the edges read from the home side's view). |
loser_team_id | Int64 | Losing team's id (null on a tie). |
edge | String | Edge name. Accounting: even_strength_goals, power_play_goals, short_handed_goals, empty_net_goals, penalty_shot_goals, shootout (the one goal the final credits the shootout's winner); together the official margin exactly. Splits: xg, xg_5v5, high_danger_xg, goaltending (goals saved above expected). |
kind | String | accounting for edges that split the game between them (their points_worth add up to the margin, exactly or nearly; see the function's docstring), split for overlapping cuts. |
unit | String | Always goals: the scoring unit the edges are priced in. |
winner_value | Float64 | Winner's value for the edge in the edge's own unit: points for a points edge, a rate for a rate edge. |
loser_value | Float64 | Loser's value for the edge, in the same unit as winner_value. |
points_worth | Float64 | The winner's edge in the sport's scoring unit: the winner's points from the edge less the loser's. Positive favours the winner. |
rank | Int64 | Rank of the edge within the game by points_worth, 1 = largest; equal worths keep the edge list's order. |
moment:
| col_name | type | description |
|---|---|---|
game_id | Int64 | The game's NHL game id (e.g. 2024020001). |
play_id | Int64 | Play id of the deciding moment (null for a hockey shootout's closing row, which no play carries). |
order | Int64 | The play's position in the game's play order. |
period | Int64 | Period of the play. |
clock | String | Game clock of the play as the source shows it. |
team_id | Int64 | Team of the play: the event's team (hockey), the batting team (baseball), the scoring team (soccer). |
text | String | Play description as the source writes it. |
wpa | Float64 | Home win probability after the play less before it. |
winner_wpa | Float64 | The same change from the winner's side (null on a tie). |
home_score | Int64 | Home score after the play. |
away_score | Int64 | Away score after the play. |
rule | String | max_abs_wpa: the play with the largest absolute win-probability change (earliest on ties); deciding_score where no play has one: the winner's score that put it ahead for good. |
periods:
| col_name | type | description |
|---|---|---|
game_id | Int64 | The game's NHL game id (e.g. 2024020001). |
period | Int64 | Period number, from 1; overtimes follow regulation. |
period_label | String | P1-P3, then OT (OT2 ... in the playoffs) and SO for a shootout. |
is_overtime | Boolean | True for a period after regulation. |
home_pts | Int64 | Home points in the period: its last running score less the previous period's. |
away_pts | Int64 | Away points in the period. |
home_cum | Int64 | Home running score at the end of the period. |
away_cum | Int64 | Away running score at the end of the period. |
runs:
| col_name | type | description |
|---|---|---|
game_id | Int64 | The game's NHL game id (e.g. 2024020001). |
team_id | Int64 | Team that made the run. |
points | Int64 | The side's largest unanswered run: points it scored in a row with no score by the other side (a score correction stays in the run and counts against its side). |
start_order | Int64 | Play order of the run's first score. |
end_order | Int64 | Play order of the run's last score. |
start_period | Int64 | Period of the run's first score. |
end_period | Int64 | Period of the run's last score. |
home_score_after | Int64 | Home score at the end of the run. |
away_score_after | Int64 | Away score at the end of the run. |
performers:
| col_name | type | description |
|---|---|---|
game_id | Int64 | The game's NHL game id (e.g. 2024020001). |
team_id | Int64 | Team of the top performer. |
player_id | Int64 | The side's top performer's player id. |
player_name | String | Player's display name. |
metric | String | Always points: goals plus assists, the metric the performer is chosen by. |
value | Float64 | The player's points, goals plus assists (ties go to goals). |
Example
import polars as pl
from sportsdataverse.nhl import load_nhl_pbp_full, load_nhl_schedules, load_nhl_skater_boxscores
from sportsdataverse.nhl.nhl_game_story import nhl_game_story
gid = 2025020001
one = lambda d: d.filter(pl.col("game_id") == gid)
story = nhl_game_story(
one(load_nhl_pbp_full([2026])), one(load_nhl_schedules([2026])), one(load_nhl_skater_boxscores([2026]))
)
story["edges"].head(3)
# The shootouts among a season's games (the frames as above, for the whole season)
story["periods"].filter(pl.col("period_label") == "SO")
nhl_game_total
nhl_game_total(games: 'pl.DataFrame', ratings: 'pl.DataFrame', *, league: 'str' = 'nhl', return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
Per-game expected total goals -- a thin re-export of model ②'s expected-goals helper.
Satisfies the "props + total" grouping of model ③ (the brief's player-prop
surface) without a second implementation of the goals math: this calls
the exact same sportsdataverse.nhl.nhl_market.predict_total that
sportsdataverse.nhl.nhl_market.nhl_predict_games uses internally.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
games | DataFrame | a schedule-shaped frame with game_id, home_team, away_team, neutral_site. | |
ratings | DataFrame | the output of sportsdataverse.nhl.nhl_team_ratings.nhl_team_ratings. | |
league | str | 'nhl' | resolves HFA/sigma/total_scale via get_constants. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
Returns
A polars (or pandas) DataFrame with game_id, exp_total. |col_name |type | |:---------|:------| |game_id |String | |exp_total |Float64|
No returns table is published for this function: no capture: it needs games with home_team / away_team / neutral_site columns that no loader returns.
Example
from sportsdataverse.nhl.nhl_player_props import nhl_game_total
nhl_game_total(games, ratings)
nhl_goalie_saves
nhl_goalie_saves(seasons: 'int | list[int]', *, starters: 'pl.DataFrame | None' = None, coverage: 'float' = 0.8, load_goalie_boxscores: 'Callable[[Any], pl.DataFrame] | None' = None, return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Starting goalie saves projection with a central interval, per goalie-game.
Expected shots against blend the goalie's team's shots-against rate with the opponent's shots-for rate
(strictly prior games of the season, shrunk toward the league's in-season mean by shrink_k games),
move by shots_hfa / 2 for home ice and scale by starter_shot_share. The save percentage is the
goalie's own record over every earlier game in seasons, shrunk toward save_pct_prior by
save_pct_kappa shots. Saves then follow a negative binomial (size shots_nb_size, mean
exp_shots_against * exp_save_pct), and saves_lo / saves_hi are its (1 - coverage) / 2 and
(1 + coverage) / 2 quantiles. Every row uses only games before its date.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | list[int] | the seasons whose goalie boxscores make the history (load_nhl_goalie_boxscores publishes 2024 onward). Without starters, every starter-game in them is projected. | |
starters | DataFrame | None | None | games still to play, one row per projected starter: game_id, game_date (Date or "YYYY-MM-DD"), team, is_home, player_id. Both teams of a game must be listed. A game already in the boxscores is projected without its own result. When given, only these rows are returned. |
coverage | float | 0.8 | central probability of the interval, in (0, 1). |
load_goalie_boxscores | Callable[[Any], DataFrame] | None | None | the goalie-box loader, called as f(seasons); None reads ~sportsdataverse.nhl.nhl_loaders.load_nhl_goalie_boxscores. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
Returns
A polars (or pandas) DataFrame, one row per projected goalie-game. Because saves are whole numbers, the interval holds at least coverage of the predicted distribution. Empty input returns a zero-row frame with this schema. |col_name |type | |:-----------------|:------| |season |Int64 | |game_id |Int64 | |game_date |Date | |player_id |Int64 | |team |String | |opp_team |String | |is_home |Boolean| |exp_shots_against |Float64| |exp_save_pct |Float64| |exp_saves |Float64| |saves_lo |Int64 | |saves_hi |Int64 | |coverage |Float64|
| col_name | type | description |
|---|---|---|
season | Int64 | NHL season id of the game, both years run together (e.g. 20242025 for 2024-25). |
game_id | Int64 | NHL game id (e.g. 2024020001). |
game_date | Date | Date of the game. |
player_id | Int64 | NHL player id of the projected starting goalie. |
team | String | Abbreviation of the goalie's team (e.g. "NJD"). |
opp_team | String | Abbreviation of the opponent whose shots the goalie faces (e.g. "BUF"). |
is_home | Boolean | True when the goalie's team is the home team. |
exp_shots_against | Float64 | Expected shots on goal the starter faces: the mean of the team's shots-against rate and the opponent's shots-for rate over earlier games that season (shrunk toward the league mean), less half the home-ice shot edge for a home goalie and plus half for a visitor, times the starter's share of a game's shots. |
exp_save_pct | Float64 | The goalie's save percentage over every earlier game in the seasons loaded, shrunk toward the league's save_pct_prior (the prior alone for a goalie with no earlier game). |
exp_saves | Float64 | Expected saves, exp_shots_against x exp_save_pct (the negative-binomial mean). |
saves_lo | Int64 | Lower end of the central interval, the (1 - coverage) / 2 quantile of the predicted saves. |
saves_hi | Int64 | Upper end of the central interval, the (1 + coverage) / 2 quantile of the predicted saves. |
coverage | Float64 | Central probability the saves_lo-saves_hi interval was built for (the coverage argument, 0.8 by default). |
Raises
| Exception | Description |
|---|---|
ValueError | If coverage is not strictly between 0 and 1, or a starters game lacks a team. |
Example
from sportsdataverse.nhl.nhl_player_props import nhl_goalie_saves
saves = nhl_goalie_saves(2026)
saves.select("game_id", "player_id", "exp_saves", "saves_lo", "saves_hi").head()
nhl_in_game_win_prob
nhl_in_game_win_prob(pbp: 'pl.DataFrame', pregame_home_prob: 'float', *, league: 'str' = 'nhl', return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
Per-play live home win probability from the bundled in-game logistic.
Builds in_game_features from pbp, scores them with the
committed logistic (sportsdataverse/nhl/models/<league>_in_game_wp.json
-- no first-use download; the coefficients are trained offline by
tools/models/nhl_prediction/train_in_game_wp.py and committed), and returns
sigmoid(coef . features + intercept).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | a play-by-play frame shaped like load_nhl_pbp_full. | |
pregame_home_prob | float | the model (2) pregame home win probability anchor. | |
league | str | 'nhl' | resolves the bundled artifact filename via get_constants. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
Returns
A polars (or pandas) DataFrame, one row per play, with a single home_win_prob: Float64 column.
| col_name | type | description |
|---|---|---|
home_win_prob | Float64 |
Example
from sportsdataverse.nhl.nhl_market import nhl_in_game_win_prob, win_prob_from_margin
pregame_p = win_prob_from_margin(0.3)
wp = nhl_in_game_win_prob(pbp, pregame_home_prob=pregame_p)
print(wp.tail())
nhl_penalty_value
nhl_penalty_value(pbp: 'pl.DataFrame', *, league: 'str' = 'nhl', return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Per-player net penalty drawn/taken value.
Tallies each player's penalties drawn (player_id == drawn_player_id)
and taken (player_id == committed_player_id), split minor/major, and
converts the net into expected goals:
net_penalty_value = (minors_drawn - minors_taken) * pp_goal_value + (majors_drawn - majors_taken) * major_penalty_value using
get_constants(league).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | Parsed pbp frame (Task-0.1 contract). | |
league | str | 'nhl' | League key for ~sportsdataverse.nhl.nhl_microstat_constants.get_constants. |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
Per-player frame: player_id, penalties_drawn, penalties_taken, minors_drawn, minors_taken, majors_drawn, majors_taken, net_penalties, net_penalty_value. League-wide net_penalty_value sums to (approximately) zero by construction -- every penalty taken by one player is drawn by another. Zero-row input returns a zero-row frame with this schema.
| col_name | type | description |
|---|---|---|
player_id | String | Unique player identifier. |
penalties_drawn | Int64 | |
penalties_taken | Int64 | |
minors_drawn | Int64 | |
minors_taken | Int64 | |
majors_drawn | Int64 | |
majors_taken | Int64 | |
net_penalties | Int64 | |
net_penalty_value | Float64 |
Example
from sportsdataverse.nhl.nhl_penalty_value import nhl_penalty_value
out = nhl_penalty_value(pbp)
# PWHL
out_pwhl = nhl_penalty_value(pwhl_pbp, league="pwhl")
nhl_player_props
nhl_player_props(seasons: 'Union[int, list[int]]', *, league: 'str' = 'nhl', as_of_date: '_dt.date | None' = None, stats: 'tuple[str, ...]' = ('shots', 'points'), load_skater_boxscores: 'Callable[[Any], pl.DataFrame] | None' = None, team_ratings: 'Callable[..., pl.DataFrame] | None' = None, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
Empirical-Bayes shots/points player-prop projections.
For every player-game in load_nhl_skater_boxscores, projects that
game's shots-on-goal / points from the player's strictly prior games
(leakage-safe per row by construction), EB-shrunk toward a position prior,
then adjusted by an opponent matchup multiplier (model ① adj_xga) and a
team game-script tilt (model ② native exp_margin -- never the market
line). See the module docstring's leakage-scope note: the per-player
rate is strictly as-of, but the matchup/game-script ratings are a single
snapshot (as-of as_of_date if given, else full-season), not
per-projected-game ratings.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | Union[int, list[int]] | an int or iterable of seasons (load_nhl_skater_boxscores only publishes seasons >= 2024). | |
league | str | 'nhl' | resolves prop_kappa/pos_priors/prop_team_volume_slope via get_constants. |
as_of_date | date | None | None | if given, only games strictly before this date are projected AND the matchup/game-script ratings snapshot is computed as-of this cutoff. NOTE: the per-player usage rate is strictly-prior regardless of this arg (it never needed a cutoff); this arg tightens which games are projected and the single ratings snapshot, but does not make the ratings per-projected-game as-of (a documented approximation -- see the module docstring). |
stats | tuple[str, ...] | ('shots', 'points') | which stat families to project ("shots", "points"). |
load_skater_boxscores | Callable[[Any], DataFrame] | None | None | the per-player-game box loader, called as f(seasons); None reads load_nhl_skater_boxscores. Another league binds its own loader here (columns game_id, player_id, game_date, season, position, team_abbrev, shots_on_goal, points). |
team_ratings | Callable[..., DataFrame] | None | None | the matchup/game-script ratings builder, called as f(seasons, as_of_date=as_of_date); None runs nhl_team_ratings with league. Its team values must match the box's team_abbrev. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
Returns
A polars (or pandas) DataFrame, one row per (player, game, stat). Empty/malformed input returns a zero-row frame with the documented schema. |col_name |type | |:---------|:------| |season |Int64 | |game_id |Int64 | |player_id |Int64 | |team |String | |opp_team |String | |stat |String | |proj_mean |Float64| |proj_sd |Float64| |p_over |Float64| |line |Float64|
| col_name | type | description |
|---|---|---|
season | Int64 | Season year (echoed from arg). |
game_id | Int64 | Unique game identifier. |
player_id | Int64 | Unique player identifier. |
team | String | Team name. |
opp_team | String | |
stat | String | |
proj_mean | Float64 | |
proj_sd | Float64 | |
p_over | Float64 | |
line | Float64 |
Example
from sportsdataverse.nhl.nhl_player_props import nhl_player_props
props = nhl_player_props(2024, stats=("shots",))
print(props.sort("proj_mean", descending=True).head())
# Pipeline next step (one line)
props.filter(pl.col("player_id") == 8478402)
nhl_predict_games
nhl_predict_games(games: 'pl.DataFrame', ratings: 'pl.DataFrame', *, league: 'str' = 'nhl', odds: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
Vectorized pregame margin/win-prob/total (+ market edge) over a schedule.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
games | DataFrame | a schedule-shaped frame with game_id, home_team, away_team, neutral_site (home_team/away_team must share nhl_team_ratings's team dtype -- asserted below). | |
ratings | DataFrame | the output of sportsdataverse.nhl.nhl_team_ratings.nhl_team_ratings (team, adj_xgf, adj_xga). | |
league | str | 'nhl' | resolves HFA/sigma via get_constants. |
odds | Optional[DataFrame] | None | optional frame with game_id, close_puck_line_home; when supplied, market_edge = exp_margin - close_puck_line_home. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
Returns
A polars (or pandas) DataFrame, one row per game. The five regulation columns come from regulation_goal_means: the 60-minute score model whose final-score win probability and expected total equal home_win_prob and exp_total. |col_name |type | |:------------------|:------| |game_id |Int64 | |home_team |String | |away_team |String | |neutral_site |Boolean| |exp_margin |Float64| |home_win_prob |Float64| |exp_total |Float64| |market_edge |Float64| |home_reg_win_prob |Float64| |reg_tie_prob |Float64| |away_reg_win_prob |Float64| |exp_home_reg_goals |Float64| |exp_away_reg_goals |Float64|
No returns table is published for this function: no capture: it needs games with home_team / away_team / neutral_site columns that no loader returns.
Example
from sportsdataverse.nhl.nhl_market import nhl_predict_games
preds = nhl_predict_games(games, ratings)
print(preds.sort("home_win_prob", descending=True).head())
nhl_score_distribution
nhl_score_distribution(preds: 'pl.DataFrame', *, top_n: 'int' = 10, league: 'str' = 'nhl', return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Most likely final scores per game, from the regulation score model behind nhl_predict_games.
A final score counts overtime and shootout wins as one goal, as the NHL scores them. Summed over every
scoreline, the home-win probability equals the row's home_win_prob and the mean total equals its
exp_total (see regulation_goal_means).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
preds | DataFrame | a frame with game_id, home_win_prob and exp_total, e.g. nhl_predict_games. Rows where either value is missing are skipped. | |
top_n | int | 10 | how many scorelines to keep per game, most likely first (at least 1). |
league | str | 'nhl' | resolves reg_draw_inflation via get_constants. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
Returns
A polars (or pandas) DataFrame, top_n rows per game. prob_beyond_regulation is the part of prob from games tied after 60 minutes (a one-goal score only). game_id keeps the input's dtype (Int64 from nhl_predict_games). |col_name |type | |:----------------------|:------| |game_id |Int64 | |rank |Int64 | |home_goals |Int64 | |away_goals |Int64 | |prob |Float64| |prob_beyond_regulation |Float64|
| col_name | type | description |
|---|---|---|
game_id | Int64 | Game id, the input predictions' game_id with its dtype kept. |
rank | Int64 | Scoreline's rank within the game, 1 for the most likely final score. |
home_goals | Int64 | Home team's goals in this final score (an overtime or shootout win counts as one goal). |
away_goals | Int64 | Away team's goals in this final score (an overtime or shootout win counts as one goal). |
prob | Float64 | Probability the game ends with exactly this score; over every scoreline the home-win share equals the row's home_win_prob. |
prob_beyond_regulation | Float64 | Part of prob from games tied after 60 minutes and settled in overtime or a shootout; zero unless the score is a one-goal margin. |
Raises
| Exception | Description |
|---|---|
ValueError | If top_n is below 1 or league has no constants row. |
Example
import polars as pl
from sportsdataverse.nhl.nhl_market import nhl_score_distribution
preds = pl.DataFrame({"game_id": [2025020001], "home_win_prob": [0.55], "exp_total": [6.2]})
nhl_score_distribution(preds, top_n=5)
nhl_special_teams_value
nhl_special_teams_value(pbp: 'pl.DataFrame', shifts: 'pl.DataFrame', *, model_dir: "'str | None'" = None, league: 'str' = 'nhl', return_as_pandas: 'bool' = False, xg_scored: 'bool' = False, _stints: 'pl.DataFrame | None' = None) -> "'pl.DataFrame | pd.DataFrame'"
Per-skater share of power-play/penalty-kill value (goals) above/below the league rate.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | a load_nhl_pbp_full-shaped frame. | |
shifts | DataFrame | a load_nhl_shifts-shaped frame. | |
model_dir | str | None | None | passed through to nhl_xg. |
league | str | 'nhl' | "nhl" or "pwhl" -- selects league_xg_rate_pp/_pk via LEAGUE_CONSTANTS. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
xg_scored | bool | False | pbp already carries the shot xg to use (another league's own xG model); skip re-scoring with the NHL boosters, which would replace it. |
_stints | DataFrame | None | None | internal test hook -- inject a pre-built stints frame. |
Returns
player_id:Int64, pp_toi_minutes:Float64, pk_toi_minutes:Float64, pp_value:Float64, pk_value:Float64. *_toi_minutes is the skater's own time on the ice; pp_value/pk_value are goals above the league rate, each skater carrying an equal share of their unit's (a fifth on a 5v4 power play), so a unit's skaters sum to its value. Empty input returns a zero-row frame with this schema.
| col_name | type | description |
|---|---|---|
player_id | Int64 | Unique player identifier. |
pp_toi_minutes | Float64 | |
pk_toi_minutes | Float64 | |
pp_value | Float64 | |
pk_value | Float64 |
Example
import polars as pl
from sportsdataverse.nhl.nhl_special_teams import nhl_special_teams_value
pbp = pl.read_parquet("tests/fixtures/nhl_player_impact/pbp_sample.parquet")
shifts = pl.read_parquet("tests/fixtures/nhl_player_impact/shifts_sample.parquet")
st = nhl_special_teams_value(pbp, shifts, model_dir="tests/fixtures/nhl_player_impact/xg_models")
print(st.sort("pp_value", descending=True).head(10))
nhl_total_goals_distribution
nhl_total_goals_distribution(preds: 'pl.DataFrame', *, league: 'str' = 'nhl', return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Distribution of the final-score total goals per game, from the same model as nhl_score_distribution.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
preds | DataFrame | a frame with game_id, home_win_prob and exp_total, e.g. nhl_predict_games. Rows where either value is missing are skipped. | |
league | str | 'nhl' | resolves reg_draw_inflation via get_constants. |
return_as_pandas | bool | False | return a pandas DataFrame instead of polars. |
Returns
A polars (or pandas) DataFrame, one row per game and total from 0 to 32 goals. prob_over is P(total > total_goals), the over probability for a line of total_goals + 0.5. Per game the probabilities sum to 1 and their mean is the row's exp_total. game_id keeps the input's dtype. |col_name |type | |:-----------|:------| |game_id |Int64 | |total_goals |Int64 | |prob |Float64| |prob_over |Float64|
| col_name | type | description |
|---|---|---|
game_id | Int64 | Game id, the input predictions' game_id with its dtype kept. |
total_goals | Int64 | Total goals in the final score, both teams (0 to 32; an overtime or shootout win adds one). |
prob | Float64 | Probability the final score totals exactly total_goals; a game's rows sum to 1, and their prob-weighted mean of total_goals is the row's exp_total. |
prob_over | Float64 | Probability the total is above total_goals, the over price for a line of total_goals + 0.5. |
Raises
| Exception | Description |
|---|---|
ValueError | If league has no constants row. |
Example
import polars as pl
from sportsdataverse.nhl.nhl_market import nhl_total_goals_distribution
preds = pl.DataFrame({"game_id": [2025020001], "home_win_prob": [0.55], "exp_total": [6.2]})
totals = nhl_total_goals_distribution(preds)
totals.filter(pl.col("total_goals") == 5) # prob_over == P(over 5.5)
nhl_zone_transitions
nhl_zone_transitions(pbp: 'pl.DataFrame', *, league: 'str' = 'nhl', tags: 'pl.DataFrame | None' = None, return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Per-player controlled/dump entry & exit rates + xG-weighted values.
entry_value = controlled_entries * zone_entry_value_controlled + dump_entries * zone_entry_value_dump; exit_value = exits * zone_exit_value -- all from get_constants(league).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | Parsed pbp frame (Task-0.1 contract). | |
league | str | 'nhl' | League key for the value constants. |
tags | DataFrame | None | None | Optional ground-truth controlled/dump override (see infer_zone_transitions). |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
Per-player frame: player_id, controlled_entries, dump_entries, exits, controlled_entry_rate, entry_value, exit_value. Zero-row input returns a zero-row frame with this schema.
| col_name | type | description |
|---|---|---|
player_id | String | Unique player identifier. |
controlled_entries | Int64 | |
dump_entries | Int64 | |
exits | Int64 | |
controlled_entry_rate | Float64 | |
entry_value | Float64 | |
exit_value | Float64 |
Example
from sportsdataverse.nhl.nhl_zone_transitions import nhl_zone_transitions
out = nhl_zone_transitions(pbp)
# PWHL
out_pwhl = nhl_zone_transitions(pwhl_pbp, league="pwhl")
predict_margin
predict_margin(adj_xgf_home: 'float', adj_xga_home: 'float', adj_xgf_away: 'float', adj_xga_away: 'float', neutral: 'bool', *, league: 'str' = 'nhl') -> 'float'
Expected home-minus-away goal margin.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
adj_xgf_home | float | home team's opponent-adjusted xG-for rate. | |
adj_xga_home | float | home team's opponent-adjusted xG-against rate. | |
adj_xgf_away | float | away team's opponent-adjusted xG-for rate. | |
adj_xga_away | float | away team's opponent-adjusted xG-against rate. | |
neutral | bool | whether the game is at a neutral site. | |
league | str | 'nhl' | resolves hfa via get_constants. |
Returns
eg_home - eg_away.
Example
from sportsdataverse.nhl.nhl_market import predict_margin
predict_margin(2.8, 2.2, 2.5, 2.4, False)
predict_total
predict_total(adj_xgf_home: 'float', adj_xga_home: 'float', adj_xgf_away: 'float', adj_xga_away: 'float', neutral: 'bool', *, league: 'str' = 'nhl') -> 'float'
Expected total goals, variance-corrected by the fitted total_scale.
The raw eg_home + eg_away sum is built from opponent-adjusted,
shrunk ratings, which systematically compress the total's spread
below the real-world variance (confirmed at fitting time: the OLS slope
of realized total on the raw sum is ~1.91, not 1.0). total_scale
corrects for that: the raw total's deviation from its own league mean is
stretched by total_scale before adding back the league-average total.
The ratings are even-strength xG, so that mean is 2 * avg_xgf, not
avg_total_goals: the gap between the two is the power-play,
short-handed and empty-net scoring the ratings leave out.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
adj_xgf_home | float | home team's opponent-adjusted xG-for rate. | |
adj_xga_home | float | home team's opponent-adjusted xG-against rate. | |
adj_xgf_away | float | away team's opponent-adjusted xG-for rate. | |
adj_xga_away | float | away team's opponent-adjusted xG-against rate. | |
neutral | bool | whether the game is at a neutral site. | |
league | str | 'nhl' | resolves hfa/avg_total_goals/total_scale via get_constants. |
Returns
The variance-corrected expected combined goal total for the game.
Example
from sportsdataverse.nhl.nhl_market import predict_total
predict_total(2.8, 2.2, 2.5, 2.4, False)
regulation_goal_means
regulation_goal_means(home_win_prob: 'np.ndarray', exp_total: 'np.ndarray', *, league: 'str' = 'nhl') -> 'tuple[np.ndarray, np.ndarray]'
Per-team regulation goal means consistent with a game's win probability and expected total.
The 60-minute score is a draw-inflated pair of Poissons (see reg_draw_inflation). A game level
after regulation is decided by one more goal (overtime or the shootout winner, both of which add
exactly one goal to the final score), won by the home side with probability
P(home ahead) / (P(home ahead) + P(away ahead)). The two means are solved by bisection so that
the model's final-score home win probability equals home_win_prob and its expected final total
equals exp_total. exp_total is used as given, so the regulation means inherit its centring
(avg_total_goals / total_scale). A pair the grid cannot reach (an exp_total below about 1,
say) gets NaN means rather than the nearest bracket.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
home_win_prob | ndarray | final-score home win probabilities in (0, 1), e.g. nhl_predict_games's column. | |
exp_total | ndarray | expected final-score total goals, same length. | |
league | str | 'nhl' | resolves reg_draw_inflation via get_constants. |
Returns
A (home_means, away_means) tuple of float arrays.
Raises
| Exception | Description |
|---|---|
ValueError | If league has no constants row. |
Example
import numpy as np
from sportsdataverse.nhl.nhl_market import regulation_goal_means
regulation_goal_means(np.array([0.55]), np.array([6.1]))
special_teams_split
special_teams_split(rec: 'dict') -> 'tuple[str, str, float] | None'
Which side of a stint is on the power play, and that side's xG (shared with the fitter).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
rec | dict | one build_stints row as a dict. |
Returns
(pp_ids_column, pk_ids_column, pp_xg) for a special-teams stint: one with unequal skater counts in strength_state and a positive duration. That includes a pulled goalie (6v5), credited as a power play for the trailing team. None otherwise (even strength, unparseable or missing state). The power play's shots are the penalty kill's shots against, so pp_xg is both.
Example
from sportsdataverse.nhl.nhl_special_teams import special_teams_split
special_teams_split({"strength_state": "4v5", "duration": 60, "xgf_home": 0.0, "xgf_away": 0.2})
win_prob_from_margin
win_prob_from_margin(exp_margin: 'float', *, league: 'str' = 'nhl') -> 'float'
Convert an expected goal margin to a home win probability via Phi(margin/sigma).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
exp_margin | float | expected home-minus-away goal margin. | |
league | str | 'nhl' | resolves margin_sd via get_constants. |
Returns
P(home win) in (0, 1).
Example
from sportsdataverse.nhl.nhl_market import win_prob_from_margin
win_prob_from_margin(0.35)