NBA — additional Python functions — Analytics: nba_team–shot_selection
nba_team_strength
nba_team_strength(seasons: 'int | list[int]', *, league_id: 'str' = '00', season_type: 'str' = 'regular-season', return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'
Team strength from possessions: adjusted ratings, SOS, SOV, pace and the four factors.
One row per team and season. The adjusted ratings are a ridge regression of points per 100
on each possession on offense, defense and home terms (penalty
~sportsdataverse._common.team_strength.RIDGE_LAMBDA, fit by season-disjoint CV):
points scored / allowed per 100 against an average opponent on a neutral court. SOS is the
mean opponent adj_net_rtg over the team's games, SOV the same over its wins.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | list[int] | A season or list of seasons, named by the year it ends (2026 is 2025-26). The WNBA season is its calendar year. | |
league_id | str | '00' | "00" NBA or "10" WNBA. |
season_type | str | 'regular-season' | "regular-season" (default), "preseason", "playoffs" or "play-in", matched to the schedule's season_type. The ridge, the rates and the games all use it. |
return_as_pandas | bool | False | Return a pandas frame instead of polars. |
Returns
One row per (season, team_id); team_id is the stats.nba.com team id (Int64). games, poss / opp_poss, pts / opp_pts are the season totals from the possessions; wins / losses come from the schedule's final scores. The rated metrics are adj_off_rtg, adj_def_rtg, adj_net_rtg, sos, sov and the BB-D3 rates (off_rtg, def_rtg, net_rtg, pace, the four factors and the four against). Each has <m>_rank (1 = best; adj_def_rtg, def_rtg, tov_pct and the opponent shooting, rebounding and free-throw rates rank low first; sos ranks the hardest schedule first), <m>_pct (the Weibull percentile) and <m>_n (possessions for the ratings, completed games against a rated opponent for SOS, the clock in regulation games for pace, wins over a rated opponent for SOV). Ranks are within the season, among teams with at least half the most games, the BB-D3 rates' also behind their ~sportsdataverse._common.rate_gates.TEAM_MIN_N gate, and null under five teams. Empty input returns that schema with zero rows.
| col_name | type | description |
|---|---|---|
season | Int64 | Season, named by the year it ends (2026 is 2025-26). |
team_id | Int64 | stats.nba.com team id (the 10-digit franchise id). |
games | Int64 | Games with at least one possession in the season (from the possession release). |
wins | Int64 | Wins in the season type's completed games (the schedule's final scores). |
losses | Int64 | Losses in the season type's completed games. |
poss | Int64 | Offensive possessions in the season, counted from possession rows. |
opp_poss | Int64 | Defensive possessions in the season (the opponents' offensive possessions). |
pts | Int64 | Points scored on the team's offensive possessions in the season. Counted from each possession's made shots and free throws. |
opp_pts | Int64 | Points allowed on the team's defensive possessions in the season. |
adj_off_rtg | Float64 | Adjusted offensive rating: points per 100 possessions against an average defense on a neutral court. The ridge intercept plus the team's offense coefficient (points per 100 on each possession on offense, defense and home terms; penalty RIDGE_LAMBDA). |
adj_def_rtg | Float64 | Adjusted defensive rating: points allowed per 100 possessions against an average offense on a neutral court. The ridge intercept plus the team's defense coefficient; lower is better. |
adj_net_rtg | Float64 | Adjusted net rating: adj_off_rtg minus adj_def_rtg. |
sos | Float64 | Strength of schedule: the mean adj_net_rtg of the opponents of the team's completed games, one weight per game (an opponent met four times counts four times). |
sov | Float64 | Strength of victory: the mean adj_net_rtg of the opponents the team beat, one weight per win; null with no win. |
off_rtg | Float64 | Offensive rating: points scored per 100 offensive possessions. |
def_rtg | Float64 | Defensive rating: points allowed per 100 defensive possessions. |
net_rtg | Float64 | Net rating: off_rtg minus def_rtg. |
pace | Float64 | Pace: possessions per 48 minutes (40 with league_id="10", the WNBA), the mean of poss and opp_poss over the game clock those possessions used. |
efg_pct | Float64 | Effective field-goal percentage, (FGM + 0.5 * 3PM) / FGA, as a fraction. |
tov_pct | Float64 | Turnovers per offensive possession, as a fraction. |
orb_pct | Float64 | Offensive rebound rate: offensive rebounds over offensive-rebound chances (own OREB plus the defense's DREB), as a fraction. |
ft_rate | Float64 | Free-throw rate, FTA / FGA. |
opp_efg_pct | Float64 | Opponents' effective field-goal percentage, (FGM + 0.5 * 3PM) / FGA, as a fraction. |
opp_tov_pct | Float64 | Opponents' turnovers per possession (turnovers forced), as a fraction. |
opp_orb_pct | Float64 | Opponents' offensive rebound rate, as a fraction (one minus the team's defensive rebound rate). |
opp_ft_rate | Float64 | Opponents' free-throw rate, FTA / FGA. |
adj_off_rtg_rank | Float64 | Rank of adj_off_rtg within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season; null for a non-qualifier, a null value, or fewer than five qualifiers. |
adj_def_rtg_rank | Float64 | Rank of adj_def_rtg within the season (the lowest value ranks 1; ties average), among teams that played at least half the most games any team played in the season; null for a non-qualifier, a null value, or fewer than five qualifiers. |
adj_net_rtg_rank | Float64 | Rank of adj_net_rtg within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season; null for a non-qualifier, a null value, or fewer than five qualifiers. |
sos_rank | Float64 | Rank of sos within the season (the highest value ranks 1; the hardest schedule ranks 1; ties average), among teams that played at least half the most games any team played in the season; null for a non-qualifier, a null value, or fewer than five qualifiers. |
sov_rank | Float64 | Rank of sov within the season (the highest value ranks 1; the strongest wins rank 1; ties average), among teams that played at least half the most games any team played in the season; null for a non-qualifier, a null value, or fewer than five qualifiers. |
off_rtg_rank | Float64 | Rank of off_rtg within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose off_rtg_n is at least 1,300 offensive possessions (the sample at which the rate is half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
def_rtg_rank | Float64 | Rank of def_rtg within the season (the lowest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose def_rtg_n is at least 2,000 defensive possessions (the sample at which the rate is half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
net_rtg_rank | Float64 | Rank of net_rtg within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose net_rtg_n is at least 2,000 possessions (offense plus defense) (the sample at which the rate was, on the fit seasons, half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
pace_rank | Float64 | Rank of pace within the season (the highest value ranks 1; pace has no better direction; ties average), among teams that played at least half the most games any team played in the season, whose pace_n is at least 5 games (the sample at which the rate is half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
efg_pct_rank | Float64 | Rank of efg_pct within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose efg_pct_n is at least 1,200 field-goal attempts (the sample at which the rate is half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
tov_pct_rank | Float64 | Rank of tov_pct within the season (the lowest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose tov_pct_n is at least 1,400 offensive possessions (the sample at which the rate is half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
orb_pct_rank | Float64 | Rank of orb_pct within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose orb_pct_n is at least 410 offensive-rebound chances (the sample at which the rate is half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
ft_rate_rank | Float64 | Rank of ft_rate within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose ft_rate_n is at least 1,300 field-goal attempts (the sample at which the rate is half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
opp_efg_pct_rank | Float64 | Rank of opp_efg_pct within the season (the lowest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose opp_efg_pct_n is at least 1,900 opponent field-goal attempts (the sample at which the rate was, on the fit seasons, half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
opp_tov_pct_rank | Float64 | Rank of opp_tov_pct within the season (the highest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose opp_tov_pct_n is at least 960 defensive possessions (the sample at which the rate was, on the fit seasons, half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
opp_orb_pct_rank | Float64 | Rank of opp_orb_pct within the season (the lowest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose opp_orb_pct_n is at least 1,200 opponent offensive-rebound chances (the sample at which the rate was, on the fit seasons, half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
opp_ft_rate_rank | Float64 | Rank of opp_ft_rate within the season (the lowest value ranks 1; ties average), among teams that played at least half the most games any team played in the season, whose opp_ft_rate_n is at least 1,500 opponent field-goal attempts (the sample at which the rate was, on the fit seasons, half signal, rate_gates); null for a non-qualifier, a sample under that gate, a null rate, or fewer than five qualifiers. |
adj_off_rtg_pct | Float64 | Percentile of adj_off_rtg within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
adj_def_rtg_pct | Float64 | Percentile of adj_def_rtg within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
adj_net_rtg_pct | Float64 | Percentile of adj_net_rtg within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
sos_pct | Float64 | Percentile of sos within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
sov_pct | Float64 | Percentile of sov within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
off_rtg_pct | Float64 | Percentile of off_rtg within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
def_rtg_pct | Float64 | Percentile of def_rtg within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
net_rtg_pct | Float64 | Percentile of net_rtg within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
pace_pct | Float64 | Percentile of pace within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
efg_pct_pct | Float64 | Percentile of efg_pct within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
tov_pct_pct | Float64 | Percentile of tov_pct within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
orb_pct_pct | Float64 | Percentile of orb_pct within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
ft_rate_pct | Float64 | Percentile of ft_rate within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
opp_efg_pct_pct | Float64 | Percentile of opp_efg_pct within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
opp_tov_pct_pct | Float64 | Percentile of opp_tov_pct within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
opp_orb_pct_pct | Float64 | Percentile of opp_orb_pct within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
opp_ft_rate_pct | Float64 | Percentile of opp_ft_rate within the season among the same qualified teams: 100 * (n + 1 - rank) / (n + 1), n the number ranked, so the best team is under 100 and nobody is 0; null when the rank is null. |
adj_off_rtg_n | Int64 | Sample size of adj_off_rtg: the team's offensive possessions in the season. |
adj_def_rtg_n | Int64 | Sample size of adj_def_rtg: the team's defensive possessions in the season. |
adj_net_rtg_n | Int64 | Sample size of adj_net_rtg: the team's offensive plus defensive possessions in the season. |
sos_n | Int64 | Sample size of sos: the completed games against a rated opponent. |
sov_n | Int64 | Sample size of sov: the wins against a rated opponent. |
off_rtg_n | Int64 | Sample size of off_rtg: the team's offensive possessions in the season. |
def_rtg_n | Int64 | Sample size of def_rtg: the team's defensive possessions in the season. |
net_rtg_n | Int64 | Sample size of net_rtg: the team's offensive plus defensive possessions in the season. |
pace_n | Int64 | Sample size of pace: the game clock the season's possessions used, in regulation games (48 minutes, 40 in the WNBA and college), rounded: about the games played, overtime adding a little. |
efg_pct_n | Int64 | Sample size of efg_pct: the team's field-goal attempts in the season. |
tov_pct_n | Int64 | Sample size of tov_pct: the team's offensive possessions in the season. |
orb_pct_n | Int64 | Sample size of orb_pct: the team's offensive-rebound chances in the season. |
ft_rate_n | Int64 | Sample size of ft_rate: the team's field-goal attempts in the season. |
opp_efg_pct_n | Int64 | Sample size of opp_efg_pct: the opponents' field-goal attempts in the season. |
opp_tov_pct_n | Int64 | Sample size of opp_tov_pct: the team's defensive possessions in the season. |
opp_orb_pct_n | Int64 | Sample size of opp_orb_pct: the opponents' offensive-rebound chances in the season. |
opp_ft_rate_n | Int64 | Sample size of opp_ft_rate: the opponents' field-goal attempts in the season. |
Raises
| Exception | Description |
|---|---|
ValueError | If league_id is not "00" or "10", or season_type is not one of the four above (checked before any data is loaded). |
Example
from sportsdataverse.nba.nba_team_strength import nba_team_strength
strength = nba_team_strength(2026)
strength.sort("adj_net_rtg_rank").select("team_id", "adj_net_rtg", "sos", "sov").head()
# WNBA via ``league_id``
wnba = nba_team_strength(2025, league_id="10")
nba_tracking_drive_value
nba_tracking_drive_value(seasons: "'int | str | list'", *, league_id: 'str' = '00', per_mode: 'str' = 'Totals', by_position: 'bool' = True, positions: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False, _get_fn: 'Optional[Callable[..., dict]]' = None) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Drive value over expected + rim-pressure, per player-season.
Fetches the Drives leaguedashptstats measure and computes
drive_pts_oe = drive_pts - drives * bucket_pts_per_drive. rim_pressure
is the z-score of drive_fta / drives within the player's role bucket
(a proxy for foul-drawing pressure independent of scoring efficiency).
drive_ast/drive_tov are passed through unchanged.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | str | list | A single season or list of seasons. | |
league_id | str | '00' | "00" NBA (default), "10" WNBA, "20" G-League. |
per_mode | str | 'Totals' | per_mode_simple passed to the fetch (default "Totals"). |
by_position | bool | True | Compute the baseline within role buckets (default); False forces one league-wide bucket. |
positions | Optional[DataFrame] | None | Optional pre-fetched positions frame. |
return_as_pandas | bool | False | Return a pandas.DataFrame instead of polars. |
_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_leaguedashptstats. |
Returns
One row per player-season: season:Int64, player_id:Utf8, player_name:Utf8, team_id:Utf8, position_bucket:Utf8, gp:Int64, min:Float64, drives:Float64, drive_pts:Float64, drive_baseline_rate:Float64, drive_expected:Float64, drive_pts_oe:Float64, drive_pts_oe_per_36:Float64, drive_fta:Float64, rim_pressure:Float64, drive_ast:Float64, drive_tov:Float64, league_id:Utf8. Empty/malformed input returns a zero-row frame with this schema.
No returns table is published for this function: no capture: it reads stats.nba.com, which answers HTTP 403 to the datacenter IP the docs are built on; the function works from a residential IP.
Example
from sportsdataverse.nba import nba_tracking_drive_value
df = nba_tracking_drive_value(2024)
print(df.sort("drive_pts_oe", descending=True).head())
nba_tracking_pass_value
nba_tracking_pass_value(seasons: "'int | str | list'", *, league_id: 'str' = '00', per_mode: 'str' = 'Totals', by_position: 'bool' = True, positions: 'Optional[pl.DataFrame]' = None, fetch_potential_assists: 'bool' = False, max_players: 'int' = 0, return_as_pandas: 'bool' = False, _get_fn: 'Optional[Callable[..., dict]]' = None, _pass_get_fn: 'Optional[Callable[..., dict]]' = None) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Expected-assists / passer value: ast_oe per player-season.
Fetches the Passing leaguedashptstats measure (one call) and computes
ast_oe = ast - passes * bucket_assist_rate. When
fetch_potential_assists=True, also fetches nba_stats_playerdashptpass
for the top-max_players passers (capped, optional -- never a hard
dependency) and recomputes the residual against the richer
potential_assists denominator for that subset; max_players=0
(default) makes exactly one request total. ast_pts_created is passed
through directly from the Passing measure (it is already computed there;
not re-derived).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | str | list | A single season or list of seasons. | |
league_id | str | '00' | "00" NBA (default), "10" WNBA, "20" G-League. |
per_mode | str | 'Totals' | per_mode_simple passed to the fetch (default "Totals"). |
by_position | bool | True | Compute the baseline within role buckets (default); False forces one league-wide bucket. |
positions | Optional[DataFrame] | None | Optional pre-fetched positions frame. |
fetch_potential_assists | bool | False | Enrich the top passers with playerdashptpass potential-assist counts. |
max_players | int | 0 | Cap on per-player enrichment fetches; 0 disables enrichment regardless of fetch_potential_assists. |
return_as_pandas | bool | False | Return a pandas.DataFrame instead of polars. |
_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_leaguedashptstats. |
_pass_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_playerdashptpass. |
Returns
One row per player-season: season:Int64, player_id:Utf8, player_name:Utf8, team_id:Utf8, position_bucket:Utf8, gp:Int64, min:Float64, ast:Float64, passes:Float64, ast_baseline_rate:Float64, ast_expected:Float64, ast_oe:Float64, ast_oe_per_36:Float64, ast_pts_created:Float64, league_id:Utf8. Empty/malformed input returns a zero-row frame with this schema.
No returns table is published for this function: no capture: it reads stats.nba.com, which answers HTTP 403 to the datacenter IP the docs are built on; the function works from a residential IP.
Example
from sportsdataverse.nba import nba_tracking_pass_value
df = nba_tracking_pass_value(2024)
print(df.sort("ast_oe", descending=True).head())
# With potential-assist enrichment for the top 50 passers
df = nba_tracking_pass_value(2024, fetch_potential_assists=True, max_players=50)
nba_tracking_reb_oe
nba_tracking_reb_oe(seasons: "'int | str | list'", *, league_id: 'str' = '00', per_mode: 'str' = 'Totals', by_position: 'bool' = True, positions: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False, _get_fn: 'Optional[Callable[..., dict]]' = None) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Rebounding-over-expected: reb_oe plus OREB/DREB splits, per player-season.
Fetches the Rebounding leaguedashptstats measure, attaches a
guard/wing/big role bucket, and computes
reb_oe = reb - reb_chances * bucket_rate (contest-difficulty-adjusted
when the endpoint carries separate contested/uncontested CHANCE columns;
the live stats.nba.com payload currently does not, so this degrades
gracefully to the plain rate -- see the fixtures README for the finding).
OREB/DREB residuals are computed identically against their own chance
columns. Baselines are recomputed from the same season slice on every
call -- there is no fitted constant or bundled artifact.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | str | list | A single season (int ending-year or "YYYY-YY" string) or a list of seasons to concatenate. | |
league_id | str | '00' | "00" NBA (default), "10" WNBA, "20" G-League. |
per_mode | str | 'Totals' | per_mode_simple passed to the fetch (default "Totals"). |
by_position | bool | True | Compute the baseline within guard/wing/big buckets (default). False forces one league-wide bucket. |
positions | Optional[DataFrame] | None | Optional pre-fetched positions frame (see _attach_role_bucket); mostly for injecting a fixture in tests. |
return_as_pandas | bool | False | Return a pandas.DataFrame instead of polars. |
_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_leaguedashptstats returning the raw payload dict directly -- offline testing hook. |
Returns
One row per player-season: season:Int64, player_id:Utf8, player_name:Utf8, team_id:Utf8, position_bucket:Utf8, gp:Int64, min:Float64, reb:Float64, reb_chances:Float64, reb_baseline_rate:Float64, reb_expected:Float64, reb_oe:Float64, reb_oe_per_36:Float64, oreb_oe:Float64, dreb_oe:Float64, league_id:Utf8. Empty/malformed input returns a zero-row frame with this schema.
No returns table is published for this function: no capture: it reads stats.nba.com, which answers HTTP 403 to the datacenter IP the docs are built on; the function works from a residential IP.
Example
from sportsdataverse.nba import nba_tracking_reb_oe
df = nba_tracking_reb_oe(2024)
print(df.sort("reb_oe", descending=True).head())
# League-wide baseline (no position split)
df_all = nba_tracking_reb_oe(2024, by_position=False)
# Pandas output
df_pd = nba_tracking_reb_oe(2024, return_as_pandas=True)
nba_tracking_rim_protect_value
nba_tracking_rim_protect_value(seasons: "'int | str | list'", *, league_id: 'str' = '00', per_mode: 'str' = 'Totals', by_position: 'bool' = True, positions: 'Optional[pl.DataFrame]' = None, source: 'str' = 'leaguedash', max_players: 'int' = 0, return_as_pandas: 'bool' = False, _get_fn: 'Optional[Callable[..., dict]]' = None, _defend_get_fn: 'Optional[Callable[..., dict]]' = None) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Rim-protection / shot-defend points-saved over expected, per player-season.
Fetches the Defense leaguedashptstats measure -- which on the live
stats.nba.com payload exposes only rim-band defended shooting
(def_rim_fgm/def_rim_fga/def_rim_fg_pct, no separate overall
figure -- see the fixtures README) -- and computes
rim_protect_pts_saved = (normal_fg_pct - d_fg_pct) * d_fga * 2 where
normal_fg_pct is the bucket-mean defended rate (there is no
shooters'-own-average column on this endpoint, so the bucket mean is the
baseline; this is the same attempts-weighted construction as every other
model, just sign-flipped so a defender who holds shooters BELOW the
bucket mean gets a positive points-saved value).
source="shotdefend" swaps in the Less-Than-6-Ft band from
nba_stats_playerdashptshotdefend for the top-max_players defenders
by attempt volume (capped, optional -- never a hard dependency);
max_players=0 (default) uses the leaguedash figures for everyone.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | str | list | A single season or list of seasons. | |
league_id | str | '00' | "00" NBA (default), "10" WNBA, "20" G-League. |
per_mode | str | 'Totals' | per_mode_simple passed to the fetch (default "Totals"). |
by_position | bool | True | Compute the baseline within role buckets (default); False forces one league-wide bucket. |
positions | Optional[DataFrame] | None | Optional pre-fetched positions frame. |
source | str | 'leaguedash' | "leaguedash" (default) or "shotdefend". |
max_players | int | 0 | Cap on per-player shotdefend enrichment fetches; ignored unless source="shotdefend". |
return_as_pandas | bool | False | Return a pandas.DataFrame instead of polars. |
_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_leaguedashptstats. |
_defend_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_playerdashptshotdefend. |
Returns
One row per player-season: season:Int64, player_id:Utf8, player_name:Utf8, team_id:Utf8, position_bucket:Utf8, gp:Int64, min:Float64, d_fga:Float64, d_fgm:Float64, d_fg_pct:Float64, normal_fg_pct:Float64, rim_protect_pts_saved:Float64, rim_protect_pts_saved_per_36:Float64, source:Utf8, league_id:Utf8. Empty/malformed input returns a zero-row frame with this schema.
No returns table is published for this function: no capture: it reads stats.nba.com, which answers HTTP 403 to the datacenter IP the docs are built on; the function works from a residential IP.
Example
from sportsdataverse.nba import nba_tracking_rim_protect_value
df = nba_tracking_rim_protect_value(2024)
print(df.sort("rim_protect_pts_saved", descending=True).head())
nba_tracking_shot_diet_value
nba_tracking_shot_diet_value(seasons: "'int | str | list'", *, league_id: 'str' = '00', per_mode: 'str' = 'Totals', by_position: 'bool' = True, positions: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False, _get_fn: 'Optional[Callable[..., dict]]' = None) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Catch-&-shoot vs pull-up points-over-expected, per player-season.
Fetches CatchShoot and PullUpShot (two calls), scores each with the
shared engine, joins on player_id (dtype-asserted Utf8 both sides
first), and computes shot_diet_delta = (cs_pts_oe / cs_fga) - (pu_pts_oe / pu_fga) (null-safe on zero attempts) -- positive means the
player's efficiency edge comes from catch-&-shoot, negative from
off-the-dribble.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | str | list | A single season or list of seasons. | |
league_id | str | '00' | "00" NBA (default), "10" WNBA, "20" G-League. |
per_mode | str | 'Totals' | per_mode_simple passed to each fetch (default "Totals"). |
by_position | bool | True | Compute each measure's baseline within role buckets (default); False forces one league-wide bucket. |
positions | Optional[DataFrame] | None | Optional pre-fetched positions frame. |
return_as_pandas | bool | False | Return a pandas.DataFrame instead of polars. |
_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_leaguedashptstats, dispatched by the pt_measure_type kwarg for each of the two calls. |
Returns
One row per player-season: season:Int64, player_id:Utf8, player_name:Utf8, team_id:Utf8, position_bucket:Utf8, cs_fga:Float64, cs_pts:Float64, cs_pts_oe:Float64, pu_fga:Float64, pu_pts:Float64, pu_pts_oe:Float64, shot_diet_delta:Float64, league_id:Utf8. Empty/malformed input returns a zero-row frame with this schema.
No returns table is published for this function: no capture: it reads stats.nba.com, which answers HTTP 403 to the datacenter IP the docs are built on; the function works from a residential IP.
Example
from sportsdataverse.nba import nba_tracking_shot_diet_value
df = nba_tracking_shot_diet_value(2024)
print(df.sort("cs_pts_oe", descending=True).head())
nba_tracking_touch_value
nba_tracking_touch_value(seasons: "'int | str | list'", *, league_id: 'str' = '00', per_mode: 'str' = 'Totals', by_position: 'bool' = True, positions: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False, _get_fn: 'Optional[Callable[..., dict]]' = None) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Touch / possession-time value over expected, per player-season.
Fetches the Possessions leaguedashptstats measure and computes
pts_per_touch_oe = pts - touches * bucket_pts_per_touch.
time_of_poss_eff is the z-score of pts / time_of_poss within the
player's role bucket -- scoring economy per second of possession,
independent of touch volume.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | int | str | list | A single season or list of seasons. | |
league_id | str | '00' | "00" NBA (default), "10" WNBA, "20" G-League. |
per_mode | str | 'Totals' | per_mode_simple passed to the fetch (default "Totals"). |
by_position | bool | True | Compute the baseline within role buckets (default); False forces one league-wide bucket. |
positions | Optional[DataFrame] | None | Optional pre-fetched positions frame. |
return_as_pandas | bool | False | Return a pandas.DataFrame instead of polars. |
_get_fn | Optional[Callable[..., dict]] | None | Injectable replacement for nba_stats_leaguedashptstats. |
Returns
One row per player-season: season:Int64, player_id:Utf8, player_name:Utf8, team_id:Utf8, position_bucket:Utf8, gp:Int64, min:Float64, touches:Float64, pts:Float64, touch_baseline_rate:Float64, touch_expected:Float64, pts_per_touch_oe:Float64, time_of_poss:Float64, time_of_poss_eff:Float64, league_id:Utf8. Empty/malformed input returns a zero-row frame with this schema.
No returns table is published for this function: no capture: it reads stats.nba.com, which answers HTTP 403 to the datacenter IP the docs are built on; the function works from a residential IP.
Example
from sportsdataverse.nba import nba_tracking_touch_value
df = nba_tracking_touch_value(2024)
print(df.sort("pts_per_touch_oe", descending=True).head())
nbadraft_mock_draft
nbadraft_mock_draft(year: 'Optional[int]' = None, *, proxy: 'Any' = None, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
The current consensus mock draft from NBADraft.net.
One row per pick across both rounds. The page renders round 1 and round 2 as
the first two pick tables and then repeats round 1 in a third table, so
only the first two are taken -- concatenating all three double-counts round 1.
The <noscript> fallback is another false-positive JS challenge; the pick
tables are static. A traded pick's team cell carries *, which is stripped.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
year | Optional[int] | None | Draft year (e.g. 2025). None (default) reads the site's current mock; a year uses the /nba-mock-drafts/{year}/ path where NBADraft.net has one. |
proxy | Any | None | Proxy configuration forwarded to ~sportsdataverse.dl_utils.download (requests proxies= shape). |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
One row per pick with round (1 or 2), pick, team, player, height, weight, position, school and class. An unreachable or table-less page yields a zero-row frame with that schema.
| col_name | type | description |
|---|---|---|
round | Int64 | Draft round of the pick, 1 or 2 (NBADraft.net's first two pick tables). |
pick | Int64 | Pick number within the round. |
team | String | Team-side label or team identifier. |
player | String | Player name. |
height | String | Player height (string e.g. '6-2' or inches). |
weight | Int64 | Player weight in pounds. |
position | String | Listed roster position (G, F, C, etc.). |
school | String | Player school / pre-draft team. |
class | String | College class / draft eligibility note. |
Raises
| Exception | Description |
|---|---|
UserWarning | Emitted (not raised) when the page cannot be fetched or carries no pick table; the call still returns an empty frame. |
Example
import polars as pl
from sportsdataverse.nba import nbadraft_mock_draft
mock = nbadraft_mock_draft()
print(mock.shape)
# A specific draft year, as pandas
mock_pd = nbadraft_mock_draft(year=2025, return_as_pandas=True)
# Pipeline next step (lottery only)
mock.filter((pl.col("round") == 1) & (pl.col("pick") <= 14))
player_play_context
player_play_context(possessions: 'pl.DataFrame', *, league_non_transition_ppp: 'Optional[float]' = None, apply_ctg_filters: 'bool' = True, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
Per-player offensive On/Off Play-Context table (CTG's On/Off page, offense half).
For each player: their team's offensive play-context with them on the floor
(on_*), without them (off_*), and the on-minus-off difference
(diff_*) — which is the number CTG actually displays.
The OFF side is derived by subtraction (team total minus on-court), not by a
second scan. That is deliberate: it makes the partition exact by construction —
on_poss + off_poss == team_poss and the same for points — so a leak (a
double-counted possession, a dropped lineup slot) is impossible to hide. The
test suite asserts that identity directly.
Like CTG's on/off, this is a raw split: no luck adjustment, no opponent
adjustment, no minutes threshold. It is a descriptive difference, not a causal
estimate — for that, use the RAPM surface
(~sportsdataverse.nba.nba_rapm.nba_rapm).
Requires off_player_1..5 from
~sportsdataverse.nba.nba_possessions.attach_possession_lineups.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
possessions | DataFrame | Frame from add_play_context with lineups attached. | |
league_non_transition_ppp | Optional[float] | None | Pts+/Poss baseline; see team_play_context. One baseline is shared across the on and off sides so the diffs are comparable. |
apply_ctg_filters | bool | True | Drop garbage-time / heave / non-counting possessions first. |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
One row per (player, team) with PLAYER_PLAY_CONTEXT_SCHEMA. Empty input returns a zero-row frame with that schema.
| col_name | type | description |
|---|---|---|
player_id | Int64 | Unique player identifier. |
offense_team_id | Int64 | Unique identifier for offense team. |
on_poss | Int64 | |
off_poss | Int64 | |
on_points | Int64 | |
off_points | Int64 | |
on_pts_per_100 | Float64 | |
off_pts_per_100 | Float64 | |
diff_pts_per_100 | Float64 | |
on_transition_freq | Float64 | |
off_transition_freq | Float64 | |
diff_transition_freq | Float64 | |
on_transition_pts_per_100 | Float64 | |
off_transition_pts_per_100 | Float64 | |
diff_transition_pts_per_100 | Float64 | |
on_halfcourt_pts_per_100 | Float64 | |
off_halfcourt_pts_per_100 | Float64 | |
diff_halfcourt_pts_per_100 | Float64 | |
on_transition_pts_added_per_100 | Float64 | |
off_transition_pts_added_per_100 | Float64 |
Raises
| Exception | Description |
|---|---|
ValueError | When the off_player_* columns are missing. |
Example
poss = attach_possession_lineups(add_play_context(enh), oncourt, enh, home_team_id=home)
onoff = player_play_context(poss)
print(onoff.sort("diff_pts_per_100", descending=True).head())
# Who makes their team run?
print(onoff.sort("diff_transition_freq", descending=True).head())
player_rates
player_rates(box_logs: 'pl.DataFrame', *, prior_logs: 'pl.DataFrame | None' = None, league_id: 'str | None' = None, recent_games: 'int | None' = None) -> 'pl.DataFrame'
Per-player per-minute rate stats from box logs, shrunk toward a tier prior in the NBA.
Rows with null, zero or negative minutes (DNPs) are dropped before anything
is counted, so games counts only games the player logged minutes in.
The raw rate is total stat / total minutes across those games; minutes_pg is the
mean minutes. A traded player gets one row: the rates pool every team's
games, and team_id is the team on the player's last kept input row
(sort box_logs by date to make that the latest team).
With a league_id that has fitted rate_prior_minutes (the NBA, "00"), each
rate is (stat_sum + k * tier_rate) / (min_sum + k): k pseudo-minutes of the
pooled rate of the player's minutes-and-role tier (minutes_pg in [0,12), [12,20),
[20,28), 28+, split by starter share >= .5). The tier rate pools box_logs and
prior_logs, each player tiered by his own profile in each frame; pass the previous
regular season as prior_logs so a player's first games have a prior.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
box_logs | DataFrame | Per-player-per-game frame with player_id, team_id, minutes and the stats pts, reb, ast, fg3m; stl, blk, tov, fgm, ftm are optional (a stat missing from the frame, or null on every played row, gets a null rate). Shrinkage also needs starter. | |
prior_logs | DataFrame | None | None | Earlier games (same columns), pooled into the tier rates only; they never enter a player's own totals. |
league_id | str | None | None | None (default) for raw rates; "00" / "10" / "20" for that league's fitted shrinkage. Only the NBA has one, so WNBA and G-League stay raw. |
recent_games | int | None | None | When set, each player's own totals (games, minutes_pg and the rates) cover only his last recent_games played rows by game_date, while his tier and the tier rates still come from all of box_logs (needs game_date). |
Returns
One row per player: player_id, team_id, games, minutes_pg, then pts_per_min, reb_per_min, ast_per_min, fg3m_per_min, stl_per_min, blk_per_min, tov_per_min, fgm_per_min, ftm_per_min; games is Int64. player_id and team_id keep the input's dtype (String from the nba_player_props loader; integer ids come back as integers); empty input returns the documented schema, with String ids, and zero rows.
| col_name | type | description |
|---|---|---|
player_id | String | Unique player identifier. |
team_id | String | Unique team identifier. |
games | Int64 | Games played. |
minutes_pg | Float64 | |
pts_per_min | Float64 | |
reb_per_min | Float64 | |
ast_per_min | Float64 | |
fg3m_per_min | Float64 | |
stl_per_min | Float64 | |
blk_per_min | Float64 | |
tov_per_min | Float64 | |
fgm_per_min | Float64 | |
ftm_per_min | Float64 |
Raises
| Exception | Description |
|---|---|
ValueError | Shrinkage is on and box_logs or prior_logs has no starter value on any played row (the tiers split on it); or recent_games is set and box_logs has no game_date. |
Example
from sportsdataverse.nba.nba_player_props import player_rates
rates = player_rates(box_logs)
# Shrunk toward the tier prior, with last season pooled in
rates = player_rates(box_logs, prior_logs=last_season_logs, league_id="00")
players_on_court_from_pbp
players_on_court_from_pbp(enhanced_pbp: 'pl.DataFrame', raw_box: 'dict', *, home_team_id: 'int', away_team_id: 'int') -> 'pl.DataFrame'
Reconstruct the 5-on-5 on-court lineup from pbp subs + boxscore starters.
Pure function (no network). A gamerotation-free alternative to
players_on_court_from_rotation returning the identical
LINEUPS_SCHEMA frame (one row per action, slots sorted ascending or
None). See the module design for the algorithm.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
enhanced_pbp | DataFrame | Output of enhanced_pbp_from_payload. Must carry game_id, action_number, order_index, period, team_id, person_id, description, is_substitution. | |
raw_box | dict | Raw boxscoretraditionalv3 dict (starters + name map). | |
home_team_id | int | Home team id (from boxscore_home_away). | |
away_team_id | int | Away team id (from boxscore_home_away). |
Returns
polars.DataFrame conforming to LINEUPS_SCHEMA. Empty input returns a zero-row frame (never raises).
| col_name | type | description |
|---|---|---|
game_id | String | Unique game identifier. |
action_number | Int64 | Sequential action number within a game (V3 PBP). |
period | Int64 | Period of the game (1-4 quarters; 5+ for OT). |
home_player_1 | Int64 | |
home_player_2 | Int64 | |
home_player_3 | Int64 | |
home_player_4 | Int64 | |
home_player_5 | Int64 | |
away_player_1 | Int64 | |
away_player_2 | Int64 | |
away_player_3 | Int64 | |
away_player_4 | Int64 | |
away_player_5 | Int64 |
Example
import json, pathlib
from sportsdataverse.nba.nba_enhanced_pbp import enhanced_pbp_from_payload
from sportsdataverse.nba.nba_lineups import (
boxscore_home_away, players_on_court_from_pbp,
)
box = json.loads(pathlib.Path("boxscoretraditionalv3.json").read_text())
pbp = json.loads(pathlib.Path("playbyplayv3.json").read_text())
enh = enhanced_pbp_from_payload(pbp)
home, away = boxscore_home_away(box)
oc = players_on_court_from_pbp(enh, box, home_team_id=home, away_team_id=away)
print(oc.shape)
players_on_court_from_quarter_boxscores
players_on_court_from_quarter_boxscores(enhanced_pbp: 'pl.DataFrame', period_boxscores: 'Dict[int, dict]', raw_box: 'Optional[dict]' = None, *, home_team_id: 'int', away_team_id: 'int') -> 'pl.DataFrame'
Reconstruct the 5-on-5 on-court lineup, seeding each period exactly where possible.
A structural sibling of players_on_court_from_pbp — same
LINEUPS_SCHEMA output, same sub-batching walk / ffill-bfill / ascending
sort tail — whose only difference is how each period is seeded: when
that period's range-boxscore (_period_box_oncourt) narrows to
exactly 5 on-court candidates for a team, the period is seeded EXACTLY
from it; otherwise it falls back to the same gamerotation-free
first-appearance inference players_on_court_from_pbp uses
(_period_starters, carrying the prior period's ending lineup as
the silent-starter fallback). See _period_box_oncourt for the
narrowing recipe (empirically re-derived against pbpstats'
StartOfPeriod._get_starters_from_boxscore_request — see that
function's docstring for the concrete evidence behind its zero-sentinel
polarity).
Substitution name resolution merges up to three sources via
_merge_name_maps: _name_map_from_period_boxes (the union
of every period's range-box roster), _name_map_from_pbp_actors
(every row's own actor identity — covers bench players who never touch a
period boundary but do record at least one action), and — when the
caller supplies it — _boxscore_name_map over the full-game
raw_box payload, the SAME full-roster source
players_on_court_from_pbp uses. That third source is what fixes
the one residual name-resolution gap the first two cannot cover: a
player who is subbed in and then records zero further pbp actions for
the rest of the game (so never appears in _name_map_from_pbp_actors)
and never happens to be on court at an exact period-opening tick (so
never appears in _name_map_from_period_boxes) is still present in the
full-game boxscore roster — which lists every player on both teams
regardless of playing time — and therefore still resolvable. Passing
raw_box is optional (None preserves the pre-existing two-source
behavior) but strongly recommended: without it this producer's per-game
agreement with the gamerotation oracle can regress well below
players_on_court_from_pbp's own floor on a fixture with a
late, stat-less bench appearance (see
tests/nba/test_nba_lineups.py::test_quarter_box_agreement_floors).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
enhanced_pbp | DataFrame | Output of ~sportsdataverse.nba.nba_enhanced_pbp.enhanced_pbp_from_payload. Must carry game_id, action_number, order_index, period, team_id, person_id, player_name, player_name_i, description, is_substitution. | |
period_boxscores | Dict[int, dict] | {period: raw_boxscoretraditionalv3_range_payload} — one entry per period, captured at that period's _period_start_range window. A missing period key falls back to pbp seeding for that period only (never raises). | |
raw_box | Optional[dict] | None | Optional raw full-game boxscoretraditionalv3 payload (the same one players_on_court_from_pbp and boxscore_home_away consume) — supplies the full-roster name map described above. None (default) falls back to resolving names from period_boxscores + pbp actors only. |
home_team_id | int | Home team id (from boxscore_home_away). | |
away_team_id | int | Away team id (from boxscore_home_away). |
Returns
polars.DataFrame conforming to LINEUPS_SCHEMA. Empty enhanced_pbp returns a zero-row frame (never raises).
| col_name | type | description |
|---|---|---|
game_id | String | Unique game identifier. |
action_number | Int64 | Sequential action number within a game (V3 PBP). |
period | Int64 | Period of the game (1-4 quarters; 5+ for OT). |
home_player_1 | Int64 | |
home_player_2 | Int64 | |
home_player_3 | Int64 | |
home_player_4 | Int64 | |
home_player_5 | Int64 | |
away_player_1 | Int64 | |
away_player_2 | Int64 | |
away_player_3 | Int64 | |
away_player_4 | Int64 | |
away_player_5 | Int64 |
Example
import json, pathlib
from sportsdataverse.nba.nba_enhanced_pbp import enhanced_pbp_from_payload
from sportsdataverse.nba.nba_lineups import (
boxscore_home_away, players_on_court_from_quarter_boxscores,
)
box = json.loads(pathlib.Path("boxscoretraditionalv3.json").read_text())
pbp = json.loads(pathlib.Path("playbyplayv3.json").read_text())
periods = json.loads(pathlib.Path("boxv3_periods.json").read_text())
period_boxscores = {int(k): v for k, v in periods.items()}
enh = enhanced_pbp_from_payload(pbp)
home, away = boxscore_home_away(box)
oc = players_on_court_from_quarter_boxscores(
enh, period_boxscores, box, home_team_id=home, away_team_id=away
)
print(oc.shape)
players_on_court_from_rotation
players_on_court_from_rotation(enhanced_pbp: 'pl.DataFrame', rotation: 'dict[str, list[dict]]', *, home_team_id: 'int', away_team_id: 'int', league_id: 'Optional[str]' = None) -> 'pl.DataFrame'
Reconstruct the 5-on-5 on-court lineup via the rotation (gamerotation) algorithm.
Pure function — no network calls. Port of hoopR's .players_on_court_v3()
(R/nba_stats_pbp.R lines 857-1041).
The rotation dict may use either "HomeTeam"/"AwayTeam" or
"homeTeam"/"awayTeam" as keys — both are accepted.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
enhanced_pbp | DataFrame | Output of ~sportsdataverse.nba.nba_enhanced_pbp.enhanced_pbp_from_payload. Must contain game_id, action_number, period, seconds_remaining, is_substitution, and team_id. | |
rotation | dict[str, list[dict]] | Parsed rotation dict, typically from parse_rotation_resultsets. Each team's list contains stint dicts with numeric PERSON_ID, IN_TIME_REAL, OUT_TIME_REAL. | |
home_team_id | int | Integer team ID of the home team. | |
away_team_id | int | Integer team ID of the away team. | |
league_id | Optional[str] | None | "00" NBA, "10" WNBA, "15" Summer League, "20" G League. Sets the period lengths the rotation clock runs on; when None the league is read off the game id. |
Returns
polars.DataFrame conforming to LINEUPS_SCHEMA with one row per action in enhanced_pbp (same row count, same ordering). Never raises — an empty or malformed rotation (stints that do not sum to five players' game time, or carry negative / inverted clocks) logs a warning and returns a zero-row frame, so callers fall back to another lineup source.
| col_name | type | description |
|---|---|---|
game_id | String | Unique game identifier. |
action_number | Int64 | Sequential action number within a game (V3 PBP). |
period | Int64 | Period of the game (1-4 quarters; 5+ for OT). |
home_player_1 | Int64 | |
home_player_2 | Int64 | |
home_player_3 | Int64 | |
home_player_4 | Int64 | |
home_player_5 | Int64 | |
away_player_1 | Int64 | |
away_player_2 | Int64 | |
away_player_3 | Int64 | |
away_player_4 | Int64 | |
away_player_5 | Int64 |
Example
import json, pathlib
import polars as pl
from sportsdataverse.nba.nba_enhanced_pbp import enhanced_pbp_from_payload
from sportsdataverse.nba.nba_lineups import (
boxscore_home_away, parse_rotation_resultsets,
players_on_court_from_rotation,
)
box = json.loads(pathlib.Path("boxscoretraditionalv3.json").read_text())
pbp = json.loads(pathlib.Path("playbyplayv3.json").read_text())
rot = json.loads(pathlib.Path("gamerotation.json").read_text())
enh = enhanced_pbp_from_payload(pbp)
home, away = boxscore_home_away(box)
rotation = parse_rotation_resultsets(rot)
df = players_on_court_from_rotation(
enh, rotation, home_team_id=home, away_team_id=away
)
print(df.shape)
prob_over
prob_over(exp_value: 'float', line: 'float', stat: 'str', *, league_id: 'str' = '00', recent_value: 'float | None' = None, recent_weight: 'float | None' = None) -> 'float'
Probability a stat finishes strictly above line.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
exp_value | float | Projected mean of the stat. | |
line | float | The prop line. | |
stat | str | A prop_distribution stat ("pts" ... "ftm"). | |
league_id | str | '00' | "00" NBA / "10" WNBA / "20" G-League (passed to prop_distribution). |
recent_value | float | None | None | The recent-window mean, for the mixture (see prop_distribution). |
recent_weight | float | None | None | The mixture weight; None or 0 prices the single distribution. |
Returns
P(stat > line) in [0, 1].
Example
from sportsdataverse.nba.nba_player_props import prob_over
prob_over(24.0, 22.5, "pts")
# Priced as the recent-window mixture (the ``nba_player_props`` columns)
prob_over(24.0, 22.5, "pts", recent_value=28.0, recent_weight=0.4)
project_player_line
project_player_line(rate_row: 'dict[str, Any]', exp_minutes: 'float', pace_factor: 'float' = 1.0) -> 'dict[str, float]'
Project a player's expected counting line from per-minute rates.
exp_stat = rate_per_min * exp_minutes * pace_factor -- counting stats
scale with both projected minutes and pace.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
rate_row | dict[str, Any] | One row of player_rates (as a dict). | |
exp_minutes | float | Projected minutes for the game. | |
pace_factor | float | 1.0 | Pace multiplier (exp_poss / avg_pace); 1.0 for a league-average-pace matchup. |
Returns
{"exp_<stat>": value} for each <stat>_per_min in rate_row that is not null: exp_pts, exp_reb, exp_ast, exp_fg3m, plus exp_stl ... exp_ftm from a player_rates row whose input carried those stats.
Example
from sportsdataverse.nba.nba_player_props import player_rates, project_player_line
r = player_rates(box_logs).row(0, named=True)
line = project_player_line(r, exp_minutes=32.0, pace_factor=1.02)
prop_distribution
prop_distribution(exp_value: 'float', stat: 'str', *, league_id: 'str' = '00', recent_value: 'float | None' = None, recent_weight: 'float | None' = None) -> 'tuple[str, dict[str, Any]]'
Distribution family + parameters for a projected stat mean.
Points -> Normal (mu, sd) with sd = a + b*sqrt(mu); counts
(reb/ast/fg3m, and stl/blk/tov/fgm/ftm where the league has their fit) ->
Negative-Binomial (r, p) matching mean mu and variance
dispersion*mu (Poisson if dispersion <= 1). With a positive
recent_weight it is the two-component mixture
(1 - w) F(exp_value) + w F(recent_value) of nba_player_props; its
points components use the mixture's own SD law (recent_mixture in
~sportsdataverse.nba.nba_prediction_constants.LEAGUE_CONSTANTS).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
exp_value | float | Projected mean of the stat (stat_<stat>_exp). | |
stat | str | One of "pts", "reb", "ast", "fg3m", "stl", "blk", "tov", "fgm", "ftm". | |
league_id | str | '00' | "00" NBA / "10" WNBA / "20" G-League; selects that league's fitted SD law and dispersion. |
recent_value | float | None | None | The recent-window mean (stat_<stat>_recent_exp). |
recent_weight | float | None | None | The mixture weight (recent_weight); None or 0 gives the single distribution. |
Returns
(family, params) where family is "normal", "nbinom" or "poisson"; or "mixture" with params {"weights": [1 - w, w], "components": [(family, params), (family, params)]}.
Raises
| Exception | Description |
|---|---|
ValueError | stat is one of stl/blk/tov/fgm/ftm and the league has no fitted dispersion for it (only the NBA has one); or recent_weight is positive and the league has no fitted mixture or recent_value is missing. |
Example
from sportsdataverse.nba.nba_player_props import prop_distribution
fam, par = prop_distribution(24.0, "pts")
# A player whose last 10 games run hotter than his season
fam, par = prop_distribution(24.0, "pts", recent_value=28.0, recent_weight=0.4)
ratings_as_of
ratings_as_of(model: 'AnyModel', possessions: 'pl.DataFrame', asof: 'datetime.date') -> 'RatingsFit'
Fit model on every possession dated on or before asof and return ratings.
This is the through-date primitive: possessions with game_date > asof
are excluded from the fit entirely (never merely down-weighted), which is
what makes the panel built from repeated calls to this function leakage-free
by construction — see tests/nba/test_nba_ratings_panel.py::test_ratings_as_of_is_leakage_free_append_invariant.
NOTE: the leakage property is proven by the append-invariance test TOGETHER
with the panel's per-date-parity test — neither alone covers
cross-checkpoint-window leaks; do not prune one without the other.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
model | AnyModel | A harness model conforming to nba_model_validation.AnyModel (a RapmModel, RatingsModel, or PriorModel). | |
possessions | DataFrame | A possession+lineup frame that MUST carry a game_date (pl.Date) column (as emitted by compile_nba_season). | |
asof | date | The through-date checkpoint (inclusive: game_date <= asof). A pregame consumer of a game on day D passes D - 1 day; the pregame surfaces (nba_player_props, nba_team_ratings) take a strict as_of_date instead. |
Returns
RatingsFit with per-player offense/defense ratings (per-100-possession scale, same sign convention as nba_rapm: positive d_ratings means good defense). Empty dicts when no possessions fall on or before asof or when possessions is empty.
Raises
| Exception | Description |
|---|---|
ValueError | If possessions (non-empty) does not carry a game_date column — this is a caller-contract violation, not a normal empty case, so it raises rather than silently returning empty ratings. |
Example
import datetime
from sportsdataverse.nba.nba_model_validation import RidgeRapmModel
from sportsdataverse.nba.nba_ratings_panel import ratings_as_of
rf = ratings_as_of(RidgeRapmModel(), season_poss, datetime.date(2023, 12, 1))
print(rf.o_ratings[201939]) # per-100 offensive rating through Dec 1
rotowire_injuries
rotowire_injuries(*, proxy: 'Any' = None, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'
The current NBA injury report from RotoWire.
One row per injured player: team, position, the injury, the designation (Out / Doubtful / Questionable / GTD / Day-To-Day) and a link to the player's RotoWire page. This is the live replacement for the defunct RotoWorld feed.
The rendered grid at /basketball/news.php?view=injuries builds itself
client-side, so this reads the JSON table endpoint the grid calls
(/basketball/tables/injury-report.php?team=ALL&pos=ALL) rather than
scraping the page. The projected return date is subscriber-gated and comes
back as "Subscribers Only"; it is returned as null for non-subscribers.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
proxy | Any | None | Proxy configuration forwarded to ~sportsdataverse.dl_utils.download (requests proxies= shape). |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
One row per injured player with player_id, player, first_name, last_name, team, position, injury, status, return_date and url. An unreachable endpoint or a non-list body yields a zero-row frame with that schema.
| col_name | type | description |
|---|---|---|
player_id | String | Unique player identifier. |
player | String | Player name. |
first_name | String | Player's first name. |
last_name | String | Player's last name. |
team | String | Team-side label or team identifier. |
position | String | Listed roster position (G, F, C, etc.). |
injury | String | Injury (body part / description). |
status | String | Status label. |
return_date | String | Projected return date as RotoWire shows it; null for non-subscribers (the endpoint sends "Subscribers Only") and when the cell is blank. |
url | String | RotoWire player page URL. |
Raises
| Exception | Description |
|---|---|
UserWarning | Emitted (not raised) when the endpoint cannot be fetched or does not answer with a JSON array; the call still returns an empty frame. |
Example
import polars as pl
from sportsdataverse.nba import rotowire_injuries
injuries = rotowire_injuries()
print(injuries.shape)
# As pandas
injuries_pd = rotowire_injuries(return_as_pandas=True)
# Pipeline next step (who is ruled out)
injuries.filter(pl.col("status") == "Out").select("player", "team", "injury")
score_shot_xpoints
score_shot_xpoints(shots: 'pl.DataFrame', league_avgs: 'pl.DataFrame', *, league_id: 'str' = '00', model: "Literal['zone', 'location'] | None" = None, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Score each shot with its make chance and expected points.
base_fg_pct is the make chance: model="location" (NBA default) is add_shot_make_prob
on loc_x / loc_y / action_type / shot_type for twos, the zone value for threes and
unlocated shots; model="zone" (WNBA / G League default, no booster) is the LeagueAverages
zone-triple FG% (unmatched: the shot_zone_range mean). Adds shot_value (3 for 3PT else
2), xpoints = base_fg_pct * shot_value, actual_points = shot_made_flag * shot_value.
Walk-forward (tools/models/nba_shot_value/shot_make_nba_holdout.json) its log loss is 3% to 4%
under the zone table's every season since 2018-19, nearly all at the rim; its level misses by over
a point on 2018-19, 2020-21 and 2022-23 (owner-accepted).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
shots | DataFrame | Per-shot Shot_Chart_Detail frame (needs shot_type, the three zone keys and shot_made_flag; the location model also reads loc_x, loc_y and action_type). | |
league_avgs | DataFrame | The LeagueAverages frame (see xpoints_baseline). | |
league_id | str | '00' | "00" NBA, "10" WNBA, "20" G-League (the booster to load). |
model | Literal['zone', 'location'] | None | None | "location", "zone" or None (location where a booster ships). |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
The input shots plus shot_value:Int64, base_fg_pct:Float64, xpoints:Float64, actual_points:Float64. Empty input returns the augmented schema with zero rows.
No returns table is published for this function: no capture: its input is stats.nba.com shot-chart detail (shot zones and types), which answers HTTP 403 to the datacenter IP the docs are built on and is not in the raw store.
Raises
| Exception | Description |
|---|---|
ValueError | A zone join key's dtype differs between the frames, model is unknown, or model="location" lacks a booster for league_id or a location column. |
Example
import polars as pl
from sportsdataverse.nba.nba_shot_value import score_shot_xpoints
scored = score_shot_xpoints(shots, league_avgs)
located = score_shot_xpoints(shots, league_avgs, model="location")
# Pipeline next step (one line)
scored.group_by("player_id").agg(pl.col("xpoints").sum())
shooter_talent
shooter_talent(scored_shots: 'pl.DataFrame', *, league_id: 'str' = '00', min_attempts: 'int' = 50, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Regressed shooter true-talent: make%-above-expected, shrunk to the mean.
Aggregates score_shot_xpoints output per shooter and regresses the
raw over-expected rate toward zero by n/(n+k) (k = get_shrinkage_k(league_id), fitted split-half). As-of leakage
boundary: to score a shooter's talent for shots after date D, pass
only that shooter's shots before D -- this function does not enforce the
cut itself.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
scored_shots | DataFrame | score_shot_xpoints output (needs player_id, shot_made_flag, base_fg_pct, xpoints, actual_points). | |
league_id | str | '00' | "00" NBA, "10" WNBA, "20" G-League. |
min_attempts | int | 50 | Drop shooters with fewer attempts (unstable estimate). |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
One row per player_id: player_id:Int64, n_att:Int64, actual_makes:Int64, exp_makes:Float64, points_above_expected:Float64, raw_above_pct:Float64, talent_pct:Float64. Empty input returns the zero-row schema.
No returns table is published for this function: no capture: its input is stats.nba.com shot-chart detail (shot zones and types), which answers HTTP 403 to the datacenter IP the docs are built on and is not in the raw store.
Example
from sportsdataverse.nba.nba_shot_value import score_shot_xpoints, shooter_talent
talent = shooter_talent(score_shot_xpoints(shots, league_avgs))
# Pipeline next step (one line)
talent.sort("talent_pct", descending=True).head(15)
shot_selection_quality
shot_selection_quality(scored_shots: 'pl.DataFrame', *, min_attempts: 'int' = 50, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"
Player shot-selection quality: mean expected value vs the league mean.
xev_per_shot is a player's mean xpoints (the value of the LOOKS
they take, independent of makes); selection_quality is that minus the
league-wide mean xpoints over the same frame -- a rim-and-three diet
scores positive, a mid-range diet negative.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
scored_shots | DataFrame | score_shot_xpoints output (needs player_id, xpoints). | |
min_attempts | int | 50 | Drop players with fewer attempts. |
return_as_pandas | bool | False | Return a pandas DataFrame instead of polars. |
Returns
One row per player_id: player_id:Int64, n_att:Int64, xev_per_shot:Float64, league_xev_per_shot:Float64, selection_quality:Float64. Empty input returns the zero-row schema.
No returns table is published for this function: no capture: its input is stats.nba.com shot-chart detail (shot zones and types), which answers HTTP 403 to the datacenter IP the docs are built on and is not in the raw store.
Example
from sportsdataverse.nba.nba_shot_value import score_shot_xpoints, shot_selection_quality
sel = shot_selection_quality(score_shot_xpoints(shots, league_avgs))
# Pipeline next step (one line)
sel.sort("selection_quality", descending=True).head(15)