Skip to main content

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, 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; a pandas frame with return_as_pandas=True. Zero rows, with the release's 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".

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)