Skip to main content

Women's college basketball — additional Python functions — stats.ncaa.org: enrich_shot–ncaa_wbb

enrich_shot_events_with_pbp​

enrich_shot_events_with_pbp(sorted_shot_events: 'list[ShotEvent]', sorted_pbp_events: 'list[PlayByPlayEvent]', lineup_events: 'list[LineupEvent]', bad_lineup_events: 'list[LineupEvent]', box_lineup: 'LineupEvent') -> 'list[ShotEvent]'

Enrich each shot with its play-by-play event + on-floor lineup

(PlayByPlayUtils.enrich_shot_events_with_pbp).

Folds over the (time-sorted) shots, threading two iterators (play-by-play and lineup) and a small amount of carry-over state. For each shot it:

  1. gathers the play-by-play events at the shot's time (find_pbp_clump), keeping only the ones on the shot's side (team if is_off);
  2. picks the matching shot event via a strict -> loose -> first-of-N cascade (right_kind_of_shot then matching_player);
  3. locates the on-floor lineup (find_lineup), falling back to bad_lineup_events if the good lineups yield nothing (a bad-lineup match is used for players but its id is suppressed);
  4. attributes an assist (a same-time non-self assist event) and transition flag ("fastbreak" in the event string), and fills in lineup_id / players / pts / value / ast_by / is_ast / is_trans -- exactly the fields the parser left as placeholders.

Shots with no matching play-by-play clump, no matching shot event, or no matching lineup are dropped (the Scala logs a WARN and discards; the logging is dropped per the module note, the discard preserved).

Parameters

ParameterTypeDefaultDescription
sorted_shot_eventslist[ShotEvent]Shots in ascending game-clock order.
sorted_pbp_eventslist[PlayByPlayEvent]The full play-by-play event stream, ascending.
lineup_eventslist[LineupEvent]The good (validation-passing) stint events.
bad_lineup_eventslist[LineupEvent]The validation-flagged stint events, used only as a last resort (their ids are never attributed).
box_lineupLineupEventThe roster lineup event (drives name resolution).

Returns

The enriched, still-time-sorted list of shots (a subset of the input -- unmatchable shots are dropped).

Example

from sportsdataverse.mbb.mbb_ncaa_pbp_glue import enrich_shot_events_with_pbp
enriched = enrich_shot_events_with_pbp(
shots, pbp, good_lineups, bad_lineups, box_lineup
)

enrich_stats​

enrich_stats(lineup: 'LineupEvent', event_parser: 'PossessionEvent', stats: 'LineupEventStats', player_filter_coder: 'Optional[PlayerFilterCoder]' = None, player_index: 'int' = -1) -> 'LineupEventStats'

Fold a lineup's raw events into a counting-stat tree (``protected def

enrich_stats``). Reuses the concurrent-clump batching (~sportsdataverse.mbb.mbb_ncaa_possessions .lineup_as_raw_clumps + ~sportsdataverse.mbb.mbb_ncaa_possessions .concurrent_event_handler) rather than duplicating it -- both were already public/exported.

stats is deep-copied once up front (see the module docstring's "Scala idiom decisions"), so this function never mutates the caller's stats argument -- safe to call repeatedly against the same starting literal (e.g. a shared "empty stats" fixture).

Parameters

ParameterTypeDefaultDescription
lineupLineupEventThe lineup whose raw_game_events to fold over.
event_parserPossessionEventSelects which side (team/opponent) is "attacking".
statsLineupEventStatsThe starting stat tree (not mutated -- see above).
player_filter_coderOptional[PlayerFilterCoder]NoneOptional name -> (is_this_player, code) predicate/coder, for per-player scoping.
player_indexint-1Lineup-slot index for ~sportsdataverse.mbb .mbb_ncaa_models.PlayerShotInfo tuples (-1 for team-level calls).

Returns

A new ~sportsdataverse.mbb.mbb_ncaa_models.LineupEventStats with every matching event folded in.

ensure_ev_uniqueness​

ensure_ev_uniqueness(clump: 'ConcurrentClump') -> 'ConcurrentClump'

Nudge each event's min by a tiny per-index delta so truly

concurrent (identical-min) events within a clump don't collapse under == (ensure_ev_uniqueness).

Parameters

ParameterTypeDefaultDescription
clumpConcurrentClumpThe clump whose events to nudge.

Returns

A new ~sportsdataverse.mbb.mbb_ncaa_possessions.ConcurrentClump with each event's min incremented by 1e-6 * index.

extract_player_from_ev​

extract_player_from_ev(shot: 'ShotEvent', pbp_event: 'MiscGameEvent', tidy_ctx: 'TidyPlayerContext') -> 'Optional[PlayerCodeId]'

Resolve the player named in pbp_event to a

~sportsdataverse.mbb.mbb_ncaa_models.PlayerCodeId (ShotEnrichmentUtils.extract_player_from_ev).

For a shot by the team under analysis (shot.is_off) the name is tidied against the box score before coding (so a mis-spelled play-by-play name resolves to the roster identity); for an opponent shot it is coded verbatim with no team context.

Parameters

ParameterTypeDefaultDescription
shotShotEventThe shot being enriched (only is_off is read).
pbp_eventMiscGameEventThe play-by-play event naming the player.
tidy_ctxTidyPlayerContextThe name-resolution context for this game.

Returns

The resolved PlayerCodeId, or None if the event string names no player (~sportsdataverse.mbb.mbb_ncaa_events.parse_any_play found nothing).

Example

from sportsdataverse.mbb.mbb_ncaa_pbp_glue import extract_player_from_ev
pc = extract_player_from_ev(shot, pbp_event, tidy_ctx)

field_keys​

field_keys(field: 'str') -> 'dict[str, str]'

Off/def stat-key names for a field (fieldKeys, ts:77-79).

Parameters

ParameterTypeDefaultDescription
fieldstrA stat field ("efg" / "3p" / "2pmid" / "2prim").

Returns

{"off": f"off_{field}", "def": f"def_{field}"}.

Example

from sportsdataverse.mbb.mbb_ncaa_strength import field_keys

keys = field_keys("3p")
print(keys["off"], keys["def"]) # off_3p def_3p

filter_matching_own​

filter_matching_own(tags: 'list[Tag]', regex: 'str') -> 'list[Tag]'

JSoup :matchesOwn(regex) applied to an already-computed candidate

list, rather than a fresh root.select(selector) call (see the module docstring's note on composing this with attr_regex_filter).

Same own-text-only semantics as select_matching_own -- JSoup's Element.ownText() walks only the element's direct TextNode children, not text nested inside child elements.

Parameters

ParameterTypeDefaultDescription
tagslist[Tag]Candidate tags to filter (typically the result of an earlier .select()/attr_regex_filter call).
regexstrThe pattern each candidate's own (whitespace-collapsed) text must re.search-match.

Returns

The subset of tags whose own text contains a regex match, in the input list's order.

Example

from sportsdataverse.mbb.mbb_ncaa_html import attr_regex_filter, filter_matching_own, parse_html
soup = parse_html('<td style="font-size:36px">92</td><td style="color:red">x</td>')
candidates = attr_regex_filter(soup.find_all("td"), "style", r"font-size:36px")
filter_matching_own(candidates, r"[0-9]+") # [<td style="font-size:36px">92</td>]

find_lineup​

find_lineup(shot: 'ShotEvent', curr_pbp: 'Optional[MiscGameEvent]', curr_lineups: 'list[LineupEvent]', lineup_it: "'PeekableIterator[LineupEvent]'") -> 'tuple[Optional[LineupEvent], list[LineupEvent]]'

Find the lineup (stint) event on the floor for shot

(ShotEnrichmentUtils.find_lineup).

A recursive state machine over three lists: curr_lineup (the current candidate), fallback_lineups (time-matching lineups whose raw events did not contain curr_pbp -- kept as fallbacks), and stashed_lineups (lineups pulled from the iterator but not yet stepped into, available for future shots). The branch cases (labelled 2.1-2.4 in the Scala):

  • 2.1 -- no time-matching lineup left: return the fallbacks.
  • 2.2 -- the next lineup starts after the shot: no match, stash it.
  • 2.3 -- strictly inside a lineup with no prior fallbacks: take it.
  • 2.4 -- shot is exactly at a lineup boundary (or we are already choosing among multiple fallbacks): take this lineup iff its raw game events contain curr_pbp's event string (curr_pbp is None takes it unconditionally); otherwise keep it as a fallback and recurse.

Parameters

ParameterTypeDefaultDescription
shotShotEventThe shot to place (only min / is_off are read).
curr_pbpOptional[MiscGameEvent]The already-matched play-by-play event for this shot, used to disambiguate boundary lineups; None disables that check.
curr_lineupslist[LineupEvent]Lineups pulled from the iterator on a previous call and still available (the current one first).
lineup_itPeekableIterator[LineupEvent]The shared lineup iterator (consumed in place).

Returns

(matched_lineup_or_None, lineups_to_retry_next_time) -- the second element always includes the matched lineup (so out-of-order shots sharing it still resolve) plus any leftover stash.

Example

from sportsdataverse.mbb.mbb_ncaa_pbp_glue import (
PeekableIterator,
find_lineup,
)
matched, retry = find_lineup(shot, None, [lineup], PeekableIterator([]))

find_missing_subs​

find_missing_subs(clump: 'BadLineupClump', box_lineup: 'LineupEvent', valid_player_codes: 'set[str]') -> 'tuple[list[LineupEvent], BadLineupClump]'

Trims a clump whose lineups carry TOO MANY players by identifying the

"ghost" player(s) a missing sub-out left behind (LineupErrorAnalysisUtils.find_missing_subs).

Fires only when the clump's first event has >= 6 on-floor players (candidates.size < 6 is a no-op). expected_size_diff is first_event_player_count - 5 -- the number of ghosts the trim should end up removing.

Phase 1 -- shrink the candidate pool. Starting from the first event's players, walk the clump chronologically. At each event a candidate is confirmed present (and dropped from the pool) if it subs out (ev.players_out, skipped for the first event -- :445, literal port of clump.evs.headOption.contains(ev) as value equality ev == clump.evs[0]; for a well-formed clump of distinct events this is exactly index == 0) or is named in one of the event's team-side raw plays (parse_any_play -> ~sportsdataverse.mbb.mbb_ncaa_names .tidy_player -> ~sportsdataverse.mbb.mbb_ncaa_stints .build_player_code; unlike validate_lineup this does NOT skip the literal "team" token -- ported verbatim). matching_index is the FIRST event index at which the pool size first equals expected_size_diff; once set it freezes -- all later events are skipped in phase 1.

Accept gate: the final pool must be non-empty and no larger than expected_size_diff. If matching_index never fired (the pool jumped past expected_size_diff in a single step, or never shrank to it), the gate still accepts iff the residual pool is a non-empty subset of size <= expected_size_diff -- in which case phase 3 routes every event through the "before match" branch (index > None is always false). On failure the original clump is returned unchanged.

Phase 3 -- rebuild the events (a scanLeft ported as a manual accumulate loop that drops the seed). For events at/before matching_index the ghost pool is simply removed from players (filterNot). For events strictly after matching_index (index > matching_index -- the matched event itself is "before") players is rebuilt from the previous tidied event via ~sportsdataverse.mbb.mbb_ncaa_stints.build_new_player_list (the scanLeft threads the previously-emitted event; its seed is None, but the first event can never be an "after match" event, so the getOrElse(ev) fallback is only ever a formality -- ported faithfully all the same). The rebuilt events are partitioned by validate_lineup.

Parameters

ParameterTypeDefaultDescription
clumpBadLineupClumpThe bad-lineup clump to attempt to repair.
box_lineupLineupEventThe team's box-score lineup event (roster + name context).
valid_player_codesset[str]Every player code on the box score / roster.

Returns

(fixed_lineups, still_to_fix) -- the now-valid rebuilt events and a clump of the still-invalid ones (carrying the input's next_good); or ([], clump) on a no-op / rejected fix.

Example

from sportsdataverse.mbb.mbb_ncaa_stint_validation import (
find_missing_subs,
)
fixed, still = find_missing_subs(clump, box_lineup, valid_codes)

find_pbp_clump​

find_pbp_clump(shot_time: 'float', pbp_it: "'PeekableIterator[PlayByPlayEvent]'", curr_pbp_clump: 'list[MiscGameEvent]', maybe_next_pbp_event: 'Optional[MiscGameEvent]') -> 'tuple[list[MiscGameEvent], Optional[MiscGameEvent]]'

Gather every play-by-play shot/assist event sharing shot_time

(ShotEnrichmentUtils.find_pbp_clump).

If curr_pbp_clump (carried over from the previous shot) already holds events at shot_time they are returned as-is; otherwise the iterator is walked forward, discarding earlier events, accumulating the equal-time ones, and stopping (returning it as maybe_next_pbp_event) at the first later event.

Parameters

ParameterTypeDefaultDescription
shot_timefloatThe shot's game-clock minute to gather events for.
pbp_itPeekableIterator[PlayByPlayEvent]The shared play-by-play iterator (consumed in place).
curr_pbp_clumplist[MiscGameEvent]Events left over from the previous shot's clump.
maybe_next_pbp_eventOptional[MiscGameEvent]The look-ahead event stashed by the previous call, if any.

Returns

(clump, maybe_next) -- the equal-time events, plus the first strictly-later event (or None at end of stream).

Example

from sportsdataverse.mbb.mbb_ncaa_pbp_glue import (
PeekableIterator,
find_pbp_clump,
)
clump, nxt = find_pbp_clump(5.0, PeekableIterator([]), [], None)
# ([], None)

fix_combos​

fix_combos(first: 'str', last: 'str', code_start: 'Optional[str]' = None) -> 'list[tuple[str, Optional[str]]]'

Pair each of combos' three name variants with a shared

player-code override (DataQualityIssues.fix_combos).

Parameters

ParameterTypeDefaultDescription
firststrThe player's first name.
laststrThe player's last name.
code_startOptional[str]NoneThe forced player-code prefix for every variant, or None to leave the default build_player_code truncation behavior in place.

Returns

Three (name_variant, code_start) pairs.

fix_possible_score_swap_bug​

fix_possible_score_swap_bug(lineup: 'list[LineupEvent]', box_lineup: 'LineupEvent') -> 'list[LineupEvent]'

Undo a rare NCAA data bug where the scores get transposed

(fix_possible_score_swap_bug).

If the last lineup's ending score is the exact transpose of the box score's ending score, every lineup's score_info is un-transposed and pts/plus_minus are swapped/negated between team_stats and opponent_stats -- nothing else in the stat trees changes.

Parameters

ParameterTypeDefaultDescription
lineuplist[LineupEvent]The lineups to (maybe) fix, in chronological order.
box_lineupLineupEventThe trusted box-score lineup to compare the final score against.

Returns

lineup unchanged if the scores aren't transposed (or lineup is empty); otherwise a new list with every entry's score/pts/ plus_minus corrected.

get_ascending_time​

get_ascending_time(event: 'ShotEvent', period: 'int', is_women_game: 'bool') -> 'float'

Converts the descending in-period clock time to an ascending

game-elapsed time (ShotEventParser.get_ascending_time).

Parameters

ParameterTypeDefaultDescription
eventShotEventThe shot event (only ~sportsdataverse.mbb .mbb_ncaa_models.ShotEvent.min, the raw descending clock minute, is read).
periodintThe 1-indexed period the shot was taken in.
is_women_gameboolWhether to use women's-quarters (10min) or men's- halves (20min, then 5min OTs) period lengths.

Returns

The ascending game-elapsed time, in minutes.

Example

from sportsdataverse.mbb.mbb_ncaa_shot_parser import get_ascending_time
get_ascending_time(shot_with_min_4, period=1, is_women_game=False) # 16.0

get_box_lineup​

get_box_lineup(filename: 'str', in_html: 'str', team_id: 'TeamId', format_version: 'int', external_roster: 'tuple[list[str], list[RosterEntry]]' = ([], []), neutral_game_dates: 'AbstractSet[str]' = frozenset(), home_team: 'Optional[str]' = None, away_team: 'Optional[str]' = None) -> 'Union[LineupEvent, list[ParseError]]'

Gets the boxscore lineup from the HTML page (``BoxscoreParser

.get_box_lineup``).

Parameters

ParameterTypeDefaultDescription
filenamestrThe source file name -- used both for error reporting and to extract the period via parse_period_from_filename (e.g. "test_p2.html").
in_htmlstrThe raw box-score-page HTML.
team_idTeamIdThe team this box score is being parsed for.
format_versionint0 for the legacy layout, 1 for the 2018+ layout (see the module docstring's selector-translation notes).
external_rostertuple[list[str], list[RosterEntry]]([], [])(other_players, roster_players) -- either just names, or a full roster, to validate/fuzzy-correct box names against (see inject_validated_players). Also seeds ~sportsdataverse.mbb.mbb_ncaa_models.LineupEvent.players_out on the interim lineup (roster_players, each's code replaced by its jersey number).
neutral_game_datesAbstractSet[str]frozenset()Date strings (the first whitespace-separated token of the raw date-cell text) known to be neutral-site games -- overrides the default home/away inference.
home_teamOptional[str]NoneThe game's home team when the caller already knows it, forwarded to team-name resolution so a box page that names only one side (a non-D-I opponent has no header) still resolves.
away_teamOptional[str]NoneThe game's away team, same purpose. Both are required together or neither is used.

Returns

A ~sportsdataverse.mbb.mbb_ncaa_models.LineupEvent whose players is the validated box-score lineup (natural HTML order -- see the module docstring's "not sorted" note), or a list[ParseError] if any parsing step failed.

Example

from sportsdataverse.mbb.mbb_ncaa_boxscore_parser import get_box_lineup
from sportsdataverse.mbb.mbb_ncaa_models import TeamId

with open("tests/fixtures/ncaa/test_lineup.html", encoding="utf-8") as f:
html = f.read()
result = get_box_lineup("test_p1.html", html, TeamId("TeamA"), format_version=0)

get_config​

get_config() -> 'NcaaFetchConfig'

Return the live NcaaFetchConfig singleton.

Returns

The live singleton (cache_dir, proxy_url, the ProxyBonanza settings, timeout, impersonate, max_retries and the rotation / Terms-gate backoffs, transport).

Example

from sportsdataverse.mbb.mbb_ncaa_fetch import get_config
cfg = get_config()
print(cfg.cache_dir, cfg.timeout)

get_game_weight​

get_game_weight(opp: 'OpponentGame', field: 'str', side: 'str') -> 'float'

Weight for one game/field/side (getGameWeight, ts:119-140).

The field-specific shot volume (FGA for efg, 3PA for 3p, 2pmid_attempts / 2prim_attempts for the mid/rim fields); when that is 0 (no shots of that type), falls back to off_poss / def_poss so the game still carries weight.

Parameters

ParameterTypeDefaultDescription
oppOpponentGameOne opponent game dict.
fieldstrA stat field.
sidestr"off" or "def".

Returns

The (non-negative) game weight.

Example

from sportsdataverse.mbb.mbb_ncaa_strength import get_game_weight

game = {"off_3p_attempts": 0, "off_poss": 70}
print(get_game_weight(game, "3p", "off")) # 70.0 (poss fallback)

get_neutral_games​

get_neutral_games(filename: 'str', in_html: 'str', format_version: 'int') -> 'Union[tuple[TeamId, set[str]], list[ParseError]]'

Extracts the set of neutral/away-marked game dates from a saved NCAA

team-schedule page (TeamScheduleParser.get_neutral_games).

Parameters

ParameterTypeDefaultDescription
filenamestrThe source file name, used only for error reporting.
in_htmlstrThe raw team-schedule-page HTML.
format_versionint0 for the legacy fieldset/legend layout, 1 for the 2018+ div.card-header/div.card-body layout.

Returns

(team, neutral_game_dates) -- the team parsed from the page's image alt attribute, and every "MM/DD/YYYY" date string found on an "@Opponent"-marked row -- or a single-element list[ParseError] if the HTML fails to parse, or the team name can't be located.

Example

from sportsdataverse.mbb.mbb_ncaa_team_parsers import get_neutral_games

with open("tests/fixtures/ncaa/test_schedule.html", encoding="utf-8") as f:
html = f.read()
result = get_neutral_games("test_schedule.html", html, format_version=0)
if isinstance(result, list):
raise RuntimeError(result) # list[ParseError]
team, neutral_dates = result

get_per_game_raw​

get_per_game_raw(opp: 'OpponentGame', field: 'str', side: 'str') -> 'Optional[float]'

Per-game raw shooting rate from one opponent row (getPerGameRaw, ts:82-116).

efg is (2pmid_made + 2prim_made + 1.5 * 3p_made) / (2pmid_att + 2prim_att + 3p_att); 3p / 2pmid / 2prim are made / attempts. Every counter read is nullish (missing -> 0); the sole guard is on total attempts.

Parameters

ParameterTypeDefaultDescription
oppOpponentGameOne opponent game dict.
fieldstrA stat field; an unknown field returns None.
sidestr"off" or "def" (selects the off_/def_ prefix).

Returns

The rate as a float, or None when the relevant attempts total is <= 0 (game skipped by the weighted means -- not a 0-rate).

Example

from sportsdataverse.mbb.mbb_ncaa_strength import get_per_game_raw

game = {"off_3p_made": 4, "off_3p_attempts": 10}
print(get_per_game_raw(game, "3p", "off")) # 0.4

get_sorted_pbp_events​

get_sorted_pbp_events(filename: 'str', in_html: 'str', box_lineup: 'LineupEvent', format_version: 'int') -> 'Union[list[PlayByPlayEvent], list[ParseError]]'

Handy util to return the play-by-play events in chronological order,

used in a few other places (PlayByPlayParser.get_sorted_pbp_events).

Parameters

ParameterTypeDefaultDescription
filenamestrThe source file name, used only for error reporting.
in_htmlstrThe raw play-by-play-page HTML.
box_lineupLineupEventThe team's box-score lineup (supplies team/year).
format_versionint0 for the legacy layout, 1 for the 2018+ layout.

Returns

The play-by-play events in chronological (earliest-to-latest) order, or a list[ParseError] on failure. enrich=True is used internally to get the correct ascending timestamps, and its reversal is undone here (.reverse) to restore chronological order.

Example

from sportsdataverse.mbb.mbb_ncaa_boxscore_parser import get_box_lineup
from sportsdataverse.mbb.mbb_ncaa_models import TeamId
from sportsdataverse.mbb.mbb_ncaa_pbp_parser import get_sorted_pbp_events

with open("tests/fixtures/ncaa/test_lineup.html", encoding="utf-8") as f:
box_html = f.read()
box_lineup = get_box_lineup("test_p1.html", box_html, TeamId("TeamA"), format_version=0)

with open("tests/fixtures/ncaa/test_play_by_play.html", encoding="utf-8") as f:
pbp_html = f.read()
events = get_sorted_pbp_events("test.html", pbp_html, box_lineup, format_version=0)

get_team_raw_from_per_game​

get_team_raw_from_per_game(team: 'TeamDetail', field: 'str') -> 'SideValues'

A team's field rate as the weighted mean of its per-game raws (getTeamRawFromPerGame, ts:224-250).

Same accumulation as compute_league_averages_from_per_game but scoped to one team's games; empty -> 0.

Parameters

ParameterTypeDefaultDescription
teamTeamDetailA team_details team dict.
fieldstrA stat field.

Returns

{"off": float, "def": float}.

Example

from sportsdataverse.mbb.mbb_ncaa_strength import get_team_raw_from_per_game

team = {"opponents": [{"off_3p_made": 4, "off_3p_attempts": 10}]}
print(get_team_raw_from_per_game(team, "3p")["off"]) # 0.4

get_team_triples​

get_team_triples(filename: 'str', in_html: 'str', old_format: 'bool' = False) -> 'Union[list[tuple[TeamId, str, ConferenceId]], list[ParseError]]'

Extracts (team, NCAA id, conference) triples from a saved NCAA

team-list/attendance page (TeamIdParser.get_team_triples).

Parameters

ParameterTypeDefaultDescription
filenamestrThe source file name, used only for error reporting.
in_htmlstrThe raw team-list-page HTML.
old_formatboolFalseTrue for pages where the team name and conference are in separate <td>s; False (default) for pages where the conference is embedded in the team-name cell as "Team (Conf)".

Returns

One (TeamId, ncaa_id, ConferenceId) triple per row that has both a resolvable id and name/conference (rows missing either are silently skipped, matching the Scala's case _ => Nil), or a single-element list[ParseError] if the HTML itself fails to parse.

Example

from sportsdataverse.mbb.mbb_ncaa_team_parsers import get_team_triples

with open("tests/fixtures/ncaa/test_attendance_list.html", encoding="utf-8") as f:
html = f.read()
result = get_team_triples("test_attendance_list.html", html, old_format=True)

get_unified_ncaa_id​

get_unified_ncaa_id(filename: 'str', in_html: 'str') -> 'Union[Optional[str], list[ParseError]]'

Gets a player's lowest cross-season NCAA id from a saved player page

(RosterParser.get_unified_ncaa_id).

Always uses the v1 selector table -- this bonus lookup only exists on 2018+-era pages.

Parameters

ParameterTypeDefaultDescription
filenamestrThe source file name, used only for error reporting.
in_htmlstrThe raw player-page HTML.

Returns

The numerically-lowest NCAA id found, None if the page has no tr[id^=player_season_] rows, or a single-element list[ParseError] if the HTML couldn't be parsed at all.

Example

from sportsdataverse.mbb.mbb_ncaa_roster_parser import get_unified_ncaa_id
get_unified_ncaa_id("player.html", player_page_html)

handle_common_sub_bug​

handle_common_sub_bug(clump: 'BadLineupClump', box_lineup: 'LineupEvent', valid_player_codes: 'set[str]') -> 'tuple[list[LineupEvent], BadLineupClump]'

Fixes the "2-in-1-out then a compensating 1-out" substitution bug

(LineupErrorAnalysisUtils.handle_common_sub_bug).

Handles a single-event bad clump whose next known-good lineup carries a lone sub-out that the clump's event should have applied but didn't (e.g. IN: X, Y, Z; OUT: A, B in the bad event, then OUT: C in the good one). Fires only when all three guard conditions hold:

  • the bad event has more players subbing IN than OUT (len(players_in) > len(players_out)),
  • the good event has no sub-ins (len(good.players_in) == 0 -- otherwise there's no way to tell which of its sub-outs to borrow), and
  • the good event has at least one sub-out (len(good.players_out) > 0).

The fix removes the good event's sub-outs from the bad event's on-floor players (value-equality not in -- the Scala's filterNot(good.players_out.toSet)) and appends them to the bad event's players_out (order-preserving _distinct -- the Scala's (bad.players_out ++ good.players_out).distinct). The fix is accepted only if the result then passes validate_lineup: on success the fixed event is returned as the sole fixed lineup and the still-to-fix clump is emptied; on failure the fixed event (not the original) is returned as the still-to-fix clump, keeping the same next_good so a later pass can try again.

Parameters

ParameterTypeDefaultDescription
clumpBadLineupClumpThe bad-lineup clump to attempt to repair.
box_lineupLineupEventThe team's box-score lineup event (roster + name context).
valid_player_codesset[str]Every player code on the box score / roster.

Returns

(fixed_lineups, still_to_fix) -- fixed_lineups is [fixed] on an accepted fix else []; still_to_fix is an empty clump on accept, the (unchanged) input clump on a guard miss, or the single-event fixed-but-still-invalid clump on a rejected fix.

Example

from sportsdataverse.mbb.mbb_ncaa_stint_validation import (
handle_common_sub_bug,
)
fixed, still = handle_common_sub_bug(clump, box_lineup, valid_codes)

inject_starting_lineup_into_box​

inject_starting_lineup_into_box(sorted_pbp_events: 'list[PlayByPlayEvent]', box_lineup: 'LineupEvent', external_roster: 'tuple[list[str], list[RosterEntry]]', format_version: 'int') -> 'LineupEvent'

Infer the starting five and reorder the box-score roster so they lead

(PlayByPlayUtils.inject_starting_lineup_into_box).

The v1 (2018+) NCAA box score dropped the ordered list of starters, so we reconstruct it from the play-by-play sub sequencing. A player is a starter if, walking the events forward, they are seen before their first sub-in -- either subbed out (before ever being subbed in), or named in a team-side play that isn't concurrent with a sub. Anyone subbed in before ever being seen is excluded. The reconstruction stops once five starters are found.

Parameters

ParameterTypeDefaultDescription
sorted_pbp_eventslist[PlayByPlayEvent]The full play-by-play event stream, ascending time.
box_lineupLineupEventThe box-score lineup event (its players is the full roster to reorder).
external_rostertuple[list[str], list[RosterEntry]]Unused here -- carried for signature parity with the Scala (its pipeline caller passes it). See the module note.
format_versionintUnused here -- carried for signature parity. See the module note.

Returns

A copy of box_lineup with players reordered so the inferred starters lead. If fewer than five starters could be inferred (a "40-trillion" player who was never subbed nor mentioned), the roster is ordered starters -> possible-starters -> definitely-not-starters as the best available guess.

Example

from sportsdataverse.mbb.mbb_ncaa_pbp_glue import inject_starting_lineup_into_box
fixed = inject_starting_lineup_into_box(pbp_events, box_lineup, ([], []), 1)

inject_validated_players​

inject_validated_players(ordered_lineup_from_box: 'list[str]', box_minus_players: 'LineupEvent', external_roster: 'tuple[list[str], list[RosterEntry]]') -> 'list[str]'

Validates box players against the roster (if available) and any

other available box scores (BoxscoreParser.inject_validated_players).

See the module docstring's "un-threaded tidy_ctx" note -- every fuzzy-resolution call inside the loop uses the SAME original context, never the updated one a call returns (ported verbatim, including this apparent Scala oversight).

Parameters

ParameterTypeDefaultDescription
ordered_lineup_from_boxlist[str]The raw player-name strings scraped straight off the box-score page (already v0-normalized if the source was v1, by get_box_lineup's caller).
box_minus_playersLineupEventThe in-progress ~sportsdataverse.mbb.mbb_ncaa_models.LineupEvent (used only for its team field, both to scope the fuzzy-match context and to key ~sportsdataverse.mbb.mbb_ncaa_data_quality.players_missing_from_boxscore).
external_rostertuple[list[str], list[RosterEntry]](other_players, roster_players) -- extra known player names, and a full team roster (if available) to validate against / fuzzy-correct box names onto.

Returns

ordered_lineup_from_box with any name not found in roster_players fuzzy-corrected onto the closest roster name (if a roster was supplied at all), followed by any roster/other/ known-missing players not already present in that corrected list (see the module docstring's "Extra-players Set ordering" note for this trailing group's order).

Example

from sportsdataverse.mbb.mbb_ncaa_boxscore_parser import inject_validated_players
inject_validated_players(["Player One"], box_lineup, ([], []))

is_cached​

is_cached(path: 'str', *, cache_dir: 'Optional[Path]' = None) -> 'bool'

Return whether path already has a cache file on disk.

Parameters

ParameterTypeDefaultDescription
pathstrThe stats.ncaa.org URL path (with its query string, if any).
cache_dirOptional[Path]NoneThe cache root; the active config's cache_dir when None.

Returns

True when cached_path already exists on disk.

is_end_of_game_fouling_vs_fastbreak​

is_end_of_game_fouling_vs_fastbreak(curr_clump: 'ConcurrentClump', event_parser: 'PossessionEvent') -> 'bool'

Check for intentional fouling to prolong the game, specifically so it

can be excluded from being counted as a fast break (is_end_of_game_fouling_vs_fastbreak).

Parameters

ParameterTypeDefaultDescription
curr_clumpConcurrentClumpThe clump to classify.
event_parserPossessionEventSelects which side of each event is "attacking".

Returns

True iff the FIRST attacking-side FT-made/FT-missed event in curr_clump.evs is both near the end of a period AND has the attacking team ahead by (0, 10] points; False if no such event exists.

Example

from sportsdataverse.mbb.mbb_ncaa_lineup_enrich import is_end_of_game_fouling_vs_fastbreak

is_end_of_game_fouling_vs_fastbreak(curr_clump, event_parser)

is_gen2​

is_gen2(ev: 'RawGameEvent') -> 'bool'

Detect the new/"gen2" NCAA event format (EventUtils.is_gen2).

Parameters

ParameterTypeDefaultDescription
evRawGameEventThe raw game event to inspect.

Returns

True if ev.info contains a comma-space (", "), the gen2 format's field separator; False for the old/legacy format.

is_scramble​

is_scramble(curr_clump: 'ConcurrentClump', prev_clumps: 'list[ConcurrentClump]', event_parser: 'PossessionEvent', player_version: 'bool') -> 'tuple[Callable[[RawGameEvent], bool], str]'

Figure out if (each event of) the current clump is part of a

"scramble scenario" following an ORB (is_scramble, LineupUtils .scala).

Returns a (predicate, debug_tag) tuple -- the tuple shape is load-bearing: the oracle asserts the debug tag string directly ("N/A"/"0a"/"1aa"/"1ab"/"1b"/"2aa"/"2ab").

Parameters

ParameterTypeDefaultDescription
curr_clumpConcurrentClumpThe clump to classify.
prev_clumpslist[ConcurrentClump]Prior merged clumps, most-recent-first.
event_parserPossessionEventSelects which side of each event is "attacking".
player_versionboolUnused -- see the module docstring's is_scramble port notes (the Scala's debug-print gate this flag controls is permanently false regardless of its value).

Returns

(predicate, debug_tag) where predicate(ev) reports whether ev is part of a scramble.

Example

from sportsdataverse.mbb.mbb_ncaa_lineup_enrich import is_scramble

predicate, tag = is_scramble(curr_clump, prev_clumps, event_parser, player_version=False)
[predicate(ev) for ev in curr_clump.evs]

is_team_shooting_left_to_start​

is_team_shooting_left_to_start(sorted_very_raw_events: 'list[tuple[int, ShotEvent]]') -> 'tuple[bool, int]'

Infers which side of the SVG court the team under analysis shoots

towards in the first period, from its own made/missed shot locations (ShotEventParser.is_team_shooting_left_to_start).

Parameters

ParameterTypeDefaultDescription
sorted_very_raw_eventslist[tuple[int, ShotEvent]]The chronologically-sorted (period, shot) pairs, pre-geometry-transform.

Returns

(team_shooting_left_in_first_period, first_period) -- the first element of sorted_very_raw_events, if any, determines first_period; the majority side (by count) of the team's own (is_off) shots within that period determines the direction.

Example

from sportsdataverse.mbb.mbb_ncaa_shot_parser import is_team_shooting_left_to_start
is_team_shooting_left_to_start([(1, shot_a), (1, shot_b)])

is_transition​

is_transition(curr_clump: 'ConcurrentClump', prev_clumps: 'list[ConcurrentClump]', event_parser: 'PossessionEvent', player_version: 'bool') -> 'tuple[Callable[[RawGameEvent, bool], bool], str]'

Figure out if the current clump is part of a transition offense

following opponent offense (or a marked-fastbreak play) (is_transition).

Returns a (predicate, debug_tag) tuple mirroring is_scramble -- the oracle asserts the debug tag directly ("N/A"/"0a.X"/ "1a.a"/"1a.b"/"1b.a"/"1b.b"/"1b.X"/"NOT"). Unlike is_scramble's predicate, this one takes a second argument -- is_scramble -- so scramble always wins: an event already classified as a scramble is never additionally tagged transition (!is_scramble && is_transition_event).

Parameters

ParameterTypeDefaultDescription
curr_clumpConcurrentClumpThe clump to classify.
prev_clumpslist[ConcurrentClump]Prior merged clumps, most-recent-first.
event_parserPossessionEventSelects which side of each event is "attacking" (and, for this heuristic, "defending").
player_versionboolUnused -- see is_scramble's port notes in the module docstring (the Scala's debug-print gate this flag controls is permanently false regardless of its value).

Returns

(predicate, debug_tag) where predicate(ev, is_scramble) reports whether ev is part of a transition play, given whether it was already classified as a scramble.

Example

from sportsdataverse.mbb.mbb_ncaa_lineup_enrich import is_transition

predicate, tag = is_transition(curr_clump, prev_clumps, event_parser, player_version=False)
[predicate(ev, is_scramble=False) for ev in curr_clump.evs]

is_women_game​

is_women_game(sorted_very_raw_events: 'list[tuple[int, ShotEvent]]') -> 'bool'

Infers men's vs. women's game from timing evidence

(ShotEventParser.is_women_game). Shot-parser-specific variant -- distinct from the play-by-play parser's own is_women_game, which uses PbP event timing instead of shot timing; the plan's recon flags both as "its OWN is_women_game variant" per module.

Parameters

ParameterTypeDefaultDescription
sorted_very_raw_eventslist[tuple[int, ShotEvent]]The chronologically-sorted (period, shot) pairs.

Returns

True if at least 4 periods were seen AND no shot was taken with more than 10 minutes showing on the (descending) clock in the very first event (women's quarters are 10 minutes; a shot at >10:00 remaining could only happen in a longer men's period).

Example

from sportsdataverse.mbb.mbb_ncaa_shot_parser import is_women_game
is_women_game([(1, shot), (2, shot), (3, shot), (4, shot)]) # True

jsoup_text​

jsoup_text(el: 'Optional[Tag]') -> 'str'

JSoup Element.text(): all descendant text, whitespace-collapsed.

JSoup's .text() joins every text node under el (including descendants) and collapses runs of whitespace (spaces, tabs, newlines) into single spaces, trimming the ends. bs4's .get_text() does the joining but not the collapsing, so captured HTML's indentation/newlines would otherwise leak into every extracted value.

Parameters

ParameterTypeDefaultDescription
elOptional[Tag]The element to extract text from, or None.

Returns

The whitespace-collapsed text, or "" if el is None.

Example

from sportsdataverse.mbb.mbb_ncaa_html import jsoup_text, parse_html
soup = parse_html("<td>\n Akin,\tDaniel </td>")
jsoup_text(soup.find("td")) # "Akin, Daniel"

load_proxybonanza_pool​

load_proxybonanza_pool(api_key: 'str', pkg: 'str', *, transport: 'Optional[PoolTransport]' = None) -> "'list[str]'"

Resolve a ProxyBonanza package into a list of http://login:pass@ip:port URLs.

Graduated from dev/ncaa_proxy.py's load_proxy_pool -- same endpoint shape, minus the .Renviron reader (creds are now explicit params, per the creds-hygiene directive).

Endpoint: GET https://api.proxybonanza.com/v1/userpackages/{pkg}.json

Parameters

ParameterTypeDefaultDescription
api_keystrProxyBonanza API key.
pkgstrProxyBonanza package id.
transportOptional[PoolTransport]NoneInjectable (url, headers) -> (status, text) callable for offline testing. Defaults to a curl_cffi GET.

Returns

One http://login:password@ip:port URL per IP in the package.

Raises

ExceptionDescription
ValueErrorHTTP 400 / 422 (the request itself is wrong).
AssetFetchErrorAny other non-200 response, or a 200 whose body is not the package JSON (an error or HTML page).

Example

def fake(url, headers):
return 200, '{"data": {"login": "u", "password": "p", "ippacks": []}}'
pool = load_proxybonanza_pool("key", "pkg", transport=fake)

matching_player​

matching_player(shot: 'ShotEvent', pbp_event: 'MiscGameEvent', tidy_ctx: 'TidyPlayerContext', code_match: 'bool') -> 'bool'

Whether the player in pbp_event matches shot's shooter

(ShotEnrichmentUtils.matching_player).

Parameters

ParameterTypeDefaultDescription
shotShotEventThe shot being enriched.
pbp_eventMiscGameEventThe candidate play-by-play event.
tidy_ctxTidyPlayerContextThe name-resolution context.
code_matchboolIf True, compare on player code only (looser -- lets a name that resolves to the wrong identity but the right code match); if False, require full ~sportsdataverse.mbb .mbb_ncaa_models.PlayerCodeId equality.

Returns

True if the resolved player matches shot.player under the selected comparison, else False.

Example

from sportsdataverse.mbb.mbb_ncaa_pbp_glue import matching_player
matching_player(shot, pbp_event, tidy_ctx, code_match=False)

misspellings​

misspellings(team: 'Optional[TeamId]') -> 'dict[str, str]'

Team-scoped misspelling map, falling back to the generic map

(DataQualityIssues.misspellings -- see the module docstring's "fallback semantics" note for why this is a precomputed merge, not a runtime two-level lookup).

Parameters

ParameterTypeDefaultDescription
teamOptional[TeamId]The team to look up team-specific corrections for. None (like any team absent from the table) falls back to generic_misspellings.

Returns

A fresh dict -- the team's misspelling map merged with generic_misspellings, or a copy of generic_misspellings if team has no specific entries.

Example

from sportsdataverse.mbb.mbb_ncaa_data_quality import misspellings
from sportsdataverse.mbb.mbb_ncaa_models import TeamId

misspellings(TeamId("NJIT"))["Lewal, Levi"] # 'Lawal, Levi'
misspellings(TeamId("Some Unlisted Team")) # {} (generic fallback)
misspellings(None) # {} (generic fallback)

ncaa_wbb_box_scores​

ncaa_wbb_box_scores(game_ids: 'Union[str, int, Iterable[Union[str, int]]]', *, multi_games: 'bool' = False, fetcher: 'Optional[Any]' = None, return_as_pandas: 'bool' = False, errors: "Literal['raise', 'skip']" = 'raise') -> "Union['pl.DataFrame', 'pd.DataFrame']"

Scrape WBB per-player box scores (wbigballR get_box_scores/scrape_box).

Pure delegation to sportsdataverse.mbb.mbb_ncaa_box_stats.ncaa_mbb_box_scores — see it for the column contract, the tolerant header renames, and the fixed multi_games aggregation (R's groups by a Pos column the current markup no longer ships).

Parameters

ParameterTypeDefaultDescription
game_idsUnion[str, int, Iterable[Union[str, int]]]NCAA contest ids; None/NaN entries are dropped.
multi_gamesboolFalseAggregate per player across all games (fixed grouping on player/clean_name/team).
fetcherOptional[Any]NoneOptional injected fetcher exposing fetch_game_individual_stats (tests/offline). Defaults to a fresh NcaaFetcher.with_browser() context per call.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.
errorsLiteral['raise', 'skip']'raise'"raise" (default) raises AssetFetchError on a failed fetch; "skip" skips it and adds a scrape_status column (see ~sportsdataverse.mbb.mbb_ncaa_box_stats.ncaa_mbb_box_scores).

Returns

Per-player box rows (or per-player aggregates with multi_games).

col_nametypedescription
game_idStringUnique game identifier.
box_idString
playerStringPlayer name.
clean_nameString
teamStringTeam-side label or team identifier.
mpFloat64Minutes played.
ptsFloat64Points scored.
orbFloat64
drbFloat64
trbFloat64Career total rebounds.
astFloat64Assists.
toFloat64To.
stlFloat64Steals.
blkFloat64Blocks.
fgaFloat64Field goal attempts.
fgmFloat64Field goals made.
fg_pctFloat64Field goal percentage (0-1).
tpaFloat64
tpmFloat64
tp_pctFloat64
ftaFloat64Free throw attempts.
ftmFloat64Free throws made.
ft_pctFloat64Free throw percentage (0-1).
ts_pctFloat64True shooting percentage (0-1).
efg_pctFloat64
foulsFloat64Personal fouls.
dqFloat64
techFloat64

Raises

ExceptionDescription
AssetFetchErrorA fetch failed and errors="raise".
ValueErrorAn unknown errors, or errors="skip" with multi_games.

Example

from sportsdataverse.wbb.wbb_ncaa_box_stats import ncaa_wbb_box_scores
box = ncaa_wbb_box_scores(["5722355"])
print(box.shape)

ncaa_wbb_date_games​

ncaa_wbb_date_games(date: 'Optional[str]' = None, *, conference: 'str' = 'All', conference_id: 'Optional[int]' = None, fetcher: "Optional['NcaaFetcher']" = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Discover every NCAA WBB game played on a date (wbigballR get_date_games).

Same engine as sportsdataverse.mbb.mbb_ncaa_scoreboard.ncaa_mbb_date_games with the WBB season_divisions table bound (see the module docstring for the 2010-11..2025-26 coverage caveat).

Parameters

ParameterTypeDefaultDescription
dateOptional[str]None"MM/DD/YYYY". Defaults to yesterday (R default).
conferencestr'All'Conference name filter (e.g. "SEC", "Summit League"); case/punctuation-insensitive. Default "All" (every conference). Unknown names raise.
conference_idOptional[int]NoneExplicit stats.ncaa.org conference id; overrides conference when given.
fetcherOptional['NcaaFetcher']NoneInjectable ~sportsdataverse.mbb.mbb_ncaa_fetch. NcaaFetcher (tests pass an offline fake). None uses NcaaFetcher.with_browser().
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per game — see the MBB sibling for the full SCOREBOARD_SCHEMA column contract.

col_nametypedescription
dateStringDate in YYYY-MM-DD format.
start_timeString
homeStringHome.
awayStringAway record.
box_idString
game_idStringUnique game identifier.
home_scoreStringHome team score at the time of the play.
away_scoreStringAway team score at the time of the play.
attendanceStringReported attendance.
neutral_siteBooleanNeutral site.
home_winsInt64Home team's wins.
home_lossesInt64Home team's losses.
away_winsInt64Away team's wins.
away_lossesInt64Away team's losses.

Raises

ExceptionDescription
ValueErrorStats.ncaa.org lists no WBB season for the date (a season missing from the bundled table is looked up live first, see the module docstring), conference is not a known conference, the date is not MM/DD/YYYY, or the fetched page has no games table.

Example

from sportsdataverse.wbb.wbb_ncaa_scoreboard import ncaa_wbb_date_games
games = ncaa_wbb_date_games("12/05/2024")
print(games.shape)

ncaa_wbb_join_pbp_shots​

ncaa_wbb_join_pbp_shots(pbp: 'pl.DataFrame', shots: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Attach WBB chart shots onto the pbp frame (pure delegation).

See sportsdataverse.mbb.mbb_ncaa_shots.ncaa_mbb_join_pbp_shots for the matching rules (FG-only, within-second same-result sequence) and the joined 40-column contract.

Parameters

ParameterTypeDefaultDescription
pbpDataFrame35-column snake_case pbp frame (ncaa_wbb_play_by_play).
shotsDataFrameShots frame from ncaa_wbb_shot_locations.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

The pbp frame with shot columns attached (unmatched rows NA-filled).

col_nametypedescription
game_idStringUnique game identifier.
game_dateStringGame date (YYYY-MM-DD).
homeStringHome.
awayStringAway record.
periodInt64Period of the game (1-4 quarters; 5+ for OT).
clockStringGame clock value.
game_timeStringGame start time.
game_secondsInt64
home_scoreInt64Home team score at the time of the play.
away_scoreInt64Away team score at the time of the play.
event_teamString
event_descriptionString
player_1String
player_2String
event_typeStringEvent / play type code (V2 PBP).
event_resultString
shot_valueInt64Point value of the shot (2 or 3).
event_lengthInt64
poss_numInt64
poss_teamString
poss_lengthInt64
is_transitionBoolean
home_1String
home_2String
home_3String
home_4String
home_5String
away_1String
away_2String
away_3String
away_4String
away_5String
statusStringStatus label.
is_garbage_timeBoolean
sub_deviateInt64
teamStringTeam-side label or team identifier.
playerStringPlayer name.
xFloat64X.
yFloat64Y.
shot_distFloat64

Example

from sportsdataverse.wbb.wbb_ncaa_shots import ncaa_wbb_join_pbp_shots
joined = ncaa_wbb_join_pbp_shots(pbp, shots)
print(joined.shape)

ncaa_wbb_player_stats​

ncaa_wbb_player_stats(pbp: 'pl.DataFrame', *, multi_games: 'bool' = False, simple: 'bool' = False, fix_tip_in: 'bool' = True, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Aggregate WBB play-by-play into per-player box stats (wbigballR get_player_stats).

Pure delegation to sportsdataverse.mbb.mbb_ncaa_stats_agg.ncaa_mbb_player_stats — see it for the algorithm and column contracts.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlay-by-play frame in the sdv-py 35-column snake_case bigballR contract (ncaa_wbb_game_pbp output).
multi_gamesboolFalseAggregate across games per (player, team) — the season-stat surface.
simpleboolFalseReturn the reduced surface without the transition / assisted / putback / block-location splits.
fix_tip_inboolTrueCount the real "Tip In" vocabulary (default); False reproduces R's "Tip-In" bug for oracle parity.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per player+team (+game when multi_games=False).

col_nametypedescription
game_idStringUnique game identifier.
game_dateStringGame date (YYYY-MM-DD).
homeStringHome.
awayStringAway record.
teamStringTeam-side label or team identifier.
playerStringPlayer name.
minsFloat64
o_possFloat64
ptsFloat64Points scored.
orbFloat64
drbFloat64
astFloat64Assists.
stlFloat64Steals.
blkFloat64Blocks.
tovFloat64Turnovers.
pfFloat64Personal fouls.
ts_pctFloat64True shooting percentage (0-1).
efg_pctFloat64
fgmFloat64Field goals made.
fgaFloat64Field goal attempts.
fg_pctFloat64Field goal percentage (0-1).
tpmFloat64
tpaFloat64
tp_pctFloat64
ftmFloat64Free throws made.
ftaFloat64Free throw attempts.
ft_pctFloat64Free throw percentage (0-1).
rimmFloat64
rimaFloat64
rim_pctFloat64
midmFloat64
midaFloat64
mid_pctFloat64
pbackmFloat64
pbackaFloat64
pback_pctFloat64
blk_rimFloat64
blk_midFloat64
blk_threeFloat64
pct_fga_transFloat64
pct_tpa_transFloat64
pct_rima_transFloat64
pct_fgm_transFloat64
pct_tpm_transFloat64
pct_rimm_transFloat64
pct_fgm_astFloat64
pct_tpm_astFloat64
pct_rimm_astFloat64
pts_transFloat64
orb_transFloat64
drb_transFloat64
ast_transFloat64
stl_transFloat64
blk_transFloat64
tov_transFloat64
ts_pct_transFloat64
efg_pct_transFloat64
fgm_transFloat64
fga_transFloat64
fg_pct_transFloat64
tpm_transFloat64
tpa_transFloat64
tp_pct_transFloat64
ftm_transFloat64
fta_transFloat64
ft_pct_transFloat64
rimm_transFloat64
rima_transFloat64
rim_pct_transFloat64
midm_transFloat64
mida_transFloat64
mid_pct_transFloat64
pts_halfFloat64
orb_halfFloat64
drb_halfFloat64
ast_halfFloat64
stl_halfFloat64
blk_halfFloat64
tov_halfFloat64
ts_pct_halfFloat64
efg_pct_halfFloat64
fgm_halfFloat64
fga_halfFloat64
fg_pct_halfFloat64
tpm_halfFloat64
tpa_halfFloat64
tp_pct_halfFloat64
ftm_halfFloat64
fta_halfFloat64
ft_pct_halfFloat64
rimm_halfFloat64
rima_halfFloat64
rim_pct_halfFloat64
midm_halfFloat64
mida_halfFloat64
mid_pct_halfFloat64
pts_astFloat64
fgm_astFloat64
tpm_astFloat64
rimm_astFloat64
midm_astFloat64
pts_unastFloat64
efg_pct_unastFloat64
fgm_unastFloat64
fga_unastFloat64
fg_pct_unastFloat64
tpm_unastFloat64
tpa_unastFloat64
tp_pct_unastFloat64
rimm_unastFloat64
rima_unastFloat64
rim_pct_unastFloat64
midm_unastFloat64
mida_unastFloat64
mid_pct_unastFloat64

Example

from sportsdataverse.wbb.wbb_ncaa_stats_agg import ncaa_wbb_player_stats
stats = ncaa_wbb_player_stats(pbp)
print(stats.shape)

ncaa_wbb_possessions​

ncaa_wbb_possessions(pbp: 'pl.DataFrame', *, simple: 'bool' = False, fix_cross_game_leak: 'bool' = True, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Aggregate WBB play-by-play into one row per possession (wbigballR get_possessions).

Pure delegation to sportsdataverse.mbb.mbb_ncaa_possession_seg.ncaa_mbb_possessions — see it for the algorithm, the 28/17-column contracts, and the fixed-vs- faithful flag convention.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlay-by-play frame in the sdv-py 35-column snake_case bigballR contract (ncaa_wbb_game_pbp output).
simpleboolFalseReturn only the 17-column possession/points frame.
fix_cross_game_leakboolTrueWhen True (default, and the CORRECT behavior), window the start_event_type lag with .over("game_id") so a game's first possession does not inherit the previous game's last event. When False, reproduce R's ungrouped dplyr::lag (all_functions.R:3698). Parity tests pass False.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per possession.

col_nametypedescription
game_idStringstats.ncaa.org game id of the play-by-play page the possession comes from.
game_dateStringGame date (YYYY-MM-DD).
homeStringHome team's name as the stats.ncaa.org play-by-play page lists it.
awayStringAway team's name as the stats.ncaa.org play-by-play page lists it.
periodInt64Period number from the stats.ncaa.org page: 1-2 for halves (3+ = overtime), or 1-4 for quarters (5+ = overtime) on a quarters page (women's games from 2015-16).
poss_numInt64Possession number within the game, stamped upstream by the play-by-play chain (parse_ncaa_bb_game_pbp).
poss_teamStringName of the team in possession.
home_1StringHome on-court player 1 of 5. The full variant sorts the five names alphabetically within the row, so a lineup always occupies the same columns; simple=True keeps on-court order.
home_2StringHome on-court player 2 of 5 (alphabetical in the full variant, on-court order with simple=True).
home_3StringHome on-court player 3 of 5 (alphabetical in the full variant, on-court order with simple=True).
home_4StringHome on-court player 4 of 5 (alphabetical in the full variant, on-court order with simple=True).
home_5StringHome on-court player 5 of 5 (alphabetical in the full variant, on-court order with simple=True).
away_1StringAway on-court player 1 of 5. The full variant sorts the five names alphabetically within the row, so a lineup always occupies the same columns; simple=True keeps on-court order.
away_2StringAway on-court player 2 of 5 (alphabetical in the full variant, on-court order with simple=True).
away_3StringAway on-court player 3 of 5 (alphabetical in the full variant, on-court order with simple=True).
away_4StringAway on-court player 4 of 5 (alphabetical in the full variant, on-court order with simple=True).
away_5StringAway on-court player 5 of 5 (alphabetical in the full variant, on-court order with simple=True).
home_scoreInt64Home team's score on the possession's first event row (the page's running score after that event).
away_scoreInt64Away team's score on the possession's first event row (the page's running score after that event).
ptsInt64Points scored on the possession, summing shot_value (3, 2, or 1 for a free throw) over its made shots.
is_assistedInt64Count of the possession's events that carry a second player (player_2), usually 0 or 1 -- a count, not a flag, kept from bigballR's get_possessions for parity.
is_transitionInt641 when the possession is a transition possession, else 0: its first event (a steal or a shot type, or a foul in the possessing team's favour) came within 10 seconds of the possession start and the previous possession ended on a terminal event. Null when any event of the possession has no flag.
is_garbage_timeInt641 when any event of the possession falls in garbage time, else 0. Garbage time starts at the first event with a margin of 25+ inside the last 10 minutes of regulation (or later), 20+ inside the last 5 or 15+ inside the last 2, while at most 3 of the two teams' 10 starters are on the floor, and lasts to the end of the game. Null when any event has no flag.
start_event_typeStringEvent type of the play immediately before the possession's first event (what started it, e.g. a defensive rebound or a made basket). Null for a game's first possession (fix_cross_game_leak=True, the default).
first_shot_timeInt64Seconds into the possession (poss_length) at its first field-goal attempt; null when the possession had no shot.
first_shot_typeStringEvent type of the possession's first field-goal attempt ("Layup", "Three Point Jumper", "Two Point Jumper", "Hook", "Dunk", "Tip In"); null when the possession had no shot.
last_event_timeInt64Seconds into the possession (poss_length) at its final event.
last_event_typeStringEvent type of the possession's final event (e.g. a made shot, a turnover or a defensive rebound).

Example

from sportsdataverse.wbb.wbb_ncaa_possession_seg import ncaa_wbb_possessions
poss = ncaa_wbb_possessions(pbp)
print(poss.shape)

# Faithful (R-buggy) start-event lag

poss = ncaa_wbb_possessions(pbp, fix_cross_game_leak=False)

ncaa_wbb_shot_locations​

ncaa_wbb_shot_locations(game_ids: 'Sequence[object]', *, season: 'Optional[object]' = None, fetcher: 'Optional[Any]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Scrape WBB shot locations for one or more games.

Same driver as sportsdataverse.mbb.mbb_ncaa_shots.ncaa_mbb_shot_locations with the WBB period_model for the game's era bound — see the mbb sibling for the parse algorithm and the ~sportsdataverse.mbb.mbb_ncaa_shots.SHOTS_SCHEMA contract. The default is the quarters model: stats.ncaa.org shot locations only exist from 2019 (rules/wbb.yaml#wbb-2019-ncaa-stats-shot-locations), so unlike ~sportsdataverse.wbb.wbb_ncaa_game_pbp.ncaa_wbb_game_pbp there is no page inference; season resolves the model through sportsdataverse.scrape.ncaa.parse.wbb_period_model (halves through 2014-15, quarters from 2015-16, rules/wbb.yaml#wbb-2016-four-quarters).

Parameters

ParameterTypeDefaultDescription
game_idsSequence[object]NCAA contest ids; None/NaN entries are dropped.
seasonOptional[object]NoneSeason as an ending year (2015) or span ("2014-15"); applies to every game in game_ids. None binds quarters.
fetcherOptional[Any]NoneOptional injected fetcher exposing fetch_game_box (tests/offline). Defaults to a fresh NcaaFetcher.with_browser() context per call.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

All games' shots row-bound (zero-row schema frame when none found).

col_nametypedescription
game_idStringUnique game identifier.
periodInt64Period of the game (1-4 quarters; 5+ for OT).
clockStringGame clock value.
game_secondsInt64
teamStringTeam-side label or team identifier.
playerStringPlayer name.
shot_resultStringShot result ('Made' / 'Missed').
xFloat64X.
yFloat64Y.
shot_distFloat64

Example

from sportsdataverse.wbb.wbb_ncaa_shots import ncaa_wbb_shot_locations
shots = ncaa_wbb_shot_locations(["5722355"])
print(shots.shape)

ncaa_wbb_team_roster​

ncaa_wbb_team_roster(team_id: 'Optional[int]' = None, *, team: 'Optional[str]' = None, season: 'Optional[str]' = None, fetcher: "Optional['NcaaFetcher']" = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Scrape a women's team roster from stats.ncaa.org.

Port of wbigballR get_team_roster with name resolution fixed to the WBB crosswalk (see the module docstring). The roster parser itself is league-agnostic; algorithm detail: sportsdataverse.mbb.mbb_ncaa_schedule.ncaa_mbb_team_roster.

Parameters

ParameterTypeDefaultDescription
team_idOptional[int]Nonestats.ncaa.org team id (changes every season).
teamOptional[str]NoneSchool name, e.g. "South Carolina".
seasonOptional[str]NoneSeason string, e.g. "2024-25"; required with team.
fetcherOptional['NcaaFetcher']NoneInjectable ~sportsdataverse.mbb.mbb_ncaa_fetch. NcaaFetcher; defaults to a fresh browser-transport fetcher.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per player — see ~sportsdataverse.mbb.mbb_ncaa_schedule.parse_ncaa_bb_team_roster for the column contract.

col_nametypedescription
gpStringGames played.
gsStringGames started.
jerseyStringJersey number worn by the player.
nameStringDisplay name.
classStringCollege class / draft eligibility note.
positionStringListed roster position (G, F, C, etc.).
heightStringPlayer height (string e.g. '6-2' or inches).
hometownStringPlayer hometown.
high_schoolString
playerStringPlayer name.
clean_nameString
ht_inchesInt64
player_idStringUnique player identifier.

Raises

ExceptionDescription
ValueErrorNeither team_id nor a resolvable team/season pair was given.

Example

from sportsdataverse.wbb.wbb_ncaa_schedule import ncaa_wbb_team_roster
df = ncaa_wbb_team_roster(team="South Carolina", season="2024-25")
print(df.select("jersey", "player", "ht_inches").head())