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
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | a 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_name | type | description |
|---|---|---|
event_type | String | Standardized event type code. |
event | String | Event description label. |
secondary_type | String | Secondary event type (e.g. shot type). |
event_team_abbr | String | Abbreviation of the team credited with the event. |
event_team_type | String | Whether the event team is home or away. |
description | String | Full text description of the event. |
period | Int64 | Period number. |
period_type | String | Period type (REG/OT/SO). |
period_time | String | Elapsed time in the period (MM:SS). |
period_seconds | Int64 | Elapsed seconds in the period. |
period_seconds_remaining | Int64 | Seconds remaining in the period. |
period_time_remaining | String | Time remaining in the period (MM:SS). |
game_seconds | Int64 | Elapsed seconds in the game. |
game_seconds_remaining | Int64 | Seconds remaining in regulation. |
home_score | Int64 | Home team final score. |
away_score | Int64 | Away team final score. |
event_player_1_name | String | Name of the primary event player. |
event_player_1_type | String | Role of the primary event player. |
event_player_1_id | Int64 | Player id of the primary event player. |
event_player_2_name | String | Name of the secondary event player. |
event_player_2_type | String | Role of the secondary event player. |
event_player_2_id | Int64 | Player id of the secondary event player. |
event_player_3_name | String | Name of the tertiary event player. |
event_player_3_type | String | Role of the tertiary event player. |
event_player_3_id | Int64 | Player ID of the tertiary event player. |
event_goalie_name | String | Name of the goalie on the event. |
event_goalie_id | Int64 | Player id of the goalie on the event. |
penalty_severity | String | Severity of the penalty. |
penalty_minutes | Int64 | Penalty minutes. |
strength_state | String | Strength state (e.g. 5v5, 5v4). |
strength_code | String | Strength state code (e.g., all, even, pp, pk). |
strength | String | Strength label (Even, Power Play, Shorthanded). |
empty_net | Int64 | Whether the net was empty. |
extra_attacker | Boolean | Whether an extra attacker was on the ice. |
x | Int64 | Raw x-coordinate of the event. |
y | Int64 | Raw y-coordinate of the event. |
x_fixed | Int64 | Normalized x coordinate (home shoots right). |
y_fixed | Int64 | Normalized y coordinate (home shoots right). |
shot_distance | Float64 | Distance of the shot from the net. |
shot_angle | Float64 | Angle of the shot relative to the net. |
home_skaters | Int64 | Number of home skaters on the ice. |
away_skaters | Int64 | Number of away skaters on the ice. |
home_on_1 | String | Name of home skater 1 on the ice. |
home_on_2 | String | Name of home skater 2 on the ice. |
home_on_3 | String | Name of home skater 3 on the ice. |
home_on_4 | String | Name of home skater 4 on the ice. |
home_on_5 | String | Name of home skater 5 on the ice. |
home_on_6 | String | Name of home skater 6 on the ice. |
home_on_7 | String | Name of home skater 7 on the ice. |
away_on_1 | String | Name of away skater 1 on the ice. |
away_on_2 | String | Name of away skater 2 on the ice. |
away_on_3 | String | Name of away skater 3 on the ice. |
away_on_4 | String | Name of away skater 4 on the ice. |
away_on_5 | String | Name of away skater 5 on the ice. |
away_on_6 | String | Name of away skater 6 on the ice. |
away_on_7 | String | Name of away skater 7 on the ice. |
home_goalie | String | Name of the home goalie on the ice. |
away_goalie | String | Name of the away goalie on the ice. |
num_on | Int64 | Number of players coming on (line change). |
players_on | String | Names of players coming on. |
num_off | Int64 | Number of players going off (line change). |
players_off | String | Names of players going off. |
game_id | Int64 | Unique game identifier. |
season | String | Season year (echoed from arg). |
season_type | String | Season type code (echoed from arg). |
home_abbr | String | Home team abbreviation. |
away_abbr | String | Away team abbreviation. |
event_idx | Int64 | Sequential event index within the game. |
event_id | Int64 | ESPN event id (echoed from arg). |
pptReplayUrl | String | URL to the play replay, if available. |
away_goalie_in | Int64 | Whether the away goalie is on the ice (1/0). |
home_goalie_in | Int64 | Whether the home goalie is on the ice (1/0). |
reason | String | Reason for the event (e.g. stoppage reason). |
secondaryReason | String | Secondary reason for a stoppage. |
ids_on | String | Player ids coming on. |
ids_off | String | Player ids going off. |
home_on_1_id | Int64 | Player id of home skater 1 on the ice. |
away_on_1_id | Int64 | Player id of away skater 1 on the ice. |
home_on_2_id | Int64 | Player id of home skater 2 on the ice. |
away_on_2_id | Int64 | Player id of away skater 2 on the ice. |
home_on_3_id | Int64 | Player id of home skater 3 on the ice. |
away_on_3_id | Int64 | Player id of away skater 3 on the ice. |
home_on_4_id | Int64 | Player id of home skater 4 on the ice. |
away_on_4_id | Int64 | Player id of away skater 4 on the ice. |
home_on_5_id | Int64 | Player id of home skater 5 on the ice. |
away_on_5_id | Int64 | Player id of away skater 5 on the ice. |
home_on_6_id | Int64 | Player id of home skater 6 on the ice. |
away_on_6_id | Int64 | Player id of away skater 6 on the ice. |
home_on_7_id | Int64 | Player id of home skater 7 on the ice. |
away_on_7_id | Int64 | Player id of away skater 7 on the ice. |
home_goalie_id | Int64 | Player ID of the home goalie on the ice. |
away_goalie_id | Int64 | Player ID of the away goalie on the ice. |
xg | Float64 | Expected goals value for the shot event. |
game_date | String | Game date. |
event_zone | String | |
last_event_type | String | |
last_event_team | String | |
time_since_last | Int64 | |
last_x | Int64 | |
last_y | Int64 | |
last_event_zone | String | |
distance_from_last | Float64 | |
era_2011_2013 | Int64 | |
era_2014_2018 | Int64 | |
era_2019_2021 | Int64 | |
era_2022_2024 | Int64 | |
era_2025_on | Int64 | |
total_skaters_on | Int64 | |
event_team_advantage | Int64 | |
rebound | Int64 | |
rush | Int64 | |
cross_ice_event | Int64 | |
wrist_shot | Int64 | |
snap_shot | Int64 | |
slap_shot | Int64 | |
backhand | Int64 | |
wrap_around | Int64 | |
tip_in | Int64 | |
deflected | Int64 | |
poke | Int64 | |
batted | Int64 | |
between_legs | Int64 | |
cradle | Int64 | |
last_faceoff | Int64 | |
last_giveaway | Int64 | |
last_takeaway | Int64 | |
last_blocked_shot | Int64 | |
last_hit | Int64 | |
last_missed_shot | Int64 | |
last_shot | Int64 | |
last_stop | Int64 | |
last_penalty | Int64 | |
last_goal | Int64 |
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
| Parameter | Type | Default | Description |
|---|---|---|---|
a | ndarray | First array of values. | |
b | ndarray | Second 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
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | a 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
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | a 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). | |
schedule | DataFrame | a 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_only | bool | True | restrict 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
| Parameter | Type | Default | Description |
|---|---|---|---|
X | Any | design matrix, dense numpy.ndarray or any scipy.sparse matrix. | |
y | ndarray | response vector. | |
w | ndarray | nonnegative observation weights (e.g. stint duration in seconds). | |
lam | float | ridge 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)