Skip to main content
Version: 0.1.5

NBA — additional Python functions — Highlights

bref_players_stats​

bref_players_stats(season: 'Optional[int]' = None, table: 'str' = 'per_game', league: 'str' = 'nba', *, return_as_pandas: 'bool' = False, proxy: 'Any' = None, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame'

Player season statistics for an entire league season.

Port of hoopR's bref_players_stats() (NBA) and wehoop's bref_wnba_player_stats() (WNBA). One row per player, with columns named by Basketball-Reference data-stat keys.

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]NoneSeason in 4-digit ending-year format (2024 = 2023-24). The WNBA season is a plain calendar year. Defaults to the current season.
tablestr'per_game'Which stat table. NBA accepts per_game (default), totals, advanced, per_minute (per 36) and per_poss (per 100 possessions); WNBA accepts per_game, totals and advanced.
leaguestr'nba'"nba" (default) or "wnba".
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
proxyAnyNoneProxy configuration in the requests proxies= shape.

Returns

One row per player: ranker, player, age, team, pos, g, gs plus the box columns scaled to table (the advanced table adds per, ts_pct, usg_pct, ws, bpm, vorp …), and echoed season / table / league columns. A zero-row frame when the page carries no player table.

col_nametypedescription
rankerdoubleRow rank.
playercharacterPlayer name.
agedoublePlayer age (in years).
teamcharacterTeam-side label or team identifier.
poscharacterPosition.
gdoubleGames played.
gsdoubleGames started.
mp_per_gdoubleMinutes (per_game table) / mp total (totals table).
fg_per_gdoubleField goals made per game over the season (Float64, one decimal, e.g. 10.8); null where the page leaves the cell blank.
fga_per_gdoubleField goal attempts per game over the season (Float64, one decimal, e.g. 22.8); null where the page leaves the cell blank.
fg_pctdoubleField goal percentage (0-1).
fg3_per_gdoubleThree-point field goals made per game over the season (Float64, one decimal, e.g. 4.0); null where the page leaves the cell blank.
fg3a_per_gdoubleThree-point field goal attempts per game over the season (Float64, one decimal, e.g. 10.8); null where the page leaves the cell blank.
fg3_pctdoubleThree-point field goal percentage (0-1).
fg2_per_gdoubleTwo-point field goals made per game over the season (Float64, one decimal, e.g. 6.9); null where the page leaves the cell blank.
fg2a_per_gdoubleTwo-point field goal attempts per game over the season (Float64, one decimal, e.g. 11.9); null where the page leaves the cell blank.
fg2_pctdoubleTwo-point field goal percentage as a 0-1 proportion (e.g. 0.575); null where the page leaves the cell blank.
efg_pctdoubleEffective field goal percentage as a 0-1 proportion (e.g. 0.563), crediting made threes at 1.5 field goals: (FG + 0.5 * 3P) / FGA; null where the page leaves the cell blank.
ft_per_gdoubleFree throws made per game over the season (Float64, one decimal, e.g. 7.9); null where the page leaves the cell blank.
fta_per_gdoubleFree throw attempts per game over the season (Float64, one decimal, e.g. 10.1); null where the page leaves the cell blank.
ft_pctdoubleFree throw percentage (0-1).
orb_per_gdoubleOffensive rebounds per game over the season (Float64, one decimal, e.g. 0.6); null where the page leaves the cell blank.
drb_per_gdoubleDefensive rebounds per game over the season (Float64, one decimal, e.g. 7.1); null where the page leaves the cell blank.
trb_per_gdoubleTotal rebounds per game over the season (Float64, one decimal, e.g. 7.7); null where the page leaves the cell blank.
ast_per_gdoubleAssists per game over the season (Float64, one decimal, e.g. 8.3); null where the page leaves the cell blank.
stl_per_gdoubleSteals per game over the season (Float64, one decimal, e.g. 1.6); null where the page leaves the cell blank.
blk_per_gdoubleBlocks per game over the season (Float64, one decimal, e.g. 0.8); null where the page leaves the cell blank.
tov_per_gdoubleTurnovers per game over the season (Float64, one decimal, e.g. 4.0); null where the page leaves the cell blank.
pf_per_gdoublePersonal fouls per game over the season (Float64, one decimal, e.g. 2.4); null where the page leaves the cell blank.
pts_per_gdoublePoints (scaled to the chosen table).
awardscharacterComma-separated Basketball-Reference award codes for the season (e.g. 'MVP-4,CPOY-8,AS,NBA1'): voting finishes as CODE-place, AS for All-Star, NBA1/NBA2/NBA3 for the All-NBA team; empty string when the player has none.
seasonintegerSeason year.
tablecharacterStat table requested through the table argument, echoed on every row ('per_game' in sampled data).
leaguecharacterLeague slug.

Example

import polars as pl
from sportsdataverse.nba.bref import bref_players_stats

df = bref_players_stats(season=2024)
print(df.shape)

# Advanced metrics, and the WNBA page

adv = bref_players_stats(season=2024, table="advanced")
wnba = bref_players_stats(season=2024, league="wnba")

# Pipeline next step (one line)

adv.filter(pl.col("vorp") > 3.0).sort("vorp", descending=True).head()

bref_standings​

bref_standings(season: 'Optional[int]' = None, league: 'str' = 'nba', *, return_as_pandas: 'bool' = False, proxy: 'Any' = None, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame'

Conference standings for a season, both conferences stacked.

Port of hoopR's bref_standings() (NBA) and wehoop's bref_wnba_standings() (WNBA).

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]NoneSeason in 4-digit ending-year format. Defaults to the current season.
leaguestr'nba'"nba" (default) or "wnba".
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
proxyAnyNoneProxy configuration in the requests proxies= shape.

Returns

One row per team: conference ("E" / "W" for both leagues -- wehoop emits "Eastern"/"Western"), team (playoff * marker stripped), playoffs (bool, from that marker), wins, losses, win_loss_pct, gb, pts_per_g, opp_pts_per_g, srs, plus echoed season / league. Zero rows when neither conference table is present.

col_nametypedescription
teamcharacterTeam-side label or team identifier.
winsdoubleTotal wins.
lossesdoubleTotal losses.
win_loss_pctdoubleWin-loss percentage.
gbcharacterGames behind the conference leader.
pts_per_gdoublePoints (scaled to the chosen table).
opp_pts_per_gdoubleOpponent points per game.
srsdoubleSimple Rating System (point margin + SOS).
conferencecharacterConference name.
playoffslogicalTRUE if the team made the playoffs (* marker).
seasonintegerSeason year.
leaguecharacterLeague slug.

Example

import polars as pl
from sportsdataverse.nba.bref import bref_standings

df = bref_standings(season=2024)
print(df.shape)

# The WNBA page

wnba = bref_standings(season=2024, league="wnba")

# Pipeline next step (one line)

df.filter(pl.col("playoffs") == True).sort("srs", descending=True).head()

bref_teams_stats​

bref_teams_stats(season: 'Optional[int]' = None, table: 'str' = 'per_game', league: 'str' = 'nba', *, return_as_pandas: 'bool' = False, proxy: 'Any' = None, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame'

Team season statistics from the league season page.

Port of hoopR's bref_teams_stats() (NBA) and wehoop's bref_wnba_team_stats() (WNBA). Every team table lives on the one season page and all but the first are comment-hidden, which is why the table id selection in bref_table` matters here.

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]NoneSeason in 4-digit ending-year format (2024 = 2023-24). Defaults to the current season.
tablestr'per_game'NBA accepts per_game (default), totals, per_poss, advanced and opponent (opponent per-game); WNBA accepts the same set minus opponent.
leaguestr'nba'"nba" (default) or "wnba".
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
proxyAnyNoneProxy configuration in the requests proxies= shape.

Returns

One row per team: ranker, team, g, mp and the box categories scaled to table, plus echoed season / table / league. The WNBA path drops the League Average footer row, as wehoop does. A zero-row frame when the table id is absent.

col_nametypedescription
rankerdoubleRow rank.
teamcharacterTeam-side label or team identifier.
gdoubleGames played.
mpdoubleMinutes played.
fgdoubleField goals made by the team, scaled to the requested table (per game in the sampled per_game table, e.g. 43.5).
fgadoubleField goal attempts.
fg_pctdoubleField goal percentage (0-1).
fg3doubleThree-point field goals made by the team, scaled to the requested table (per game in the sampled per_game table, e.g. 14.2).
fg3adoubleThree-point field goal attempts.
fg3_pctdoubleThree-point field goal percentage (0-1).
fg2doubleTwo-point field goals made by the team, scaled to the requested table (per game in the sampled per_game table, e.g. 29.4).
fg2adoubleTwo-point field goal attempts by the team, scaled to the requested table (per game in the sampled per_game table, e.g. 52.0).
fg2_pctdoubleTeam two-point field goal percentage as a 0-1 proportion (e.g. 0.565).
ftdoubleFree throws made by the team, scaled to the requested table (per game in the sampled per_game table, e.g. 20.8).
ftadoubleFree throw attempts.
ft_pctdoubleFree throw percentage (0-1).
orbdoubleOffensive rebounds by the team, scaled to the requested table (per game in the sampled per_game table, e.g. 9.8).
drbdoubleDefensive rebounds by the team, scaled to the requested table (per game in the sampled per_game table, e.g. 34.2).
trbdoubleCareer total rebounds.
astdoubleAssists.
stldoubleSteals.
blkdoubleBlocks.
tovdoubleTurnovers.
pfdoublePersonal fouls.
ptsdoublePoints scored.
seasonintegerSeason year.
tablecharacterStat table requested through the table argument, echoed on every row ('per_game' in sampled data).
leaguecharacterLeague slug.

Example

from sportsdataverse.nba.bref import bref_teams_stats

df = bref_teams_stats(season=2024)
print(df.shape)

# Opponent per-game, and pandas output

opp = bref_teams_stats(season=2024, table="opponent")
df_pd = bref_teams_stats(season=2024, return_as_pandas=True)

# Pipeline next step (one line)

df.sort("pts_per_g", descending=True).head()

compile_nba_season​

compile_nba_season(season: 'int', season_type: 'str' = 'Regular Season', *, resume: 'bool' = True, cache_dir: 'Optional[str]' = None, delay_s: 'float' = 0.6, lineup_source: 'str' = 'auto', proxy_provider: 'Optional[Callable[[], Optional[str]]]' = None, raw_store_dir: 'RawStoreDir' = None, raw_store_readonly: 'Optional[bool]' = None, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'

Compile a full season's possession stint matrix (cached + resumable + throttled).

Discovers game ids, dedupes, then per game loads the cached parquet if present (resume), else fetches via fetch_possessions, caches it, and sleeps delay_s(throttle; only on live fetches). A game that errors or returns no possessions is logged and skipped (best-effort — a per-game failure never raises; seeRaisesfor the game_date integrity error). The assembled frame is tagged with aseason` column.

Parameters

ParameterTypeDefaultDescription
seasonintSeason END year (e.g. 2024 for 2023-24).
season_typestr'Regular Season'"Regular Season" (default) or "Playoffs".
resumeboolTrueReuse per-game cached parquet when present.
cache_dirOptional[str]NoneCache root; defaults to SDV_PY_NBA_CACHE_DIR or ~/.sdv_py_nba_cache/possessions.
delay_sfloat0.6Seconds to sleep after each live fetch (rate-limit throttle).
lineup_sourcestr'auto'Which on-court lineup producer to use — "auto" (default; tries rotation then falls back to pbp), "rotation" (gamerotation endpoint only), or "pbp" (pbp-derived, no gamerotation fetch — useful when the gamerotation endpoint is throttled or unavailable).
proxy_providerOptional[Callable[[], Optional[str]]]NoneOptional zero-arg callable returning a proxy URL (or None). Called once for game discovery, then once per game (N + 1 calls for an N-game season), so a rotating pool spreads a season's fetches across many exit IPs rather than hammering stats.nba.com from one address. stats.nba.com rejects or hangs on datacenter/cloud IPs, so an unattended host (CI, a droplet) MUST supply one — a proxied request is judged on the proxy's exit IP, which is what makes such a host viable at all. Note discovery is proxied too: an unproxied index call returns no rows there, compiling the season to zero games without an error. Any () -> str | None works; a round-robin pool's .next matches the signature directly:: compile_nba_season(2024, proxy_provider=round_robin.next)
raw_store_dirRawStoreDirNoneExplicit raw JSON store root forwarded to every per-game fetch — a single path, or a per-endpoint mapping ("*" default key) so payload families can live in independent trees. None -> env vars (per-endpoint SDV_PY_NBA_RAW_JSON_DIR_{ENDPOINT}, then the generic SDV_PY_NBA_RAW_JSON_DIR); "" force-disables. Same spirit as cache_dir's arg-over-env precedence.
raw_store_readonlyOptional[bool]NoneIf True, per-game fetches are fully offline — the store is the only source, and a game with no capture raises ~sportsdataverse.errors.RawStoreMissError, which this loop's per-game handler logs and skips (so an uncaptured game is visibly skipped instead of silently completed from the live API). None defers to SDV_PY_NBA_RAW_JSON_READONLY.
return_as_pandasboolFalseReturn pandas instead of polars.

Returns

The season possession frame (+ season and game_date cols). Empty typed frame if no games.

No returns table is published for this function: no capture: it reads stats.nba.com (HTTP 403 to the datacenter IP the docs are built on), and compiling a season from the raw store takes far longer than the capture allows.

Example

from sportsdataverse.nba.nba_season_compile import compile_nba_season

poss = compile_nba_season(2024)
print(poss.shape) # (n_possessions, n_cols)
print(poss["season"][0]) # 2024

# Resume a partially completed run and return as pandas

poss_pd = compile_nba_season(2024, resume=True, return_as_pandas=True)
print(type(poss_pd)) # <class 'pandas.core.frame.DataFrame'>

# Compile Playoffs with a custom cache directory

poss = compile_nba_season(
2024,
season_type="Playoffs",
cache_dir="/tmp/nba_cache",
)

espn_nba_player_stats​

espn_nba_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 NBA 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, the athlete / team metadata blocks, and the season_type / total parameters. For the richer multi-category web-v3 payload use sportsdataverse.nba.espn_nba_player_stats_v3.

Parameters

ParameterTypeDefaultDescription
athlete_idintESPN NBA athlete identifier (e.g. 1966 for LeBron James).
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.
season_typecharacterSeason type (1=pre-season, 2=regular season, 3=postseason, 4=off-season for ESPN; or string label for WNBA Stats).
totallogicalTotal.
athlete_idintegerUnique athlete identifier (ESPN).
athlete_uidcharacterESPN athlete UID (universal identifier).
athlete_guidcharacterESPN athlete GUID.
athlete_typecharacterAthlete type / class.
first_namecharacterPlayer's first name.
last_namecharacterPlayer's last name.
full_namecharacterPlayer's full name.
display_namecharacterDisplay name.
short_namecharacterShort display name.
weightdoublePlayer weight in pounds.
display_weightcharacterPlayer weight in display format (e.g. '180 lbs').
heightdoublePlayer height (string e.g. '6-2' or inches).
display_heightcharacterPlayer height in display format (e.g. '6-2').
ageintegerPlayer age (in years).
date_of_birthcharacterDate of birth (YYYY-MM-DD).
jerseycharacterJersey number worn by the player.
slugcharacterURL-safe identifier.
activelogicalTRUE if the row represents an active record (player / team / season).
position_idintegerUnique position identifier.
position_namecharacterListed roster position ('Guard', 'Forward', 'Center').
position_display_namecharacterPosition display name.
position_abbreviationcharacterPosition abbreviation ('G' / 'F' / 'C').
college_namecharacterCollege / pre-draft team.
status_idintegerStatus identifier.
status_namecharacterStatus label.
defensive_blocksdoubleShort for blocked shot, number of times when a defensive player legally deflects a field goal attempt from an offensive player.
defensive_defensive_reboundsdoubleThe number of times when the defense obtains the possession of the ball after a missed shot by the offense.
defensive_stealsdoubleThe number of times a defensive player forced a turnover by intercepting or deflecting a pass or a dribble of an offensive player.
defensive_def_rebound_ratedoubleThe percentage of missed shots that a team rebounds defensively. Rebound Rate = (Defensive Rebounds x Team Minutes) divided by (Player Minutes x (Team Defensive Rebounds + Opponent Defensive Rebounds)).
defensive_avg_defensive_reboundsdoubleThe average defensive rebounds per game.
defensive_avg_blocksdoubleThe average blocks per game.
defensive_avg_stealsdoubleThe average steals per game.
defensive_avg48_defensive_reboundsdoublePlayer's average defensive rebounds per 48 minutes played.
defensive_avg48_blocksdoublePlayer's average blocked shots per 48 minutes played.
defensive_avg48_stealsdoublePlayer's average steals per 48 minutes played.
defensive_drpmdoubleDefensive Real Plus-Minus.
general_disqualificationsdoubleThe number of times a player reached the foul limit.
general_flagrant_foulsdoubleThe number of fouls that the officials thought were unnecessary or excessive.
general_foulsdoubleThe number of times a player had illegal contact with the opponent.
general_perdoubleA numerical value for each of a player's accomplishments per-minute and is pace-adjusted for the team they play on. The league average in PER to 15.00 every season.
general_rebound_ratedoubleThe percentage of missed shots that a team rebounds. Rebound Rate = (Rebounds x Team Minutes) divided by (Player Minutes x (Team Rebounds + Opponent Rebounds)).
general_ejectionsdoubleThe number of times a player or coach is removed from the game as a result of a serious offense.
general_technical_foulsdoubleThe number of times an player or coach was called for a technical foul (unsportsmanlike conduct or violations).
general_reboundsdoubleThe total number of rebounds (offensive and defensive).
general_vorpdoubleValue Over Replacement Player.
general_warpdoubleWins Above Replacement Player.
general_rpmdoubleReal Plus-Minus.
general_minutesdoubleThe total number of minutes played.
general_avg_minutesdoubleThe average number of minutes per game.
general_nba_ratingdoubleGeneral nba rating.
general_plus_minusdoubleA player's estimated on-court impact on team performance measured in point differential per 100 possessions.
general_avg_reboundsdoubleThe average rebounds per game.
general_avg_foulsdoubleThe average fouls committed per game.
general_avg_flagrant_foulsdoubleThe average number of flagrant fouls per game.
general_avg_technical_foulsdoubleThe average number of technical fouls per game.
general_avg_ejectionsdoubleThe average ejections per game.
general_avg_disqualificationsdoubleThe average number of disqualifications per game.
general_assist_turnover_ratiodoubleThe average number of assists a player or team records per turnover.
general_steal_foul_ratiodoubleThe average number of steals a player or team records per foul committed.
general_block_foul_ratiodoubleThe average number of blocks a player or record per foul committed.
general_avg_team_reboundsdoubleThe average number of rebounds for a team per game.
general_total_reboundsdoubleThe total number of rebounds for a team or player.
general_total_technical_foulsdoubleThe total number of technical fouls for a team or player.
general_team_assist_turnover_ratiodoubleThe number of assists per turnover for a team.
general_steal_turnover_ratiodoubleThe number of steals per turnover.
general_avg48_reboundsdoublePlayer's average total rebounds (offensive + defensive) per 48 minutes played.
general_avg48_foulsdoublePlayer's average personal fouls committed per 48 minutes played.
general_avg48_flagrant_foulsdoublePlayer's average flagrant fouls assessed per 48 minutes played.
general_avg48_technical_foulsdoublePlayer's average technical fouls assessed per 48 minutes played.
general_avg48_ejectionsdoublePlayer's average ejections per 48 minutes played.
general_avg48_disqualificationsdoublePlayer's average disqualifications (fouling out) per 48 minutes played.
general_r40doubleRebounds Per 40 Minutes.
general_games_playeddoubleGames Played.
general_games_starteddoubleThe number of games started by an athlete.
general_double_doubledoubleThe number of times double digit values were accumulated in 2 of the following categories: points, rebounds, assists, steals, and blocked shots.
general_triple_doubledoubleThe number of times double digit values were accumulated in 3 of the following categories: points, rebounds, assists, steals, and blocked shots.
offensive_assistsdoubleThe number of times a player who passes the ball to a teammate in a way that leads to a score by field goal, meaning that he or she was "assisting" in the basket. There is some judgment involved in deciding whether a passer should be credited with an assist.
offensive_effective_fg_pctdoubleOffensive effective field goals percentage (0-1 decimal).
offensive_field_goalsdoubleField Goal makes and attempts.
offensive_field_goals_attempteddoubleThe number of times a 2pt field goal was attempted.
offensive_field_goals_madedoubleThe number of times a 2pt field goal was made.
offensive_field_goal_pctdoubleThe ratio of field goals made to field goals attempted: FGM / FGA.
offensive_free_throwsdoubleFree Throw makes and attempts.
offensive_free_throw_pctdoubleThe ratio of free throws made to free throws attempted: FTM / FTA.
offensive_free_throws_attempteddoubleThe number of times a free throw was attempted.
offensive_free_throws_madedoubleThe number of times a free throw was made.
offensive_offensive_reboundsdoubleThe number of times when the offense obtains the possession of the ball after a missed shot.
offensive_pointsdoubleThe number of points scored.
offensive_turnoversdoubleThe number of times a player loses possession to the other team.
offensive_three_point_pctdoubleThe ratio of 3pt field goals made to 3pt field goals attempted: 3PM / 3PA.
offensive_three_point_field_goals_attempteddoubleThe number of times a 3pt field goal was attempted.
offensive_three_point_field_goals_madedoubleThe number of times a 3pt field goal was made.
offensive_true_shooting_pctdoubleWhat a team's shooting percentage would be if we accounted for free throws and 3-pointers. True Shooting Percentage = (Total points x 50) divided by ((FGA + (FTA x 0.44)).
offensive_total_turnoversdoubleThe number of turnovers plus team turnovers for the team.
offensive_assist_ratiodoubleThe percentage of a team's possessions that ends in an assist. Assist Ratio = (Assists x 100) divided by ((FGA + (FTA x 0.44) + Assists + Turnovers).
offensive_points_in_paintdoubleThe amount of points scored in the area known as "the Paint"(the rectangle between the foul line and the baseline).
offensive_off_rebound_ratedoubleThe percentage of missed shots that a team rebounds offensively. Offensive Rebound Rate = (Offensive Rebounds x Team Minutes) divided by (Player Minutes x (Team Offensive Rebounds + Opponent Defensive Rebounds)).
offensive_turnover_ratiodoubleThe percentage of a team's possessions that end in a turnover. Turnover Ratio = (Turnover x 100) divided by ((FGA + (FTA x 0.44) + Assists + Turnovers).
offensive_brick_indexdoubleHow many points a player costs his team with his shooting compared with the league average on a per-40-minute basis. ((52.8 - TS%) x (FGA + (FTA x 0.44))) / (Min/40) .
offensive_usage_ratedoublethe number of possessions a player uses per 40 minutes. Usage Rate = ((FGA + (FT Att. x 0.44) + (Ast x 0.33) + TO) x 40 x League Pace) divided by (Minutes x Team Pace).
offensive_avg_field_goals_madedoubleThe average field goals made per game.
offensive_avg_field_goals_attempteddoubleThe average field goals attempted per game.
offensive_avg_three_point_field_goals_madedoubleThe average three point field goals made per game.
offensive_avg_three_point_field_goals_attempteddoubleThe average three point field goals attempted per game.
offensive_avg_free_throws_madedoubleThe average free throw shots made per game.
offensive_avg_free_throws_attempteddoubleThe average free throw shots attempted per game.
offensive_avg_pointsdoubleThe average number of points scored per game.
offensive_avg_offensive_reboundsdoubleThe average offensive rebounds per game.
offensive_avg_assistsdoubleThe average assists per game.
offensive_avg_turnoversdoubleThe average turnovers committed per game.
offensive_offensive_rebound_pctdoubleThe percentage of the number of times they obtain the possession of the ball after a missed shot.
offensive_estimated_possessionsdoubleAn estimation of the number of possessions for a team or player.
offensive_avg_estimated_possessionsdoubleThe average number of estimated possessions per game for a team or player.
offensive_points_per_estimated_possessionsdoubleThe number of points per estimated possession for a team or player.
offensive_avg_team_turnoversdoubleThe average number of turnovers for a team per game.
offensive_avg_total_turnoversdoubleThe average number of total turnovers for a team per game.
offensive_three_point_field_goal_pctdoubleThe ratio of 3pt field goals made to 3pt field goals attempted: 3PM / 3PA.
offensive_two_point_field_goals_madedoubleThe number of 2-point field goals made for a team or player.
offensive_two_point_field_goals_attempteddoubleThe number of 2-point field goals attempted for a team or player.
offensive_avg_two_point_field_goals_madedoubleThe number of 2-point field goals made per game for a team or player.
offensive_avg_two_point_field_goals_attempteddoubleThe number of 2-point field goals attempted per game for a team or player.
offensive_two_point_field_goal_pctdoubleThe percentage of 2-points fields goals made by a team or player.
offensive_shooting_efficiencydoubleThe efficiency with which a team or player shoots the basketball.
offensive_scoring_efficiencydoubleThe efficiency with which a team or player scores the basketball.
offensive_avg48_field_goals_madedoublePlayer's average field goals made per 48 minutes played.
offensive_avg48_field_goals_attempteddoublePlayer's average field goal attempts per 48 minutes played.
offensive_avg48_three_point_field_goals_madedoublePlayer's average three-point field goals made per 48 minutes played.
offensive_avg48_three_point_field_goals_attempteddoublePlayer's average three-point field goal attempts per 48 minutes played.
offensive_avg48_free_throws_madedoublePlayer's average free throws made per 48 minutes played.
offensive_avg48_free_throws_attempteddoublePlayer's average free throw attempts per 48 minutes played.
offensive_avg48_pointsdoublePlayer's average points scored per 48 minutes played.
offensive_avg48_offensive_reboundsdoublePlayer's average offensive rebounds per 48 minutes played.
offensive_avg48_assistsdoublePlayer's average assists per 48 minutes played.
offensive_avg48_turnoversdoublePlayer's average turnovers committed per 48 minutes played.
offensive_p40doublePoints Per 40 Minutes.
offensive_a40doubleAssists Per 40 Minutes.
offensive_orpmdoubleOffensive Real Plus-Minus.
team_idintegerUnique team identifier.
team_uidcharacterESPN universal team identifier (UID format 's:40~l:...~t:...').
team_guidcharacterESPN team GUID.
team_slugcharacterURL-safe team identifier (e.g. 'lasvegas-aces' / 'aces').
team_locationcharacterTeam city or location string.
team_namecharacterFull team display name (e.g. 'Las Vegas Aces').
team_abbreviationcharacterShort team abbreviation (e.g. 'LAS').
team_display_namecharacterFull team display name.
team_short_display_namecharacterShort team display name (e.g. 'Aces').
team_colorcharacterTeam primary color (hex without leading '#').
team_alternate_colorcharacterTeam alternate color (hex without leading '#').
team_is_activelogicalTRUE if the team is currently active.
team_logo_hrefcharacter

Example

from sportsdataverse.nba import espn_nba_player_stats
df = espn_nba_player_stats(athlete_id=1966, season=2023)
df.select(["full_name", "team_display_name", "offensive_points"])

espn_nba_schedule​

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

espn_nba_schedule - look up the NBA schedule for a given date from ESPN

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
idcharacterId.
uidcharacterESPN UID string.
datecharacterDate in YYYY-MM-DD format.
attendanceintegerReported attendance.
time_validlogicalTime valid.
neutral_sitelogicalNeutral site.
conference_competitionlogicalConference competition.
play_by_play_availablelogical
recentlogicalRecent.
start_datecharacterStart date (YYYY-MM-DD).
broadcastcharacterBroadcast information string.
highlightsinteger
notes_typecharacterNotes type.
notes_headlinecharacterNotes headline.
broadcast_marketcharacterBroadcast market label (e.g. 'national', 'home').
broadcast_namecharacterBroadcast name.
type_idcharacterType identifier (numeric).
type_abbreviationcharacterType abbreviation.
venue_idcharacterUnique venue identifier.
venue_full_namecharacterVenue full name.
venue_address_citycharacterVenue address city.
venue_address_statecharacterVenue address state / region.
venue_indoorlogicalTRUE if the venue is indoors.
status_clockdoubleStatus clock.
status_display_clockcharacterStatus display clock.
status_periodintegerStatus period.
status_type_idcharacterUnique identifier for status type.
status_type_namecharacterStatus type name.
status_type_statecharacterStatus type state.
status_type_completedlogicalStatus type completed.
status_type_descriptioncharacterStatus type description.
status_type_detailcharacterStatus type detail.
status_type_short_detailcharacterStatus type short detail.
format_regulation_periodsintegerFormat regulation periods.
home_idcharacterUnique identifier for home.
home_uidcharacterHome team's uid.
home_locationcharacterHome team's location.
home_namecharacterHome name.
home_abbreviationcharacterHome team's abbreviation.
home_display_namecharacterHome display name.
home_short_display_namecharacterHome short display name.
home_colorcharacterColor code (hex) for home.
home_alternate_colorcharacterColor code (hex) for home alternate.
home_is_activelogicalHome team's is active.
home_venue_idcharacterUnique identifier for home venue.
home_logocharacterHome team logo URL.
home_scorecharacterHome team score at the time of the play.
home_winnerlogicalHome team's winner.
home_linescoreslistPeriod-by-period point totals for the home team, stored as a list of integer scores.
home_recordscharacterWin-loss record strings for the home team across relevant splits (e.g., overall, home/away, conference).
away_idcharacterUnique identifier for away.
away_uidcharacterAway team's uid.
away_locationcharacterAway team's location.
away_namecharacterAway name.
away_abbreviationcharacterAway team's abbreviation.
away_display_namecharacterAway display name.
away_short_display_namecharacterAway short display name.
away_colorcharacterColor code (hex) for away.
away_alternate_colorcharacterColor code (hex) for away alternate.
away_is_activelogicalAway team's is active.
away_venue_idcharacterUnique identifier for away venue.
away_logocharacterAway team logo URL.
away_scorecharacterAway team score at the time of the play.
away_winnerlogicalAway team's winner.
away_linescoreslistPeriod-by-period point totals for the away team, stored as a list of integer scores.
away_recordscharacterWin-loss record strings for the away team across relevant splits (e.g., overall, home/away, conference).
game_idintegerUnique game identifier.
seasonintegerSeason year.
season_typeintegerSeason type (1=pre-season, 2=regular season, 3=postseason, 4=off-season for ESPN; or string label for WNBA Stats).
home_logo_darkcharacter
away_logo_darkcharacter

Example

from sportsdataverse.nba import espn_nba_schedule
slate = espn_nba_schedule()
print(slate.shape)

# Pull a specific date

jan2 = espn_nba_schedule(dates=20230102, season_type=2)

# Pipeline next step (extract finals only)

import polars as pl
finals = espn_nba_schedule(dates=20230102).filter(
pl.col("status_type_completed") == True
)

espn_nba_teams​

espn_nba_teams(return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_nba_teams - look up NBA teams

Parameters

ParameterTypeDefaultDescription
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False, returns a polars dataframe.

Returns

Polars dataframe containing teams for the requested league. This function caches by default, so if you want to refresh the data, use the command sportsdataverse.nba.espn_nba_teams.clear_cache().

col_nametypedescription
team_abbreviationcharacterShort team abbreviation (e.g. 'LAS').
team_alternate_colorcharacterTeam alternate color (hex without leading '#').
team_colorcharacterTeam primary color (hex without leading '#').
team_display_namecharacterFull team display name.
team_idcharacterUnique team identifier.
team_is_activelogicalTRUE if the team is currently active.
team_is_all_starlogicalTRUE if the row represents an All-Star team.
team_locationcharacterTeam city or location string.
team_logosinteger
team_namecharacterFull team display name (e.g. 'Las Vegas Aces').
team_nicknamecharacterTeam nickname.
team_short_display_namecharacterShort team display name (e.g. 'Aces').
team_slugcharacterURL-safe team identifier (e.g. 'lasvegas-aces' / 'aces').
team_uidcharacterESPN universal team identifier (UID format 's:40~l:...~t:...').

Example

from sportsdataverse.nba import espn_nba_teams
teams = espn_nba_teams()
print(teams.shape)

# Pandas round-trip

teams_pd = espn_nba_teams(return_as_pandas=True)
teams_pd.head()

# Pipeline next step (build a team_id to abbreviation map)

teams = espn_nba_teams()
abbr_map = dict(zip(teams["team_id"], teams["team_abbreviation"]))

most_recent_nba_season​

most_recent_nba_season()

Return the most recent NBA season year based on today's date.

The NBA season crosses calendar years -- a season started in October of year Y is reported as season Y+1. If today is in October or later, this returns next calendar year; otherwise it returns the current calendar year.

Returns

The most recent NBA season year (e.g. 2024 for the 2023-24 season).

Example

from sportsdataverse.nba import most_recent_nba_season
year = most_recent_nba_season()
print(year)

# Combine with the loaders for a "current season" pull

from sportsdataverse.nba import load_nba_schedule, most_recent_nba_season
sched = load_nba_schedule(seasons=[most_recent_nba_season()])