Skip to main content
Version: 0.2.0

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

ParameterTypeDefaultDescription
adj_xgf_homefloathome team's opponent-adjusted xG-for rate.
adj_xga_homefloathome team's opponent-adjusted xG-against rate.
adj_xgf_awayfloataway team's opponent-adjusted xG-for rate.
adj_xga_awayfloataway team's opponent-adjusted xG-against rate.
neutralboolwhether the game is at a neutral site (drops HFA).
leaguestr'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

ParameterTypeDefaultDescription
pbpDataFramea play-by-play frame shaped like load_nhl_pbp_full.
pregame_home_probfloatthe 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_nametypedescription
score_diffInt64
sec_remainingFloat64
sqrt_sec_remainingFloat64
strength_diffInt64
home_goalie_pulledInt64
away_goalie_pulledInt64
pregame_logitFloat64

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

ParameterTypeDefaultDescription
seasonintSeason end-year (e.g. 2024 for 2023-24).
leaguestr'nhl'"nhl" or "pwhl". PWHL short-circuits to a zero-row frame (no EDGE feed) BEFORE any network access.
detail_framesDataFrame | NoneNonePre-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.
methodLiteral['zscore', 'percentile']'zscore'"zscore" (default, original composite) or "percentile" -- see the module docstring's flesh-out note.
include_zone_balanceboolFalseadd 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_pandasboolFalseReturn 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_nametypedescription
player_idInt64Unique player identifier.
seasonInt64Season year (echoed from arg).
top_speedFloat64
distance_kmFloat64
speed_bursts_20Float64
oz_time_pctFloat64
skating_valueFloat64
skating_value_rankInt64

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

ParameterTypeDefaultDescription
pbpDataFrameParsed pbp frame (Task-0.1 contract).
leaguestr'nhl'League key for ~sportsdataverse.nhl.nhl_microstat_constants.get_constants ("nhl" or "pwhl").
return_as_pandasboolFalseReturn 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_nametypedescription
player_idStringUnique player identifier.
faceoffs_takenInt64Faceoffs taken in the season.
faceoffs_wonInt64Faceoffs won in the season.
fo_win_pctFloat64
fo_win_pct_above_expFloat64
faceoff_valueFloat64

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

ParameterTypeDefaultDescription
pbpDataFrameload_nhl_pbp_full plays (with its xg), one or many games.
scheduleDataFrameload_nhl_schedules rows (game_id, home_score, away_score): the official finals, a shootout's goal included.
skater_boxDataFrameload_nhl_skater_boxscores rows: each side's team id and the players' points.
return_as_pandasboolFalseReturn 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_nametypedescription
game_idInt64The game's NHL game id (e.g. 2024020001).
home_team_idInt64Home team's NHL team id.
away_team_idInt64Away team's NHL team id.
home_scoreInt64Home team's official final score.
away_scoreInt64Away team's official final score.
winner_team_idInt64Winning team's id; null on a tie.
loser_team_idInt64Losing team's id; null on a tie.
marginInt64Winner's final score less the loser's; 0 on a tie.
decidedBooleanTrue when the game has a winner (false on a tie).
periods_agreeBooleanTrue 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_periodsInt64Periods played, overtimes included.
overtimeBooleanTrue when the game went past regulation.

edges:

col_nametypedescription
game_idInt64The game's NHL game id (e.g. 2024020001).
winner_team_idInt64Winning team's id (null on a tie, where the edges read from the home side's view).
loser_team_idInt64Losing team's id (null on a tie).
edgeStringEdge 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).
kindStringaccounting 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.
unitStringAlways goals: the scoring unit the edges are priced in.
winner_valueFloat64Winner's value for the edge in the edge's own unit: points for a points edge, a rate for a rate edge.
loser_valueFloat64Loser's value for the edge, in the same unit as winner_value.
points_worthFloat64The winner's edge in the sport's scoring unit: the winner's points from the edge less the loser's. Positive favours the winner.
rankInt64Rank of the edge within the game by points_worth, 1 = largest; equal worths keep the edge list's order.

moment:

col_nametypedescription
game_idInt64The game's NHL game id (e.g. 2024020001).
play_idInt64Play id of the deciding moment (null for a hockey shootout's closing row, which no play carries).
orderInt64The play's position in the game's play order.
periodInt64Period of the play.
clockStringGame clock of the play as the source shows it.
team_idInt64Team of the play: the event's team (hockey), the batting team (baseball), the scoring team (soccer).
textStringPlay description as the source writes it.
wpaFloat64Home win probability after the play less before it.
winner_wpaFloat64The same change from the winner's side (null on a tie).
home_scoreInt64Home score after the play.
away_scoreInt64Away score after the play.
ruleStringmax_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_nametypedescription
game_idInt64The game's NHL game id (e.g. 2024020001).
periodInt64Period number, from 1; overtimes follow regulation.
period_labelStringP1-P3, then OT (OT2 ... in the playoffs) and SO for a shootout.
is_overtimeBooleanTrue for a period after regulation.
home_ptsInt64Home points in the period: its last running score less the previous period's.
away_ptsInt64Away points in the period.
home_cumInt64Home running score at the end of the period.
away_cumInt64Away running score at the end of the period.

runs:

col_nametypedescription
game_idInt64The game's NHL game id (e.g. 2024020001).
team_idInt64Team that made the run.
pointsInt64The 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_orderInt64Play order of the run's first score.
end_orderInt64Play order of the run's last score.
start_periodInt64Period of the run's first score.
end_periodInt64Period of the run's last score.
home_score_afterInt64Home score at the end of the run.
away_score_afterInt64Away score at the end of the run.

performers:

col_nametypedescription
game_idInt64The game's NHL game id (e.g. 2024020001).
team_idInt64Team of the top performer.
player_idInt64The side's top performer's player id.
player_nameStringPlayer's display name.
metricStringAlways points: goals plus assists, the metric the performer is chosen by.
valueFloat64The 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

ParameterTypeDefaultDescription
gamesDataFramea schedule-shaped frame with game_id, home_team, away_team, neutral_site.
ratingsDataFramethe output of sportsdataverse.nhl.nhl_team_ratings.nhl_team_ratings.
leaguestr'nhl'resolves HFA/sigma/total_scale via get_constants.
return_as_pandasboolFalsereturn 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

ParameterTypeDefaultDescription
seasonsint | 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.
startersDataFrame | NoneNonegames 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.
coveragefloat0.8central probability of the interval, in (0, 1).
load_goalie_boxscoresCallable[[Any], DataFrame] | NoneNonethe goalie-box loader, called as f(seasons); None reads ~sportsdataverse.nhl.nhl_loaders.load_nhl_goalie_boxscores.
return_as_pandasboolFalsereturn 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_nametypedescription
seasonInt64NHL season id of the game, both years run together (e.g. 20242025 for 2024-25).
game_idInt64NHL game id (e.g. 2024020001).
game_dateDateDate of the game.
player_idInt64NHL player id of the projected starting goalie.
teamStringAbbreviation of the goalie's team (e.g. "NJD").
opp_teamStringAbbreviation of the opponent whose shots the goalie faces (e.g. "BUF").
is_homeBooleanTrue when the goalie's team is the home team.
exp_shots_againstFloat64Expected 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_pctFloat64The 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_savesFloat64Expected saves, exp_shots_against x exp_save_pct (the negative-binomial mean).
saves_loInt64Lower end of the central interval, the (1 - coverage) / 2 quantile of the predicted saves.
saves_hiInt64Upper end of the central interval, the (1 + coverage) / 2 quantile of the predicted saves.
coverageFloat64Central probability the saves_lo-saves_hi interval was built for (the coverage argument, 0.8 by default).

Raises

ExceptionDescription
ValueErrorIf 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

ParameterTypeDefaultDescription
pbpDataFramea play-by-play frame shaped like load_nhl_pbp_full.
pregame_home_probfloatthe model (2) pregame home win probability anchor.
leaguestr'nhl'resolves the bundled artifact filename via get_constants.
return_as_pandasboolFalsereturn 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_nametypedescription
home_win_probFloat64

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

ParameterTypeDefaultDescription
pbpDataFrameParsed pbp frame (Task-0.1 contract).
leaguestr'nhl'League key for ~sportsdataverse.nhl.nhl_microstat_constants.get_constants.
return_as_pandasboolFalseReturn 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_nametypedescription
player_idStringUnique player identifier.
penalties_drawnInt64
penalties_takenInt64
minors_drawnInt64
minors_takenInt64
majors_drawnInt64
majors_takenInt64
net_penaltiesInt64
net_penalty_valueFloat64

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

ParameterTypeDefaultDescription
seasonsUnion[int, list[int]]an int or iterable of seasons (load_nhl_skater_boxscores only publishes seasons >= 2024).
leaguestr'nhl'resolves prop_kappa/pos_priors/prop_team_volume_slope via get_constants.
as_of_datedate | NoneNoneif 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).
statstuple[str, ...]('shots', 'points')which stat families to project ("shots", "points").
load_skater_boxscoresCallable[[Any], DataFrame] | NoneNonethe 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_ratingsCallable[..., DataFrame] | NoneNonethe 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_pandasboolFalsereturn 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_nametypedescription
seasonInt64Season year (echoed from arg).
game_idInt64Unique game identifier.
player_idInt64Unique player identifier.
teamStringTeam name.
opp_teamString
statString
proj_meanFloat64
proj_sdFloat64
p_overFloat64
lineFloat64

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

ParameterTypeDefaultDescription
gamesDataFramea 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).
ratingsDataFramethe output of sportsdataverse.nhl.nhl_team_ratings.nhl_team_ratings (team, adj_xgf, adj_xga).
leaguestr'nhl'resolves HFA/sigma via get_constants.
oddsOptional[DataFrame]Noneoptional frame with game_id, close_puck_line_home; when supplied, market_edge = exp_margin - close_puck_line_home.
return_as_pandasboolFalsereturn 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

ParameterTypeDefaultDescription
predsDataFramea frame with game_id, home_win_prob and exp_total, e.g. nhl_predict_games. Rows where either value is missing are skipped.
top_nint10how many scorelines to keep per game, most likely first (at least 1).
leaguestr'nhl'resolves reg_draw_inflation via get_constants.
return_as_pandasboolFalsereturn 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_nametypedescription
game_idInt64Game id, the input predictions' game_id with its dtype kept.
rankInt64Scoreline's rank within the game, 1 for the most likely final score.
home_goalsInt64Home team's goals in this final score (an overtime or shootout win counts as one goal).
away_goalsInt64Away team's goals in this final score (an overtime or shootout win counts as one goal).
probFloat64Probability the game ends with exactly this score; over every scoreline the home-win share equals the row's home_win_prob.
prob_beyond_regulationFloat64Part 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

ExceptionDescription
ValueErrorIf 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

ParameterTypeDefaultDescription
pbpDataFramea load_nhl_pbp_full-shaped frame.
shiftsDataFramea load_nhl_shifts-shaped frame.
model_dirstr | NoneNonepassed through to nhl_xg.
leaguestr'nhl'"nhl" or "pwhl" -- selects league_xg_rate_pp/_pk via LEAGUE_CONSTANTS.
return_as_pandasboolFalsereturn a pandas DataFrame instead of polars.
xg_scoredboolFalsepbp already carries the shot xg to use (another league's own xG model); skip re-scoring with the NHL boosters, which would replace it.
_stintsDataFrame | NoneNoneinternal 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_nametypedescription
player_idInt64Unique player identifier.
pp_toi_minutesFloat64
pk_toi_minutesFloat64
pp_valueFloat64
pk_valueFloat64

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

ParameterTypeDefaultDescription
predsDataFramea frame with game_id, home_win_prob and exp_total, e.g. nhl_predict_games. Rows where either value is missing are skipped.
leaguestr'nhl'resolves reg_draw_inflation via get_constants.
return_as_pandasboolFalsereturn 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_nametypedescription
game_idInt64Game id, the input predictions' game_id with its dtype kept.
total_goalsInt64Total goals in the final score, both teams (0 to 32; an overtime or shootout win adds one).
probFloat64Probability 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_overFloat64Probability the total is above total_goals, the over price for a line of total_goals + 0.5.

Raises

ExceptionDescription
ValueErrorIf 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

ParameterTypeDefaultDescription
pbpDataFrameParsed pbp frame (Task-0.1 contract).
leaguestr'nhl'League key for the value constants.
tagsDataFrame | NoneNoneOptional ground-truth controlled/dump override (see infer_zone_transitions).
return_as_pandasboolFalseReturn 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_nametypedescription
player_idStringUnique player identifier.
controlled_entriesInt64
dump_entriesInt64
exitsInt64
controlled_entry_rateFloat64
entry_valueFloat64
exit_valueFloat64

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

ParameterTypeDefaultDescription
adj_xgf_homefloathome team's opponent-adjusted xG-for rate.
adj_xga_homefloathome team's opponent-adjusted xG-against rate.
adj_xgf_awayfloataway team's opponent-adjusted xG-for rate.
adj_xga_awayfloataway team's opponent-adjusted xG-against rate.
neutralboolwhether the game is at a neutral site.
leaguestr'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

ParameterTypeDefaultDescription
adj_xgf_homefloathome team's opponent-adjusted xG-for rate.
adj_xga_homefloathome team's opponent-adjusted xG-against rate.
adj_xgf_awayfloataway team's opponent-adjusted xG-for rate.
adj_xga_awayfloataway team's opponent-adjusted xG-against rate.
neutralboolwhether the game is at a neutral site.
leaguestr'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

ParameterTypeDefaultDescription
home_win_probndarrayfinal-score home win probabilities in (0, 1), e.g. nhl_predict_games's column.
exp_totalndarrayexpected final-score total goals, same length.
leaguestr'nhl'resolves reg_draw_inflation via get_constants.

Returns

A (home_means, away_means) tuple of float arrays.

Raises

ExceptionDescription
ValueErrorIf 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

ParameterTypeDefaultDescription
recdictone 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

ParameterTypeDefaultDescription
exp_marginfloatexpected home-minus-away goal margin.
leaguestr'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)