Skip to main content
Version: 0.2.0

NBA — additional Python functions — ESPN

espn_nba_calendar​

espn_nba_calendar(season=None, ondays=None, return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_nba_calendar - look up the NBA calendar for a given season from ESPN

Parameters

ParameterTypeDefaultDescription
seasonintNoneUsed to define different seasons. 2002 is the earliest available season.
ondaysbooleanNoneUsed to return dates for calendar ondays
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False, returns a polars dataframe.

Returns

Polars dataframe containing calendar dates for the requested season.

col_nametypedescription
seasonInt64Season year.
datetimeStringThe calendar day as ESPN sends it, an ISO 8601 UTC timestamp string.
dateStringDate in YYYY-MM-DD format.
yearString4-digit year.
monthStringMonth of the calendar day as a two-digit string.
dayStringDay number within the month.
dateURLStringThe calendar day as YYYYMMDD, the dates= value of that day's scoreboard request.
urlStringRotoWire player page URL.

Raises

ExceptionDescription
ValueErrorIf season is less than 2002.

Example

from sportsdataverse.nba import espn_nba_calendar
cal = espn_nba_calendar(season=2023)
print(cal.shape)

# Use ondays to get every scheduled date for the season

ondays = espn_nba_calendar(season=2023, ondays=True)

# Pipeline next step (loop the URLs to scrape day-by-day)

cal = espn_nba_calendar(season=2023, ondays=True)
urls = cal["url"].to_list() # feed each into espn_nba_schedule

espn_nba_game_all​

espn_nba_game_all(game_id: 'int', return_as_pandas: 'bool' = False, **kwargs)

espn_nba_game_all() - Pull one game's plays, team box and player box from one ESPN request.

The hoopR name for this request (hoopR::espn_nba_game_all): a single nba/summary fetch, returned as the three frames espn_nba_pbp, espn_nba_team_box and espn_nba_player_box would return one request each.

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from espn_nba_schedule().
return_as_pandasboolFalseIf True, the three frames are pandas instead of polars.

Returns

hoopR's list names as keys -- "Plays" (the load_nba_pbp release frame), "Team" (the team box) and "Player" (the player box).

Example

from sportsdataverse.nba import espn_nba_game_all
game = espn_nba_game_all(game_id=401585183)
print(game["Plays"].shape, game["Team"].shape, game["Player"].shape)

# Pipeline next step (one line)

game["Player"].sort("points", descending=True, nulls_last=True).select("athlete_display_name", "points").head()

espn_nba_game_rosters​

espn_nba_game_rosters(game_id: 'int', raw=False, return_as_pandas=False, **kwargs) -> 'pl.DataFrame | pd.DataFrame | dict'

espn_nba_game_rosters() - Pull the game by id.

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from espn_nba_schedule().
rawboolFalseIf True, returns the Core v2 competitors payload (dict) as ESPN sent it; its roster, team and athlete $ref links are not followed.
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' plus the athlete's position_id, position_name, position_display_name, position_abbreviation and position_leaf. With raw=True, the competitors payload (dict).

col_nametypedescription
athlete_idInt64Unique athlete identifier (ESPN).
athlete_uidStringESPN athlete UID (universal identifier).
athlete_guidStringESPN athlete GUID.
athlete_typeStringAthlete type / class.
first_nameStringPlayer's first name.
last_nameStringPlayer's last name.
full_nameStringPlayer's full name.
athlete_display_nameStringAthlete display name (full).
short_nameStringShort display name.
weightFloat64Player weight in pounds.
display_weightStringPlayer weight in display format (e.g. '180 lbs').
heightFloat64Player height (string e.g. '6-2' or inches).
display_heightStringPlayer height in display format (e.g. '6-2').
ageInt64Player age (in years).
date_of_birthStringDate of birth (YYYY-MM-DD).
debut_yearInt64Year of professional debut.
citizenshipStringCitizenship.
slugStringURL-safe identifier.
jerseyStringJersey number worn by the player.
linkedBooleanTRUE if the record is linked to a related entity.
activeBooleanTRUE if the row represents an active record (player / team / season).
alternate_ids_sdrString
birth_place_cityStringBirth place city.
birth_place_countryStringBirth place country.
headshot_hrefStringHeadshot image URL.
headshot_altStringAlternative-text label for the headshot.
contracts_hrefString
experience_yearsInt64Experience years.
contract_hrefString
contract_bird_statusInt64Contract bird status.
contract_base_year_compensation_activeBooleanContract base year compensation active.
contract_poison_pill_provision_activeBoolean
contract_incoming_trade_valueInt64Contract incoming trade value.
contract_outgoing_trade_valueInt64Contract outgoing trade value.
contract_minimum_salary_exceptionBooleanContract minimum salary exception.
contract_option_typeInt64Contract option type.
contract_salaryInt64Contract salary.
contract_salary_remainingInt64Contract salary remaining.
contract_years_remainingInt64Contract years remaining.
contract_season_hrefString
contract_team_hrefString
contract_trade_kicker_activeBooleanContract trade kicker active.
contract_trade_kicker_percentageFloat64Contract trade kicker percentage (0-1 decimal).
contract_trade_kicker_valueInt64Contract trade kicker value.
contract_trade_kicker_trade_valueInt64Contract trade kicker trade value.
contract_trade_restrictionBooleanContract trade restriction.
contract_unsigned_foreign_pickBooleanContract unsigned foreign pick.
contract_activeBooleanContract active.
draft_display_textStringDraft display text.
draft_roundInt64Round of the draft selection.
draft_yearInt64Draft year (4-digit).
draft_selectionInt64Draft selection.
draft_team_hrefString
draft_pick_hrefString
status_idInt64Status identifier.
status_nameStringStatus label.
status_typeStringStatus type.
status_abbreviationStringStatus abbreviation.
position_idInt64ESPN's numeric identifier of the athlete's listed position (the Core v2 position resource id).
position_nameStringName of the athlete's listed position from ESPN's position resource, e.g. Guard or Forward.
position_display_nameStringDisplay form of the athlete's listed position as ESPN renders it; usually equal to position_name.
position_abbreviationStringShort code of the athlete's listed position (e.g. G, F, RW, OL), from ESPN's position resource.
position_leafBooleanWhether the position is a leaf of ESPN's position tree; False marks a grouping, not a specific role.
birth_place_stateStringBirth place state.
college_athlete_hrefString
hand_typeStringHand type.
hand_abbreviationStringHand abbreviation.
hand_display_valueStringHand display value.
starterBooleanTRUE if the player was in the starting lineup; FALSE otherwise.
jersey_rightString
validBooleanValid.
did_not_playBooleanTRUE if the player did not appear in the game.
display_nameStringDisplay name.
reasonStringReason.
ejectedBooleanTRUE if the player was ejected from the game.
athlete_hrefString
position_hrefString
statistics_hrefString
team_idInt64Unique team identifier.
orderInt64Display order within the result set.
home_awayStringGame venue label ('home' or 'away').
winnerBooleanWinner.
team_guidStringESPN team GUID.
team_uidStringESPN universal team identifier (UID format 's:40~l:...~t:...').
team_slugStringURL-safe team identifier (e.g. 'lasvegas-aces' / 'aces').
team_locationStringTeam city or location string.
team_nameStringFull team display name (e.g. 'Las Vegas Aces').
team_abbreviationStringShort team abbreviation (e.g. 'LAS').
team_display_nameStringFull team display name.
team_short_display_nameStringShort team display name (e.g. 'Aces').
team_colorStringTeam primary color (hex without leading '#').
team_alternate_colorStringTeam alternate color (hex without leading '#').
is_activeBooleanIs active.
is_all_starBooleanIs all star.
logo_hrefStringTeam or league logo URL.
logo_dark_hrefStringLogo URL for dark backgrounds.
game_idInt64Unique game identifier.

Raises

ExceptionDescription
NoDataErrorESPN has no competitors, roster or athlete resource for the game (404), or every rostered athlete's $ref answered 404. A single 404 athlete is left out with a UserWarning and the rest of the roster is returned.
AssetFetchErrorA fetch failed (403, 429, 5xx, a dropped connection); never treated as a missing athlete.

Example

from sportsdataverse.nba import espn_nba_game_rosters
rosters = espn_nba_game_rosters(game_id=401585183)
print(rosters.shape)

# Pandas round-trip

rosters_pd = espn_nba_game_rosters(game_id=401585183, return_as_pandas=True)
rosters_pd.head()

# Pipeline next step (filter to game starters)

import polars as pl
starters = espn_nba_game_rosters(game_id=401585183).filter(
pl.col("starter") == True
)

espn_nba_pbp​

espn_nba_pbp(game_id: 'int', raw: 'bool' = False, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs)

espn_nba_pbp() - Pull one game's play-by-play from ESPN's nba/summary endpoint.

By default the plays come back as the frame the espn_nba_pbp release publishes (what ~sportsdataverse.nba.load_nba_pbp reads): snake_case columns, Int32 team / athlete / game ids, the Int64 play id and its play_id copy, game_date / game_date_time, the hoopR shot coordinates, athlete_name_{1,2,3}, and home_score / away_score rebuilt from the scoring plays when that reproduces the final (score_source says which).

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from nba_schedule().
rawboolFalseIf True, returns the raw json from the API endpoint (wins over return_parsed).
return_parsedboolTrueIf True (default), returns the release play-by-play frame. If False, returns the game dictionary (the shape before 0.2.0, which helper_nba_play_by_play / helper_nba_team_box / helper_nba_player_box and game_page_frames read).
return_as_pandasboolFalseIf True, returns the frame as pandas instead of polars. Ignored with raw=True or return_parsed=False, which return a dict.

Returns

One row per play, columns (in order) and dtypes as the release (load_nba_pbp) for that season, then the labeled actor roles ({role}_player_id / {role}_player_name for the shooter, assist, block, steal, turnover, foul, rebound, sub in / out and jump-ball winner / loser / recoverer) and shot_distance (feet), which the published releases predate; a pandas frame with return_as_pandas=True. Zero rows, with the release's columns and the role columns, when ESPN has no play-by-play for the game (playByPlaySource == "none") or 10 or fewer plays (hoopR returns NULL). With return_parsed=False, a dictionary of game data with keys - "gameId", "plays", "winprobability", "boxscore", "header", "broadcasts", "videos", "playByPlaySource", "standings", "leaders", "seasonseries", "timeouts", "pickcenter", "againstTheSpread", "odds", "predictor", "espnWP", "gameInfo", "season".

col_nametypedescription
game_play_numberInt32Sequential play number within the game.
idInt64Id.
play_idInt64ESPN play id, the same value as id as an Int64, under the name the game-story and win-probability frames use; sdv-py adds it at load when the release does not ship it.
sequence_numberInt32Sequence number representing a shot-possession (V3 PBP).
type_idInt32Type identifier (numeric).
type_textStringDisplay text for the type field.
textStringText description of the play / record.
away_scoreInt32Away team's score after the play. Rebuilt from the scoring plays in feed order when that reaches the official final (score_source 'rebuilt'), otherwise ESPN's per-play value (score_source 'espn'). Seasons published before the repair carry ESPN's per-play value.
home_scoreInt32Home team's score after the play. Rebuilt from the scoring plays in feed order when that reaches the official final (score_source 'rebuilt'), otherwise ESPN's per-play value (score_source 'espn'). Seasons published before the repair carry ESPN's per-play value.
period_numberInt32Numeric period (1-4 for quarters; 5+ for OT).
period_display_valueStringPeriod display label (e.g. '1st Quarter', 'OT').
clock_display_valueStringGame clock display string (e.g. '8:32').
scoring_playBooleanTRUE if the play resulted in points scored.
score_valueInt32Point value of the play (2 / 3 / 1).
team_idInt32Unique team identifier.
athlete_id_1Int32Primary athlete identifier (e.g. shooter).
athlete_id_2Int32Secondary athlete identifier (e.g. assister / fouler).
athlete_id_3Int32Athlete id 3.
wallclockStringWallclock.
shooting_playBooleanTRUE if the play was a shooting attempt.
coordinate_x_rawFloat64X coordinate as returned by the API before any adjustment.
coordinate_y_rawFloat64Y coordinate as returned by the API before any adjustment.
points_attemptedInt32Point value attempted on the shot (2 or 3; 1 for a free throw).
short_descriptionStringShort text description of the play from ESPN.
game_idInt32Unique game identifier.
seasonInt32Season year.
season_typeInt32Season type (1=pre-season, 2=regular season, 3=postseason, 4=off-season for ESPN; or string label for WNBA Stats).
home_team_idInt32Unique identifier for the home team.
home_team_nameStringHome team name.
home_team_mascotStringHome team mascot.
home_team_abbrevStringHome team three-letter abbreviation.
home_team_name_altStringAlternate home team name.
away_team_idInt32Unique identifier for the away team.
away_team_nameStringAway team name.
away_team_mascotStringAway team mascot.
away_team_abbrevStringAway team three-letter abbreviation.
away_team_name_altStringAlternate away team name.
game_spreadFloat64Game spread (signed; positive = home favored).
home_favoriteBooleanTRUE if the home team is the betting favorite.
game_spread_availableBooleanTRUE if a point spread was available.
home_team_spreadFloat64Home team's point spread.
qtrInt32Quarter (1-4) or OT period (5+).
timeStringTime / clock value.
clock_minutesInt32Clock minutes split out for convenience.
clock_secondsFloat64Clock seconds split out for convenience.
home_timeout_calledBooleanWhether the play is a timeout called by the home team.
away_timeout_calledBooleanWhether the play is a timeout called by the away team.
halfInt32Half of the game (1 or 2).
game_halfInt32Half of the game (1 or 2).
lag_qtrInt32Quarter lag (the previous-play's quarter).
lead_qtrInt32Quarter lead (the next-play's quarter).
lag_halfInt32A lag column on the half
lead_halfInt32A lead column on the half
start_quarter_seconds_remainingFloat64Seconds remaining in the period at the start of the play.
start_half_seconds_remainingFloat64Seconds remaining in the half at the start of the play.
start_game_seconds_remainingFloat64Seconds remaining in the game at the start of the play.
end_quarter_seconds_remainingFloat64Seconds remaining in the period at the end of the play.
end_half_seconds_remainingFloat64Seconds remaining in the half at the end of the play.
end_game_seconds_remainingFloat64Seconds remaining in the game at the end of the play.
periodInt32Period of the game (1-4 quarters; 5+ for OT).
coordinate_xFloat64X coordinate on the court (half-court layout).
coordinate_yFloat64Y coordinate on the court (half-court layout).
game_dateDateGame date (YYYY-MM-DD).
game_date_timeDatetime(time_unit='us', time_zone='America/New_York')Game start date/time (ISO 8601).
athlete_name_1StringName of the primary athlete involved in the play (pairs with athlete_id_1).
athlete_name_2StringName of the secondary athlete involved in the play (e.g. the assister or fouled player).
athlete_name_3StringName of the tertiary athlete involved in the play.
type_abbreviationStringType abbreviation.
score_sourceStringWhere this game's home_score/away_score come from: 'rebuilt' (summed from the scoring plays and equal to the official final on the last play) or 'espn' (ESPN's per-play values, kept when the rebuild misses the final or the game has no final). Absent from seasons published before the repair. Select it by name: it is the play-by-play builder's last column, but a release can carry columns after it.
shooter_player_idInt32ESPN athlete id of the player who took the shot, field goal or free throw: athlete_id_1 on a shooting play; null on a make the text credits to no shooter (team makes ... (X assists)). The play text fills it only where the slot is empty, and only with a player in the game's box score.
shooter_player_nameStringBox-score display name of shooter_player_id.
assist_player_idInt32ESPN athlete id of the passer credited with the assist on a made field goal: athlete_id_2 (the text's (X assists) / Assisted by X.). The play text fills it only where the slot is empty, and only with a player in the game's box score.
assist_player_nameStringBox-score display name of assist_player_id.
block_player_idInt32ESPN athlete id of the player who blocked the shot: athlete_id_2 on a missed NBA / WNBA field goal (X blocks Y's ...), athlete_id_1 on a college Block Shot row (X Block.). The play text fills it only where the slot is empty, and only with a player in the game's box score.
block_player_nameStringBox-score display name of block_player_id.
steal_player_idInt32ESPN athlete id of the player credited with the steal: athlete_id_2 on an NBA / WNBA turnover ((X steals)), athlete_id_1 on a college Steal row (X Steal.) and on an older turnover that lists the stealer first. The play text fills it only where the slot is empty, and only with a player in the game's box score.
steal_player_nameStringBox-score display name of steal_player_id.
turnover_player_idInt32ESPN athlete id of the player charged with the turnover: athlete_id_1 on a turnover play (athlete_id_2 when an older play lists the stealer first). The play text fills it only where the slot is empty, and only with a player in the game's box score.
turnover_player_nameStringBox-score display name of turnover_player_id.
foul_player_idInt32ESPN athlete id of the player charged with the foul (personal, shooting, offensive, loose ball, blocking, take, technical, flagrant): athlete_id_1 on a foul play (X personal foul / Foul on X.); ESPN does not name the player fouled. The play text fills it only where the slot is empty, and only with a player in the game's box score.
foul_player_nameStringBox-score display name of foul_player_id.
rebound_player_idInt32ESPN athlete id of the rebounder: athlete_id_1 on an offensive or defensive rebound; null on a team rebound. The play text fills it only where the slot is empty, and only with a player in the game's box score.
rebound_player_nameStringBox-score display name of rebound_player_id.
sub_in_player_idInt32ESPN athlete id of the player entering the game: athlete_id_1 on an NBA / WNBA substitution (X enters the game for Y); the player of a college X subbing in for TEAM row. The play text fills it only where the slot is empty, and only with a player in the game's box score.
sub_in_player_nameStringBox-score display name of sub_in_player_id.
sub_out_player_idInt32ESPN athlete id of the player leaving the game: athlete_id_2 on an NBA / WNBA substitution; the player of a college X subbing out for TEAM row. The play text fills it only where the slot is empty, and only with a player in the game's box score.
sub_out_player_nameStringBox-score display name of sub_out_player_id.
jump_ball_winner_player_idInt32ESPN athlete id of the jumper who won the jump ball: on an NBA / WNBA jump ball (A vs. B (C gains possession)), the jumper (athlete_id_1 or athlete_id_2) on the box-score team of the recoverer C, null when no player gains possession; the player of a college Jump Ball won by TEAM row. The play text fills it only where the slot is empty, and only with a player in the game's box score.
jump_ball_winner_player_nameStringBox-score display name of jump_ball_winner_player_id.
jump_ball_loser_player_idInt32ESPN athlete id of the jumper who lost the jump ball: on an NBA / WNBA jump ball, the other jumper (not on the recoverer's team), null when no player gains possession; the player of a college Jump Ball lost by TEAM row. The play text fills it only where the slot is empty, and only with a player in the game's box score.
jump_ball_loser_player_nameStringBox-score display name of jump_ball_loser_player_id.
jump_ball_recoverer_player_idInt32ESPN athlete id of the player who gained possession off the jump ball (the winner's teammate): athlete_id_3 ((C gains possession)); NBA / WNBA only. The play text fills it only where the slot is empty, and only with a player in the game's box score.
jump_ball_recoverer_player_nameStringBox-score display name of jump_ball_recoverer_player_id.
shot_distanceFloat64Field-goal distance in feet: the play text's N-foot, else the distance from the hoop by ESPN's shot coordinates, truncated to whole feet (within a foot of the text where both exist); null on free throws, non-shots and unlocated shots.

Example

from sportsdataverse.nba import espn_nba_pbp
plays = espn_nba_pbp(game_id=401585183)
print(plays.shape)

# Pipeline next step (made threes)

import polars as pl
plays.filter(pl.col("scoring_play") == True, pl.col("score_value") == 3).height

# The game dictionary (box score, header, pickcenter, ...)

pbp = espn_nba_pbp(game_id=401585183, return_parsed=False)
print(list(pbp.keys()))

# Pull only the raw ESPN summary payload (skip cleaning)

raw_pbp = espn_nba_pbp(game_id=401585183, raw=True)

espn_nba_player_box​

espn_nba_player_box(game_id: 'int', return_as_pandas: 'bool' = False, **kwargs)

espn_nba_player_box() - Pull one game's player box score from ESPN's nba/summary endpoint.

The hoopR name for this request (hoopR::espn_nba_player_box): one summary fetch run through ~sportsdataverse.nba.helper_nba_player_box, so the frame is the one the espn_nba_player_boxscores release publishes (what ~sportsdataverse.nba.load_nba_player_boxscore reads) for that game.

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from espn_nba_schedule().
return_as_pandasboolFalseIf True, returns a pandas frame instead of polars.

Returns

One row per athlete (did-not-play athletes included, with null stats), away team first, with the release's player-box columns. A frame with no columns when ESPN has no box score for the game.

Example

from sportsdataverse.nba import espn_nba_player_box
player_box = espn_nba_player_box(game_id=401585183)
print(player_box.shape)

# Pipeline next step (one line)

player_box.filter(pl.col("did_not_play") == False).select("athlete_display_name", "points")

espn_nba_team_box​

espn_nba_team_box(game_id: 'int', return_as_pandas: 'bool' = False, **kwargs)

espn_nba_team_box() - Pull one game's team box score from ESPN's nba/summary endpoint.

The hoopR name for this request (hoopR::espn_nba_team_box): one summary fetch run through ~sportsdataverse.nba.helper_nba_team_box, so the frame is the one the espn_nba_team_boxscores release publishes (what ~sportsdataverse.nba.load_nba_team_boxscore reads) for that game.

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from espn_nba_schedule().
return_as_pandasboolFalseIf True, returns a pandas frame instead of polars.

Returns

Two rows, one per team, with the release's team-box columns. A frame with no columns when ESPN has no box score for the game.

Example

from sportsdataverse.nba import espn_nba_team_box
team_box = espn_nba_team_box(game_id=401585183)
print(team_box.shape)

# Pipeline next step (one line)

team_box.select("team_display_name", "team_score", "team_winner")

scoreboard_event_parsing​

scoreboard_event_parsing(event)

Internal helper that flattens an ESPN NBA scoreboard event dict into a

shape suitable for pd.json_normalize.

Parameters

ParameterTypeDefaultDescription
eventdictA single scoreboard events[*] entry from the ESPN NBA scoreboard API.

Returns

The same event dict, mutated in place with home/away copies of the competitors and trimmed of unused link/odds keys.

Example

from sportsdataverse.nba import espn_nba_schedule
sched = espn_nba_schedule(dates=20230102)