Skip to main content
Version: 0.2.0

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

ParameterTypeDefaultDescription
seasonsint | 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_idstr'00'"00" NBA or "10" WNBA.
season_typestr'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_pandasboolFalseReturn 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_nametypedescription
seasonInt64Season, named by the year it ends (2026 is 2025-26).
team_idInt64stats.nba.com team id (the 10-digit franchise id).
gamesInt64Games with at least one possession in the season (from the possession release).
winsInt64Wins in the season type's completed games (the schedule's final scores).
lossesInt64Losses in the season type's completed games.
possInt64Offensive possessions in the season, counted from possession rows.
opp_possInt64Defensive possessions in the season (the opponents' offensive possessions).
ptsInt64Points scored on the team's offensive possessions in the season. Counted from each possession's made shots and free throws.
opp_ptsInt64Points allowed on the team's defensive possessions in the season.
adj_off_rtgFloat64Adjusted 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_rtgFloat64Adjusted 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_rtgFloat64Adjusted net rating: adj_off_rtg minus adj_def_rtg.
sosFloat64Strength 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).
sovFloat64Strength of victory: the mean adj_net_rtg of the opponents the team beat, one weight per win; null with no win.
off_rtgFloat64Offensive rating: points scored per 100 offensive possessions.
def_rtgFloat64Defensive rating: points allowed per 100 defensive possessions.
net_rtgFloat64Net rating: off_rtg minus def_rtg.
paceFloat64Pace: 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_pctFloat64Effective field-goal percentage, (FGM + 0.5 * 3PM) / FGA, as a fraction.
tov_pctFloat64Turnovers per offensive possession, as a fraction.
orb_pctFloat64Offensive rebound rate: offensive rebounds over offensive-rebound chances (own OREB plus the defense's DREB), as a fraction.
ft_rateFloat64Free-throw rate, FTA / FGA.
opp_efg_pctFloat64Opponents' effective field-goal percentage, (FGM + 0.5 * 3PM) / FGA, as a fraction.
opp_tov_pctFloat64Opponents' turnovers per possession (turnovers forced), as a fraction.
opp_orb_pctFloat64Opponents' offensive rebound rate, as a fraction (one minus the team's defensive rebound rate).
opp_ft_rateFloat64Opponents' free-throw rate, FTA / FGA.
adj_off_rtg_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_rankFloat64Rank 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_pctFloat64Percentile 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_nInt64Sample size of adj_off_rtg: the team's offensive possessions in the season.
adj_def_rtg_nInt64Sample size of adj_def_rtg: the team's defensive possessions in the season.
adj_net_rtg_nInt64Sample size of adj_net_rtg: the team's offensive plus defensive possessions in the season.
sos_nInt64Sample size of sos: the completed games against a rated opponent.
sov_nInt64Sample size of sov: the wins against a rated opponent.
off_rtg_nInt64Sample size of off_rtg: the team's offensive possessions in the season.
def_rtg_nInt64Sample size of def_rtg: the team's defensive possessions in the season.
net_rtg_nInt64Sample size of net_rtg: the team's offensive plus defensive possessions in the season.
pace_nInt64Sample 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_nInt64Sample size of efg_pct: the team's field-goal attempts in the season.
tov_pct_nInt64Sample size of tov_pct: the team's offensive possessions in the season.
orb_pct_nInt64Sample size of orb_pct: the team's offensive-rebound chances in the season.
ft_rate_nInt64Sample size of ft_rate: the team's field-goal attempts in the season.
opp_efg_pct_nInt64Sample size of opp_efg_pct: the opponents' field-goal attempts in the season.
opp_tov_pct_nInt64Sample size of opp_tov_pct: the team's defensive possessions in the season.
opp_orb_pct_nInt64Sample size of opp_orb_pct: the opponents' offensive-rebound chances in the season.
opp_ft_rate_nInt64Sample size of opp_ft_rate: the opponents' field-goal attempts in the season.

Raises

ExceptionDescription
ValueErrorIf 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

ParameterTypeDefaultDescription
seasonsint | str | listA single season or list of seasons.
league_idstr'00'"00" NBA (default), "10" WNBA, "20" G-League.
per_modestr'Totals'per_mode_simple passed to the fetch (default "Totals").
by_positionboolTrueCompute the baseline within role buckets (default); False forces one league-wide bucket.
positionsOptional[DataFrame]NoneOptional pre-fetched positions frame.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
_get_fnOptional[Callable[..., dict]]NoneInjectable 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

ParameterTypeDefaultDescription
seasonsint | str | listA single season or list of seasons.
league_idstr'00'"00" NBA (default), "10" WNBA, "20" G-League.
per_modestr'Totals'per_mode_simple passed to the fetch (default "Totals").
by_positionboolTrueCompute the baseline within role buckets (default); False forces one league-wide bucket.
positionsOptional[DataFrame]NoneOptional pre-fetched positions frame.
fetch_potential_assistsboolFalseEnrich the top passers with playerdashptpass potential-assist counts.
max_playersint0Cap on per-player enrichment fetches; 0 disables enrichment regardless of fetch_potential_assists.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
_get_fnOptional[Callable[..., dict]]NoneInjectable replacement for nba_stats_leaguedashptstats.
_pass_get_fnOptional[Callable[..., dict]]NoneInjectable 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

ParameterTypeDefaultDescription
seasonsint | str | listA single season (int ending-year or "YYYY-YY" string) or a list of seasons to concatenate.
league_idstr'00'"00" NBA (default), "10" WNBA, "20" G-League.
per_modestr'Totals'per_mode_simple passed to the fetch (default "Totals").
by_positionboolTrueCompute the baseline within guard/wing/big buckets (default). False forces one league-wide bucket.
positionsOptional[DataFrame]NoneOptional pre-fetched positions frame (see _attach_role_bucket); mostly for injecting a fixture in tests.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
_get_fnOptional[Callable[..., dict]]NoneInjectable 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

ParameterTypeDefaultDescription
seasonsint | str | listA single season or list of seasons.
league_idstr'00'"00" NBA (default), "10" WNBA, "20" G-League.
per_modestr'Totals'per_mode_simple passed to the fetch (default "Totals").
by_positionboolTrueCompute the baseline within role buckets (default); False forces one league-wide bucket.
positionsOptional[DataFrame]NoneOptional pre-fetched positions frame.
sourcestr'leaguedash'"leaguedash" (default) or "shotdefend".
max_playersint0Cap on per-player shotdefend enrichment fetches; ignored unless source="shotdefend".
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
_get_fnOptional[Callable[..., dict]]NoneInjectable replacement for nba_stats_leaguedashptstats.
_defend_get_fnOptional[Callable[..., dict]]NoneInjectable 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

ParameterTypeDefaultDescription
seasonsint | str | listA single season or list of seasons.
league_idstr'00'"00" NBA (default), "10" WNBA, "20" G-League.
per_modestr'Totals'per_mode_simple passed to each fetch (default "Totals").
by_positionboolTrueCompute each measure's baseline within role buckets (default); False forces one league-wide bucket.
positionsOptional[DataFrame]NoneOptional pre-fetched positions frame.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
_get_fnOptional[Callable[..., dict]]NoneInjectable 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

ParameterTypeDefaultDescription
seasonsint | str | listA single season or list of seasons.
league_idstr'00'"00" NBA (default), "10" WNBA, "20" G-League.
per_modestr'Totals'per_mode_simple passed to the fetch (default "Totals").
by_positionboolTrueCompute the baseline within role buckets (default); False forces one league-wide bucket.
positionsOptional[DataFrame]NoneOptional pre-fetched positions frame.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.
_get_fnOptional[Callable[..., dict]]NoneInjectable 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

ParameterTypeDefaultDescription
yearOptional[int]NoneDraft 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.
proxyAnyNoneProxy configuration forwarded to ~sportsdataverse.dl_utils.download (requests proxies= shape).
return_as_pandasboolFalseReturn 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_nametypedescription
roundInt64Draft round of the pick, 1 or 2 (NBADraft.net's first two pick tables).
pickInt64Pick number within the round.
teamStringTeam-side label or team identifier.
playerStringPlayer name.
heightStringPlayer height (string e.g. '6-2' or inches).
weightInt64Player weight in pounds.
positionStringListed roster position (G, F, C, etc.).
schoolStringPlayer school / pre-draft team.
classStringCollege class / draft eligibility note.

Raises

ExceptionDescription
UserWarningEmitted (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

ParameterTypeDefaultDescription
possessionsDataFrameFrame from add_play_context with lineups attached.
league_non_transition_pppOptional[float]NonePts+/Poss baseline; see team_play_context. One baseline is shared across the on and off sides so the diffs are comparable.
apply_ctg_filtersboolTrueDrop garbage-time / heave / non-counting possessions first.
return_as_pandasboolFalseReturn 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_nametypedescription
player_idInt64Unique player identifier.
offense_team_idInt64Unique identifier for offense team.
on_possInt64
off_possInt64
on_pointsInt64
off_pointsInt64
on_pts_per_100Float64
off_pts_per_100Float64
diff_pts_per_100Float64
on_transition_freqFloat64
off_transition_freqFloat64
diff_transition_freqFloat64
on_transition_pts_per_100Float64
off_transition_pts_per_100Float64
diff_transition_pts_per_100Float64
on_halfcourt_pts_per_100Float64
off_halfcourt_pts_per_100Float64
diff_halfcourt_pts_per_100Float64
on_transition_pts_added_per_100Float64
off_transition_pts_added_per_100Float64

Raises

ExceptionDescription
ValueErrorWhen 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

ParameterTypeDefaultDescription
box_logsDataFramePer-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_logsDataFrame | NoneNoneEarlier games (same columns), pooled into the tier rates only; they never enter a player's own totals.
league_idstr | NoneNoneNone (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_gamesint | NoneNoneWhen 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_nametypedescription
player_idStringUnique player identifier.
team_idStringUnique team identifier.
gamesInt64Games played.
minutes_pgFloat64
pts_per_minFloat64
reb_per_minFloat64
ast_per_minFloat64
fg3m_per_minFloat64
stl_per_minFloat64
blk_per_minFloat64
tov_per_minFloat64
fgm_per_minFloat64
ftm_per_minFloat64

Raises

ExceptionDescription
ValueErrorShrinkage 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

ParameterTypeDefaultDescription
enhanced_pbpDataFrameOutput of enhanced_pbp_from_payload. Must carry game_id, action_number, order_index, period, team_id, person_id, description, is_substitution.
raw_boxdictRaw boxscoretraditionalv3 dict (starters + name map).
home_team_idintHome team id (from boxscore_home_away).
away_team_idintAway team id (from boxscore_home_away).

Returns

polars.DataFrame conforming to LINEUPS_SCHEMA. Empty input returns a zero-row frame (never raises).

col_nametypedescription
game_idStringUnique game identifier.
action_numberInt64Sequential action number within a game (V3 PBP).
periodInt64Period of the game (1-4 quarters; 5+ for OT).
home_player_1Int64
home_player_2Int64
home_player_3Int64
home_player_4Int64
home_player_5Int64
away_player_1Int64
away_player_2Int64
away_player_3Int64
away_player_4Int64
away_player_5Int64

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

ParameterTypeDefaultDescription
enhanced_pbpDataFrameOutput 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_boxscoresDict[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_boxOptional[dict]NoneOptional 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_idintHome team id (from boxscore_home_away).
away_team_idintAway team id (from boxscore_home_away).

Returns

polars.DataFrame conforming to LINEUPS_SCHEMA. Empty enhanced_pbp returns a zero-row frame (never raises).

col_nametypedescription
game_idStringUnique game identifier.
action_numberInt64Sequential action number within a game (V3 PBP).
periodInt64Period of the game (1-4 quarters; 5+ for OT).
home_player_1Int64
home_player_2Int64
home_player_3Int64
home_player_4Int64
home_player_5Int64
away_player_1Int64
away_player_2Int64
away_player_3Int64
away_player_4Int64
away_player_5Int64

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

ParameterTypeDefaultDescription
enhanced_pbpDataFrameOutput of ~sportsdataverse.nba.nba_enhanced_pbp.enhanced_pbp_from_payload. Must contain game_id, action_number, period, seconds_remaining, is_substitution, and team_id.
rotationdict[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_idintInteger team ID of the home team.
away_team_idintInteger team ID of the away team.
league_idOptional[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_nametypedescription
game_idStringUnique game identifier.
action_numberInt64Sequential action number within a game (V3 PBP).
periodInt64Period of the game (1-4 quarters; 5+ for OT).
home_player_1Int64
home_player_2Int64
home_player_3Int64
home_player_4Int64
home_player_5Int64
away_player_1Int64
away_player_2Int64
away_player_3Int64
away_player_4Int64
away_player_5Int64

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

ParameterTypeDefaultDescription
exp_valuefloatProjected mean of the stat.
linefloatThe prop line.
statstrA prop_distribution stat ("pts" ... "ftm").
league_idstr'00'"00" NBA / "10" WNBA / "20" G-League (passed to prop_distribution).
recent_valuefloat | NoneNoneThe recent-window mean, for the mixture (see prop_distribution).
recent_weightfloat | NoneNoneThe 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

ParameterTypeDefaultDescription
rate_rowdict[str, Any]One row of player_rates (as a dict).
exp_minutesfloatProjected minutes for the game.
pace_factorfloat1.0Pace 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

ParameterTypeDefaultDescription
exp_valuefloatProjected mean of the stat (stat_<stat>_exp).
statstrOne of "pts", "reb", "ast", "fg3m", "stl", "blk", "tov", "fgm", "ftm".
league_idstr'00'"00" NBA / "10" WNBA / "20" G-League; selects that league's fitted SD law and dispersion.
recent_valuefloat | NoneNoneThe recent-window mean (stat_<stat>_recent_exp).
recent_weightfloat | NoneNoneThe 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

ExceptionDescription
ValueErrorstat 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

ParameterTypeDefaultDescription
modelAnyModelA harness model conforming to nba_model_validation.AnyModel (a RapmModel, RatingsModel, or PriorModel).
possessionsDataFrameA possession+lineup frame that MUST carry a game_date (pl.Date) column (as emitted by compile_nba_season).
asofdateThe 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

ExceptionDescription
ValueErrorIf 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

ParameterTypeDefaultDescription
proxyAnyNoneProxy configuration forwarded to ~sportsdataverse.dl_utils.download (requests proxies= shape).
return_as_pandasboolFalseReturn 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_nametypedescription
player_idStringUnique player identifier.
playerStringPlayer name.
first_nameStringPlayer's first name.
last_nameStringPlayer's last name.
teamStringTeam-side label or team identifier.
positionStringListed roster position (G, F, C, etc.).
injuryStringInjury (body part / description).
statusStringStatus label.
return_dateStringProjected return date as RotoWire shows it; null for non-subscribers (the endpoint sends "Subscribers Only") and when the cell is blank.
urlStringRotoWire player page URL.

Raises

ExceptionDescription
UserWarningEmitted (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

ParameterTypeDefaultDescription
shotsDataFramePer-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_avgsDataFrameThe LeagueAverages frame (see xpoints_baseline).
league_idstr'00'"00" NBA, "10" WNBA, "20" G-League (the booster to load).
modelLiteral['zone', 'location'] | NoneNone"location", "zone" or None (location where a booster ships).
return_as_pandasboolFalseReturn 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

ExceptionDescription
ValueErrorA 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

ParameterTypeDefaultDescription
scored_shotsDataFramescore_shot_xpoints output (needs player_id, shot_made_flag, base_fg_pct, xpoints, actual_points).
league_idstr'00'"00" NBA, "10" WNBA, "20" G-League.
min_attemptsint50Drop shooters with fewer attempts (unstable estimate).
return_as_pandasboolFalseReturn 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

ParameterTypeDefaultDescription
scored_shotsDataFramescore_shot_xpoints output (needs player_id, xpoints).
min_attemptsint50Drop players with fewer attempts.
return_as_pandasboolFalseReturn 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)