Skip to main content
Version: 0.2.0

NBA — additional Python functions — Models and calculators: nba_war–validate_model

nba_war​

nba_war(ratings: 'pl.DataFrame', poss: 'pl.DataFrame', *, replacement_level: 'float', pts_per_win: 'float', rating_col: 'str' = 'rating', poss_col: 'str' = 'poss', return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'

Points-above-replacement -> wins for each player.

war_i = (rating_i - replacement_level) * poss_i / 100 / pts_per_win.

poss_i counts each possession once, as a team's net rating per 100 does: a game is about 100 possessions a side, not 200. A net rating per 100 (rapm = o_rapm + d_rapm) spends o_rapm over the offensive possessions and d_rapm over the defensive ones, so its points are about rapm * (off_poss + def_poss) / 2 / 100: pass (off_poss + def_poss) / 2, never the sum. The sum doubles every WAR. The 2025-26 NBA player_impact release was built with the sum: its league WAR totals 1,582 against the 791 the halved possessions give, and a team's summed WAR rose 1.55 per win (0.78 halved, under 1 as a shrunken rating's should).

Parameters

ParameterTypeDefaultDescription
ratingsDataFramePer-player rating frame with player_id and rating_col (e.g. nba_rapm's rapm column renamed, a nba_ratings_panel row filtered to one date, or nba_bpm's bpm column).
possDataFramePer-player possession-count frame with player_id and poss_col: the possessions the rating is per 100 of, each counted once ((off_poss + def_poss) / 2 from nba_rapm; see above).
replacement_levelfloatPer-100-possession rating of a replacement-level player. No built-in default — calibrate via calibrate_replacement_level.
pts_per_winfloatPoints of season point-margin per marginal win. No built-in default — calibrate via calibrate_pts_per_win.
rating_colstr'rating'Column in ratings to score.
poss_colstr'poss'Column in poss giving the possessions played, each counted once.
return_as_pandasboolFalseReturn pandas instead of polars.

Returns

Frame with WAR_SCHEMA columns (player_id, war). Empty (that schema) when either input is empty.

col_nametypedescription
player_idInt64Unique player identifier.
warFloat64

Raises

ExceptionDescription
ValueErrorIf both inputs are non-empty but share no player_id (a probable id-source or dtype mismatch, not a normal empty case).

Example

from sportsdataverse.nba.nba_war import nba_war
war = nba_war(rapm_df.rename({"rapm": "rating"}), poss_df,
replacement_level=-2.0, pts_per_win=250.0)
print(war.sort("war", descending=True).head())

# Derive both required kwargs from real data first

from sportsdataverse.nba.nba_war import (
calibrate_pts_per_win, calibrate_replacement_level, nba_war,
)
pts_per_win = calibrate_pts_per_win(team_standings)
repl = calibrate_replacement_level(
ratings, poss, pts_per_win=pts_per_win, target_total_war=300.0,
)
war = nba_war(ratings, poss, replacement_level=repl, pts_per_win=pts_per_win)

ot_adjusted_seconds​

ot_adjusted_seconds(pbp: 'pl.DataFrame', *, regulation_periods: 'int' = 4) -> 'pl.DataFrame'

Tag overtime rows and give them the overtime period clock as their seconds remaining.

The in-game models clip start_game_seconds_remaining at zero, so every overtime play (negative in the NBA frame) would score as "game over at the current margin". Each overtime is scored as its own five-minute endgame instead: on rows with period_number > regulation_periods start_game_seconds_remaining becomes the period clock, start_quarter_seconds_remaining or (men's college frames) start_period_seconds_remaining, whichever is present and not null. In a halves game (regulation_periods=2) period 3 is the first overtime.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameOne game in the basketball pbp schema.
regulation_periodsint4The game's regulation periods (4 quarters, 2 halves); see game_regulation_periods.

Returns

The frame with wp_regime ("reg" / "ot") and the adjusted seconds column.

col_nametypedescription
wp_regimeString"reg" for regulation plays; "ot" for plays after the last regulation period (period 3 on in a halves game, 5 on in a quarters game), scored on the overtime period clock as a five-minute endgame.
start_game_seconds_remainingFloat64Seconds remaining the model sees: the game clock in regulation, the overtime period clock (the quarter clock, or the period clock in men's college frames) on overtime plays.

Raises

ExceptionDescription
polars.exceptions.ColumnNotFoundErrorIf period_number or start_game_seconds_remaining is missing, or neither period clock column is present.

Example

import polars as pl
from sportsdataverse.nba.nba_game_page import ot_adjusted_seconds
from sportsdataverse.nba.nba_loaders import load_nba_pbp
pbp = load_nba_pbp([2024]).filter(pl.col("game_id") == 401585828)
tagged = ot_adjusted_seconds(pbp)
tagged.filter(pl.col("wp_regime") == "ot").select("start_game_seconds_remaining").head()

# A men's college game (two halves)

from sportsdataverse.mbb.mbb_loaders import load_mbb_pbp
one = load_mbb_pbp([2026]).filter(pl.col("game_id") == 401830342)
ot_adjusted_seconds(one, regulation_periods=2)

player_game_rates​

player_game_rates(player_box: 'pl.DataFrame', team_box: 'pl.DataFrame', *, periods: 'Optional[int]' = None, league_id: 'Optional[str]' = None, league: 'Optional[str]' = None, regulation_periods: 'Optional[int]' = None) -> 'pl.DataFrame'

True-shooting and usage for every boxed player of one game.

TS% = PTS / (2 (FGA + 0.44 FTA)) in every league; USG% = 100 ((FGA + w FTA + TOV) (team minutes / 5)) / (MIN (team FGA + w team FTA + team TOV)), with the possession weight w of team_game_rates (0.44 NBA / WNBA, 0.475 MBB / WBB) and team TOV as in team_game_rates (total_turnovers, repaired where ESPN doubled or omitted it) and team minutes = 5 x game minutes (regulation 48 NBA / 40 WNBA, MBB and WBB, 5 per overtime). For MBB and WBB team TOV follows the college rule of team_game_rates (null in WBB before 2009 and in a WBB game whose two teams together show fewer than 5, so usage is null there). A player with no shots, no minutes, or did_not_play gets null.

Parameters

ParameterTypeDefaultDescription
player_boxDataFrameOne game in the load_nba_player_boxscore schema.
team_boxDataFrameThe game's two load_nba_team_boxscore rows.
periodsOptional[int]NoneHighest period played (default: the regulation periods).
league_idOptional[str]NoneLegacy alias: "00" NBA / "10" WNBA.
leagueOptional[str]None"nba", "wnba", "mbb" or "wbb" (default NBA).
regulation_periodsOptional[int]NoneThe game's regulation periods (2 or 4); default game_regulation_periods for the league and the team box's season.

Returns

One row per (game_id, athlete_id) with team_id, ts_pct, usg_pct.

col_nametypedescription
game_idInt64ESPN game id, the join key to the play-by-play and box-score frames.
athlete_idInt64ESPN athlete id, the join key to the player box score.
team_idInt64ESPN team id, the join key to the team box score.
ts_pctFloat64True-shooting percentage, PTS / (2 x (FGA + 0.44 x FTA)); null for a player with no shots, no minutes or a DNP.
usg_pctFloat64Usage rate, 100 x (FGA + 0.44 x FTA + TOV) x (team minutes / 5) / (MIN x team (FGA + 0.44 x FTA + total turnovers)); null for no minutes, a DNP, or a team whose turnovers were not recorded (WBB before 2009, or a WBB game whose two teams together show fewer than 5 turnovers).

Raises

ExceptionDescription
ValueErrorIf team_box does not hold exactly two different teams of one game_id (a duplicated team row would double the player rows), or the league is unknown, or league contradicts league_id.
polars.exceptions.ColumnNotFoundErrorIf a required box-score column is missing.

Example

import polars as pl
from sportsdataverse.nba.nba_game_page import player_game_rates
from sportsdataverse.nba.nba_loaders import load_nba_player_boxscore, load_nba_team_boxscore
team_box = load_nba_team_boxscore([2025]).filter(pl.col("game_id") == 401766458)
player_box = load_nba_player_boxscore([2025]).filter(pl.col("game_id") == 401766458)
player_game_rates(player_box, team_box).sort("usg_pct", descending=True).head()

player_props​

player_props(props_checkpoints: 'pl.DataFrame', crosswalk: 'pl.DataFrame', player_xwalk: 'pl.DataFrame', schedule: 'pl.DataFrame', *, league: 'str | None' = None) -> 'pl.DataFrame'

Per ESPN game x athlete x stat: the closing player-prop line, its prices and the no-vig over probability.

The line is the one most books closed on (the lower line on a tie); the prices and the over probability are the medians over the books at that line. Only the five main markets are read (PROP_MARKETS), not the alternates.

Parameters

ParameterTypeDefaultDescription
props_checkpointsDataFrameThe odds store's props_checkpoints rows (event_id, sport_key, bookmaker_key, market_key, outcome_name Over / Under, outcome_description (the player), close_price, close_point, close_mins_before).
crosswalkDataFrameThe odds store's espn_crosswalk.
player_xwalkDataFrameThe league's props_player_xwalk (season, team: ESPN team id, player_name, espn_athlete_id), keyed by ESPN season.
scheduleDataFrameThe league's ESPN schedule: game_id, season, home_id, away_id.
leaguestr | NoneNone"nba", "wnba", "mbb" or "wbb" (default NBA).

Returns

PLAYER_PROPS_SCHEMA: game_id, season, athlete_id / team_id (null when the name is not in the crosswalk for either team in the game), player_name (as the books list it), stat (points, rebounds, assists, threes, pra), line, n_books (books at that line), over_price / under_price (American) and over_prob; an empty frame with those columns when nothing matches.

col_nametypedescription
game_idInt32ESPN game id, the join key to the schedule and box-score frames.
seasonInt32ESPN season of the game.
athlete_idInt32ESPN athlete id from the props player crosswalk; null when the name is not matched for either team.
team_idInt32ESPN team id of the athlete in this game.
player_nameStringPlayer name as the books list it.
statStringProp stat (points, rebounds, assists, threes, pra = points + rebounds + assists).
lineFloat64Closing line most books closed on (the lower line on a tie).
n_booksUInt32Sportsbooks with both sides quoted at that line.
over_priceFloat64Median closing over price at the line, American odds.
under_priceFloat64Median closing under price at the line, American odds.
over_probFloat64No-vig probability of the over at the line, median over books.

Raises

ExceptionDescription
ValueErrorIf the league is unknown.
polars.exceptions.ColumnNotFoundErrorIf a required column is missing.

Example

import polars as pl
from sportsdataverse.nba.nba_game_lines import player_props
from sportsdataverse.nba.nba_loaders import load_nba_schedule
odds = "odds-data/odds" # a local checkout of the odds store
props = player_props(
pl.read_parquet(f"{odds}/checkpoints/props_2025_0[1-4]_nba.parquet"),
pl.read_parquet(f"{odds}/espn_crosswalk.parquet"),
pl.read_parquet(f"{odds}/nba/props_player_xwalk_2025.parquet"),
load_nba_schedule([2025]),
league="nba",
)

# One player's points lines

props.filter(pl.col("stat") == "points", pl.col("athlete_id") == 3112335)

player_second_chance_box​

player_second_chance_box(pbp: 'pl.DataFrame', player_box: 'pl.DataFrame | None' = None, *, league: 'str | None' = None) -> 'pl.DataFrame'

Second-chance field goals, free throws and points per shooter, and assists per passer, per game.

As the module docstring defines them: the shooter (athlete_id_1) gets the field goals and free throws, the passer (athlete_id_2 on an assisted make) sc_ast; sc_pts is sc_fg_pts + sc_ft_pts. The players' counts add up to team_second_chance_box's wherever the plays name a shooter and passer of the offense. Join it to the player box on game_id, athlete_id and team_id. Rows without a game_id (in pbp or player_box) are dropped with a UserWarning.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlays in the hoopR / wehoop pbp schema plus athlete_id_1 / athlete_id_2, one or many games; see second_chance_plays.
player_boxDataFrame | NoneNoneThe games' player box (game_id, team_id, athlete_id). When given, every boxed player of a counted game gets a row (zeros without a second-chance play), as ~sportsdataverse.nba.nba_game_splits.player_game_splits does, and a play crediting a player to the other team is left out (a box with no rows gives no rows); without one, every player on a counted play gets a row.
leaguestr | NoneNone"nba", "wnba", "mbb" or "wbb" (default NBA).

Returns

One row per game, player and team (an empty frame with these columns when there is none): |col_name |type |description | |:----------|:-------|:------------------------------------------------------------------------| |game_id |Int32 |ESPN game id. | |athlete_id |Int32 |ESPN athlete id. | |team_id |Int32 |ESPN team id of the player's team. | |sc_fga |Int64 |Second-chance field-goal attempts the player took. | |sc_fgm |Int64 |Second-chance field goals the player made. | |sc_fg3a |Int64 |Second-chance three-point attempts the player took. | |sc_fg3m |Int64 |Second-chance threes the player made. | |sc_fta |Int64 |Second-chance free-throw attempts the player took. | |sc_ftm |Int64 |Second-chance free throws the player made. | |sc_fg_pts |Int64 |2 * sc_fgm + sc_fg3m. | |sc_ft_pts |Int64 |sc_ftm. | |sc_pts |Int64 |sc_fg_pts + sc_ft_pts. | |sc_ast |Int64 |Assists on second-chance field goals, credited to the passer. | |sc_fg_pct |Float64 |sc_fgm / sc_fga (null without an attempt). |

col_nametypedescription
game_idInt64ESPN game id, the join key to the play-by-play and box-score frames (Int32, as the releases carry it).
athlete_idInt64ESPN athlete id, the join key to the player box score (Int32).
team_idInt64ESPN team id, the join key to the team box score (Int32).
sc_fgaInt64Second-chance field-goal attempts: the offense's attempts after its first offensive rebound of the possession (a missed end-of-period heave left out, as the box leaves it out).
sc_fgmInt64Second-chance field goals made.
sc_fg3aInt64Second-chance three-point attempts.
sc_fg3mInt64Second-chance threes made.
sc_ftaInt64Second-chance free-throw attempts (the offense's technical free throws in the window included).
sc_ftmInt64Second-chance free throws made.
sc_fg_ptsInt64Second-chance field-goal points: 2 * sc_fgm + sc_fg3m.
sc_ft_ptsInt64Second-chance free-throw points: sc_ftm.
sc_ptsInt64The player's second-chance points: sc_fg_pts + sc_ft_pts.
sc_astInt64Assisted second-chance field goals (the make's text credits an assist and names the passer, athlete_id_2); a player's are the passes the player made.
sc_fg_pctFloat64sc_fgm / sc_fga; null without an attempt.

Raises

ExceptionDescription
ValueErrorIf the league is unknown.
polars.exceptions.ColumnNotFoundErrorIf a column the count reads is missing (athlete_id_1 and athlete_id_2 included), or a supplied player_box lacks game_id, team_id or athlete_id.

Example

import polars as pl
from sportsdataverse.nba.nba_loaders import load_nba_pbp, load_nba_player_boxscore
from sportsdataverse.nba.nba_second_chance import player_second_chance_box
pbp = load_nba_pbp([2025]).filter(pl.col("game_id") == 401705034)
box = load_nba_player_boxscore([2025]).filter(pl.col("game_id") == 401705034)
player_second_chance_box(pbp, box).sort("sc_pts", descending=True)

player_second_chance_season​

player_second_chance_season(player_box: 'pl.DataFrame') -> 'pl.DataFrame'

Second-chance totals per player, team, season and season type, summed from player_second_chance_box.

A player traded within the season gets a row per team. Rows without a game_id are dropped with a UserWarning.

Parameters

ParameterTypeDefaultDescription
player_boxDataFrameplayer_second_chance_box's rows with season and season_type joined on.

Returns

One row per (season, season_type, athlete_id, team_id) (an empty frame with these columns when there is none): |col_name |type |description | |:---------------|:-------|:------------------------------------------------------------------------| |season |Int64 |Season. | |season_type |Int64 |ESPN season type (2 regular season, 3 postseason). | |athlete_id |Int32 |ESPN athlete id. | |team_id |Int32 |ESPN team id. | |games |Int64 |Games with a box row. | |sc_fga |Int64 |The season's sum of player_second_chance_box's sc_fga (every count likewise, through sc_ast). | |sc_fg_pct |Float64 |sc_fgm / sc_fga over the season. | |sc_pts_per_game |Float64 |sc_pts / games. |

col_nametypedescription
seasonInt64Season, named by the year it ends (2025 is 2024-25; the WNBA season is its calendar year).
season_typeInt64ESPN season type: 2 regular season, 3 postseason (any other kept as its own rows).
athlete_idInt64ESPN athlete id, the join key to the player box score (Int32).
team_idInt64ESPN team id, the join key to the team box score (Int32).
gamesInt64Games counted (team: game rows; player: games with a box row).
sc_fgaInt64Second-chance field-goal attempts: the offense's attempts after its first offensive rebound of the possession (a missed end-of-period heave left out, as the box leaves it out), summed over the season.
sc_fgmInt64Second-chance field goals made, summed over the season.
sc_fg3aInt64Second-chance three-point attempts, summed over the season.
sc_fg3mInt64Second-chance threes made, summed over the season.
sc_ftaInt64Second-chance free-throw attempts (the offense's technical free throws in the window included), summed over the season.
sc_ftmInt64Second-chance free throws made, summed over the season.
sc_fg_ptsInt64Second-chance field-goal points: 2 * sc_fgm + sc_fg3m, summed over the season.
sc_ft_ptsInt64Second-chance free-throw points: sc_ftm, summed over the season.
sc_ptsInt64The player's second-chance points: sc_fg_pts + sc_ft_pts.
sc_astInt64Assisted second-chance field goals (the make's text credits an assist and names the passer, athlete_id_2); a player's are the passes the player made, summed over the season.
sc_fg_pctFloat64sc_fgm / sc_fga; null without an attempt, from the season's sums.
sc_pts_per_gameFloat64sc_pts / games.

Raises

ExceptionDescription
polars.exceptions.ColumnNotFoundErrorIf game_id, athlete_id, team_id, season, season_type or a count is missing.
ValueErrorIf season or season_type is not a whole number (2.5 or "2.5", NaN, infinity or a string that is no number).

Example

from sportsdataverse.nba.nba_loaders import load_nba_pbp, load_nba_player_boxscore
from sportsdataverse.nba.nba_second_chance import player_second_chance_box, player_second_chance_season
box = load_nba_player_boxscore([2025])
games = player_second_chance_box(load_nba_pbp([2025]), box).join(
box.select("game_id", "athlete_id", "team_id", "season", "season_type").unique(),
on=["game_id", "athlete_id", "team_id"],
)
player_second_chance_season(games).sort("sc_pts", descending=True)

predict_margin​

predict_margin(home_net: 'float', away_net: 'float', *, home_pace: 'float', away_pace: 'float', neutral: 'bool' = False, league_id: 'str' = '00') -> 'float'

Expected home-minus-away margin from two adjusted net ratings.

The AdjNet difference (points/100 possessions) is scaled by the matchup's expected_possessions before the home-court advantage is added.

Parameters

ParameterTypeDefaultDescription
home_netfloatHome team's adjusted net rating (adj_net_rtg).
away_netfloatAway team's adjusted net rating.
home_pacefloatHome team's adjusted pace.
away_pacefloatAway team's adjusted pace.
neutralboolFalseTrue for a neutral-site game (no home-court advantage).
league_idstr'00'"00"/"10"/"20" -- selects the fitted HFA.

Returns

Expected margin in points (positive favors the home team).

Example

from sportsdataverse.nba.nba_game_predict import predict_margin
predict_margin(10.0, -2.0, home_pace=100.0, away_pace=98.0, neutral=False)

predict_total​

predict_total(home_off: 'float', home_def: 'float', away_off: 'float', away_def: 'float', home_pace: 'float', away_pace: 'float', *, league_id: 'str' = '00') -> 'float'

Expected total points from adjusted ratings and paces.

Expected possessions come from expected_possessions; each side's expected points per 100 possessions blend its offense with the opponent's defense (0.5 * (off + opp_def)).

Parameters

ParameterTypeDefaultDescription
home_offfloatHome adjusted offensive rating (points/100 poss).
home_deffloatHome adjusted defensive rating.
away_offfloatAway adjusted offensive rating.
away_deffloatAway adjusted defensive rating.
home_pacefloatHome team's adjusted pace.
away_pacefloatAway team's adjusted pace.
league_idstr'00'"00"/"10"/"20" -- selects the pace anchor.

Returns

Expected combined points scored by both teams.

Example

from sportsdataverse.nba.nba_game_predict import predict_total
predict_total(118.0, 108.0, 110.0, 112.0, 100.0, 98.0)

raw_game_efficiency​

raw_game_efficiency(schedule: 'pl.DataFrame', team_box: 'pl.DataFrame') -> 'pl.DataFrame'

Per-team, per-game possessions + raw offensive/defensive rating.

Parameters

ParameterTypeDefaultDescription
scheduleDataFrameFrame with game_id, season, date, home_team_id, away_team_id, neutral_site (ids cast to Utf8 here).
team_boxDataFramePer-team box score with game_id, team_id, field_goals_attempted, offensive_rebounds, turnovers, free_throws_attempted, team_score.

Returns

One row per (game_id, team_id): game_id, season, date, team_id, opp_team_id, is_home, neutral_site, poss, off_rtg, def_rtg. Empty input returns that schema with zero rows.

col_nametypedescription
game_idStringUnique game identifier.
seasonInt64Season year.
dateDateDate in YYYY-MM-DD format.
team_idStringUnique team identifier.
opp_team_idString
is_homeBooleanWhether the team was home.
neutral_siteBooleanNeutral site.
possFloat64Poss.
off_rtgFloat64
def_rtgFloat64

Example

from sportsdataverse.nba.nba_loaders import load_nba_schedule, load_nba_team_boxscore
from sportsdataverse.nba.nba_team_ratings import raw_game_efficiency
eff = raw_game_efficiency(load_nba_schedule([2024]), load_nba_team_boxscore([2024]))

render_report​

render_report(report: 'ValidationReport') -> 'str'

Render a ValidationReport as a human-readable markdown validation card.

Parameters

ParameterTypeDefaultDescription
reportValidationReportA populated ValidationReport from validate_model.

Returns

A multi-section markdown string with one ## heading per oracle. Sections whose oracle result is None (either skipped or not applicable for a point-estimate model) are rendered as - n/a.

Example

from sportsdataverse.nba.nba_model_validation import (
RidgeRapmModel, validate_model, render_report,
)

rep = validate_model(RidgeRapmModel(), season_frames, model_name="plain_rapm")
md = render_report(rep)
print(md)

# Capture the markdown string for downstream use

with open("validation_card.md", "w") as f:
f.write(render_report(rep))

run_current_impact​

run_current_impact(possessions: 'pl.DataFrame', priors: 'pl.DataFrame', as_of: 'Sequence[dt.date]', *, params: 'CurrentImpactParams | None' = None) -> 'dict[dt.date, tuple[int, dict[int, Rating]]]'

One pass of the filter over possessions, snapshotting before each as_of date.

Parameters

ParameterTypeDefaultDescription
possessionsDataFramePossessions with game_id, game_date, season, points, offense_team_id, defense_team_id and the lineups, any number of seasons.
priorsDataFrameCURRENT_IMPACT_PRIOR_SCHEMA rows; a game uses the latest prior_date on or before its date (the caller builds each from games before that date: current_impact_prior).
as_ofSequence[date]Snapshot dates; a snapshot holds every game dated strictly before it.
paramsCurrentImpactParams | NoneNoneThe shock and decay SDs.

Returns

{as_of: (season, ratings)}: ratings as CurrentImpactFilter.ratings, season of the last game before the date (0 when none).

score_win_prob​

score_win_prob(pbp: 'pl.DataFrame', *, league_id: 'Optional[str]' = None, league: 'Optional[str]' = None, regulation_periods: 'Optional[int]' = None, neutral_site: 'Optional[bool]' = False, rated_home_prob: 'Optional[float]' = None) -> 'pl.DataFrame'

Per-play home win probability, its play-to-play delta, and the prior, for one game.

NBA and WNBA games score with the NBA / WNBA in-game booster (~sportsdataverse.nba.nba_game_predict.nba_in_game_win_prob), men's and women's college games with the men's / women's college booster (~sportsdataverse.mbb.mbb_game_predict.mbb_in_game_win_prob).

Parameters

ParameterTypeDefaultDescription
pbpDataFrameOne game in the basketball pbp schema (needs home_team_spread, game_spread_available, period_number, start_game_seconds_remaining, the period clock (start_quarter_seconds_remaining or start_period_seconds_remaining), home_score, away_score, team_id, home_team_id), in play order.
league_idOptional[str]NoneLegacy alias: "00" NBA / "10" WNBA.
leagueOptional[str]None"nba", "wnba", "mbb" or "wbb" (default NBA).
regulation_periodsOptional[int]NoneThe game's regulation periods (2 halves, 4 quarters); default from the frame's season via game_regulation_periods.
neutral_siteOptional[bool]FalseWhether the game is at a neutral site: no home-court advantage in a lineless prior; see home_prior.
rated_home_probOptional[float]NoneThe game's rated pregame home win probability (NBA / WNBA: ~sportsdataverse.nba.nba_rated_prior.nba_rated_priors), the prior when there is no line; see home_prior.

Returns

The input plus pregame_home_prob, prior_source ("spread", "rated", "neutral" or "hfa"), wp_regime, home_win_prob and wp_delta (the first play's delta is measured from the prior). home_win_prob is settled to 1.0 / 0.0 on "End Game" / "End Period" rows (type_text) from the last regulation period on (period 2 in a halves game, 4 in a quarters game) where the score is not tied, before wp_delta is taken; tied rows go to overtime and keep the model value. A frame without type_text is not settled. An empty input returns an empty frame with those columns. A null home_score / away_score means "no change" and is carried forward within the game for the model (a null before the first score is 0); the returned home_score / away_score are left as given.

col_nametypedescription
pregame_home_probFloat64Pregame home win probability fed to the in-game model: Phi(home_team_spread / margin_sd) when a line existed, else rated_home_prob when the caller passed one (nba_rated_priors), else home-court advantage alone (0.5 at a neutral site).
prior_sourceStringWhere the prior came from: "spread" (a real line), "rated" (no line; the as-of team-ratings prior passed as rated_home_prob), "hfa" (no line and no rating; home-court advantage only, so the default +2.5 never reaches the model) or "neutral" (no line or rating at a neutral site; prior 0.5).
wp_regimeString"reg" for regulation plays; "ot" for plays after the last regulation period (period 3 on in a halves game, 5 on in a quarters game), scored on the overtime period clock as a five-minute endgame.
home_win_probFloat64Home win probability before the play from the bundled in-game model (score margin, time left, the prior, possession).
wp_deltaFloat64Change in home win probability from the previous play; the first play's delta is measured from the pregame prior.

Raises

ExceptionDescription
polars.exceptions.ColumnNotFoundErrorIf a required column is missing (home_team_spread, game_spread_available, period_number, start_game_seconds_remaining, home_score, away_score, team_id, home_team_id, or neither period clock column).
ValueErrorIf the league is unknown, league contradicts league_id, or pbp holds more than one game_id.

Example

import polars as pl
from sportsdataverse.nba.nba_game_page import score_win_prob
from sportsdataverse.nba.nba_loaders import load_nba_pbp
one = load_nba_pbp([2024]).filter(pl.col("game_id") == 401585828)
wp = score_win_prob(one)

# Biggest swings

wp.sort(pl.col("wp_delta").abs(), descending=True).select("text", "wp_delta").head(10)

# A men's college tournament game

from sportsdataverse.mbb.mbb_loaders import load_mbb_pbp
one = load_mbb_pbp([2026]).filter(pl.col("game_id") == 401830342)
score_win_prob(one, league="mbb", neutral_site=True)

season_game_excitement​

season_game_excitement(pbp: 'pl.DataFrame', *, league_id: 'str | None' = None, league: 'str | None' = None, schedule: 'pl.DataFrame | None' = None) -> 'pl.DataFrame'

Every game's excitement index, lead changes and biggest swing, ranked within its season.

Scores each game with score_win_prob and game_excitement, then ranks the completed games of each season by GEI. A game whose pbp stops before the end (a truncated release) keeps its GEI so far but is not ranked. For NBA and WNBA, the exhibitions the schedule marks (All-Star games and Rising Stars: type_abbreviation ALLSTAR or a notes_headline naming one) are left out, so they neither appear nor take a rank; college schedules carry no such games.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlays of one league in the basketball pbp schema (a season's load_<league>_pbp release, or any set of games), the columns score_win_prob needs plus game_id and season.
league_idstr | NoneNoneLegacy alias: "00" NBA / "10" WNBA.
leaguestr | NoneNone"nba", "wnba", "mbb" or "wbb" (default NBA).
scheduleDataFrame | NoneNoneOptional load_<league>_schedule frame; its game_id / neutral_site give each game's neutral site for the prior (games it lacks are not neutral), and its type_abbreviation / notes_headline (when present) the NBA / WNBA exhibitions to drop. Without a schedule nothing is dropped.

Returns

One row per game, sorted by season then game_id: game_id, season, gei, lead_changes, max_swing_pts, completed, gei_rank (1 = the season's most exciting completed game, ties share the best rank), gei_pct (the share of the season's completed games with a GEI at or below this one, so the top game is 1.0), gei_n (the season's completed games), then game_excitement's comeback low: winner_team_id, winner_low_wp (0-1), winner_low_period and winner_low_clock. The three rank columns are null for a game that is not completed, the four winner columns for one that is not completed or ends tied. An empty input returns an empty frame with these columns.

col_nametypedescription
game_idInt64ESPN game id, the join key to the play-by-play and box-score frames.
seasonInt64Season year as the pbp release labels it (the year the season ends).
geiFloat64Game excitement index: the league's mean plays per game (GEI_SCALE) / the game's plays x the sum of the absolute play-to-play home win-probability changes, the first from the pregame prior and, in a completed game, the last play to the result; football's Game on Paper formula with a per-league scale.
lead_changesInt64How often the scoring leader flipped; a tie is not a lead, so one side ahead, tied, then the other ahead counts once.
max_swing_ptsFloat64Largest single-play home win-probability change, in percentage points, with no team named.
completedBooleanWhether the pbp reaches the end of the game (an End Game / End Period row from the last regulation period on with the score not tied), so the last play was taken to the result.
gei_rankInt64Rank of gei among the season's completed games, 1 = most exciting, ties share the best rank; null for a game that is not completed.
gei_pctFloat64Share of the season's completed games with a gei at or below this one (the top game is 1.0); null for a game that is not completed.
gei_nInt64Number of completed games in the season the rank and percentile are taken over; null for a game that is not completed.
winner_team_idInt64ESPN team id of the eventual winner; null for a game that is not completed or ends tied.
winner_low_wpFloat64The comeback low: the lowest win probability (0-1) the eventual winner had after any play, from the same WP series gei sums (the pregame prior is not a play); null for a game that is not completed or ends tied.
winner_low_periodInt64Period of the play at the winner's low (the earliest, on a tie); null with no winner.
winner_low_clockStringGame clock (ESPN clock_display_value) of the play at the winner's low; null with no winner.

Raises

ExceptionDescription
polars.exceptions.ColumnNotFoundErrorIf a required column is missing.
ValueErrorIf the league is unknown or league contradicts league_id.

Example

from sportsdataverse.nba.nba_game_page import season_game_excitement
from sportsdataverse.wnba.wnba_loaders import load_wnba_pbp, load_wnba_schedule
gei = season_game_excitement(load_wnba_pbp([2025]), league="wnba", schedule=load_wnba_schedule([2025]))

# The season's best games

gei.sort("gei_rank", nulls_last=True).head(10)

season_gram​

season_gram(possessions: 'pl.DataFrame') -> 'SeasonGram'

The SeasonGram of a possession frame (rows with a full lineup).

Parameters

ParameterTypeDefaultDescription
possessionsDataFramePossession+lineup rows (points, off_player_1..5, def_player_1..5).

Returns

The season's SeasonGram.

second_chance_plays​

second_chance_plays(pbp: 'pl.DataFrame', *, league: 'str | None' = None) -> 'pl.DataFrame'

The plays with their possession, chance number and second-chance flags (works mid-game).

As the module docstring defines them. One or many games; each game's plays are read in game_play_number order, and the rows come back in their input order. Rows without a game_id are dropped with a UserWarning.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlays in the hoopR / wehoop pbp schema (load_<league>_pbp or game_page_frames(...)["pbp"]): game_id, game_play_number, period_number, a period clock (start_quarter_seconds_remaining or start_period_seconds_remaining), team_id, type_text, text, shooting_play, scoring_play, home_score, away_score, home_team_id, away_team_id; points_attempted if present (else the text marks a three).
leaguestr | NoneNone"nba", "wnba", "mbb" or "wbb" (default NBA); every league counts alike.

Returns

pbp (less its rows without a game_id) plus these columns (null on a play before its period's first play that names an offense, as a possession ends with its period; sc_play_pts is 0 there): |col_name |type |description | |:---------------------------|:-------|:------------------------------------------------------------| |possession_number |Int64 |The play's possession, 1-based within the game. | |offense_team_id |Int32 |The possession's offense (ESPN team id). | |chance_number |Int64 |1 + the possession's offensive rebounds before this play. | |is_second_chance_possession |Boolean |The possession has an offensive rebound. | |is_second_chance_play |Boolean |The play is after the possession's first offensive rebound (chance_number >= 2). | |sc_play_pts |Int64 |The offense's points on a counted second-chance make (2, 3 or 1), else 0. |

col_nametypedescription
possession_numberInt64The play's possession, 1-based within the game (a field-goal attempt, a non-technical free throw, a turnover or a rebound names the offense; the possession runs until such a play is the other team's or the period ends). Null before the game's first play that names an offense.
offense_team_idInt64ESPN team id of the possession's offense. Null where possession_number is null.
chance_numberInt641 + the possession's offensive rebounds before this play (team rebounds included; not the dead-ball one between two free throws, one after a technical free throw or one with no time left). Null where possession_number is null.
is_second_chance_possessionBooleanThe play's possession has an offensive rebound (true on every play of it, before the rebound too). Null where possession_number is null.
is_second_chance_playBooleanThe play is after the possession's first offensive rebound, to the end of the possession (chance_number >= 2); the rebound itself is not. Defensive plays in the window are flagged but count nothing. Null where possession_number is null.
sc_play_ptsInt64Points the offense scored on this play as a counted second-chance make: 2, 3 or 1 (a free throw), else 0.

Raises

ExceptionDescription
ValueErrorIf the league is unknown.
polars.exceptions.ColumnNotFoundErrorIf a column the count reads is missing.

Example

import polars as pl
from sportsdataverse.nba.nba_loaders import load_nba_pbp
from sportsdataverse.nba.nba_second_chance import second_chance_plays
pbp = load_nba_pbp([2025]).filter(pl.col("game_id") == 401705034)
second_chance_plays(pbp).filter(pl.col("is_second_chance_play") == True).select("text")

# A live game

from sportsdataverse.nba.nba_game_page import game_page_frames
from sportsdataverse.wnba.wnba_pbp import espn_wnba_pbp
fr = game_page_frames(espn_wnba_pbp(401726992, return_parsed=False), league="wnba")
second_chance_plays(fr["pbp"], league="wnba")

shot_coordinates​

shot_coordinates(pbp: 'pl.DataFrame') -> 'pl.DataFrame'

Shot locations in the court frame the Game on Paper hex chart uses.

ESPN's play coordinates are feet across the court with the hoop at (25, 0) and y growing toward half court (measured on 401766458: dunks at y about 2, a 22-foot corner three at (3, 0)). The chart wants tenths of a foot with the hoop at the origin, so x_legacy = (x - 25) * 10 and y_legacy = y * 10. Free throws carry no real location (the NBA frame pins them to (25, 13.75), the college frames to the rim, (25, 0); (?i)free ?throw matches Free Throw - 1 of 2 and college MadeFreeThrow) and ESPN's missing-coordinate sentinel is a large negative number; both become null, as does every non-shooting play.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlays in the load_nba_pbp schema (shooting_play, type_text, coordinate_x_raw, coordinate_y_raw).

Returns

The input plus x_legacy and y_legacy (Float64).

col_nametypedescription
x_legacyFloat64Shot location in tenths of a foot with the hoop at the origin, x across the court; null for free throws, unlocated shots and non-shooting plays.
y_legacyFloat64Shot location in tenths of a foot with the hoop at the origin, y toward half court; null for free throws, unlocated shots and non-shooting plays.

Raises

ExceptionDescription
polars.exceptions.ColumnNotFoundErrorIf a required column is missing (shooting_play, type_text, coordinate_x_raw, coordinate_y_raw).

Example

import polars as pl
from sportsdataverse.nba.nba_game_page import shot_coordinates
from sportsdataverse.nba.nba_loaders import load_nba_pbp
pbp = load_nba_pbp([2025]).filter(pl.col("game_id") == 401766458)
shots = shot_coordinates(pbp).filter(pl.col("x_legacy").is_not_null())
shots.select("text", "x_legacy", "y_legacy").head()

team_game_rates​

team_game_rates(team_box: 'pl.DataFrame', *, periods: 'Optional[int]' = None, league_id: 'Optional[str]' = None, league: 'Optional[str]' = None, regulation_periods: 'Optional[int]' = None) -> 'pl.DataFrame'

Four factors, possessions, ratings and pace for both teams of one game.

Dean Oliver's estimates on the load_nba_team_boxscore columns: possessions = FGA - ORB + TOV + w FTA, averaged over the two teams, with w = 0.44 for NBA and WNBA and 0.475 for MBB and WBB (sportsdataverse._common.possessions.ft_possession_weight); eFG% = (FGM + 0.5 3PM) / FGA; TOV% = TOV / (FGA + w FTA + TOV); ORB% = ORB / (ORB + opponent DRB); FT rate = FTA / FGA; ORtg / DRtg per 100 possessions; pace per regulation length (48 minutes NBA; 40 WNBA, MBB and WBB). TOV is the team's player plus team turnovers: total_turnovers, except that when it is null it is turnovers + team_turnovers, and when ESPN has duplicated the team turnover (team_turnovers == turnovers and total_turnovers == 2 * turnovers, measured on every 2002-2012 game, e.g. 17/17/34) it is turnovers. Without the turnovers / team_turnovers columns it is total_turnovers as given. For MBB and WBB TOV is turnovers (team_turnovers in WBB 2009-2012, where the other two are 0), and a 0 is a real 0, except where the WBB box recorded none: in WBB before 2009 (and for a WBB box with no season) and in a WBB game of any season whose two teams together show fewer than 5, TOV%, possessions, ratings and pace are null, never computed from unrecorded turnovers. A team's 0 in a game whose total is 5 or more stays 0. A zero denominator gives null. For the NBA, orb_pct is null when either team's offensive_rebounds + defensive_rebounds differs from its total_rebounds (ESPN's 2002-2012 boxes); a box without total_rebounds and the other leagues are not checked.

Parameters

ParameterTypeDefaultDescription
team_boxDataFrameExactly two rows (one per team) of one game in the load_nba_team_boxscore schema.
periodsOptional[int]NoneHighest period played (default: the regulation periods), for the pace denominator.
league_idOptional[str]NoneLegacy alias: "00" NBA (48-minute regulation) / "10" WNBA (40).
leagueOptional[str]None"nba", "wnba", "mbb" or "wbb" (default NBA); overtime is 5 minutes in all four.
regulation_periodsOptional[int]NoneThe game's regulation periods (2 or 4); default game_regulation_periods for the league and the box's season.

Returns

One row per (game_id, team_id) with efg_pct, tov_pct, orb_pct, ft_rate, possessions, off_rtg, def_rtg, pace, total_turnovers, game_minutes.

col_nametypedescription
game_idInt64ESPN game id, the join key to the play-by-play and box-score frames.
team_idInt64ESPN team id, the join key to the team box score.
efg_pctFloat64Effective field-goal percentage, (FGM + 0.5 x 3PM) / FGA; null with no attempts.
tov_pctFloat64Turnover rate, total turnovers / (FGA + 0.44 x FTA + total turnovers); null when the denominator is not positive or the box records no turnovers (WBB before 2009, or a WBB game whose two teams together show fewer than 5 turnovers).
orb_pctFloat64Offensive rebound rate, own ORB / (own ORB + opponent DRB); null when the denominator is not positive.
ft_rateFloat64Free-throw rate, FTA / FGA; null with no attempts.
possessionsFloat64Oliver's possession estimate (FGA - ORB + total turnovers + 0.44 x FTA) averaged over the two teams; null when the box records no turnovers (WBB before 2009, or a WBB game whose two teams together show fewer than 5 turnovers).
off_rtgFloat64Points scored per 100 possessions; null when possessions are not positive.
def_rtgFloat64Points allowed per 100 possessions; null when possessions are not positive.
paceFloat64Possessions per regulation length (48 minutes NBA; 40 WNBA, MBB and WBB), overtime minutes included in the denominator; null when the box records no turnovers.
total_turnoversInt64The team turnover count every rate above uses, player plus team turnovers; ESPN's doubled pre-2013 NBA total is repaired to the player count; college: the box turnovers (team_turnovers in WBB 2009-2012), null when not recorded (WBB before 2009, or a WBB game whose two teams together show fewer than 5 turnovers).
game_minutesInt64Minutes played in the game: regulation (48 NBA, 40 WNBA and college) plus five per overtime.

Raises

ExceptionDescription
ValueErrorIf team_box does not hold exactly two rows, or the rows are not two different team_id values of one game_id, or the league is unknown, or league contradicts league_id.
polars.exceptions.ColumnNotFoundErrorIf a required box-score column is missing.

Example

import polars as pl
from sportsdataverse.nba.nba_game_page import team_game_rates
from sportsdataverse.nba.nba_loaders import load_nba_team_boxscore
box = load_nba_team_boxscore([2025]).filter(pl.col("game_id") == 401766458)
team_game_rates(box).select("team_id", "efg_pct", "off_rtg", "pace")

# WNBA box (40-minute regulation)

team_game_rates(box, league_id="10")

# A women's college game from the halves era

from sportsdataverse.wbb.wbb_loaders import load_wbb_team_boxscore
box = load_wbb_team_boxscore([2010]).filter(pl.col("game_id") == 293170052)
team_game_rates(box, league="wbb", regulation_periods=2)

team_second_chance_box​

team_second_chance_box(pbp: 'pl.DataFrame', *, league: 'str | None' = None) -> 'pl.DataFrame'

Second-chance possessions, field goals, free throws, points and assists per team and game (works mid-game).

As the module docstring defines them; sc_pts is the basketball game story's second_chance_points. Join it to the team box on game_id and team_id (both Int32, as the releases carry them). Rows without a game_id are dropped with a UserWarning.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlays in the hoopR / wehoop pbp schema, one or many games; see second_chance_plays (plus athlete_id_2 for sc_ast's passer test, read when present).
leaguestr | NoneNone"nba", "wnba", "mbb" or "wbb" (default NBA).

Returns

Two rows per game with a play that names an offense (an empty frame with these columns otherwise): |col_name |type |description | |:-------------------|:-------|:-----------------------------------------------------------------| |game_id |Int32 |ESPN game id. | |team_id |Int32 |ESPN team id. | |opp_team_id |Int32 |The opponent's ESPN team id. | |sc_poss |Int64 |Possessions with an offensive rebound (team_game_splits' second_chance_poss). | |sc_fga |Int64 |Second-chance field-goal attempts (a missed end-of-period heave left out). | |sc_fgm |Int64 |Second-chance field goals made. | |sc_fg3a |Int64 |Second-chance three-point attempts. | |sc_fg3m |Int64 |Second-chance threes made. | |sc_fta |Int64 |Second-chance free-throw attempts (technical free throws included). | |sc_ftm |Int64 |Second-chance free throws made. | |sc_fg_pts |Int64 |2 * sc_fgm + sc_fg3m. | |sc_ft_pts |Int64 |sc_ftm. | |sc_pts |Int64 |Second-chance points from the running score (the game story's second_chance_points). | |sc_ast |Int64 |Assisted second-chance field goals. | |sc_pts_unattributed |Int64 |sc_pts - sc_fg_pts - sc_ft_pts: 0 unless the feed's score and its plays disagree. | |sc_fg_pct |Float64 |sc_fgm / sc_fga (null without an attempt). | |sc_fg3_pct |Float64 |sc_fg3m / sc_fg3a. | |sc_ft_pct |Float64 |sc_ftm / sc_fta. | |sc_ppp |Float64 |sc_pts / sc_poss. | |opp_sc_poss |Int64 |The opponent's sc_poss (and opp_sc_fga ... opp_sc_ast likewise for every count above but sc_pts_unattributed). | |opp_sc_fg_pct |Float64 |The opponent's sc_fg_pct. | |opp_sc_ppp |Float64 |The opponent's sc_ppp. |

col_nametypedescription
game_idInt64ESPN game id, the join key to the play-by-play and box-score frames (Int32, as the releases carry it).
team_idInt64ESPN team id, the join key to the team box score (Int32).
opp_team_idInt64The opponent's team_id.
sc_possInt64Possessions with an offensive rebound (equals team_game_splits' second_chance_poss).
sc_fgaInt64Second-chance field-goal attempts: the offense's attempts after its first offensive rebound of the possession (a missed end-of-period heave left out, as the box leaves it out).
sc_fgmInt64Second-chance field goals made.
sc_fg3aInt64Second-chance three-point attempts.
sc_fg3mInt64Second-chance threes made.
sc_ftaInt64Second-chance free-throw attempts (the offense's technical free throws in the window included).
sc_ftmInt64Second-chance free throws made.
sc_fg_ptsInt64Second-chance field-goal points: 2 * sc_fgm + sc_fg3m.
sc_ft_ptsInt64Second-chance free-throw points: sc_ftm.
sc_ptsInt64Second-chance points from the running score: the rise of the offense's highest score so far on each play after its first offensive rebound, to the end of the possession. The basketball game story's second_chance_points.
sc_astInt64Assisted second-chance field goals (the make's text credits an assist and names the passer, athlete_id_2); a player's are the passes the player made.
sc_pts_unattributedInt64sc_pts - sc_fg_pts - sc_ft_pts: 0 unless the feed's running score and its plays disagree (a stale or corrected score row).
sc_fg_pctFloat64sc_fgm / sc_fga; null without an attempt.
sc_fg3_pctFloat64sc_fg3m / sc_fg3a; null without an attempt.
sc_ft_pctFloat64sc_ftm / sc_fta; null without an attempt.
sc_pppFloat64Second-chance points per second-chance possession, sc_pts / sc_poss; null without one.
opp_sc_possInt64The opponent's sc_poss.
opp_sc_fgaInt64The opponent's sc_fga.
opp_sc_fgmInt64The opponent's sc_fgm.
opp_sc_fg3aInt64The opponent's sc_fg3a.
opp_sc_fg3mInt64The opponent's sc_fg3m.
opp_sc_ftaInt64The opponent's sc_fta.
opp_sc_ftmInt64The opponent's sc_ftm.
opp_sc_fg_ptsInt64The opponent's sc_fg_pts.
opp_sc_ft_ptsInt64The opponent's sc_ft_pts.
opp_sc_ptsInt64The opponent's sc_pts.
opp_sc_astInt64The opponent's sc_ast.
opp_sc_fg_pctFloat64The opponent's sc_fg_pct.
opp_sc_pppFloat64The opponent's sc_ppp.

Raises

ExceptionDescription
ValueErrorIf the league is unknown.
polars.exceptions.ColumnNotFoundErrorIf a column the count reads is missing.

Example

from sportsdataverse.nba.nba_loaders import load_nba_pbp, load_nba_team_boxscore
from sportsdataverse.nba.nba_second_chance import team_second_chance_box
sc = team_second_chance_box(load_nba_pbp([2025]))
load_nba_team_boxscore([2025]).join(sc, on=["game_id", "team_id"], how="left")

# Women's college, second-chance points allowed

from sportsdataverse.wbb.wbb_loaders import load_wbb_pbp
team_second_chance_box(load_wbb_pbp([2025]), league="wbb").select("team_id", "opp_sc_pts")

team_second_chance_season​

team_second_chance_season(team_box: 'pl.DataFrame') -> 'pl.DataFrame'

Second-chance totals per team, season and season type, summed from team_second_chance_box.

The rates are recomputed from the sums, never averaged. Rows without a game_id are dropped with a UserWarning.

Parameters

ParameterTypeDefaultDescription
team_boxDataFrameteam_second_chance_box's rows with season and season_type (ESPN's: 2 regular, 3 post; any other kept as its own rows) joined on, and points (the team's points) when sc_pts_share is wanted.

Returns

One row per (season, season_type, team_id) (an empty frame with these columns when there is none): |col_name |type |description | |:---------------|:-------|:--------------------------------------------------------------------| |season |Int64 |Season. | |season_type |Int64 |ESPN season type (2 regular season, 3 postseason). | |team_id |Int32 |ESPN team id. | |games |Int64 |Games counted. | |sc_poss |Int64 |The season's sum of team_second_chance_box's sc_poss (every count likewise, sc_fga ... sc_pts_unattributed and opp_sc_poss ... opp_sc_ast). | |sc_fg_pct |Float64 |sc_fgm / sc_fga over the season (sc_fg3_pct, sc_ft_pct, sc_ppp, opp_sc_fg_pct and opp_sc_ppp likewise). | |sc_pts_per_game |Float64 |sc_pts / games. | |sc_pts_share |Float64 |sc_pts / points (null when the input carries no points or a game lacks it). |

col_nametypedescription
seasonInt64Season, named by the year it ends (2025 is 2024-25; the WNBA season is its calendar year).
season_typeInt64ESPN season type: 2 regular season, 3 postseason (any other kept as its own rows).
team_idInt64ESPN team id, the join key to the team box score (Int32).
gamesInt64Games counted (team: game rows; player: games with a box row).
sc_possInt64Possessions with an offensive rebound (equals team_game_splits' second_chance_poss), summed over the season.
sc_fgaInt64Second-chance field-goal attempts: the offense's attempts after its first offensive rebound of the possession (a missed end-of-period heave left out, as the box leaves it out), summed over the season.
sc_fgmInt64Second-chance field goals made, summed over the season.
sc_fg3aInt64Second-chance three-point attempts, summed over the season.
sc_fg3mInt64Second-chance threes made, summed over the season.
sc_ftaInt64Second-chance free-throw attempts (the offense's technical free throws in the window included), summed over the season.
sc_ftmInt64Second-chance free throws made, summed over the season.
sc_fg_ptsInt64Second-chance field-goal points: 2 * sc_fgm + sc_fg3m, summed over the season.
sc_ft_ptsInt64Second-chance free-throw points: sc_ftm, summed over the season.
sc_ptsInt64Second-chance points from the running score: the rise of the offense's highest score so far on each play after its first offensive rebound, to the end of the possession. The basketball game story's second_chance_points.
sc_astInt64Assisted second-chance field goals (the make's text credits an assist and names the passer, athlete_id_2); a player's are the passes the player made, summed over the season.
sc_pts_unattributedInt64sc_pts - sc_fg_pts - sc_ft_pts: 0 unless the feed's running score and its plays disagree (a stale or corrected score row), summed over the season.
sc_fg_pctFloat64sc_fgm / sc_fga; null without an attempt, from the season's sums.
sc_fg3_pctFloat64sc_fg3m / sc_fg3a; null without an attempt, from the season's sums.
sc_ft_pctFloat64sc_ftm / sc_fta; null without an attempt, from the season's sums.
sc_pppFloat64Second-chance points per second-chance possession, sc_pts / sc_poss; null without one, from the season's sums.
opp_sc_possInt64The opponents' sc_poss over the season.
opp_sc_fgaInt64The opponents' sc_fga over the season.
opp_sc_fgmInt64The opponents' sc_fgm over the season.
opp_sc_fg3aInt64The opponents' sc_fg3a over the season.
opp_sc_fg3mInt64The opponents' sc_fg3m over the season.
opp_sc_ftaInt64The opponents' sc_fta over the season.
opp_sc_ftmInt64The opponents' sc_ftm over the season.
opp_sc_fg_ptsInt64The opponents' sc_fg_pts over the season.
opp_sc_ft_ptsInt64The opponents' sc_ft_pts over the season.
opp_sc_ptsInt64The opponents' sc_pts over the season.
opp_sc_astInt64The opponents' sc_ast over the season.
opp_sc_fg_pctFloat64The opponents' sc_fg_pct over the season.
opp_sc_pppFloat64The opponents' sc_ppp over the season.
sc_pts_per_gameFloat64sc_pts / games.
sc_pts_shareFloat64sc_pts / points, the share of the team's points that were second-chance (null when the input carries no points column).

Raises

ExceptionDescription
polars.exceptions.ColumnNotFoundErrorIf game_id, team_id, season, season_type or a count is missing.
ValueErrorIf season or season_type is not a whole number (2.5 or "2.5", NaN, infinity or a string that is no number).

Example

import polars as pl
from sportsdataverse.nba.nba_loaders import load_nba_pbp, load_nba_team_boxscore
from sportsdataverse.nba.nba_second_chance import team_second_chance_box, team_second_chance_season
box = load_nba_team_boxscore([2025]).select("game_id", "team_id", "season", "season_type", pl.col("team_score").alias("points"))
games = team_second_chance_box(load_nba_pbp([2025])).join(box, on=["game_id", "team_id"])
team_second_chance_season(games).sort("sc_pts", descending=True)

train_box_prior​

train_box_prior(panel: 'pl.DataFrame', *, season: 'int', half_life: 'float' = 4.0, alpha: 'float' = 1.0, folds: 'int' = 5) -> 'BoxPriorModel'

Possession-weighted ridge of the career target on the box-prior features, cross-fit by player.

Fold k's rule is fit on every row whose player is NOT in fold k (player_id % folds) and is applied only to fold k's players, so no player's prior saw his own target. Each row is weighted by its possessions times the time weight of its season relative to season.

Parameters

ParameterTypeDefaultDescription
panelDataFrameTraining rows: player_id, season, poss, def_poss, o_target, d_target and BOX_PRIOR_FEATURES; seasons from box_prior_training_seasons (a row of season itself raises).
seasonintThe season the prior is for.
half_lifefloat4.0Half-life of the row time weight, in seasons.
alphafloat1.0Ridge penalty on the standardized features.
foldsint5Player folds.

Returns

A BoxPriorModel.

Raises

ExceptionDescription
ValueErrorIf panel holds a row of season or a fold has no training rows.

Example

from sportsdataverse.nba.nba_box_prior import apply_box_prior, train_box_prior
model = train_box_prior(panel, season=2015)
prior = apply_box_prior(features_2015, model)

train_spm​

train_spm(box_features: 'pl.DataFrame', rapm_target: 'pl.DataFrame', *, feature_names: 'Optional[List[str]]' = None, alpha: 'float' = 100.0, weight: 'Optional[str]' = None) -> 'SpmCoefficients'

Ridge-fit box features onto o_rapm and d_rapm (two regressions).

The two models share the same feature matrix but separate target vectors, producing independent offense and defense coefficient vectors.

The default fits every row with the same weight at SPM_ALPHA, the fit behind every published player_impact SPM. weight="min", alpha=SPM_ALPHA_WEIGHTED is the opt-in minute-weighted alternative. Low-minute players' per-100 rates and RAPM targets are both noisy, so weighting by minutes widens the SPM (its spread about doubles). It is not the default because, as the adjusted-RAPM prior, it fails the NBA producer's publish floor (see SPM_ALPHA_WEIGHTED).

Parameters

ParameterTypeDefaultDescription
box_featuresDataFramePer-player per-100 features. Must contain player_id and every column in feature_names.
rapm_targetDataFramePer-player RAPM target frame with columns player_id, o_rapm, and d_rapm. Only the rows whose player_id appears in box_features are used (inner join).
feature_namesOptional[List[str]]NoneOrdered list of feature columns to regress on. Defaults to SPM_FEATURES (= _STATS from nba_box_logs).
alphafloat100.0Ridge regularization strength (sklearn.linear_model.Ridge) on the raw per-100 features (with any weights normalized to mean 1). Defaults to SPM_ALPHA; pass SPM_ALPHA_WEIGHTED with weight="min". Lower values approach OLS; higher values shrink toward zero.
weightOptional[str]NoneNone (the default) fits every row with the same weight. Otherwise, the column (of box_features, or of rapm_target when box_features lacks it) holding each row's sample weight, e.g. "min" or "off_poss".

Returns

SpmCoefficients with offense and defense coefficient vectors, intercepts, and the ordered feature_names.

Raises

ExceptionDescription
ValueErrorIf feature_names lists a column absent from box_features, rapm_target is missing required columns, or the weight column is missing, negative, non-finite or sums to zero over the joined rows.

Example

from sportsdataverse.nba import train_spm
coef = train_spm(box_feats, rapm_ratings)

# With custom regularization, or the minute-weighted alternative

coef = train_spm(box_feats, rapm_ratings, alpha=50.0)
coef_weighted = train_spm(box_feats, rapm_ratings, weight="min", alpha=SPM_ALPHA_WEIGHTED)

validate_model​

validate_model(model: 'AnyModel', season_frames: 'List[pl.DataFrame]', *, model_name: 'str' = 'model', oracles: 'Tuple[str, ...]' = ('retrodiction', 'reliability', 'cross_season', 'calibration'), seed: 'int' = 0, external_ratings: 'Optional[pl.DataFrame]' = None, external_oracle: 'Optional[pl.DataFrame]' = None, external_rating_col: 'str' = 'rating', external_oracle_col: 'str' = 'oracle_value', external_join: 'str' = 'id', walk_forward_horizon_days: 'int' = 14, walk_forward_min_games: 'int' = 15) -> 'ValidationReport'

Run the selected oracles and assemble a ValidationReport.

retrodiction/reliability/calibration run on the pooled possessions (all seasons concatenated); cross_season runs on the ordered per-season frames. Any oracle not selected is left None.

Parameters

ParameterTypeDefaultDescription
modelAnyModelA fitted or unfitted RAPM-family estimator (fit(X, y) protocol).
season_framesList[DataFrame]Ordered list of per-season possession frames. All frames are concatenated into a single pooled frame for Oracles 1, 2, and 4.
model_namestr'model'Label written into the returned report and markdown card.
oraclesTuple[str, ...]('retrodiction', 'reliability', 'cross_season', 'calibration')Tuple of oracle names to run. Omit a name to skip that oracle and leave its result field None. Accepts "external" and "walk_forward" in addition to the four original names; the default tuple is unchanged, so existing callers are unaffected.
seedint0RNG seed forwarded to each oracle for determinism.
external_ratingsOptional[DataFrame]NoneThe model's own ratings frame -- required when "external" is in oracles.
external_oracleOptional[DataFrame]NoneA loaded oracle frame (from nba_oracle_data) -- required when "external" is in oracles.
external_rating_colstr'rating'Rating column name in external_ratings.
external_oracle_colstr'oracle_value'Value column name in external_oracle.
external_joinstr'id'"id" or "name", forwarded to external_validity.
walk_forward_horizon_daysint14Forwarded to walk_forward.
walk_forward_min_gamesint15Forwarded to walk_forward as min_games_before_first_checkpoint.

Returns

A ValidationReport whose fields are populated for every selected oracle and None for every skipped oracle.

Raises

ExceptionDescription
ValueErrorIf "external" is in oracles but external_ratings or external_oracle is None.

Example

from sportsdataverse.nba.nba_model_validation import (
RidgeRapmModel, validate_model,
)

# season_frames is a list[pl.DataFrame] of possession stints
rep = validate_model(RidgeRapmModel(), season_frames, model_name="plain_rapm")
print(rep.retrodiction.game_margin_rmse) # out-of-sample margin RMSE
print(rep.reliability.spearman_brown) # split-half Spearman-Brown
print(rep.calibration) # None — RidgeRapmModel has no posterior

# Skip slow oracles when iterating quickly

rep = validate_model(
RidgeRapmModel(), season_frames,
oracles=("retrodiction", "reliability"),
)
print(rep.cross_season) # None — not selected