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
| Parameter | Type | Default | Description |
|---|---|---|---|
k | float | 20.0 | Update step size. |
z | float | 400.0 | Logistic scale (p = 1/(10^(-diff/z)+1)). |
hfa | float | 65.0 | Home-field advantage in rating points (0 applied at neutral sites). |
init | float | 1500.0 | Rating for a team's first-ever appearance. |
carryover | float | 0.67 | Fraction of (rating - init) kept across seasons (0 = full reset, 1 = no reversion; seed ~0.53). |
mov_mult | bool | True | Apply 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
| Parameter | Type | Default | Description |
|---|---|---|---|
sigma_w | float | 0.9 | Week-to-week strength innovation SD (RESEARCH seed ~0.9). |
sigma_s | float | 2.35 | Season-to-season innovation SD (seed ~2.35). |
season_shrink | float | 0.82 | AR(1) shrink toward the league mean at each season boundary (the model's own carryover; 0 = full reset). |
sigma_y | float | 13.45 | Observation noise SD on the game margin. |
hfa | float | 2.3 | Home-field advantage in margin points (0 at neutral sites). |
init_sd | float | 5.0 | Prior 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
| Parameter | Type | Default | Description |
|---|---|---|---|
core | str | Axis A strength core. | |
response | str | Axis B response weighting (EPA-family cores only). | |
opponent_adjust | str | Axis C adjustment scheme (EPA-family cores only). | |
prior | str | Axis D preseason prior. | |
wp_map | str | Axis E rating->WP mapping. | |
hfa | str | Axis F HFA treatment. | |
params | tuple[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
| Exception | Description |
|---|---|
ValueError | An 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
| Parameter | Type | Default | Description |
|---|---|---|---|
games | DataFrame | Frame with season, week_col, and the left join key. | |
name | str | Registered table name. | |
on | dict[str, str] | Single-entry mapping {games_key: table_entity_key}. | |
prefix | str | '' | Prefix applied to the joined feature columns. |
week_col | str | '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
| Exception | Description |
|---|---|
KeyError | If name is not registered. |
ValueError | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | Table name. | |
frame | DataFrame | Frame 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_key | str | The entity column (e.g. "team_id"). | |
week_semantics | Literal['as_of', 'through'] | 'as_of' | "as_of" (default) or "through". |
Raises
| Exception | Description |
|---|---|
ValueError | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | Table 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
| Parameter | Type | Default | Description |
|---|---|---|---|
frame | DataFrame | Result rows (from result_rows). | |
path | str | Path | Leaderboard parquet path (created on first call). |
Raises
| Exception | Description |
|---|---|
ValueError | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
oracle | DataFrame | Frame from an oracle builder (module contract columns). | |
elo | DataFrame | None | None | Optional output of sportsdataverse.wexp.elo.elo_ratings (joined on game_id). |
home_rate | float | None | None | Home-rule probability; defaults to the league seed in BASELINE_HOME_RATE. |
sigma | float | None | None | Margin SD for the open-spread link; defaults per league. |
Returns
oracle with the baseline p_* columns appended.
| col_name | type | description |
|---|---|---|
league | String | League of the game, "nfl" or "cfb". |
game_id | String | Game id as text (nflverse game_id for the NFL, ESPN game id for college football). |
season | Int32 | Season of the game. |
week | Int32 | Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them). |
season_type | String | Season type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football). |
home_team | String | Home team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football). |
away_team | String | Away team, in the same form as home_team. |
home_team_id | String | Home team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football). |
away_team_id | String | Away team id as text, in the same form as home_team_id. |
neutral_site | Boolean | Whether the game was played at a neutral site (no home-field advantage applied). |
fbs_vs_fbs | Boolean | Whether both teams are FBS (always true for the NFL). |
home_margin | Float64 | Final home score minus away score; null for an unplayed game. |
home_win | Int8 | 1 when the home team won, 0 when it lost, null on a tie or an unplayed game. |
spread_close | Float64 | Closing spread as the expected home margin (positive = home favored). |
total_close | Float64 | Closing over/under total. |
ml_home_close | Float64 | Closing home moneyline (American odds). |
ml_away_close | Float64 | Closing away moneyline (American odds). |
spread_open | Float64 | Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021). |
p_close_spread | Float64 | Home win probability from the closing spread through a normal link on the margin SD. |
p_close_ml | Float64 | Vig-removed home win probability from the closing moneylines. |
p_close | Float64 | Market 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_flip | Float64 | Coin-flip baseline, 0.5 for every game. |
p_home_rule | Float64 | Home-rule baseline, the league's constant home win rate (0.5 at neutral sites). |
p_market_close | Float64 | Closing-market baseline, equal to p_close. |
p_market_open | Float64 | Opening-market baseline, the normal link on spread_open; null where no open exists. |
p_elo | Float64 | Elo baseline, the elo_ratings p_home joined on game_id. |
Raises
| Exception | Description |
|---|---|
ValueError | elo'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
| Parameter | Type | Default | Description |
|---|---|---|---|
y_true | ndarray | Array of binary outcomes (0/1). | |
p_pred | ndarray | Array 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
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | list[int] | Seasons to include. | |
line_odds_path | str | Path | None | None | Optional 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_name | type | description |
|---|---|---|
league | String | League of the game, "nfl" or "cfb". |
game_id | String | Game id as text (nflverse game_id for the NFL, ESPN game id for college football). |
season | Int32 | Season of the game. |
week | Int32 | Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them). |
season_type | String | Season type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football). |
home_team | String | Home team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football). |
away_team | String | Away team, in the same form as home_team. |
home_team_id | String | Home team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football). |
away_team_id | String | Away team id as text, in the same form as home_team_id. |
neutral_site | Boolean | Whether the game was played at a neutral site (no home-field advantage applied). |
fbs_vs_fbs | Boolean | Whether both teams are FBS (always true for the NFL). |
home_margin | Float64 | Final home score minus away score; null for an unplayed game. |
home_win | Int8 | 1 when the home team won, 0 when it lost, null on a tie or an unplayed game. |
spread_close | Float64 | Closing spread as the expected home margin (positive = home favored). |
total_close | Float64 | Closing over/under total. |
ml_home_close | Float64 | Closing home moneyline (American odds). |
ml_away_close | Float64 | Closing away moneyline (American odds). |
spread_open | Float64 | Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021). |
p_close_spread | Float64 | Home win probability from the closing spread through a normal link on the margin SD. |
p_close_ml | Float64 | Vig-removed home win probability from the closing moneylines. |
p_close | Float64 | Market 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
| Parameter | Type | Default | Description |
|---|---|---|---|
seasons | list[int] | Seasons to include. |
Returns
The oracle frame.
| col_name | type | description |
|---|---|---|
league | String | League of the game, "nfl" or "cfb". |
game_id | String | Game id as text (nflverse game_id for the NFL, ESPN game id for college football). |
season | Int32 | Season of the game. |
week | Int32 | Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them). |
season_type | String | Season type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football). |
home_team | String | Home team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football). |
away_team | String | Away team, in the same form as home_team. |
home_team_id | String | Home team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football). |
away_team_id | String | Away team id as text, in the same form as home_team_id. |
neutral_site | Boolean | Whether the game was played at a neutral site (no home-field advantage applied). |
fbs_vs_fbs | Boolean | Whether both teams are FBS (always true for the NFL). |
home_margin | Float64 | Final home score minus away score; null for an unplayed game. |
home_win | Int8 | 1 when the home team won, 0 when it lost, null on a tie or an unplayed game. |
spread_close | Float64 | Closing spread as the expected home margin (positive = home favored). |
total_close | Float64 | Closing over/under total. |
ml_home_close | Float64 | Closing home moneyline (American odds). |
ml_away_close | Float64 | Closing away moneyline (American odds). |
spread_open | Float64 | Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021). |
p_close_spread | Float64 | Home win probability from the closing spread through a normal link on the margin SD. |
p_close_ml | Float64 | Vig-removed home win probability from the closing moneylines. |
p_close | Float64 | Market 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
| Parameter | Type | Default | Description |
|---|---|---|---|
config | VariantConfig | The variant to build. | |
table | str | 'ridge' | Ratings vintage table name (EPA-family cores). |
sigma | float | 13.45 | Default margin SD for the normal link (sigma in config.params wins). |
season_priors | Optional[DataFrame] | None | Continuity-prior table (from cfb_continuity_shifts); REQUIRED when prior="carryover_continuity" and ignored otherwise. |
variance_events | Optional[DataFrame] | None |
Returns
A predictor callable for ~sportsdataverse.wexp.backtest.run_backtest.
Raises
| Exception | Description |
|---|---|
NotImplementedError | For 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
| Parameter | Type | Default | Description |
|---|---|---|---|
y_true | ndarray | Array of binary outcomes (0/1). | |
p_pred | ndarray | Array of predicted probabilities in [0, 1]. | |
n_bins | int | 10 | Number 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_name | type | description |
|---|---|---|
bin_mid | Float64 | Midpoint of the equal-width predicted-probability bin (0.05, 0.15, ... with the default 10 bins). |
mean_pred | Float64 | Mean predicted probability of the rows in the bin. |
mean_actual | Float64 | Observed outcome rate of the rows in the bin; a calibrated model has it close to mean_pred. |
n | UInt32 | Rows 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
| Parameter | Type | Default | Description |
|---|---|---|---|
returning | DataFrame | season, team_id, overall_returning (0-1). | |
qb_continuity | Optional[DataFrame] | None | Optional season, team_id, qb_continuity (0/1). Missing teams contribute the neutral 0.5. |
hc_continuity | Optional[DataFrame] | None | Optional 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). |
base | float | 0.35 | Weight floor for a team with zero continuity evidence. |
w_returning | float | 0.35 | Weight contribution of returning production. |
w_qb | float | 0.2 | Weight contribution of QB continuity. |
w_hc | float | 0.1 | Weight contribution of head-coach continuity. |
last_week | int | 4 | Final 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_name | type | description |
|---|---|---|
season | Int32 | Season the weight applies to (the season being predicted, whose prior season's metrics are carried). |
team_id | String | Team id as text (the ESPN id for college football). |
week | Int32 | Week of the season, 1 through last_week + 1. |
carry_weight | Float64 | Share 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
| Exception | Description |
|---|---|
ValueError | A 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
| Parameter | Type | Default | Description |
|---|---|---|---|
oracle | DataFrame | Market-oracle frame (contract columns incl. team ids). | |
talent | DataFrame | load_cfb_team_talent frame (season, team_id, talent_composite). | |
returning | DataFrame | load_cfb_returning_production frame (season, team_id, overall_returning). | |
beta_talent | float | 0.0 | Rating points per talent z-score. |
beta_returning | float | 0.0 | Rating 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_name | type | description |
|---|---|---|
season | Int32 | Season the prior applies to; built from preseason talent and returning production only. |
team | String | Team display name, matched to the oracle's home_team / away_team. |
prior_shift | Float64 | Elo 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
| Exception | Description |
|---|---|
ValueError | The 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_MARGINband; 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
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | Play 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_name | type | description |
|---|---|---|
game_id | Int64 | ESPN game id of the drive's game, as the play-by-play carries it. |
drive.id | String | ESPN drive id; with game_id it keys the drive. |
off | Int64 | ESPN id of the team on offense for the drive. |
deft | Int64 | ESPN id of the team on defense for the drive. |
delta | Float64 | Expected points the offense added over the drive, the sum of its plays' EPA (perspective-corrected). |
start_ep | Float64 | Expected points at the drive's first snap. |
period | Int64 | Quarter the drive started in. |
margin_start | Int64 | Offense's score margin at the drive's first snap. |
plays | Int64 | Plays in the drive that carry EPA, EP_start, both team ids and a drive id. |
pct | Float64 | Share of the drive's available expected points it captured, delta / (7 - start_ep), with the denominator floored at 0.5. |
garbage | Boolean | True when the drive started in garbage time, |margin_start| beyond the per-quarter band (overtime uses the fourth quarter's). |
clock_kill | Boolean | True for a half's last drive of 3 or fewer plays that gained no expected points (a kneel-down signature). |
Raises
| Exception | Description |
|---|---|
ValueError | A 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.availableis 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
| Parameter | Type | Default | Description |
|---|---|---|---|
pbp | DataFrame | Play 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_name | type | description |
|---|---|---|
game_id | String | ESPN game id as text. |
off_team_id | String | ESPN id (as text) of the offense the row rates. |
def_team_id | String | ESPN id (as text) of the defense it faced. |
resp | Float64 | Mean expected points added per drive by this offense in this game. |
resp_pct | Float64 | Mean share of available drive expected points captured, delta / (7 - start_ep) averaged over the offense's drives. |
drives | Int64 | Drives the offense had in the game. |
Raises
| Exception | Description |
|---|---|
ValueError | As 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
| Parameter | Type | Default | Description |
|---|---|---|---|
line_odds | DataFrame | The cfb_line_odds frame (per-side per-book rows). | |
schedules | DataFrame | ESPN CFB schedules frame (game_id, season, week, season_type, home/away names + scores) for outcomes. | |
sigma | float | 15.5 | Margin SD for the spread->prob normal link. |
blend_weight | float | 0.7 | Spread weight in the spread/ML logit blend. |
Returns
The oracle frame per the module contract.
| col_name | type | description |
|---|---|---|
league | String | League of the game, "nfl" or "cfb". |
game_id | String | Game id as text (nflverse game_id for the NFL, ESPN game id for college football). |
season | Int32 | Season of the game. |
week | Int32 | Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them). |
season_type | String | Season type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football). |
home_team | String | Home team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football). |
away_team | String | Away team, in the same form as home_team. |
home_team_id | String | Home team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football). |
away_team_id | String | Away team id as text, in the same form as home_team_id. |
neutral_site | Boolean | Whether the game was played at a neutral site (no home-field advantage applied). |
fbs_vs_fbs | Boolean | Whether both teams are FBS (always true for the NFL). |
home_margin | Float64 | Final home score minus away score; null for an unplayed game. |
home_win | Int8 | 1 when the home team won, 0 when it lost, null on a tie or an unplayed game. |
spread_close | Float64 | Closing spread as the expected home margin (positive = home favored). |
total_close | Float64 | Closing over/under total. |
ml_home_close | Float64 | Closing home moneyline (American odds). |
ml_away_close | Float64 | Closing away moneyline (American odds). |
spread_open | Float64 | Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021). |
p_close_spread | Float64 | Home win probability from the closing spread through a normal link on the margin SD. |
p_close_ml | Float64 | Vig-removed home win probability from the closing moneylines. |
p_close | Float64 | Market 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
| Parameter | Type | Default | Description |
|---|---|---|---|
p_model | ndarray | Model home win probabilities. | |
p_bet | ndarray | Vig-removed home probabilities at bet time (open or close). | |
p_close | ndarray | Vig-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
| Parameter | Type | Default | Description |
|---|---|---|---|
p_raw | Sequence[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
| Parameter | Type | Default | Description |
|---|---|---|---|
p_raw | Sequence[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
| Parameter | Type | Default | Description |
|---|---|---|---|
y_true | ndarray | Array of binary outcomes (0/1). | |
p_pred | ndarray | Array of predicted probabilities in [0, 1]. | |
n_bins | int | 10 | Number 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
| Parameter | Type | Default | Description |
|---|---|---|---|
config | EloConfig | EloConfig(k=20.0, z=400.0, hfa=65.0, init=1500.0, carryover=0.67, mov_mult=True) | Elo tunables. |
season_priors | Optional[DataFrame] | None | Optional (season, team, prior_shift) continuity table forwarded to ~sportsdataverse.wexp.elo.elo_ratings (Axis D3/D4). |
hfa_by_season | Optional[dict[int, float]] | None | Optional 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
| Parameter | Type | Default | Description |
|---|---|---|---|
games | DataFrame | Frame with game_id, season, week, home_team, away_team, neutral_site, home_margin. | |
config | EloConfig | EloConfig(k=20.0, z=400.0, hfa=65.0, init=1500.0, carryover=0.67, mov_mult=True) | Tunable parameters. |
season_priors | Optional[DataFrame] | None | Optional 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_season | Optional[dict[int, float]] | None | Optional 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_name | type | description |
|---|---|---|
league | String | League of the game, "nfl" or "cfb". |
game_id | String | Game id as text (nflverse game_id for the NFL, ESPN game id for college football). |
season | Int32 | Season of the game. |
week | Int32 | Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them). |
season_type | String | Season type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football). |
home_team | String | Home team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football). |
away_team | String | Away team, in the same form as home_team. |
home_team_id | String | Home team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football). |
away_team_id | String | Away team id as text, in the same form as home_team_id. |
neutral_site | Boolean | Whether the game was played at a neutral site (no home-field advantage applied). |
fbs_vs_fbs | Boolean | Whether both teams are FBS (always true for the NFL). |
home_margin | Float64 | Final home score minus away score; null for an unplayed game. |
home_win | Int8 | 1 when the home team won, 0 when it lost, null on a tie or an unplayed game. |
spread_close | Float64 | Closing spread as the expected home margin (positive = home favored). |
total_close | Float64 | Closing over/under total. |
ml_home_close | Float64 | Closing home moneyline (American odds). |
ml_away_close | Float64 | Closing away moneyline (American odds). |
spread_open | Float64 | Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021). |
p_close_spread | Float64 | Home win probability from the closing spread through a normal link on the margin SD. |
p_close_ml | Float64 | Vig-removed home win probability from the closing moneylines. |
p_close | Float64 | Market 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_pre | Float64 | Home team's Elo rating before the game (never includes the game's own result). |
away_elo_pre | Float64 | Away team's Elo rating before the game. |
p_home | Float64 | Elo home win probability from the pre-game ratings and home-field advantage. |
Raises
| Exception | Description |
|---|---|
ValueError | season_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
| Parameter | Type | Default | Description |
|---|---|---|---|
y_true | ndarray | Array of binary home-win outcomes (0/1). | |
p_pred | ndarray | Array 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_name | type | description |
|---|---|---|
bucket | String | The 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_pred | Float64 | Mean predicted win probability of the favorites in the band. |
mean_actual | Float64 | Share of those favorites that won. |
n | UInt32 | Games in the band. Empty bands emit no row. |
abs_gap | Float64 | Absolute 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
| Parameter | Type | Default | Description |
|---|---|---|---|
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) | Tunable parameters. |
season_priors | Optional[DataFrame] | None | Optional 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_events | Optional[DataFrame] | None | Optional (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
| Exception | Description |
|---|---|
ValueError | season_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
| Parameter | Type | Default | Description |
|---|---|---|---|
y_true | ndarray | Array of binary outcomes (0/1). | |
p_pred | ndarray | Array of predicted probabilities in [0, 1]. | |
eps | float | 1e-15 | Clipping 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
| Parameter | Type | Default | Description |
|---|---|---|---|
p_a | float | First probability in (0, 1). | |
p_b | float | Second probability in (0, 1). | |
weight_a | float | 0.7 | Weight 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
| Parameter | Type | Default | Description |
|---|---|---|---|
a | ndarray | First array of values. | |
b | ndarray | Second 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
| Parameter | Type | Default | Description |
|---|---|---|---|
home_price | float | American price on the home side. | |
away_price | float | American price on the away side. | |
method | str | 'multiplicative' | "multiplicative" (default) or "shin". |
Returns
The devigged home win probability.
Raises
| Exception | Description |
|---|---|
ValueError | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
vintages | DataFrame | Frame with season, as_of_week, team_id, adj_net. | |
scale | float | 1.0 | Margin points per unit of net-rating difference (fit on the tune window; a tunable in the variant hash). |
hfa | float | 0.0 | Home-field advantage in margin points. |
st_weight | float | 0.0 | Weight on adj_st_epa added to the net (adj_net excludes special teams; 0 = ignore ST). |
net_col | str | '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_name | type | description |
|---|---|---|
season | Int32 | Season of the vintage (Int32). |
as_of_week | Int32 | The input table's as_of_week, passed through; the view does not check which games it was built from. |
team_id | String | The input table's team_id, as text. |
off_coef | Float64 | scale times the team's net rating, so expected margin is scale times the net difference plus hfa. |
def_coef | Float64 | Minus scale times the team's net rating. |
intercept | Float64 | Always 0.0; the view folds the expected margin into off_coef, def_coef and hfa. |
hfa | Float64 | The hfa argument, the same on every row. |
lam | Float64 | The input table's lam stamp, passed through when present. |
cap | Float64 | The input table's cap stamp, passed through when present; ratings_predictor checks it against the variant's cap. |
close_filter | Float64 | The 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
| Parameter | Type | Default | Description |
|---|---|---|---|
schedule | DataFrame | Frame from load_nfl_schedule (needs game_id, season, week, game_type, teams, result, spread_line, total_line, home/away_moneyline). | |
sigma | float | 13.45 | Margin SD for the spread->prob normal link. |
blend_weight | float | 0.7 | Spread 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_name | type | description |
|---|---|---|
league | String | League of the game, "nfl" or "cfb". |
game_id | String | Game id as text (nflverse game_id for the NFL, ESPN game id for college football). |
season | Int32 | Season of the game. |
week | Int32 | Week of the game as the schedule numbers it (college football postseason weeks restart at 1; the walk-forward driver offsets them). |
season_type | String | Season type label from the schedule (nflverse game_type such as "REG" or "WC"; ESPN season type for college football). |
home_team | String | Home team (the nflverse abbreviation for the NFL, the ESPN team name, such as "Alabama", for college football). |
away_team | String | Away team, in the same form as home_team. |
home_team_id | String | Home team id as text, the join key for feature tables (the nflverse abbreviation for the NFL, the ESPN id for college football). |
away_team_id | String | Away team id as text, in the same form as home_team_id. |
neutral_site | Boolean | Whether the game was played at a neutral site (no home-field advantage applied). |
fbs_vs_fbs | Boolean | Whether both teams are FBS (always true for the NFL). |
home_margin | Float64 | Final home score minus away score; null for an unplayed game. |
home_win | Int8 | 1 when the home team won, 0 when it lost, null on a tie or an unplayed game. |
spread_close | Float64 | Closing spread as the expected home margin (positive = home favored). |
total_close | Float64 | Closing over/under total. |
ml_home_close | Float64 | Closing home moneyline (American odds). |
ml_away_close | Float64 | Closing away moneyline (American odds). |
spread_open | Float64 | Opening spread as the expected home margin; null where the source holds no open (every NFL game, thin college football coverage before 2021). |
p_close_spread | Float64 | Home win probability from the closing spread through a normal link on the margin SD. |
p_close_ml | Float64 | Vig-removed home win probability from the closing moneylines. |
p_close | Float64 | Market 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
| Parameter | Type | Default | Description |
|---|---|---|---|
drives | DataFrame | Per-drive frame from ~sportsdataverse.wexp.engines.cfb_drive_deltas (game_id, off, delta; raw Int64 ids). | |
games | DataFrame | Frame with game_id (Utf8) and home_team_id (Utf8) — the oracle frame works directly. | |
method | str | 'analytic' | "analytic" (G3 normal) or "resample" (G2 drive bootstrap). |
n_boot | int | 2000 | Bootstrap draws per game (resample method). |
seed | Optional[int] | 0 | RNG 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_name | type | description |
|---|---|---|
game_id | String | Game id as text. |
pg_we | Float64 | Home team's deserved-win probability from the two sides' per-drive expected-points deltas. |
perf_margin | Float64 | Sum of the home team's drive deltas minus the away team's. |
n_drives_home | Int64 | Home team's drives. |
n_drives_away | Int64 | Away team's drives. |
Raises
| Exception | Description |
|---|---|
ValueError | On 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
| Parameter | Type | Default | Description |
|---|---|---|---|
price | float | American odds (e.g. -110 or +150). Must be nonzero. |
Returns
The implied probability including vig (does not sum to 1 across sides).
Raises
| Exception | Description |
|---|---|
ValueError | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
price | float | Decimal odds, > 1 (e.g. 1.91). |
Returns
The implied probability including vig.
Raises
| Exception | Description |
|---|---|
ValueError | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
table | str | Table name registered on the store (ridge_margin_vintages schema). | |
wp_map | str | 'margin_normal' | "margin_normal" (E2) or "isotonic" (E3, walk-forward refit on history each week). |
sigma | float | 13.45 | Margin SD for the normal link. |
iso_min_fit | int | 100 | Minimum history games with a rated margin before the isotonic map will fit; below it the week predicts null. |
lam | Optional[float] | None | The 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. |
cap | Optional[float] | None | The 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_filter | Optional[float] | None | The Axis B4 close-game fit filter the variant claims (None = unfiltered). Same bidirectional stamp check as cap. |
join_on | tuple[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
| Exception | Description |
|---|---|
ValueError | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
responses | DataFrame | Frame from cfb_drive_ep_responses (game_id, off_team_id, def_team_id, resp). | |
oracle | DataFrame | Market-oracle frame (contract columns incl. team ids). | |
lam | float | Ridge penalty on the team coefficients. | |
close_filter | Optional[float] | None | Axis B4 — drop games with final |home_margin| > close_filter from the fit (both sides go together). |
resp_col | str | '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_name | type | description |
|---|---|---|
team_id | String | ESPN team id as text. |
off_coef | Float64 | Team'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_coef | Float64 | Team's defensive coefficient in the response's units. |
adj_net | Float64 | off_coef minus def_coef, in the response's units. |
season | Int32 | Season of the vintage. |
as_of_week | Int32 | Week the vintage is for; it was fit only on games from weeks strictly before it (postseason weeks offset so they come last). |
intercept | Float64 | Fitted intercept of the vintage, the same on every row of it. |
hfa | Float64 | Fitted home-field term of the vintage in the response's units, the same on every row of it. |
lam | Float64 | Ridge penalty the vintage was fit with. |
close_filter | Float64 | Games 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)