Skip to main content
Version: 0.2.0

Win expectancy (wexp) — Models and calculators: EloConfig–response_ridge

EloConfig​

EloConfig(k: 'float' = 20.0, z: 'float' = 400.0, hfa: 'float' = 65.0, init: 'float' = 1500.0, carryover: 'float' = 0.67, mov_mult: 'bool' = True) -> None

Tunable Elo parameters (all seeds, none sacred).

Parameters

ParameterTypeDefaultDescription
kfloat20.0Update step size.
zfloat400.0Logistic scale (p = 1/(10^(-diff/z)+1)).
hfafloat65.0Home-field advantage in rating points (0 applied at neutral sites).
initfloat1500.0Rating for a team's first-ever appearance.
carryoverfloat0.67Fraction of (rating - init) kept across seasons (0 = full reset, 1 = no reversion; seed ~0.53).
mov_multboolTrueApply the margin-of-victory multiplier.

Example

from sportsdataverse.wexp import EloConfig, build_nfl_market_oracle, elo_ratings
rated = elo_ratings(build_nfl_market_oracle([2023]), EloConfig(k=9.1, carryover=0.53))

GSConfig​

GSConfig(sigma_w: 'float' = 0.9, sigma_s: 'float' = 2.35, season_shrink: 'float' = 0.82, sigma_y: 'float' = 13.45, hfa: 'float' = 2.3, init_sd: 'float' = 5.0) -> None

Glickman-Stern state-space tunables (Axis A6; all seeds, none sacred).

Parameters

ParameterTypeDefaultDescription
sigma_wfloat0.9Week-to-week strength innovation SD (RESEARCH seed ~0.9).
sigma_sfloat2.35Season-to-season innovation SD (seed ~2.35).
season_shrinkfloat0.82AR(1) shrink toward the league mean at each season boundary (the model's own carryover; 0 = full reset).
sigma_yfloat13.45Observation noise SD on the game margin.
hfafloat2.3Home-field advantage in margin points (0 at neutral sites).
init_sdfloat5.0Prior SD for a team's first-ever strength state.

Example

from sportsdataverse.wexp import GSConfig, build_nfl_market_oracle, glickman_stern_predictor, run_backtest
oracle = build_nfl_market_oracle([2022, 2023])
probs, rows = run_backtest(oracle, glickman_stern_predictor(GSConfig(sigma_w=1.1)), model_id="gs")

VariantConfig​

VariantConfig(core: 'str', response: 'str', opponent_adjust: 'str', prior: 'str', wp_map: 'str', hfa: 'str', params: 'tuple[tuple[str, float], ...]' = <factory>) -> None

One point in the variation matrix (validated on construction).

Parameters

ParameterTypeDefaultDescription
corestrAxis A strength core.
responsestrAxis B response weighting (EPA-family cores only).
opponent_adjuststrAxis C adjustment scheme (EPA-family cores only).
priorstrAxis D preseason prior.
wp_mapstrAxis E rating->WP mapping.
hfastrAxis F HFA treatment.
paramstuple[tuple[str, float], ...]<factory>Free-form tunables (k, z, alpha, sigma, cap, ...) — part of the hash, so a re-tuned variant is a NEW variant.

Raises

ExceptionDescription
ValueErrorAn axis value is not in AXES, response or opponent_adjust is not the placeholder on a non-EPA core, or market_only is given a prior other than flat.

Example

from sportsdataverse.wexp import VariantConfig, variant_hash
v = VariantConfig(core="ridge_epa", response="capped", opponent_adjust="ridge", prior="carryover",
wp_map="margin_normal", hfa="fixed", params=(("cap", 21.0), ("lam", 25.0)))
variant_hash(v)

VintageStore​

VintageStore() -> 'None'

In-memory registry of vintage-keyed feature frames.

Example

from sportsdataverse.wexp import VintageStore, build_nfl_market_oracle, ridge_margin_vintages
games = build_nfl_market_oracle([2022, 2023])
store = VintageStore()
store.register("ridge", ridge_margin_vintages(games, lam=25.0), entity_key="team_id")
games = store.join_asof(games, "ridge", on={"home_team_id": "team_id"}, prefix="home_")

Methods

VintageStore.join_asof​

VintageStore.join_asof(games: 'pl.DataFrame', name: 'str', *, on: 'dict[str, str]', prefix: 'str' = '', week_col: 'str' = 'week') -> 'pl.DataFrame'

Join a games frame to the latest leak-free vintage of a table.

A game in week W receives the row with the greatest as_of_week <= W for its entity (backward fill across missing snapshots). Games earlier than every vintage get nulls — never a future value.

Parameters

ParameterTypeDefaultDescription
gamesDataFrameFrame with season, week_col, and the left join key.
namestrRegistered table name.
ondict[str, str]Single-entry mapping {games_key: table_entity_key}.
prefixstr''Prefix applied to the joined feature columns.
week_colstr'week'Week column on games.

Returns

games with the vintage's feature columns appended, plus {prefix}as_of_week recording which vintage served each game (leak forensics: it is always <= the game's week).

Raises

ExceptionDescription
KeyErrorIf name is not registered.
ValueErrorIf join-key dtypes disagree, or a joined feature column would collide with an existing games column.

VintageStore.register​

VintageStore.register(name: 'str', frame: 'pl.DataFrame', *, entity_key: 'str', week_semantics: "Literal['as_of', 'through']" = 'as_of') -> 'None'

Register a feature frame; refuse anything not vintage-keyed.

Parameters

ParameterTypeDefaultDescription
namestrTable name.
frameDataFrameFrame carrying vintage keys + entity_key. With week_semantics="as_of" the frame has an as_of_week column whose row W was built from weeks strictly before W. With week_semantics="through" the frame has a through_week column INCLUSIVE of its week (the CFB cfb_ratings_weekly / cfb_team_summaries_weekly convention) and the store performs the as_of_week = through_week + 1 shift itself — so reintroducing the inclusive-week leak requires a deliberate wrong argument, not a forgotten ingest comment.
entity_keystrThe entity column (e.g. "team_id").
week_semanticsLiteral['as_of', 'through']'as_of'"as_of" (default) or "through".

Raises

ExceptionDescription
ValueErrorIf a vintage key or the entity column is missing, or (season, as_of_week, entity) rows are duplicated.

VintageStore.table​

VintageStore.table(name: 'str') -> 'pl.DataFrame'

Return a registered frame.

Parameters

ParameterTypeDefaultDescription
namestrTable name passed to register.

Returns

The registered polars.DataFrame.

append_results​

append_results(frame: 'pl.DataFrame', path: 'str | Path') -> 'None'

Append result rows to the append-only leaderboard parquet.

Existing rows are never modified; the file is atomically replaced with existing + new. Schema is enforced against RESULT_SCHEMA.

Parameters

ParameterTypeDefaultDescription
frameDataFrameResult rows (from result_rows).
pathstr | PathLeaderboard parquet path (created on first call).

Raises

ExceptionDescription
ValueErrorIf frame does not match RESULT_SCHEMA.

Example

from sportsdataverse.wexp.scoring import append_results, result_rows
rows = result_rows(league="nfl", model_id="elo", variant_hash="a1", vintage_policy="V2", season=2023,
week_slice="all", era="all", metrics={"brier": 0.21}, n=272)
append_results(rows, "results/wexp/leaderboard.parquet")

baseline_probs​

baseline_probs(oracle: 'pl.DataFrame', *, elo: 'pl.DataFrame | None' = None, home_rate: 'float | None' = None, sigma: 'float | None' = None) -> 'pl.DataFrame'

Append baseline probability columns to a market-oracle frame.

Columns added: p_coin_flip (0.5), p_home_rule (constant home rate; 0.5 at neutral sites), p_market_close (= p_close), p_market_open (normal link on spread_open; null where the era holds no open — never imputed), and p_elo when an Elo frame is supplied.

Parameters

ParameterTypeDefaultDescription
oracleDataFrameFrame from an oracle builder (module contract columns).
eloDataFrame | NoneNoneOptional output of sportsdataverse.wexp.elo.elo_ratings (joined on game_id).
home_ratefloat | NoneNoneHome-rule probability; defaults to the league seed in BASELINE_HOME_RATE.
sigmafloat | NoneNoneMargin SD for the open-spread link; defaults per league.

Returns

oracle with the baseline p_* columns appended.

col_nametypedescription
leagueStringLeague of the game, "nfl" or "cfb".
game_idStringGame id as text (nflverse game_id for the NFL, ESPN game id for college football).
seasonInt32Season of the game.
weekInt32Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them).
season_typeStringSeason type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football).
home_teamStringHome team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football).
away_teamStringAway team, in the same form as home_team.
home_team_idStringHome team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football).
away_team_idStringAway team id as text, in the same form as home_team_id.
neutral_siteBooleanWhether the game was played at a neutral site (no home-field advantage applied).
fbs_vs_fbsBooleanWhether both teams are FBS (always true for the NFL).
home_marginFloat64Final home score minus away score; null for an unplayed game.
home_winInt81 when the home team won, 0 when it lost, null on a tie or an unplayed game.
spread_closeFloat64Closing spread as the expected home margin (positive = home favored).
total_closeFloat64Closing over/under total.
ml_home_closeFloat64Closing home moneyline (American odds).
ml_away_closeFloat64Closing away moneyline (American odds).
spread_openFloat64Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021).
p_close_spreadFloat64Home win probability from the closing spread through a normal link on the margin SD.
p_close_mlFloat64Vig-removed home win probability from the closing moneylines.
p_closeFloat64Market home win probability, the logit-space blend of p_close_spread and p_close_ml weighted by blend_weight (default 0.7 on the spread) where both exist, else whichever exists.
p_coin_flipFloat64Coin-flip baseline, 0.5 for every game.
p_home_ruleFloat64Home-rule baseline, the league's constant home win rate (0.5 at neutral sites).
p_market_closeFloat64Closing-market baseline, equal to p_close.
p_market_openFloat64Opening-market baseline, the normal link on spread_open; null where no open exists.
p_eloFloat64Elo baseline, the elo_ratings p_home joined on game_id.

Raises

ExceptionDescription
ValueErrorelo's game_id dtype differs from the oracle's.

Example

from sportsdataverse.wexp import baseline_probs, build_nfl_market_oracle, elo_ratings
oracle = build_nfl_market_oracle([2022, 2023])
probs = baseline_probs(oracle, elo=elo_ratings(oracle))

brier_score​

brier_score(y_true: 'np.ndarray', p_pred: 'np.ndarray') -> 'float'

Mean squared error between predicted probabilities and binary outcomes.

Parameters

ParameterTypeDefaultDescription
y_truendarrayArray of binary outcomes (0/1).
p_predndarrayArray of predicted probabilities in [0, 1].

Returns

The Brier score (0.0 is a perfect forecast).

Example

import numpy as np
from sportsdataverse._common.metrics import brier_score
brier_score(np.array([1, 0]), np.array([0.9, 0.1]))

build_cfb_market_oracle​

build_cfb_market_oracle(seasons: 'list[int]', *, line_odds_path: 'str | Path | None' = None, **kwargs: 'float') -> 'pl.DataFrame'

Load the cfb_line_odds archive + ESPN schedules and build the CFB oracle.

Parameters

ParameterTypeDefaultDescription
seasonslist[int]Seasons to include.
line_odds_pathstr | Path | NoneNoneOptional local path to cfb_line_odds.parquet; by default the published archive is loaded via sportsdataverse.cfb.load_cfb_betting_lines (the cfbfastR-data raw-main asset).

Returns

The oracle frame.

col_nametypedescription
leagueStringLeague of the game, "nfl" or "cfb".
game_idStringGame id as text (nflverse game_id for the NFL, ESPN game id for college football).
seasonInt32Season of the game.
weekInt32Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them).
season_typeStringSeason type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football).
home_teamStringHome team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football).
away_teamStringAway team, in the same form as home_team.
home_team_idStringHome team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football).
away_team_idStringAway team id as text, in the same form as home_team_id.
neutral_siteBooleanWhether the game was played at a neutral site (no home-field advantage applied).
fbs_vs_fbsBooleanWhether both teams are FBS (always true for the NFL).
home_marginFloat64Final home score minus away score; null for an unplayed game.
home_winInt81 when the home team won, 0 when it lost, null on a tie or an unplayed game.
spread_closeFloat64Closing spread as the expected home margin (positive = home favored).
total_closeFloat64Closing over/under total.
ml_home_closeFloat64Closing home moneyline (American odds).
ml_away_closeFloat64Closing away moneyline (American odds).
spread_openFloat64Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021).
p_close_spreadFloat64Home win probability from the closing spread through a normal link on the margin SD.
p_close_mlFloat64Vig-removed home win probability from the closing moneylines.
p_closeFloat64Market home win probability, the logit-space blend of p_close_spread and p_close_ml weighted by blend_weight (default 0.7 on the spread) where both exist, else whichever exists.

Example

from sportsdataverse.wexp.oracle_market import build_cfb_market_oracle
oracle = build_cfb_market_oracle([2024])

build_nfl_market_oracle​

build_nfl_market_oracle(seasons: 'list[int]', **kwargs: 'float') -> 'pl.DataFrame'

Load nflverse schedules and build the NFL market oracle.

Parameters

ParameterTypeDefaultDescription
seasonslist[int]Seasons to include.

Returns

The oracle frame.

col_nametypedescription
leagueStringLeague of the game, "nfl" or "cfb".
game_idStringGame id as text (nflverse game_id for the NFL, ESPN game id for college football).
seasonInt32Season of the game.
weekInt32Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them).
season_typeStringSeason type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football).
home_teamStringHome team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football).
away_teamStringAway team, in the same form as home_team.
home_team_idStringHome team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football).
away_team_idStringAway team id as text, in the same form as home_team_id.
neutral_siteBooleanWhether the game was played at a neutral site (no home-field advantage applied).
fbs_vs_fbsBooleanWhether both teams are FBS (always true for the NFL).
home_marginFloat64Final home score minus away score; null for an unplayed game.
home_winInt81 when the home team won, 0 when it lost, null on a tie or an unplayed game.
spread_closeFloat64Closing spread as the expected home margin (positive = home favored).
total_closeFloat64Closing over/under total.
ml_home_closeFloat64Closing home moneyline (American odds).
ml_away_closeFloat64Closing away moneyline (American odds).
spread_openFloat64Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021).
p_close_spreadFloat64Home win probability from the closing spread through a normal link on the margin SD.
p_close_mlFloat64Vig-removed home win probability from the closing moneylines.
p_closeFloat64Market home win probability, the logit-space blend of p_close_spread and p_close_ml weighted by blend_weight (default 0.7 on the spread) where both exist, else whichever exists.

Example

from sportsdataverse.wexp.oracle_market import build_nfl_market_oracle
oracle = build_nfl_market_oracle(list(range(2009, 2026)))

build_predictor​

build_predictor(config: 'VariantConfig', *, table: 'str' = 'ridge', sigma: 'float' = 13.45, season_priors: 'Optional[pl.DataFrame]' = None, variance_events: 'Optional[pl.DataFrame]' = None) -> 'WeekPredictor'

Dispatch a variant config to its implemented week predictor.

Implemented cells: elo_margin (prior flat = full season reset, carryover = the carryover tunable; wp_map must be elo_logistic) and ridge_epa with response="raw" / opponent_adjust="ridge" / prior="flat" served from a registered ridge vintage table with wp_map in margin_normal / isotonic. Every other valid config cell raises NotImplementedError until its engine lands — never a silent fallback to a different model.

Parameters

ParameterTypeDefaultDescription
configVariantConfigThe variant to build.
tablestr'ridge'Ratings vintage table name (EPA-family cores).
sigmafloat13.45Default margin SD for the normal link (sigma in config.params wins).
season_priorsOptional[DataFrame]NoneContinuity-prior table (from cfb_continuity_shifts); REQUIRED when prior="carryover_continuity" and ignored otherwise.
variance_eventsOptional[DataFrame]None

Returns

A predictor callable for ~sportsdataverse.wexp.backtest.run_backtest.

Raises

ExceptionDescription
NotImplementedErrorFor a valid config cell whose engine has not landed yet.

Example

from sportsdataverse.wexp.engines import build_predictor
from sportsdataverse.wexp.variants import VariantConfig
predict = build_predictor(VariantConfig(
core="elo_margin", response="raw", opponent_adjust="none",
prior="carryover", wp_map="elo_logistic", hfa="fixed"))

calibration_table​

calibration_table(y_true: 'np.ndarray', p_pred: 'np.ndarray', n_bins: 'int' = 10) -> 'pl.DataFrame'

Bucket predicted probabilities into bins and compare to actual outcome rates.

Parameters

ParameterTypeDefaultDescription
y_truendarrayArray of binary outcomes (0/1).
p_predndarrayArray of predicted probabilities in [0, 1].
n_binsint10Number of equal-width probability bins.

Returns

A polars.DataFrame with columns bin_mid, mean_pred, mean_actual, n (one row per non-empty bin).

col_nametypedescription
bin_midFloat64Midpoint of the equal-width predicted-probability bin (0.05, 0.15, ... with the default 10 bins).
mean_predFloat64Mean predicted probability of the rows in the bin.
mean_actualFloat64Observed outcome rate of the rows in the bin; a calibrated model has it close to mean_pred.
nUInt32Rows in the bin. Empty bins emit no row.

Example

import numpy as np
from sportsdataverse._common.metrics import calibration_table
calibration_table(np.array([1, 0, 1, 0]), np.array([0.9, 0.1, 0.8, 0.2]))

carry_forward_weights​

carry_forward_weights(returning: 'pl.DataFrame', *, qb_continuity: 'Optional[pl.DataFrame]' = None, hc_continuity: 'Optional[pl.DataFrame]' = None, base: 'float' = 0.35, w_returning: 'float' = 0.35, w_qb: 'float' = 0.2, w_hc: 'float' = 0.1, last_week: 'int' = 4) -> 'pl.DataFrame'

How much of last season's metrics to still believe, by team and week.

The weight blends three pieces of continuity evidence — returning production, whether the starting QB is the same, and whether the head coach is the same — into a 0-1 credence on last season's team metrics. It then RAMPS TO ZERO across the opening weeks: the current season carries the estimate on its own merits from week last_week + 1 onward.

Ramp: full weight in week 1, then linearly down so week last_week + 1 is exactly 0. With the default last_week=4 the multipliers are 1.00 / 0.75 / 0.50 / 0.25 / 0.00 for weeks 1-5.

Parameters

ParameterTypeDefaultDescription
returningDataFrameseason, team_id, overall_returning (0-1).
qb_continuityOptional[DataFrame]NoneOptional season, team_id, qb_continuity (0/1). Missing teams contribute the neutral 0.5.
hc_continuityOptional[DataFrame]NoneOptional season, team_id, hc_continuity (0/1). Missing teams contribute the neutral 0.5 (no free source exists yet; the term is wired for later).
basefloat0.35Weight floor for a team with zero continuity evidence.
w_returningfloat0.35Weight contribution of returning production.
w_qbfloat0.2Weight contribution of QB continuity.
w_hcfloat0.1Weight contribution of head-coach continuity.
last_weekint4Final week that carries ANY prior-season weight.

Returns

One row per (season, team_id, week) for weeks 1..last_week+1 with carry_weight in [0, 1].

col_nametypedescription
seasonInt32Season the weight applies to (the season being predicted, whose prior season's metrics are carried).
team_idStringTeam id as text (the ESPN id for college football).
weekInt32Week of the season, 1 through last_week + 1.
carry_weightFloat64Share of last season's metrics to keep this week (0-1), the continuity credence times the week ramp; exactly 0 in week last_week + 1.

Raises

ExceptionDescription
ValueErrorA continuity table shares no (season, team_id) key with returning.

Example

from sportsdataverse.cfb import load_cfb_returning_production
from sportsdataverse.wexp.features import carry_forward_weights
w = carry_forward_weights(load_cfb_returning_production(seasons=[2024]))

cfb_continuity_shifts​

cfb_continuity_shifts(oracle: 'pl.DataFrame', talent: 'pl.DataFrame', returning: 'pl.DataFrame', *, beta_talent: 'float' = 0.0, beta_returning: 'float' = 0.0) -> 'pl.DataFrame'

Compile CFB talent + returning production into Elo prior shifts (Axis D3).

prior_shift = beta_talent * talent_z + beta_returning * returning_c in rating points, where talent_z is the within-season z-score of the 247 talent composite and returning_c is the within-season centered overall returning-production share. Both are preseason knowledge for their season (leak-free by construction). Teams missing one input take 0 for that term — a neutral default, never imputed from games. The id -> display-name map comes from the oracle itself (home_team_id/home_team pairs), so no external crosswalk.

Parameters

ParameterTypeDefaultDescription
oracleDataFrameMarket-oracle frame (contract columns incl. team ids).
talentDataFrameload_cfb_team_talent frame (season, team_id, talent_composite).
returningDataFrameload_cfb_returning_production frame (season, team_id, overall_returning).
beta_talentfloat0.0Rating points per talent z-score.
beta_returningfloat0.0Rating points per centered returning share.

Returns

(season, team, prior_shift) for ~sportsdataverse.wexp.elo.elo_ratings — one row per oracle team with at least one input.

col_nametypedescription
seasonInt32Season the prior applies to; built from preseason talent and returning production only.
teamStringTeam display name, matched to the oracle's home_team / away_team.
prior_shiftFloat64Elo rating points added once at the team's season entry, beta_talent times the talent z-score plus beta_returning times the centered returning-production share; 0 for a missing input.

Raises

ExceptionDescription
ValueErrorThe shifts would carry duplicate (season, team) rows (an id with two names in the oracle, two ids sharing one name, or duplicate input rows).

Example

from sportsdataverse.cfb import load_cfb_returning_production, load_cfb_team_talent
from sportsdataverse.wexp import build_cfb_market_oracle, cfb_continuity_shifts
oracle = build_cfb_market_oracle([2024])
talent = load_cfb_team_talent(seasons=[2024])
returning = load_cfb_returning_production(seasons=[2024])
shifts = cfb_continuity_shifts(oracle, talent, returning, beta_talent=50.0, beta_returning=100.0)

cfb_drive_deltas​

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

Per-drive EP deltas from play-by-play (the shared drive substrate).

Per drive: delta = sum of play EPA (perspective-corrected — see cfb_drive_ep_responses), plus the drive's starting EP and the share-of-available pct. Feeds both the team-game response aggregation and the post-game WE resampling (G2/G3).

Inclusion/exclusion classifiers (callers filter, the substrate keeps every drive):

  • garbage — the drive STARTED in Connelly garbage time (|margin_start| exceeds the documented per-quarter ~sportsdataverse.cfb.cfb_advanced_constants.GARBAGE_TIME_MARGIN band; OT clipped to the Q4 band).
  • clock_kill — the half's final drive with <= 3 plays and a non-positive delta (kneel / clock-kill signature).

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlay frame with game_id, pos_team_id / def_pos_team_id (or the ids in pos_team / def_pos_team), drive.id, EPA, EP_start, game_play_number, period, pos_team_score, def_pos_team_score. The load_cfb_pbp frame works as is.

Returns

One row per (game, drive): game_id / drive.id, off / deft (raw Int64 ids), delta, start_ep, pct, period / margin_start / plays, and the garbage / clock_kill flags.

col_nametypedescription
game_idInt64ESPN game id of the drive's game, as the play-by-play carries it.
drive.idStringESPN drive id; with game_id it keys the drive.
offInt64ESPN id of the team on offense for the drive.
deftInt64ESPN id of the team on defense for the drive.
deltaFloat64Expected points the offense added over the drive, the sum of its plays' EPA (perspective-corrected).
start_epFloat64Expected points at the drive's first snap.
periodInt64Quarter the drive started in.
margin_startInt64Offense's score margin at the drive's first snap.
playsInt64Plays in the drive that carry EPA, EP_start, both team ids and a drive id.
pctFloat64Share of the drive's available expected points it captured, delta / (7 - start_ep), with the denominator floored at 0.5.
garbageBooleanTrue when the drive started in garbage time, |margin_start| beyond the per-quarter band (overtime uses the fourth quarter's).
clock_killBooleanTrue for a half's last drive of 3 or fewer plays that gained no expected points (a kneel-down signature).

Raises

ExceptionDescription
ValueErrorA row's team is a name with no pos_team_id / def_pos_team_id to read the id from.

Example

from sportsdataverse.cfb import load_cfb_pbp
from sportsdataverse.wexp.engines import cfb_drive_deltas
drives = cfb_drive_deltas(load_cfb_pbp(seasons=[2024]))

cfb_drive_ep_responses​

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

Per team-game drive-EP efficiency from play-by-play (both sides rated).

The user-specified "starting drive EP to end drive EP" perspective: per drive, delta = sum of play EPA over the drive — the telescoped start-to-end EP change WITH the library's possession-perspective corrections. (A naive EP_end(last) - EP_start(first) is wrong: on drive-ending plays the raw EP_end is stated from the NEW possession team's perspective, which flips the sign on punt/turnover drives — it fit a NEGATIVE margin scale on the real tune window.) Two responses per team-game, both MEANS over that offense's drives:

  • resp — the raw per-drive delta (per-drive efficiency, pace-free, the FEI-style granularity).
  • resp_pct — the user-specified share of AVAILABLE drive EP: delta / (7 - EP_start of the drive's first play) (7 = max drive EP). A drive starting at the opponent 5 has little left to gain, so capturing it counts more per point. available is floored at 0.5 so goal-line starts cannot blow the ratio up. Rate x possessions carries the volume downstream (the fitted margin scale absorbs the average pace).

Each game emits one row per offense with the defense alongside, so the weekly ridge downstream fits an off_coef AND a def_coef for every team, on either response.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlay frame as cfb_drive_deltas takes it (the load_cfb_pbp frame works as is).

Returns

One row per (game, offense): game_id (Utf8), off_team_id / def_team_id (Utf8, cast from the raw Int64 ESPN ids), resp / resp_pct (Float64), drives (Int64 count).

col_nametypedescription
game_idStringESPN game id as text.
off_team_idStringESPN id (as text) of the offense the row rates.
def_team_idStringESPN id (as text) of the defense it faced.
respFloat64Mean expected points added per drive by this offense in this game.
resp_pctFloat64Mean share of available drive expected points captured, delta / (7 - start_ep) averaged over the offense's drives.
drivesInt64Drives the offense had in the game.

Raises

ExceptionDescription
ValueErrorAs cfb_drive_deltas (a team name with no id column).

Example

from sportsdataverse.cfb import load_cfb_pbp
from sportsdataverse.wexp.engines import cfb_drive_ep_responses
rows = cfb_drive_ep_responses(load_cfb_pbp(seasons=[2024]))

cfb_market_oracle_from_lines​

cfb_market_oracle_from_lines(line_odds: 'pl.DataFrame', schedules: 'pl.DataFrame', *, sigma: 'float' = 15.5, blend_weight: 'float' = 0.7) -> 'pl.DataFrame'

Build the CFB market oracle from the cfb_line_odds archive + schedules.

Consensus semantics ported from cfbfastR-cfb-data spread_backfill.load_consensus_spreads: per game the home spread is the NEGATED median home-team line across books (home-positive), clipped to +/-60; totals and side moneylines are book medians. Opens use the same recipe on opening_lines and stay null where no book held one.

Parameters

ParameterTypeDefaultDescription
line_oddsDataFrameThe cfb_line_odds frame (per-side per-book rows).
schedulesDataFrameESPN CFB schedules frame (game_id, season, week, season_type, home/away names + scores) for outcomes.
sigmafloat15.5Margin SD for the spread->prob normal link.
blend_weightfloat0.7Spread weight in the spread/ML logit blend.

Returns

The oracle frame per the module contract.

col_nametypedescription
leagueStringLeague of the game, "nfl" or "cfb".
game_idStringGame id as text (nflverse game_id for the NFL, ESPN game id for college football).
seasonInt32Season of the game.
weekInt32Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them).
season_typeStringSeason type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football).
home_teamStringHome team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football).
away_teamStringAway team, in the same form as home_team.
home_team_idStringHome team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football).
away_team_idStringAway team id as text, in the same form as home_team_id.
neutral_siteBooleanWhether the game was played at a neutral site (no home-field advantage applied).
fbs_vs_fbsBooleanWhether both teams are FBS (always true for the NFL).
home_marginFloat64Final home score minus away score; null for an unplayed game.
home_winInt81 when the home team won, 0 when it lost, null on a tie or an unplayed game.
spread_closeFloat64Closing spread as the expected home margin (positive = home favored).
total_closeFloat64Closing over/under total.
ml_home_closeFloat64Closing home moneyline (American odds).
ml_away_closeFloat64Closing away moneyline (American odds).
spread_openFloat64Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021).
p_close_spreadFloat64Home win probability from the closing spread through a normal link on the margin SD.
p_close_mlFloat64Vig-removed home win probability from the closing moneylines.
p_closeFloat64Market home win probability, the logit-space blend of p_close_spread and p_close_ml weighted by blend_weight (default 0.7 on the spread) where both exist, else whichever exists.

Example

import polars as pl
from sportsdataverse.cfb import load_cfb_schedule
from sportsdataverse.cfb.cfb_loaders_extra import load_cfb_betting_lines
from sportsdataverse.wexp.oracle_market import cfb_market_oracle_from_lines
lines = load_cfb_betting_lines().filter(pl.col("season").cast(pl.Int32) == 2024)
oracle = cfb_market_oracle_from_lines(lines, load_cfb_schedule(seasons=[2024]))

closing_line_value​

closing_line_value(p_model: 'np.ndarray', p_bet: 'np.ndarray', p_close: 'np.ndarray') -> 'float'

Mean closing line value captured by betting the model's disagreements.

Spec (documented, since no authoritative public one exists): for each game the model "bets" the side it likes more than the bet-time market (home if p_model > p_bet, else away). CLV per game is the signed move of the vig-removed close toward that side: sign(p_model - p_bet) * (p_close - p_bet). Positive mean = the close moved toward the model's picks (the model bought value). Games where p_model == p_bet are no-bets that contribute 0 and DILUTE the mean toward zero (deliberate: the mean is per-game, not per-bet; divide by nonzero sides yourself for a per-bet CLV).

Parameters

ParameterTypeDefaultDescription
p_modelndarrayModel home win probabilities.
p_betndarrayVig-removed home probabilities at bet time (open or close).
p_closendarrayVig-removed home probabilities at close.

Returns

Mean CLV in probability points (positive = value captured).

Example

import numpy as np
from sportsdataverse.wexp.scoring import closing_line_value
closing_line_value(np.array([0.6]), np.array([0.5]), np.array([0.55]))

devig_multiplicative​

devig_multiplicative(p_raw: 'Sequence[float]') -> 'list[float]'

Remove vig by normalizing raw implied probabilities to sum to 1.

The basic multiplicative method — as good as or better than fancier methods at the close on log probability score (Matter of Stats study).

Parameters

ParameterTypeDefaultDescription
p_rawSequence[float]Raw implied probabilities for all outcomes (with vig).

Returns

Probabilities scaled to sum to 1, order preserved.

Example

from sportsdataverse.wexp.market import devig_multiplicative
devig_multiplicative([0.5238, 0.5238]) # [0.5, 0.5]

devig_shin​

devig_shin(p_raw: 'Sequence[float]') -> 'list[float]'

Remove vig with Shin's method (insider-trading model).

Attributes the overround disproportionately to longshots; kept as a sensitivity check for CFB big-dog moneylines. With zero overround this reduces to the identity.

Parameters

ParameterTypeDefaultDescription
p_rawSequence[float]Raw implied probabilities for all outcomes (with vig).

Returns

Shin-devigged probabilities summing to 1, order preserved.

Example

from sportsdataverse.wexp.market import devig_shin
devig_shin([0.85, 0.25])

ece​

ece(y_true: 'np.ndarray', p_pred: 'np.ndarray', n_bins: 'int' = 10) -> 'float'

Expected calibration error: n-weighted mean |mean_pred - mean_actual| per bin.

Parameters

ParameterTypeDefaultDescription
y_truendarrayArray of binary outcomes (0/1).
p_predndarrayArray of predicted probabilities in [0, 1].
n_binsint10Number of equal-width probability bins.

Returns

The expected calibration error (0.0 is perfectly calibrated).

Example

import numpy as np
from sportsdataverse.wexp.scoring import ece
ece(np.array([1, 0, 1, 0]), np.array([0.9, 0.1, 0.8, 0.2]))

elo_predictor​

elo_predictor(config: 'EloConfig' = EloConfig(k=20.0, z=400.0, hfa=65.0, init=1500.0, carryover=0.67, mov_mult=True), season_priors: 'Optional[pl.DataFrame]' = None, hfa_by_season: 'Optional[dict[int, float]]' = None) -> 'WeekPredictor'

Wrap the margin-Elo engine (Axis A1) as a week predictor.

Each week the engine replays Elo over the completed history plus the outcome-less slate; ~sportsdataverse.wexp.elo.elo_ratings rates unplayed games without updating on them, so the per-week refit reconstructs the exact chronological walk.

Parameters

ParameterTypeDefaultDescription
configEloConfigEloConfig(k=20.0, z=400.0, hfa=65.0, init=1500.0, carryover=0.67, mov_mult=True)Elo tunables.
season_priorsOptional[DataFrame]NoneOptional (season, team, prior_shift) continuity table forwarded to ~sportsdataverse.wexp.elo.elo_ratings (Axis D3/D4).
hfa_by_seasonOptional[dict[int, float]]NoneOptional season -> HFA override map forwarded to the engine (Axis F per_era).

Returns

A predictor callable for run_backtest.

Example

from sportsdataverse.wexp import build_nfl_market_oracle, elo_predictor, run_backtest
oracle = build_nfl_market_oracle([2022, 2023])
probs, rows = run_backtest(oracle, elo_predictor(), model_id="elo")

elo_ratings​

elo_ratings(games: 'pl.DataFrame', config: 'EloConfig' = EloConfig(k=20.0, z=400.0, hfa=65.0, init=1500.0, carryover=0.67, mov_mult=True), season_priors: 'Optional[pl.DataFrame]' = None, hfa_by_season: 'Optional[dict[int, float]]' = None) -> 'pl.DataFrame'

Walk games chronologically and emit pre-game Elo ratings + P(home).

Games are processed in (season, week) order; the emitted rating for a game NEVER includes that game's result (walk-forward by construction). Ties (margin 0) score as 0.5. Unplayed games (null home_margin) still get a pre-game rating and probability but do not update ratings.

The order is the raw (season, week). ESPN restarts college football postseason weeks at 1, so on a raw CFB oracle bowl results would update ratings ahead of the regular season: pass sportsdataverse.wexp.backtest.normalize_walk_weeks(oracle) instead (run_backtest does this itself).

Parameters

ParameterTypeDefaultDescription
gamesDataFrameFrame with game_id, season, week, home_team, away_team, neutral_site, home_margin.
configEloConfigEloConfig(k=20.0, z=400.0, hfa=65.0, init=1500.0, carryover=0.67, mov_mult=True)Tunable parameters.
season_priorsOptional[DataFrame]NoneOptional continuity-prior table with season, team, prior_shift (rating points). The shift is added ONCE per team at its season entry (first appearance or season boundary, after the carryover reversion) — the Axis D3/D4 hook. Teams absent from the table shift by 0. Priors are preseason knowledge for their season; never derive them from that season's games.
hfa_by_seasonOptional[dict[int, float]]NoneOptional season -> HFA override in rating points (Axis F per_era; e.g. {2020: 0.0} for the no-fans COVID season). Seasons absent from the map use config.hfa. Values are a-priori/tuned parameters — never fit them from the season they apply to inside a walk-forward run.

Returns

The input rows (original order) with home_elo_pre, away_elo_pre, p_home appended.

col_nametypedescription
leagueStringLeague of the game, "nfl" or "cfb".
game_idStringGame id as text (nflverse game_id for the NFL, ESPN game id for college football).
seasonInt32Season of the game.
weekInt32Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them).
season_typeStringSeason type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football).
home_teamStringHome team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football).
away_teamStringAway team, in the same form as home_team.
home_team_idStringHome team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football).
away_team_idStringAway team id as text, in the same form as home_team_id.
neutral_siteBooleanWhether the game was played at a neutral site (no home-field advantage applied).
fbs_vs_fbsBooleanWhether both teams are FBS (always true for the NFL).
home_marginFloat64Final home score minus away score; null for an unplayed game.
home_winInt81 when the home team won, 0 when it lost, null on a tie or an unplayed game.
spread_closeFloat64Closing spread as the expected home margin (positive = home favored).
total_closeFloat64Closing over/under total.
ml_home_closeFloat64Closing home moneyline (American odds).
ml_away_closeFloat64Closing away moneyline (American odds).
spread_openFloat64Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021).
p_close_spreadFloat64Home win probability from the closing spread through a normal link on the margin SD.
p_close_mlFloat64Vig-removed home win probability from the closing moneylines.
p_closeFloat64Market home win probability, the logit-space blend of p_close_spread and p_close_ml weighted by blend_weight (default 0.7 on the spread) where both exist, else whichever exists.
home_elo_preFloat64Home team's Elo rating before the game (never includes the game's own result).
away_elo_preFloat64Away team's Elo rating before the game.
p_homeFloat64Elo home win probability from the pre-game ratings and home-field advantage.

Raises

ExceptionDescription
ValueErrorseason_priors has duplicate (season, team) rows.

Example

from sportsdataverse.wexp import EloConfig, build_nfl_market_oracle, elo_ratings
games = build_nfl_market_oracle([2022, 2023])
rated = elo_ratings(games, EloConfig(k=9.1, z=402, carryover=0.53))

enumerate_variants​

enumerate_variants() -> 'list[VariantConfig]'

Generate the pruned axis cross-product.

EPA-family cores expand across all of B x C; other cores appear once per (D, E, F) cell with the placeholder B/C values. Invalid cells are skipped via the constructor's compatibility rules.

Returns

The list of valid variants (deduplicated by construction).

Example

from sportsdataverse.wexp.variants import enumerate_variants
variants = enumerate_variants()
len(variants)

favorite_bucket_table​

favorite_bucket_table(y_true: 'np.ndarray', p_pred: 'np.ndarray') -> 'pl.DataFrame'

FPI-style calibration buckets from the favorite's perspective.

Folds every game to the predicted favorite (p_fav = max(p, 1-p)) and buckets into 50-60 / 60-70 / 70-80 / 80-90 / 90-100, comparing the mean predicted favorite probability to the favorite's actual win rate. The Phase-2 gate reads abs_gap on buckets with n >= 200.

Parameters

ParameterTypeDefaultDescription
y_truendarrayArray of binary home-win outcomes (0/1).
p_predndarrayArray of predicted home win probabilities.

Returns

A polars.DataFrame with columns bucket, mean_pred, mean_actual, n, abs_gap (one row per non-empty bucket).

col_nametypedescription
bucketStringThe favorite's predicted win probability band in percent ("50-60", "60-70", ... "90-100"), the favorite being the side the model gives at least 0.5.
mean_predFloat64Mean predicted win probability of the favorites in the band.
mean_actualFloat64Share of those favorites that won.
nUInt32Games in the band. Empty bands emit no row.
abs_gapFloat64Absolute difference between mean_pred and mean_actual.

Example

import numpy as np
from sportsdataverse.wexp.scoring import favorite_bucket_table
favorite_bucket_table(np.array([1, 0]), np.array([0.75, 0.4]))

glickman_stern_predictor​

glickman_stern_predictor(config: 'GSConfig' = GSConfig(sigma_w=0.9, sigma_s=2.35, season_shrink=0.82, sigma_y=13.45, hfa=2.3, init_sd=5.0), season_priors: 'Optional[pl.DataFrame]' = None, variance_events: 'Optional[pl.DataFrame]' = None) -> 'WeekPredictor'

Wrap the Glickman-Stern (1998) Kalman filter as a week predictor.

Team strengths follow a weekly random walk (sigma_w innovation) with an AR(1) season transition (season_shrink + sigma_s); each week the filter batch-updates on that week's observed margins. The filter re-runs FORWARD over the driver's history every week — filtering only, never smoothing, so predictions are walk-forward by construction. P(home) uses the model's own predictive margin distribution: Phi(mu / sqrt(state var + sigma_y^2)) — the margin_normal map with a per-game predictive SD.

Parameters

ParameterTypeDefaultDescription
configGSConfigGSConfig(sigma_w=0.9, sigma_s=2.35, season_shrink=0.82, sigma_y=13.45, hfa=2.3, init_sd=5.0)Tunable parameters.
season_priorsOptional[DataFrame]NoneOptional continuity table (season, team, prior_shift) in MARGIN points (Axis D3 composed into A6): each team's shift is added to its state mean at season entry — the start season at filter init, then every boundary after the AR shrink. Preseason knowledge only; never derive shifts from the season they apply to.
variance_eventsOptional[DataFrame]NoneOptional (season, week, team, extra_var) table of state-uncertainty events in squared margin points — e.g. a starting-QB change known at kickoff. The team's state VARIANCE is inflated by extra_var when the filter arrives at that week, widening the update gate without moving the mean. Events must be pre-game knowledge for their week.

Returns

A predictor callable for ~sportsdataverse.wexp.backtest.run_backtest.

Raises

ExceptionDescription
ValueErrorseason_priors has duplicate (season, team) rows, or variance_events has duplicate (season, week, team) rows. When the predictor runs: season_priors match no team on the slate (keyed on the wrong team column).

Example

from sportsdataverse.wexp import GSConfig, build_nfl_market_oracle, glickman_stern_predictor, run_backtest
oracle = build_nfl_market_oracle([2022, 2023])
probs, rows = run_backtest(oracle, glickman_stern_predictor(GSConfig()), model_id="gs")

log_loss_score​

log_loss_score(y_true: 'np.ndarray', p_pred: 'np.ndarray', eps: 'float' = 1e-15) -> 'float'

Binary cross-entropy loss between predicted probabilities and outcomes.

Parameters

ParameterTypeDefaultDescription
y_truendarrayArray of binary outcomes (0/1).
p_predndarrayArray of predicted probabilities in [0, 1].
epsfloat1e-15Clipping bound to avoid log(0).

Returns

The mean log loss.

Example

import numpy as np
from sportsdataverse._common.metrics import log_loss_score
log_loss_score(np.array([1, 0]), np.array([0.9, 0.1]))

logit_blend​

logit_blend(p_a: 'float', p_b: 'float', weight_a: 'float' = 0.7) -> 'float'

Blend two probabilities in logit space (70/30 by default).

Parameters

ParameterTypeDefaultDescription
p_afloatFirst probability in (0, 1).
p_bfloatSecond probability in (0, 1).
weight_afloat0.7Weight on p_a; p_b gets 1 - weight_a.

Returns

The logit-space weighted blend, back on the probability scale.

Example

from sportsdataverse.wexp.market import logit_blend
logit_blend(0.61, 0.64, weight_a=0.7)

mae​

mae(a: 'np.ndarray', b: 'np.ndarray') -> 'float'

Mean absolute error between two arrays.

Parameters

ParameterTypeDefaultDescription
andarrayFirst array of values.
bndarraySecond array of values (same length as a).

Returns

The mean absolute error.

Example

import numpy as np
from sportsdataverse._common.metrics import mae
mae(np.array([1.0, 2.0]), np.array([1.5, 2.5]))

moneyline_pair_prob​

moneyline_pair_prob(home_price: 'float', away_price: 'float', method: 'str' = 'multiplicative') -> 'float'

Vig-removed home win probability from a two-way American moneyline pair.

Parameters

ParameterTypeDefaultDescription
home_pricefloatAmerican price on the home side.
away_pricefloatAmerican price on the away side.
methodstr'multiplicative'"multiplicative" (default) or "shin".

Returns

The devigged home win probability.

Raises

ExceptionDescription
ValueErrorIf method is not recognized.

Example

from sportsdataverse.wexp.market import moneyline_pair_prob
moneyline_pair_prob(-150, 130)

net_vintages_view​

net_vintages_view(vintages: 'pl.DataFrame', *, scale: 'float' = 1.0, hfa: 'float' = 0.0, st_weight: 'float' = 0.0, net_col: 'str' = 'adj_net') -> 'pl.DataFrame'

Adapt a net-rating vintage table to the ratings_predictor contract.

For tables like load_nfl_ratings_weekly (one adj_net per team per vintage): expected margin becomes scale * (net_h - net_a) + hfa via off_coef = scale*net, def_coef = -scale*net, intercept = 0. Under the isotonic map scale is irrelevant (monotone); it matters only for margin_normal. Keys are normalized to the store contract (season Int32, team_id Utf8).

Parameters

ParameterTypeDefaultDescription
vintagesDataFrameFrame with season, as_of_week, team_id, adj_net.
scalefloat1.0Margin points per unit of net-rating difference (fit on the tune window; a tunable in the variant hash).
hfafloat0.0Home-field advantage in margin points.
st_weightfloat0.0Weight on adj_st_epa added to the net (adj_net excludes special teams; 0 = ignore ST).
net_colstr'adj_net'The net-rating column ("adj_net" for the A3 EPA core; "fei_net" on the CFB vintages for the A5 FEI core).

Returns

A vintage table registrable on ~sportsdataverse.wexp.store.VintageStore.

col_nametypedescription
seasonInt32Season of the vintage (Int32).
as_of_weekInt32The input table's as_of_week, passed through; the view does not check which games it was built from.
team_idStringThe input table's team_id, as text.
off_coefFloat64scale times the team's net rating, so expected margin is scale times the net difference plus hfa.
def_coefFloat64Minus scale times the team's net rating.
interceptFloat64Always 0.0; the view folds the expected margin into off_coef, def_coef and hfa.
hfaFloat64The hfa argument, the same on every row.
lamFloat64The input table's lam stamp, passed through when present.
capFloat64The input table's cap stamp, passed through when present; ratings_predictor checks it against the variant's cap.
close_filterFloat64The input table's close_filter stamp, passed through when present.

Example

from sportsdataverse.nfl import load_nfl_ratings_weekly
from sportsdataverse.wexp.engines import net_vintages_view
from sportsdataverse.wexp.store import VintageStore
store = VintageStore()
store.register("epa", net_vintages_view(load_nfl_ratings_weekly(seasons=[2024]),
scale=24.0, hfa=2.3), entity_key="team_id")

nfl_market_oracle_from_schedule​

nfl_market_oracle_from_schedule(schedule: 'pl.DataFrame', *, sigma: 'float' = 13.45, blend_weight: 'float' = 0.7) -> 'pl.DataFrame'

Build the NFL market oracle from an nflverse schedule frame.

Parameters

ParameterTypeDefaultDescription
scheduleDataFrameFrame from load_nfl_schedule (needs game_id, season, week, game_type, teams, result, spread_line, total_line, home/away_moneyline).
sigmafloat13.45Margin SD for the spread->prob normal link.
blend_weightfloat0.7Spread weight in the spread/ML logit blend.

Returns

The oracle frame per the module contract (spread_open all null — nflverse holds closing lines only).

col_nametypedescription
leagueStringLeague of the game, "nfl" or "cfb".
game_idStringGame id as text (nflverse game_id for the NFL, ESPN game id for college football).
seasonInt32Season of the game.
weekInt32Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them).
season_typeStringSeason type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football).
home_teamStringHome team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football).
away_teamStringAway team, in the same form as home_team.
home_team_idStringHome team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football).
away_team_idStringAway team id as text, in the same form as home_team_id.
neutral_siteBooleanWhether the game was played at a neutral site (no home-field advantage applied).
fbs_vs_fbsBooleanWhether both teams are FBS (always true for the NFL).
home_marginFloat64Final home score minus away score; null for an unplayed game.
home_winInt81 when the home team won, 0 when it lost, null on a tie or an unplayed game.
spread_closeFloat64Closing spread as the expected home margin (positive = home favored).
total_closeFloat64Closing over/under total.
ml_home_closeFloat64Closing home moneyline (American odds).
ml_away_closeFloat64Closing away moneyline (American odds).
spread_openFloat64Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021).
p_close_spreadFloat64Home win probability from the closing spread through a normal link on the margin SD.
p_close_mlFloat64Vig-removed home win probability from the closing moneylines.
p_closeFloat64Market home win probability, the logit-space blend of p_close_spread and p_close_ml weighted by blend_weight (default 0.7 on the spread) where both exist, else whichever exists.

Example

from sportsdataverse.nfl import load_nfl_schedule
from sportsdataverse.wexp.oracle_market import nfl_market_oracle_from_schedule
oracle = nfl_market_oracle_from_schedule(load_nfl_schedule([2023]))

postgame_we​

postgame_we(drives: 'pl.DataFrame', games: 'pl.DataFrame', *, method: 'str' = 'analytic', n_boot: 'int' = 2000, seed: 'Optional[int]' = 0) -> 'pl.DataFrame'

Deserved-win probability per game from per-drive EP deltas.

Parameters

ParameterTypeDefaultDescription
drivesDataFramePer-drive frame from ~sportsdataverse.wexp.engines.cfb_drive_deltas (game_id, off, delta; raw Int64 ids).
gamesDataFrameFrame with game_id (Utf8) and home_team_id (Utf8) — the oracle frame works directly.
methodstr'analytic'"analytic" (G3 normal) or "resample" (G2 drive bootstrap).
n_bootint2000Bootstrap draws per game (resample method).
seedOptional[int]0RNG seed for the bootstrap (fixed default: reproducible).

Returns

One row per game with both sides observed: game_id (Utf8), pg_we (home-perspective deserved-win probability), perf_margin (sum of home drive deltas minus away's), n_drives_home / n_drives_away. Games missing a side are dropped.

col_nametypedescription
game_idStringGame id as text.
pg_weFloat64Home team's deserved-win probability from the two sides' per-drive expected-points deltas.
perf_marginFloat64Sum of the home team's drive deltas minus the away team's.
n_drives_homeInt64Home team's drives.
n_drives_awayInt64Away team's drives.

Raises

ExceptionDescription
ValueErrorOn an unknown method.

Example

from sportsdataverse.cfb import load_cfb_pbp
from sportsdataverse.wexp import build_cfb_market_oracle, cfb_drive_deltas, postgame_we
oracle = build_cfb_market_oracle([2024])
drives = cfb_drive_deltas(load_cfb_pbp(seasons=[2024]))
we = postgame_we(drives, oracle)

# Drive bootstrap instead of the normal approximation

we_boot = postgame_we(drives, oracle, method="resample")

prob_from_american​

prob_from_american(price: 'float') -> 'float'

Convert an American moneyline price to its raw implied probability.

Parameters

ParameterTypeDefaultDescription
pricefloatAmerican odds (e.g. -110 or +150). Must be nonzero.

Returns

The implied probability including vig (does not sum to 1 across sides).

Raises

ExceptionDescription
ValueErrorIf price is 0.

Example

from sportsdataverse.wexp.market import prob_from_american
prob_from_american(-110) # 0.5238...

prob_from_decimal​

prob_from_decimal(price: 'float') -> 'float'

Convert a decimal (European) price to its raw implied probability.

Parameters

ParameterTypeDefaultDescription
pricefloatDecimal odds, > 1 (e.g. 1.91).

Returns

The implied probability including vig.

Raises

ExceptionDescription
ValueErrorIf price is not greater than 1.

Example

from sportsdataverse.wexp.market import prob_from_decimal
prob_from_decimal(2.0) # 0.5

ratings_predictor​

ratings_predictor(table: 'str', *, wp_map: 'str' = 'margin_normal', sigma: 'float' = 13.45, iso_min_fit: 'int' = 100, lam: 'Optional[float]' = None, cap: 'Optional[float]' = None, close_filter: 'Optional[float]' = None, join_on: 'tuple[str, str]' = ('home_team', 'away_team')) -> 'WeekPredictor'

Wrap a registered ratings vintage table as a week predictor.

Joins home and away ratings through the store's leak-free join_asof, reconstructs the expected home margin, and maps it to P(home) per the Axis E wp_map. Games where either team lacks a served vintage get a null probability (scored-on-coverage, never imputed).

Parameters

ParameterTypeDefaultDescription
tablestrTable name registered on the store (ridge_margin_vintages schema).
wp_mapstr'margin_normal'"margin_normal" (E2) or "isotonic" (E3, walk-forward refit on history each week).
sigmafloat13.45Margin SD for the normal link.
iso_min_fitint100Minimum history games with a rated margin before the isotonic map will fit; below it the week predicts null.
lamOptional[float]NoneThe ridge penalty the variant hash claims. When given, the predictor refuses (ValueError) a table stamped with a different lam — a store/variant mismatch must error, not write mislabeled leaderboard rows.
capOptional[float]NoneThe Axis B2 response cap the variant claims (None = raw response). Checked BIDIRECTIONALLY against the table's cap stamp when present — a raw variant served from a capped table is just as mislabeled as the reverse.
close_filterOptional[float]NoneThe Axis B4 close-game fit filter the variant claims (None = unfiltered). Same bidirectional stamp check as cap.
join_ontuple[str, str]('home_team', 'away_team')The (home, away) oracle columns matched against the table's team_id. Default team-NAME columns fit tables keyed by name (ridge_margin_vintages; NFL, where the abbr IS the id). Tables keyed by provider id (CFB ratings vintages) need ("home_team_id", "away_team_id") — same dtype either way, so a wrong choice fails as zero matches, which the driver refuses loudly.

Returns

A predictor callable for ~sportsdataverse.wexp.backtest.run_backtest.

Raises

ExceptionDescription
ValueErrorIf wp_map is unknown, or the predictor is invoked without a store.

Example

from sportsdataverse.wexp import VintageStore, build_nfl_market_oracle, ratings_predictor, run_backtest
from sportsdataverse.wexp import ridge_margin_vintages
oracle = build_nfl_market_oracle([2022, 2023])
store = VintageStore()
store.register("ridge", ridge_margin_vintages(oracle, lam=25.0), entity_key="team_id")
probs, rows = run_backtest(oracle, ratings_predictor("ridge"), model_id="ridge_margin", store=store)

response_ridge_vintages​

response_ridge_vintages(responses: 'pl.DataFrame', oracle: 'pl.DataFrame', *, lam: 'float', close_filter: 'Optional[float]' = None, resp_col: 'str' = 'resp') -> 'pl.DataFrame'

Weekly opponent-adjusted ridge on per-team-game responses (off + def).

Joins the responses to the oracle by game_id (walk-normalized week, home flag, final margin), then per (season, week) fits ~sportsdataverse._common.ratings.opponent_adjusted_ridge on that season's rows from strictly earlier weeks — EXCLUSIVE vintages, same convention as ridge_margin_vintages. Each game contributes one row per side, so offense and defense are separately identified; adj_net = off_coef - def_coef is the margin-driving team strength (register the output and serve it through net_vintages_view).

Parameters

ParameterTypeDefaultDescription
responsesDataFrameFrame from cfb_drive_ep_responses (game_id, off_team_id, def_team_id, resp).
oracleDataFrameMarket-oracle frame (contract columns incl. team ids).
lamfloatRidge penalty on the team coefficients.
close_filterOptional[float]NoneAxis B4 — drop games with final |home_margin| > close_filter from the fit (both sides go together).
resp_colstr'resp'Which response to fit ("resp" = raw per-drive delta; "resp_pct" = share of available drive EP).

Returns

Vintage table: season / as_of_week / team_id (Utf8) / off_coef / def_coef / adj_net plus per-vintage intercept / hfa and the lam / close_filter stamps.

col_nametypedescription
team_idStringESPN team id as text.
off_coefFloat64Team's offensive coefficient in the response's units (mean expected points added per drive for "resp", share of available drive expected points for "resp_pct").
def_coefFloat64Team's defensive coefficient in the response's units.
adj_netFloat64off_coef minus def_coef, in the response's units.
seasonInt32Season of the vintage.
as_of_weekInt32Week the vintage is for; it was fit only on games from weeks strictly before it (postseason weeks offset so they come last).
interceptFloat64Fitted intercept of the vintage, the same on every row of it.
hfaFloat64Fitted home-field term of the vintage in the response's units, the same on every row of it.
lamFloat64Ridge penalty the vintage was fit with.
close_filterFloat64Games with a final |home_margin| beyond this were left out of the fit; null when no filter was set.

Example

from sportsdataverse.cfb import load_cfb_pbp
from sportsdataverse.wexp import build_cfb_market_oracle, cfb_drive_ep_responses, response_ridge_vintages
oracle = build_cfb_market_oracle([2024])
rows = cfb_drive_ep_responses(load_cfb_pbp(seasons=[2024]))
vint = response_ridge_vintages(rows, oracle, lam=1.0)