NHL — additional Python functions — Play-by-play processing
nhl_microstat_pbp
nhl_microstat_pbp(game_ids: 'Union[int, Iterable[int]]', *, sleep_seconds: 'float' = 0.25, require_final: 'bool' = True, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
Fetch NHL games from api-web and return their plays in the microstat pbp contract.
One request per game to api-web.nhle.com/v1/gamecenter/{game_id}/play-by-play,
made one at a time with sleep_seconds between them, then converted by
nhl_web_pbp_to_microstat. The result is the input that
nhl_expected_assists, nhl_faceoff_value, nhl_penalty_value and
nhl_zone_transitions take. A failed request raises (see Raises) rather
than dropping the game, and with require_final so does a game that is
not final. A game whose feed holds no plays (or, with
require_final=False, one not yet started) contributes no rows.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
game_ids | Union[int, Iterable[int]] | One NHL game id or an iterable of them (e.g. 2023020001). A season's ids come from load_nhl_schedules([season])["game_id"]. | |
sleep_seconds | float | 0.25 | Pause between requests, in seconds. |
require_final | bool | True | Refuse a game that is not final (see nhl_web_pbp_to_microstat). False keeps a partial game's plays. |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
One row per play across the games, in the order the ids were given. Same columns as nhl_web_pbp_to_microstat. |col_name |type | |:------------------------|:-------| |game_id |String | |season |Int64 | |event_idx |Int64 | |period |Int64 | |time_in_period |String | |type_desc_key |String | |event_owner_team_id |String | |zone_code |String | |x_coord |Float64 | |y_coord |Float64 | |situation_code |String | |home_team_id |String | |home_team_defending_side |String | |winning_player_id |String | |losing_player_id |String | |scoring_player_id |String | |assist1_player_id |String | |assist2_player_id |String | |shooting_player_id |String | |committed_player_id |String | |drawn_player_id |String | |penalty_type_code |String | |shot_type |String |
| col_name | type | description |
|---|---|---|
game_id | String | NHL game id as a string (e.g. "2023020001"), from the payload's id. |
season | Int64 | Season's end year (2024 for 2023-24), as the loaders and release tags use it. |
event_idx | Int64 | 0-based position of the play within its game, in the feed's order. |
period | Int64 | Period number. 1-3 are regulation and 4 is overtime; in the playoffs 5 and up are further overtimes, while a regular-season shootout is logged as period 5. |
time_in_period | String | Clock time elapsed in the period, as "MM:SS". |
type_desc_key | String | api-web event type (e.g. "faceoff", "shot-on-goal", "goal", "penalty", "giveaway"). |
event_owner_team_id | String | NHL team id of the team the event belongs to (the faceoff winner's team, the shooting team, the penalized team). |
zone_code | String | Zone of the event from the owning team's point of view, "O" (offensive), "D" (defensive) or "N" (neutral). |
x_coord | Float64 | Rink x coordinate of the event in feet, -100 to 100, from the feed (not normalized for direction). |
y_coord | Float64 | Rink y coordinate of the event in feet, -42.5 to 42.5. |
situation_code | String | Four digits, away goalie in net (1/0), away skaters, home skaters, home goalie in net (e.g. "1551" at five on five). |
home_team_id | String | NHL team id of the home team, from the payload's homeTeam.id. |
home_team_defending_side | String | Side of the rink the home team defends in this period, "left" or "right". |
winning_player_id | String | NHL player id of the faceoff winner. |
losing_player_id | String | NHL player id of the faceoff loser. |
scoring_player_id | String | NHL player id of the goal scorer. |
assist1_player_id | String | NHL player id of the primary assister on a goal. |
assist2_player_id | String | NHL player id of the secondary assister on a goal. |
shooting_player_id | String | NHL player id of the shooter on a shot, missed shot or blocked shot. |
committed_player_id | String | NHL player id of the player who committed the penalty. |
drawn_player_id | String | NHL player id of the player who drew the penalty. |
penalty_type_code | String | api-web penalty class code (e.g. "MIN" minor, "MAJ" major, "BEN" bench minor, "PS" penalty shot). |
shot_type | String | Shot type the feed records (e.g. "wrist", "snap", "slap", "backhand", "tip-in"). |
Raises
| Exception | Description |
|---|---|
NoDataError | Api-web answered 404 for a game id. |
AssetFetchError | A request failed after retries (e.g. 429 or 5xx). |
ValueError | With require_final, a game is not final. |
Example
import polars as pl
from sportsdataverse.nhl import load_nhl_schedules
from sportsdataverse.nhl.nhl_microstat_pbp import nhl_microstat_pbp
from sportsdataverse.nhl.nhl_penalty_value import nhl_penalty_value
ids = load_nhl_schedules([2024]).filter(pl.col("game_type") == "R")["game_id"]
pbp = nhl_microstat_pbp(ids.to_list()[:10])
print(nhl_penalty_value(pbp).head())
nhl_pbp_disk
nhl_pbp_disk(game_id, path_to_json)
Read a saved ESPN NHL play-by-play payload from disk.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
game_id | The ESPN game id; the file read is {game_id}.json. | ||
path_to_json | The directory holding the saved payloads. |
Returns
The payload exactly as saved (the raw ESPN summary JSON), ready for helper_nhl_pbp.
Raises
| Exception | Description |
|---|---|
FileNotFoundError | There is no {game_id}.json in path_to_json. |
nhl_web_pbp_to_microstat
nhl_web_pbp_to_microstat(payloads: 'Union[Mapping[str, Any], Iterable[Mapping[str, Any]]]', *, require_final: 'bool' = True, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
Convert raw api-web play-by-play payloads to the microstat pbp contract.
No network access: pass payloads already fetched with
nhl_web_pbp(game_id, return_parsed=False) (or read from disk). Plays
keep the feed's order, and event_idx numbers them from 0 within each
game. game_id and home_team_id come from the payload's id and
homeTeam.id. game_id is a string, as in the fitting corpus (the
schedule loaders carry it as an integer: cast before joining). The models'
constants were fitted on regular-season games; the converter does not
filter by game type, so choose the games you pass.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
payloads | Union[Mapping[str, Any], Iterable[Mapping[str, Any]]] | One raw gamecenter/{game_id}/play-by-play JSON payload, or an iterable of them. | |
require_final | bool | True | Refuse a payload whose gameState is not "FINAL" or "OFF" (a game not started or still in progress would give no plays or only some). False converts whatever plays it holds. |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
One row per play, in the column order below. Zero payloads, or payloads with no plays, return a zero-row frame with this schema. |col_name |type | |:------------------------|:-------| |game_id |String | |season |Int64 | |event_idx |Int64 | |period |Int64 | |time_in_period |String | |type_desc_key |String | |event_owner_team_id |String | |zone_code |String | |x_coord |Float64 | |y_coord |Float64 | |situation_code |String | |home_team_id |String | |home_team_defending_side |String | |winning_player_id |String | |losing_player_id |String | |scoring_player_id |String | |assist1_player_id |String | |assist2_player_id |String | |shooting_player_id |String | |committed_player_id |String | |drawn_player_id |String | |penalty_type_code |String | |shot_type |String |
| col_name | type | description |
|---|---|---|
game_id | String | NHL game id as a string (e.g. "2023020001"), from the payload's id. |
season | Int64 | Season's end year (2024 for 2023-24), as the loaders and release tags use it. |
event_idx | Int64 | 0-based position of the play within its game, in the feed's order. |
period | Int64 | Period number. 1-3 are regulation and 4 is overtime; in the playoffs 5 and up are further overtimes, while a regular-season shootout is logged as period 5. |
time_in_period | String | Clock time elapsed in the period, as "MM:SS". |
type_desc_key | String | api-web event type (e.g. "faceoff", "shot-on-goal", "goal", "penalty", "giveaway"). |
event_owner_team_id | String | NHL team id of the team the event belongs to (the faceoff winner's team, the shooting team, the penalized team). |
zone_code | String | Zone of the event from the owning team's point of view, "O" (offensive), "D" (defensive) or "N" (neutral). |
x_coord | Float64 | Rink x coordinate of the event in feet, -100 to 100, from the feed (not normalized for direction). |
y_coord | Float64 | Rink y coordinate of the event in feet, -42.5 to 42.5. |
situation_code | String | Four digits, away goalie in net (1/0), away skaters, home skaters, home goalie in net (e.g. "1551" at five on five). |
home_team_id | String | NHL team id of the home team, from the payload's homeTeam.id. |
home_team_defending_side | String | Side of the rink the home team defends in this period, "left" or "right". |
winning_player_id | String | NHL player id of the faceoff winner. |
losing_player_id | String | NHL player id of the faceoff loser. |
scoring_player_id | String | NHL player id of the goal scorer. |
assist1_player_id | String | NHL player id of the primary assister on a goal. |
assist2_player_id | String | NHL player id of the secondary assister on a goal. |
shooting_player_id | String | NHL player id of the shooter on a shot, missed shot or blocked shot. |
committed_player_id | String | NHL player id of the player who committed the penalty. |
drawn_player_id | String | NHL player id of the player who drew the penalty. |
penalty_type_code | String | api-web penalty class code (e.g. "MIN" minor, "MAJ" major, "BEN" bench minor, "PS" penalty shot). |
shot_type | String | Shot type the feed records (e.g. "wrist", "snap", "slap", "backhand", "tip-in"). |
Raises
| Exception | Description |
|---|---|
ValueError | With require_final, a payload's game is not final; or a payload's id is not an integer. |
Example
import polars as pl
from sportsdataverse.nhl.nhl_api_web import nhl_web_pbp
from sportsdataverse.nhl.nhl_microstat_pbp import nhl_web_pbp_to_microstat
raw = nhl_web_pbp(2023020001, return_parsed=False)
pbp = nhl_web_pbp_to_microstat(raw)
print(pbp.filter(pl.col("type_desc_key") == "faceoff").head())