Skip to main content
Version: 0.2.0

NHL — additional Python functions — Models and calculators: prepare_xg–weighted_ridge

prepare_xg_features​

prepare_xg_features(pbp: 'pl.DataFrame') -> 'pl.DataFrame'

Port of helper_nhl_prepare_xg_data -- one row per unblocked shot, model features.

Parameters

ParameterTypeDefaultDescription
pbpDataFramea load_nhl_pbp_full-shaped frame (x, x_fixed, strength_state, home_skaters/away_skaters, game_seconds, event_id, secondary_type, event_team_abbr, home_abbr/away_abbr, season, empty_net -- see load_nhl_pbp_full's returns table).

Returns

one row per unblocked shot (SHOT/MISSED_SHOT/GOAL) carrying every era one-hot, shot-type one-hot, last-event one-hot, and the derived rebound/rush/cross_ice_event/total_skaters_on/ event_team_advantage/empty_net columns the boosters expect. Empty/ malformed input returns a zero-row frame (never raises).

col_nametypedescription
event_typeStringStandardized event type code.
eventStringEvent description label.
secondary_typeStringSecondary event type (e.g. shot type).
event_team_abbrStringAbbreviation of the team credited with the event.
event_team_typeStringWhether the event team is home or away.
descriptionStringFull text description of the event.
periodInt64Period number.
period_typeStringPeriod type (REG/OT/SO).
period_timeStringElapsed time in the period (MM:SS).
period_secondsInt64Elapsed seconds in the period.
period_seconds_remainingInt64Seconds remaining in the period.
period_time_remainingStringTime remaining in the period (MM:SS).
game_secondsInt64Elapsed seconds in the game.
game_seconds_remainingInt64Seconds remaining in regulation.
home_scoreInt64Home team final score.
away_scoreInt64Away team final score.
event_player_1_nameStringName of the primary event player.
event_player_1_typeStringRole of the primary event player.
event_player_1_idInt64Player id of the primary event player.
event_player_2_nameStringName of the secondary event player.
event_player_2_typeStringRole of the secondary event player.
event_player_2_idInt64Player id of the secondary event player.
event_player_3_nameStringName of the tertiary event player.
event_player_3_typeStringRole of the tertiary event player.
event_player_3_idInt64Player ID of the tertiary event player.
event_goalie_nameStringName of the goalie on the event.
event_goalie_idInt64Player id of the goalie on the event.
penalty_severityStringSeverity of the penalty.
penalty_minutesInt64Penalty minutes.
strength_stateStringStrength state (e.g. 5v5, 5v4).
strength_codeStringStrength state code (e.g., all, even, pp, pk).
strengthStringStrength label (Even, Power Play, Shorthanded).
empty_netInt64Whether the net was empty.
extra_attackerBooleanWhether an extra attacker was on the ice.
xInt64Raw x-coordinate of the event.
yInt64Raw y-coordinate of the event.
x_fixedInt64Normalized x coordinate (home shoots right).
y_fixedInt64Normalized y coordinate (home shoots right).
shot_distanceFloat64Distance of the shot from the net.
shot_angleFloat64Angle of the shot relative to the net.
home_skatersInt64Number of home skaters on the ice.
away_skatersInt64Number of away skaters on the ice.
home_on_1StringName of home skater 1 on the ice.
home_on_2StringName of home skater 2 on the ice.
home_on_3StringName of home skater 3 on the ice.
home_on_4StringName of home skater 4 on the ice.
home_on_5StringName of home skater 5 on the ice.
home_on_6StringName of home skater 6 on the ice.
home_on_7StringName of home skater 7 on the ice.
away_on_1StringName of away skater 1 on the ice.
away_on_2StringName of away skater 2 on the ice.
away_on_3StringName of away skater 3 on the ice.
away_on_4StringName of away skater 4 on the ice.
away_on_5StringName of away skater 5 on the ice.
away_on_6StringName of away skater 6 on the ice.
away_on_7StringName of away skater 7 on the ice.
home_goalieStringName of the home goalie on the ice.
away_goalieStringName of the away goalie on the ice.
num_onInt64Number of players coming on (line change).
players_onStringNames of players coming on.
num_offInt64Number of players going off (line change).
players_offStringNames of players going off.
game_idInt64Unique game identifier.
seasonStringSeason year (echoed from arg).
season_typeStringSeason type code (echoed from arg).
home_abbrStringHome team abbreviation.
away_abbrStringAway team abbreviation.
event_idxInt64Sequential event index within the game.
event_idInt64ESPN event id (echoed from arg).
pptReplayUrlStringURL to the play replay, if available.
away_goalie_inInt64Whether the away goalie is on the ice (1/0).
home_goalie_inInt64Whether the home goalie is on the ice (1/0).
reasonStringReason for the event (e.g. stoppage reason).
secondaryReasonStringSecondary reason for a stoppage.
ids_onStringPlayer ids coming on.
ids_offStringPlayer ids going off.
home_on_1_idInt64Player id of home skater 1 on the ice.
away_on_1_idInt64Player id of away skater 1 on the ice.
home_on_2_idInt64Player id of home skater 2 on the ice.
away_on_2_idInt64Player id of away skater 2 on the ice.
home_on_3_idInt64Player id of home skater 3 on the ice.
away_on_3_idInt64Player id of away skater 3 on the ice.
home_on_4_idInt64Player id of home skater 4 on the ice.
away_on_4_idInt64Player id of away skater 4 on the ice.
home_on_5_idInt64Player id of home skater 5 on the ice.
away_on_5_idInt64Player id of away skater 5 on the ice.
home_on_6_idInt64Player id of home skater 6 on the ice.
away_on_6_idInt64Player id of away skater 6 on the ice.
home_on_7_idInt64Player id of home skater 7 on the ice.
away_on_7_idInt64Player id of away skater 7 on the ice.
home_goalie_idInt64Player ID of the home goalie on the ice.
away_goalie_idInt64Player ID of the away goalie on the ice.
xgFloat64Expected goals value for the shot event.
game_dateStringGame date.
event_zoneString
last_event_typeString
last_event_teamString
time_since_lastInt64
last_xInt64
last_yInt64
last_event_zoneString
distance_from_lastFloat64
era_2011_2013Int64
era_2014_2018Int64
era_2019_2021Int64
era_2022_2024Int64
era_2025_onInt64
total_skaters_onInt64
event_team_advantageInt64
reboundInt64
rushInt64
cross_ice_eventInt64
wrist_shotInt64
snap_shotInt64
slap_shotInt64
backhandInt64
wrap_aroundInt64
tip_inInt64
deflectedInt64
pokeInt64
battedInt64
between_legsInt64
cradleInt64
last_faceoffInt64
last_giveawayInt64
last_takeawayInt64
last_blocked_shotInt64
last_hitInt64
last_missed_shotInt64
last_shotInt64
last_stopInt64
last_penaltyInt64
last_goalInt64

Example

import polars as pl
from sportsdataverse.nhl.nhl_xg import prepare_xg_features
pbp = pl.read_parquet("tests/fixtures/nhl_player_impact/pbp_sample.parquet")
feat = prepare_xg_features(pbp)
print(feat.shape)

spearman_corr​

spearman_corr(a: 'np.ndarray', b: 'np.ndarray') -> 'float'

Spearman rank correlation between two arrays.

Parameters

ParameterTypeDefaultDescription
andarrayFirst array of values.
bndarraySecond array of values (same length as a).

Returns

The Spearman rank correlation coefficient.

Example

import numpy as np
from sportsdataverse._common.metrics import spearman_corr
spearman_corr(np.array([1, 2, 3]), np.array([3, 1, 2]))

team_fullname_to_abbr​

team_fullname_to_abbr(name: 'str') -> 'str | None'

Map an NHL full team display name to its abbreviation, or None if unknown.

Parameters

ParameterTypeDefaultDescription
namestra full team display name as it appears in load_nhl_shifts's event_team column (e.g. "Buffalo Sabres").

Returns

The team abbreviation matching load_nhl_pbp_full's event_team_abbr / home_abbr / away_abbr convention, or None for an unmapped name.

Example

from sportsdataverse.nhl.nhl_player_impact_constants import team_fullname_to_abbr
team_fullname_to_abbr("Buffalo Sabres") # "BUF"

team_game_xg_rates​

team_game_xg_rates(pbp: 'pl.DataFrame', schedule: 'pl.DataFrame', *, even_strength_only: 'bool' = True) -> 'pl.DataFrame'

Per-(game, team) even-strength xG-for/against + realized goals.

Parameters

ParameterTypeDefaultDescription
pbpDataFramea play-by-play frame shaped like load_nhl_pbp_full/load_nhl_pbp_lite (needs game_id, event_team_abbr, home_abbr, away_abbr, home_skaters, away_skaters, home_goalie_in, away_goalie_in, xg).
scheduleDataFramea schedule frame with game_id, season, date, home_abbr, away_abbr, neutral_site (home_goals/away_goals are accepted but ignored -- realized gf/ga are derived from the pbp's own GOAL events, never from schedule scores; see the module note on the load_nhl_schedule(s) placeholder-score bug for seasons <= 2023).
even_strength_onlyboolTruerestrict to home_skaters == away_skaters == 5 with both goalies in net (filters out PP/PK/empty-net distortion).

Returns

A polars DataFrame, one row per (game_id, team), both home and away. |col_name |type | |:------------|:------| |game_id |String | |season |Int64 | |date |Date | |team |String | |opp_team |String | |is_home |Boolean| |neutral_site |Boolean| |xgf |Float64| |xga |Float64| |gf |Int64 | |ga |Int64 |

No returns table is published for this function: no capture: it needs a schedule with date / home_abbr / away_abbr / neutral_site, and no loader returns one (load_nhl_schedules carries game_date / home_team_abbr).

Example

from sportsdataverse.nhl.nhl_team_ratings import team_game_xg_rates
from sportsdataverse.nhl import load_nhl_pbp_full, load_nhl_schedules

pbp = load_nhl_pbp_full([2023])
sched = load_nhl_schedules([2023])
rates = team_game_xg_rates(pbp, sched)
print(rates.filter(pl.col("team") == "TOR").head())

weighted_ridge​

weighted_ridge(X: 'Any', y: 'np.ndarray', w: 'np.ndarray', lam: 'float') -> 'np.ndarray'

Solve the weighted ridge normal equations (X'WX + lam*I)^-1 X'Wy.

Dense path (numpy.linalg.solve) for small/dense X; conjugate-gradient (scipy.sparse.linalg.cg) for scipy.sparse X (the skater-RAPM design matrix, ~thousands of columns).

Parameters

ParameterTypeDefaultDescription
XAnydesign matrix, dense numpy.ndarray or any scipy.sparse matrix.
yndarrayresponse vector.
wndarraynonnegative observation weights (e.g. stint duration in seconds).
lamfloatridge penalty.

Returns

The fitted coefficient vector.

Example

import numpy as np
from sportsdataverse.nhl.nhl_player_impact_constants import weighted_ridge
X = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
y = np.array([2.0, -1.0, 1.0])
beta = weighted_ridge(X, y, np.ones(3), lam=1e-6)