Skip to main content

NHL — additional Python functions — Play-by-play, schedule & rosters

espn_nhl_game_rosters​

espn_nhl_game_rosters(game_id: 'int', raw=False, return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_nhl_game_rosters() - Pull the game by id.

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from espn_nhl_schedule().
rawFalse
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False, returns a polars dataframe.

Returns

Polars dataframe of game roster data with columns: 'athlete_id', 'athlete_uid', 'athlete_guid', 'athlete_type', 'first_name', 'last_name', 'full_name', 'athlete_display_name', 'short_name', 'weight', 'display_weight', 'height', 'display_height', 'age', 'date_of_birth', 'slug', 'jersey', 'linked', 'active', 'alternate_ids_sdr', 'birth_place_city', 'birth_place_state', 'birth_place_country', 'headshot_href', 'headshot_alt', 'experience_years', 'experience_display_value', 'experience_abbreviation', 'status_id', 'status_name', 'status_type', 'status_abbreviation', 'hand_type', 'hand_abbreviation', 'hand_display_value', 'draft_display_text', 'draft_round', 'draft_year', 'draft_selection', 'player_id', 'starter', 'valid', 'did_not_play', 'display_name', 'ejected', 'athlete_href', 'position_href', 'statistics_href', 'team_id', 'team_guid', 'team_uid', 'team_slug', 'team_location', 'team_name', 'team_abbreviation', 'team_display_name', 'team_short_display_name', 'team_color', 'team_alternate_color', 'is_active', 'is_all_star', 'logo_href', 'logo_dark_href', 'game_id'

col_nametypedescription
athlete_idintegerESPN athlete identifier (echoed from arg).
athlete_uidcharacterESPN athlete UID (universal identifier).
athlete_guidcharacterESPN athlete GUID.
athlete_typecharacterAthlete type / class.
alternate_idcharacterAlternate player identifier.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
full_namecharacterPlayer full name.
athlete_display_namecharacterPlayer display name.
short_namecharacterShort game name.
weightdoublePlayer weight in pounds.
display_weightcharacterFormatted weight string.
heightdoublePlayer height in inches.
display_heightcharacterFormatted height string.
ageintegerPlayer age.
date_of_birthcharacterDate of birth (ISO 8601).
debut_yearintegerYear of NHL debut.
slugcharacterURL slug.
jerseycharacterJersey number.
linkedlogicalTRUE if the record is linked to a related entity.
activelogicalWhether athlete is currently active.
alternate_ids_sdrcharacterAlternate ids sdr.
birth_place_citycharacterBirth place city.
birth_place_statecharacterBirth place state.
birth_place_countrycharacterBirth place country.
birth_country_abbreviationcharacterBirth country abbreviation.
headshot_hrefcharacterPlayer headshot image URL.
headshot_altcharacterHeadshot alt text.
hand_typecharacterShooting/catching hand type.
hand_abbreviationcharacterHand abbreviation.
hand_display_valuecharacterHand display value.
contracts_hrefcharacterESPN API hypermedia URL pointing to the contract history resource for this player.
experience_yearsintegerExperience years.
draft_display_textcharacterDraft display text.
draft_roundintegerDraft round.
draft_yearintegerDraft year the lottery applies to.
draft_selectionintegerDraft selection.
draft_team_hrefcharacterESPN API hypermedia URL linking to the team that originally drafted this player.
status_idcharacterStatus identifier.
status_namecharacterStatus name.
status_typecharacterStatus type.
status_abbreviationcharacterStatus abbreviation.
jersey_rightcharacterRight-aligned display string for the player's jersey number, used in ESPN scoreboard rendering contexts.
display_namecharacterPlayer display name.
scratchedlogicalWhether the player was a healthy scratch.
scratch_reasoncharacterReason for scratch (if applicable).
athlete_hrefcharacterESPN API hypermedia URL linking to the full athlete resource for this player, usable to fetch detailed biographical and statistical data.
position_hrefcharacterESPN API hypermedia URL pointing to the position resource that defines this player's positional classification.
statistics_hrefcharacterESPN API hypermedia URL linking to the statistics resource for this player's season or career totals.
team_idintegerUnique team identifier.
orderintegerDisplay order within officials list.
home_awaycharacterHome or away indicator.
winnerlogicalWhether this competitor won the game.
team_guidcharacterESPN team GUID.
team_uidcharacterESPN team uid.
team_slugcharacterTeam URL slug.
team_locationcharacterTeam city/location.
team_namecharacterTeam name.
team_nicknamecharacterTeam nickname.
team_abbreviationcharacterTeam abbreviation.
team_display_namecharacterTeam display name.
team_short_display_namecharacterTeam short display name.
team_colorcharacterTeam primary color hex.
team_alternate_colorcharacterTeam alternate color hex.
is_activelogicalWhether the team is active.
is_all_starlogicalWhether the team is an all-star team.
team_alternate_ids_sdrcharacterAlternate team identifier from the ESPN SDR (Sports Data Repository) system, used to cross-reference team records across ESPN data sources.
logo_hrefcharacterTeam or league logo URL.
logo_dark_hrefcharacterLogo URL for dark backgrounds.
game_idintegerUnique game identifier.

Example

from sportsdataverse.nhl import espn_nhl_game_rosters
rosters = espn_nhl_game_rosters(game_id=401559395)
print(rosters.shape)
rosters.select(["athlete_display_name", "jersey", "team_abbreviation", "starter"]).head(10)

# Just the starters

import polars as pl
rosters.filter(pl.col("starter") == True).select(["athlete_display_name", "team_abbreviation"])

# Pandas round-trip

rosters_pd = espn_nhl_game_rosters(game_id=401559395, return_as_pandas=True)
rosters_pd[["athlete_display_name", "team_abbreviation", "did_not_play"]].head()

espn_nhl_pbp​

espn_nhl_pbp(game_id: 'int', raw=False, **kwargs) -> 'Dict'

espn_nhl_pbp() - Pull the game by id. Data from API endpoints - nhl/playbyplay, nhl/summary

Parameters

ParameterTypeDefaultDescription
game_idintUnique ESPN event id (NOT the NHL native game id), can be obtained from nhl_schedule().
rawFalse

Returns

Dictionary of game data with keys - "gameId", "plays", "boxscore", "header", "broadcasts", "videos", "playByPlaySource", "standings", "leaders", "seasonseries", "pickcenter", "againstTheSpread", "odds", "onIce", "gameInfo", "season"

Example

from sportsdataverse.nhl import espn_nhl_pbp
game = espn_nhl_pbp(game_id=401559395)
list(game.keys()) # 'gameId', 'plays', 'boxscore', ...

# Inspect parsed plays and a quick filter on goal events

import polars as pl
plays = pl.DataFrame(game["plays"])
print(plays.shape)
goals = plays.filter(pl.col("type.text") == "Goal")
goals.select(["period", "time", "text"]).head()

# Pull the unparsed payload for custom downstream parsing

raw = espn_nhl_pbp(game_id=401559395, raw=True)
sorted(raw.keys())[:5]

espn_nhl_player_stats​

espn_nhl_player_stats(athlete_id: 'int', season: 'int', *, season_type: 'str' = 'regular', total: 'bool' = False, raw: 'bool' = False, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame | dict[str, Any]'

Pull an NHL athlete's ESPN season stat line as one wide row.

See sportsdataverse.wbb.espn_wbb_player_stats for full documentation of the wide return shape, the {category}_{stat} stat columns (for hockey: offensive_*, defensive_*, penalties_*, ...), the athlete / team metadata blocks, and the season_type / total parameters. For the richer multi-category web-v3 payload use sportsdataverse.nhl.espn_nhl_player_stats_v3.

Parameters

ParameterTypeDefaultDescription
athlete_idintESPN NHL athlete identifier (e.g. 3895074 for Connor McDavid).
seasonintSeason year, used in the core-v2 path.
season_typestr'regular'"regular" (type 2) or "postseason" (type 3).
totalboolFalseForward-compat totals passthrough.
rawboolFalseIf True, returns the raw core-v2 statistics JSON dict.
return_as_pandasboolFalseIf True, returns a pandas DataFrame; else polars.

Returns

A single-row wide DataFrame (polars by default). When raw=True returns the raw statistics JSON dict.

col_nametypedescription
seasonintegerSeason year (echoed from arg).
season_typecharacterSeason type code (echoed from arg).
totallogicalTotal.
athlete_idintegerESPN athlete identifier (echoed from arg).
athlete_uidcharacterESPN athlete UID (universal identifier).
athlete_guidcharacterESPN athlete GUID.
athlete_typecharacterAthlete type / class.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
full_namecharacterPlayer full name.
display_namecharacterPlayer display name.
short_namecharacterShort game name.
weightdoublePlayer weight in pounds.
display_weightcharacterFormatted weight string.
heightdoublePlayer height in inches.
display_heightcharacterFormatted height string.
ageintegerPlayer age.
date_of_birthcharacterDate of birth (ISO 8601).
jerseycharacterJersey number.
slugcharacterURL slug.
activelogicalWhether athlete is currently active.
position_idintegerOfficial position identifier.
position_namecharacterOfficial position name (e.g. "Referee", "Linesman").
position_display_namecharacterPosition display name.
position_abbreviationcharacterPosition abbreviation.
college_namecharacterCollege name.
status_idintegerStatus identifier.
status_namecharacterStatus name.
defensive_goals_againstdoubleTotal goals allowed by a goaltender over the selected season and season type.
defensive_avg_goals_againstdoubleAverage goals allowed per game by a goaltender over the selected season and season type, equivalent to goals-against average (GAA).
defensive_shots_againstdoubleTotal shots on goal faced by a goaltender across all game situations over the selected season and season type.
defensive_avg_shots_againstdoubleAverage number of shots on goal faced by a goaltender per game over the selected season and season type.
defensive_shootout_savescharacterTotal number of shootout attempts stopped by a goaltender over the selected season and season type.
defensive_shootout_shots_againstdoubleTotal number of penalty-shootout attempts faced by a goaltender over the selected season and season type.
defensive_shootout_save_pctdoublePercentage of shootout attempts stopped by a goaltender, calculated as shootout saves divided by shootout shots faced over the season.
defensive_empty_net_goals_againstcharacterNumber of goals allowed by a goaltender into an empty net (opponent pulled goalie) over the selected season and season type.
defensive_shutoutsdoubleTotal number of games in which a goaltender allowed zero goals over the selected season and season type.
defensive_savesdoubleTotal saves made by a goaltender across all game situations over the selected season and season type.
defensive_save_pctdoublePercentage of shots stopped by a goaltender, calculated as saves divided by shots against, over the selected season and season type.
defensive_overtime_lossesdoubleNumber of games a goaltender's team lost in overtime (OT or shootout) while the goaltender was the decision goalie over the selected season.
defensive_blocked_shotsdoubleTotal number of shots blocked by a skater before reaching the goaltender over the selected season and season type.
defensive_hitsdoubleTotal body checks delivered by a skater over the selected season and season type as tracked by ESPN.
defensive_even_strength_savesdoubleTotal saves made by a goaltender while both teams were at full strength (5-on-5) over the selected season and season type.
defensive_power_play_savesdoubleTotal saves made by a goaltender while the opponent had a power-play advantage over the selected season and season type.
defensive_short_handed_savesdoubleTotal saves made by a goaltender while the goaltender's team was short-handed (killing a penalty) over the selected season and season type.
general_gamesdoubleCareer games played.
general_game_starteddoubleNumber of games in which the player was the starting goaltender over the selected season and season type.
general_team_games_playeddoubleTotal number of regular-season or playoff games played by the player's team during the selected season and season type.
general_winsdoubleTotal wins recorded by a goaltender as the decision goalie over the selected season and season type.
general_lossesdoubleTotal regulation-time losses recorded by a goaltender as the decision goalie over the selected season and season type.
general_tiescharacterNumber of games that ended in a tie credited to a goaltender, applicable to seasons before the NHL eliminated ties in 2005-06.
general_plus_minusdoubleA player's estimated on-court impact on team performance measured in point differential per 100 possessions.
general_time_on_icedoubleCumulative time on ice for a skater or goaltender across all games in the selected season and season type, in total seconds or minutes as provided by ESPN.
general_time_on_ice_per_gamedoubleAverage time on ice per game for a skater or goaltender over the selected season and season type.
general_shiftsdoubleTotal number of shifts a skater took during the selected season and season type.
general_shifts_per_gamedoubleAverage number of shifts per game taken by a skater over the selected season and season type.
general_productiondoubleComposite production metric combining goals, assists, and other scoring contributions for a skater, as defined by ESPN, over the selected season.
offensive_goalsdoubleGoals (offensive category).
offensive_avg_goalsdoubleAverage goals scored per game by a skater over the selected season and season type.
offensive_assistsdoubleCareer assists.
offensive_shots_totaldoubleShots on goal.
offensive_avg_shotsdoubleAverage shots on goal taken per game by a skater over the selected season and season type.
offensive_pointsdoubleCareer points.
offensive_points_per_gamedoubleAverage points (goals plus assists) earned per game by a skater over the selected season and season type.
offensive_power_play_goalsdoublePower-play goals.
offensive_power_play_assistsdoubleTotal assists recorded by a skater while on the power play over the selected season and season type.
offensive_short_handed_goalsdoubleTotal goals scored by a skater while the player's team was shorthanded over the selected season and season type.
offensive_short_handed_assistsdoubleTotal assists recorded by a skater while killing a penalty (shorthanded) over the selected season and season type.
offensive_shootout_attemptsdoubleTotal number of penalty-shootout attempts taken by a skater over the selected season and season type.
offensive_shootout_goalsdoubleTotal goals scored by a skater in penalty shootouts over the selected season and season type.
offensive_shootout_shot_pctdoublePercentage of penalty-shootout attempts by a skater that resulted in a goal over the selected season and season type.
offensive_shooting_pctdoubleShooting percentage.
offensive_total_face_offsdoubleTotal number of faceoffs taken by the player across all situations over the selected season and season type.
offensive_faceoffs_wondoubleTotal number of faceoffs won by the player over the selected season and season type.
offensive_faceoffs_lostdoubleTotal number of faceoffs lost by the player over the selected season and season type.
offensive_faceoff_percentdoublePercentage of faceoffs won by the player, calculated as faceoffs won divided by total faceoffs taken, over the selected season and season type.
offensive_game_tying_goalscharacterNumber of goals scored by a skater that tied the game at the time of the goal, over the selected season and season type.
offensive_game_winning_goalsdoubleGame-winning goals.
penalties_penalty_minutesdoubleCareer penalty minutes.
penalties_major_penaltiesdoubleTotal number of five-minute major penalties assessed to the player over the selected season and season type.
penalties_minor_penaltiesdoubleTotal number of two-minute minor penalties assessed to the player over the selected season and season type.
penalties_match_penaltiesdoubleTotal number of match penalties assessed to the player for deliberately injuring an opponent, resulting in ejection, over the selected season and season type.
penalties_misconductsdoubleTotal number of ten-minute misconduct penalties assessed to the player over the selected season and season type.
penalties_game_misconductsdoubleTotal number of game misconduct penalties assessed to the player, resulting in ejection, over the selected season and season type.
penalties_boarding_penaltiesdoubleTotal number of boarding infractions (hitting an opponent into the boards from behind) called against the player over the selected season and season type.
penalties_unsportsmanlike_penaltiesdoubleTotal number of unsportsmanlike conduct penalties assessed to the player over the selected season and season type.
penalties_fighting_penaltiesdoubleTotal number of fighting majors assessed to the player over the selected season and season type.
penalties_avg_fightsdoubleAverage number of fights per game involving the player over the selected season and season type, as tracked by ESPN.
penalties_time_between_fightscharacterAverage time elapsed between fights involving the player during the selected season and season type, as tracked by ESPN.
penalties_instigator_penaltiesdoubleTotal number of instigator penalties assessed to the player for initiating a fight over the selected season and season type.
penalties_charging_penaltiesdoubleTotal number of charging infractions (skating excessive distance to deliver a hit) called against the player over the selected season and season type.
penalties_hooking_penaltiesdoubleTotal number of hooking infractions (using the stick to impede an opponent's movement) called against the player over the selected season and season type.
penalties_tripping_penaltiesdoubleTotal number of tripping infractions (using a stick, arm, or leg to cause an opponent to fall) called against the player over the selected season and season type.
penalties_roughing_penaltiesdoubleTotal number of roughing infractions (unnecessary physical altercations after the whistle) called against the player over the selected season and season type.
penalties_holding_penaltiesdoubleTotal number of holding infractions (impeding an opponent with the hands or arms) called against the player over the selected season and season type.
penalties_interference_penaltiesdoubleTotal number of interference infractions (impeding a player not in possession of the puck) called against the player over the selected season and season type.
penalties_slashing_penaltiesdoubleTotal number of slashing infractions (swinging the stick at an opponent) called against the player over the selected season and season type.
penalties_high_sticking_penaltiesdoubleTotal number of high-sticking infractions (stick contacting an opponent above the shoulders) called against the player over the selected season and season type.
penalties_cross_checking_penaltiesdoubleTotal number of cross-checking infractions (using the shaft of the stick to check an opponent) called against the player over the selected season and season type.
penalties_stick_holding_penaltiesdoubleTotal number of stick-holding infractions called against the player for grabbing an opponent's stick over the selected season and season type.
penalties_goalie_interference_penaltiesdoubleTotal number of goalie interference infractions called against the player for impeding the goaltender over the selected season and season type.
penalties_elbowing_penaltiesdoubleTotal number of elbowing infractions (using the elbow to check an opponent) called against the player over the selected season and season type.
penalties_diving_penaltiesdoubleTotal number of diving or embellishment infractions called against the player over the selected season and season type.
rpi_winsdoubleTotal wins recorded under ESPN's RPI-based standings metric for the player's team over the selected season and season type.
rpi_lossesdoubleTotal losses recorded under ESPN's RPI-based standings metric for the player's team over the selected season and season type.
rpi_ot_lossescharacterOvertime losses recorded under ESPN's RPI-based standings metric for the player's team over the selected season and season type.
rpi_pointsdoubleStandings points accumulated under ESPN's RPI-based standings metric for the player's team over the selected season and season type.
rpi_rpicharacterRating Percentage Index (RPI) value for the player's team, reflecting strength of schedule and win/loss record, over the selected season and season type.
rpi_soscharacterStrength of Schedule (SOS) component of the ESPN RPI calculation for the player's team over the selected season and season type.
rpi_power_rankcharacterESPN Power Rank position for the player's team within the selected season and season type, derived from the RPI standings model.
rpi_points_forcharacterTotal goals or points scored used in ESPN's RPI-based standings computation for the player's team over the selected season and season type.
rpi_points_againstcharacterTotal goals or points allowed used in ESPN's RPI-based standings computation for the player's team over the selected season and season type.
team_idintegerUnique team identifier.
team_uidcharacterESPN team uid.
team_guidcharacterESPN team GUID.
team_slugcharacterTeam URL slug.
team_locationcharacterTeam city/location.
team_namecharacterTeam name.
team_abbreviationcharacterTeam abbreviation.
team_display_namecharacterTeam display name.
team_short_display_namecharacterTeam short display name.
team_colorcharacterTeam primary color hex.
team_alternate_colorcharacterTeam alternate color hex.
team_is_activelogicalTRUE if the team is currently active.
team_logo_hrefcharacterDefault team logo URL; team_detail = TRUE only.

Example

from sportsdataverse.nhl import espn_nhl_player_stats
df = espn_nhl_player_stats(athlete_id=3895074, season=2023)
df.select(["full_name", "team_display_name", "offensive_goals"])

espn_nhl_schedule​

espn_nhl_schedule(dates=None, season_type=None, limit=500, return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_nhl_schedule - look up the NHL schedule for a given date

Parameters

ParameterTypeDefaultDescription
datesintNoneUsed to define different seasons. 2002 is the earliest available season.
season_typeintNoneseason type, 1 for pre-season, 2 for regular season, 3 for post-season, 4 for all-star, 5 for off-season
limitint500number of records to return, default: 500.
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False, returns a polars dataframe.

Returns

Polars dataframe containing schedule dates for the requested season. Returns None if no games

col_nametypedescription
idcharacterUnique player identifier.
uidcharacterCompetitor uid string.
datecharacterGame date (ISO 8601 datetime string).
attendanceintegerGame attendance.
time_validlogicalWhether the start time is confirmed.
neutral_sitelogicalWhether the game is at a neutral site.
play_by_play_availablelogicalWhether play-by-play data is available.
recentlogicalWhether the game is recent.
start_datecharacterSeason start date.
broadcastcharacterBroadcast network(s).
highlightscharacterGame highlight urls.
notes_typecharacterNotes type.
notes_headlinecharacterNotes headline.
broadcast_marketcharacterBroadcast market label (e.g. 'national', 'home').
broadcast_namecharacterBroadcast name.
type_idcharacterPlay type id.
type_abbreviationcharacterPlay type abbreviation.
venue_idcharacterVenue identifier.
venue_full_namecharacterVenue full name.
venue_address_citycharacterVenue address city.
venue_address_statecharacterVenue address state / region.
venue_address_countrycharacterCountry name or code for the country in which the game venue is located, as provided by ESPN's schedule endpoint.
venue_indoorlogicalWhether the venue is indoors.
status_clockdoubleGame clock in seconds.
status_display_clockcharacterDisplay clock string.
status_periodintegerCurrent period.
status_type_idcharacterStatus type identifier.
status_type_namecharacterStatus type name.
status_type_statecharacterStatus state (pre/in/post).
status_type_completedlogicalWhether the game is complete.
status_type_descriptioncharacterStatus description.
status_type_detailcharacterStatus detail text.
status_type_short_detailcharacterShort status detail.
format_regulation_periodsintegerFormat regulation periods.
home_idcharacterHome team ESPN identifier.
home_uidcharacterHome team's uid.
home_locationcharacterHome team city.
home_namecharacterHome team display name.
home_abbreviationcharacterHome team abbreviation.
home_display_namecharacterHome team display name.
home_short_display_namecharacterHome short display name.
home_colorcharacterHome team primary color hex.
home_alternate_colorcharacterHome team alternate color hex.
home_is_activelogicalHome team's is active.
home_venue_idcharacterUnique identifier for home venue.
home_logocharacterHome team logo URL.
home_scorecharacterHome team final score.
home_linescoreslistPeriod-by-period goal totals for the home team, stored as an array of integer scores indexed by period.
home_recordscharacterSerialized win-loss-overtime record string for the home team at the time of the scheduled game.
away_idcharacterAway team ESPN identifier.
away_uidcharacterAway team's uid.
away_locationcharacterAway team city.
away_namecharacterAway team display name.
away_abbreviationcharacterAway team abbreviation.
away_display_namecharacterAway team display name.
away_short_display_namecharacterAway short display name.
away_colorcharacterAway team primary color hex.
away_alternate_colorcharacterAway team alternate color hex.
away_is_activelogicalAway team's is active.
away_venue_idcharacterUnique identifier for away venue.
away_logocharacterAway team logo URL.
away_scorecharacterAway team final score.
away_linescoreslistPeriod-by-period goal totals for the away team, stored as an array of integer scores indexed by period.
away_recordscharacterSerialized win-loss-overtime record string for the away team at the time of the scheduled game.
game_idintegerUnique game identifier.
seasonintegerSeason year (echoed from arg).
season_typeintegerSeason type code (echoed from arg).

Example

from sportsdataverse.nhl import espn_nhl_schedule
sched = espn_nhl_schedule(dates=20230613) # 2023 Stanley Cup Final game date
print(sched.shape)
sched.select(["game_id", "home_name", "away_name", "status_type_description"]).head()

# Pull a regular-season slate from a season-year

reg = espn_nhl_schedule(dates=2023, season_type=2, limit=500)
reg.group_by("status_type_description").len().sort("len", descending=True)

# Pandas round-trip for one date

espn_nhl_schedule(dates=20230613, return_as_pandas=True).head()