Win expectancy (wexp) — Models and calculators: result_rows–winner_accuracy
result_rows
result_rows(*, league: 'str', model_id: 'str', variant_hash: 'str', vintage_policy: 'str', season: 'int', week_slice: 'str', era: 'str', metrics: 'dict[str, float]', n: 'int') -> 'pl.DataFrame'
Build long-format result rows (one row per metric) for the leaderboard.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
league | str | League slug ("nfl" / "cfb"). | |
model_id | str | Stable model family identifier. | |
variant_hash | str | Stable hash of the full variant config. | |
vintage_policy | str | Knowledge-cycle vintage ("V0".."V3"). | |
season | int | Season being scored. | |
week_slice | str | Game slice label ("all", "wk1-3", ...). | |
era | str | Era label ("covid", "post2017", ...). | |
metrics | dict[str, float] | Mapping of metric name to value. | |
n | int | Number of games scored. |
Returns
A polars.DataFrame matching RESULT_SCHEMA.
| col_name | type | description |
|---|---|---|
league | String | League slug ("nfl" or "cfb"). |
model_id | String | Model identifier (a baseline's column name without the p_ prefix for score_baselines). |
variant_hash | String | Stable hash of the full variant configuration. |
vintage_policy | String | Knowledge-cycle vintage label of the run. |
season | Int32 | Season scored; -1 for the row pooled over every season. |
week_slice | String | Game-slice label ("all", "wk1-3", ...; "lined" for the rows scored only on games with a closing market line). |
era | String | Era label the run was scored under ("all" unless the caller passes one). |
metric | String | Metric name (brier, log_loss, winner_accuracy, ece). |
value | Float64 | The metric's value for this model, season and slice. |
n | Int64 | Games scored (ties and null probabilities dropped). |
Example
from sportsdataverse.wexp.scoring import result_rows
result_rows(league="nfl", model_id="elo", variant_hash="a1",
vintage_policy="V2", season=2023, week_slice="all",
era="modern", metrics={"brier": 0.21}, n=272)
ridge_margin_vintages
ridge_margin_vintages(oracle: 'pl.DataFrame', *, lam: 'float', resp_col: 'str' = 'home_margin', cap: 'Optional[float]' = None, close_filter: 'Optional[float]' = None, history_seasons: 'int' = 0, season_decay: 'float' = 0.5) -> 'pl.DataFrame'
Build per-week opponent-adjusted ridge rating vintages from an oracle frame.
For every (season, week) present, fits the ridge on that season's
completed games in strictly earlier (walk-normalized) weeks — so the
vintage at as_of_week = W satisfies the store's EXCLUSIVE
convention by construction. Weeks with no prior completed games (week
- emit no rows. Neutral-site games carry no HFA indicator in the fit.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
oracle | DataFrame | Market-oracle frame (module contract columns). | |
lam | float | Ridge penalty on the team coefficients. | |
resp_col | str | 'home_margin' | Response column (default "home_margin"; a team-game EPA margin column slots in unchanged). |
cap | Optional[float] | None | Axis B2 capped response — clip the response to [-cap, cap] before the fit (blowout damping). None = raw (B1). |
close_filter | Optional[float] | None | Axis B4 garbage filter at game granularity — DROP games with |response| > close_filter from the fit entirely (both mirrored rows, so offense and defense sides go together), rating teams on competitive games only. Distinct from cap: a filtered blowout contributes nothing; a capped one still contributes at the cap. None = keep all. |
history_seasons | int | 0 | Prior seasons folded into each fit (default 0 = the within-season-only convention, which rates week 2 off a single week of games). Prior-season games enter down-weighted by season_decay ** seasons_back, applied as integer row replication of the CURRENT season (weight 1 -> the current season repeats 1/season_decay ** history_seasons times), so the shared unweighted solver is reused unchanged. |
season_decay | float | 0.5 | Per-season-back weight for history_seasons (0.5 = last season counts half). |
Returns
A vintage table — season / as_of_week / team_id (Utf8) / off_coef / def_coef plus the per-vintage intercept and hfa scalars denormalized onto every row. Expected margin for (home h, away a): h.off_coef + a.def_coef + intercept [+ hfa].
| col_name | type | description |
|---|---|---|
season | Int32 | Season of the vintage. |
as_of_week | Int32 | Week the vintage is for; its current-season games all come from weeks strictly before it (history_seasons can add earlier seasons' games, from any week). |
team_id | String | The team as the oracle's home_team / away_team names it (the nflverse abbreviation for the NFL, the team name, not the ESPN id, for college football). |
off_coef | Float64 | Team's offensive coefficient in margin points. |
def_coef | Float64 | Team's defensive coefficient in margin points; expected home margin is home off_coef + away def_coef + intercept (+ hfa). |
intercept | Float64 | Fitted intercept of the vintage, the same on every row of it. |
hfa | Float64 | Home-field advantage in margin points for the vintage, the same on every row of it. |
lam | Float64 | Ridge penalty the vintage was fit with. |
cap | Float64 | Response cap applied before the fit (|response| clipped to it); null when no cap was set. |
close_filter | Float64 | Games with |response| beyond this were left out of the fit; null when no filter was set. |
Example
from sportsdataverse.wexp import VintageStore, build_nfl_market_oracle, ridge_margin_vintages
oracle = build_nfl_market_oracle([2022, 2023])
store = VintageStore()
store.register("ridge", ridge_margin_vintages(oracle, lam=100.0), entity_key="team_id")
run_backtest
run_backtest(oracle: 'pl.DataFrame', predict: 'WeekPredictor', *, model_id: 'str', variant: 'Optional[VariantConfig]' = None, store: 'Optional[VintageStore]' = None, vintage_policy: 'str' = 'observed', week_slice: 'str' = 'all', era: 'str' = 'all', path: 'Optional[Union[str, Path]]' = None) -> 'tuple[pl.DataFrame, pl.DataFrame]'
Walk an oracle frame forward week by week and score the predictions.
For each (season, week) in walk order the engine receives
(history, slate, store) — history holds only completed games
strictly earlier in the walk; the slate has OUTCOME_COLUMNS
removed and its week postseason-normalized. Predictions are
validated (length, range) and scored per season + pooled via
~sportsdataverse.wexp.scoring.score_probs, keyed by
variant_hash(variant).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
oracle | DataFrame | Market-oracle frame (one row per game, unique game_id). | |
predict | WeekPredictor | Week predictor returning one P(home) per slate row (nulls allowed for games the engine declines to rate). | |
model_id | str | Stable model family identifier for the result rows. | |
variant | Optional[VariantConfig] | None | Variant config; its hash keys the result rows ("none" when omitted). |
store | Optional[VintageStore] | None | Vintage feature store handed to the engine each week. |
vintage_policy | str | 'observed' | Vintage label for the result rows. |
week_slice | str | 'all' | Game-slice label. |
era | str | 'all' | Era label. |
path | Optional[Union[str, Path]] | None | If given, result rows are appended to this leaderboard parquet. |
Returns
(probs, rows) — the oracle with p_home appended (original row order and original week labels), and the result rows.
Raises
| Exception | Description |
|---|---|
ValueError | On duplicate game_id rows, a prediction length mismatch, or probabilities outside [0, 1]. |
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", path="results/wexp/leaderboard.parquet")
score_baselines
score_baselines(probs: 'pl.DataFrame', *, vintage_policy: 'str' = 'observed', week_slice: 'str' = 'all', era: 'str' = 'all', path: 'str | Path | None' = None) -> 'pl.DataFrame'
Score every p_* baseline column per season and pooled.
Pooled rows use season = -1. Metrics per model/season: brier,
log_loss, winner_accuracy, ece. Ties (null home_win)
and null probabilities are dropped per model, so the open-market
baseline is scored only on games that actually held an open.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
probs | DataFrame | Output of baseline_probs. | |
vintage_policy | str | 'observed' | Vintage label for the result rows. |
week_slice | str | 'all' | Game-slice label. |
era | str | 'all' | Era label. |
path | str | Path | None | None | If given, rows are appended to this leaderboard parquet. |
Returns
The result rows (long format, RESULT_SCHEMA).
| col_name | type | description |
|---|---|---|
league | String | League slug ("nfl" or "cfb"). |
model_id | String | Model identifier (a baseline's column name without the p_ prefix for score_baselines). |
variant_hash | String | Stable hash of the full variant configuration. |
vintage_policy | String | Knowledge-cycle vintage label of the run. |
season | Int32 | Season scored; -1 for the row pooled over every season. |
week_slice | String | Game-slice label ("all", "wk1-3", ...; "lined" for the rows scored only on games with a closing market line). |
era | String | Era label the run was scored under ("all" unless the caller passes one). |
metric | String | Metric name (brier, log_loss, winner_accuracy, ece). |
value | Float64 | The metric's value for this model, season and slice. |
n | Int64 | Games scored (ties and null probabilities dropped). |
Example
from sportsdataverse.wexp import baseline_probs, build_nfl_market_oracle, score_baselines
probs = baseline_probs(build_nfl_market_oracle([2022, 2023]))
rows = score_baselines(probs, path="results/wexp/leaderboard.parquet")
score_probs
score_probs(frame: 'pl.DataFrame', prob_col: 'str', *, league: 'str', model_id: 'str', variant_hash: 'str', vintage_policy: 'str', week_slice: 'str' = 'all', era: 'str' = 'all') -> 'pl.DataFrame'
Score one probability column per season and pooled into result rows.
The canonical scoring loop shared by the baseline driver and the
walk-forward backtest. Pooled rows use season = -1. Ties (null
home_win) and null probabilities are dropped, so a model scored on
a partial-coverage column (e.g. the open-market baseline) is scored
only on the games it actually predicted.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
frame | DataFrame | Frame with season, home_win, and prob_col. | |
prob_col | str | The probability column to score. | |
league | str | League slug for the result rows. | |
model_id | str | Stable model family identifier. | |
variant_hash | str | Stable hash of the variant config. | |
vintage_policy | str | Vintage label for the result rows. | |
week_slice | str | 'all' | Game-slice label. |
era | str | 'all' | Era label. |
Returns
Result rows (long format, RESULT_SCHEMA); empty frame with that schema if no season has a scorable game.
| col_name | type | description |
|---|---|---|
league | String | League slug ("nfl" or "cfb"). |
model_id | String | Model identifier (a baseline's column name without the p_ prefix for score_baselines). |
variant_hash | String | Stable hash of the full variant configuration. |
vintage_policy | String | Knowledge-cycle vintage label of the run. |
season | Int32 | Season scored; -1 for the row pooled over every season. |
week_slice | String | Game-slice label ("all", "wk1-3", ...; "lined" for the rows scored only on games with a closing market line). |
era | String | Era label the run was scored under ("all" unless the caller passes one). |
metric | String | Metric name (brier, log_loss, winner_accuracy, ece). |
value | Float64 | The metric's value for this model, season and slice. |
n | Int64 | Games scored (ties and null probabilities dropped). |
Example
from sportsdataverse.wexp import build_nfl_market_oracle, elo_ratings, score_probs
probs = elo_ratings(build_nfl_market_oracle([2022, 2023]))
rows = score_probs(probs, "p_home", league="nfl", model_id="elo", variant_hash="a1", vintage_policy="V2")
sos_sor_vintages
sos_sor_vintages(oracle: 'pl.DataFrame', ratings: 'pl.DataFrame', *, sigma: 'float' = 15.5, hfa: 'float' = 3.0) -> 'pl.DataFrame'
As-of strength of schedule + strength of record, per team per week.
For each (season, as_of_week) the team's completed games in
strictly earlier weeks are joined to that vintage's opponent ratings.
Strength of record uses the standard construction: the wins a
league-average team (rating 0) would be expected to take from the
same opponents at the same sites, subtracted from the wins actually
taken. Positive SOR = the record is better than the schedule alone
would produce.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
oracle | DataFrame | Market-oracle frame (contract columns incl. team ids, home_win and neutral_site). | |
ratings | DataFrame | Tidy vintage ratings — season, as_of_week, team_id (Utf8) and rating in MARGIN points (e.g. off_coef - def_coef, or adj_net). | |
sigma | float | 15.5 | Margin SD for the expected-wins normal link. |
hfa | float | 3.0 | Home-field advantage in margin points (0 at neutral sites). |
Returns
One row per (season, as_of_week, team_id): sos_played (mean rating of opponents already faced), sos_remaining (mean rating of opponents still scheduled, rated as-of; postseason games count too, so this includes opponents a team meets only by qualifying), sor (wins above a league-average team's expectation), games_played. Weeks with no completed games emit no rows.
| col_name | type | description |
|---|---|---|
season | Int32 | Season of the vintage. |
as_of_week | Int32 | Week the vintage is for; only games from weeks strictly before it count. |
team_id | String | Team id as text. |
sos_played | Float64 | Mean rating of the opponents already faced. |
sos_remaining | Float64 | Mean rating of the opponents still on the schedule from this week on, rated as of this week. Postseason games count too, so before the postseason it already includes opponents a team meets only by qualifying. |
sor | Float64 | Strength of record, wins taken minus the wins a league-average team would expect from the same games. |
games_played | UInt32 | Completed games against opponents that have a rating in this vintage. |
Example
import polars as pl
from sportsdataverse.wexp import build_nfl_market_oracle, ridge_margin_vintages, sos_sor_vintages
oracle = build_nfl_market_oracle([2022, 2023])
ratings = ridge_margin_vintages(oracle, lam=25.0).select(
"season", "as_of_week", "team_id", rating=pl.col("off_coef") - pl.col("def_coef"))
sos = sos_sor_vintages(oracle, ratings)
sos.filter(pl.col("as_of_week") == 10).sort("sor", descending=True).head()
spearman_corr
spearman_corr(a: 'np.ndarray', b: 'np.ndarray') -> 'float'
Spearman rank correlation 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 Spearman rank correlation coefficient.
Example
import numpy as np
from sportsdataverse._common.metrics import spearman_corr
spearman_corr(np.array([1, 2, 3]), np.array([3, 1, 2]))
spread_to_prob
spread_to_prob(spread: 'float', sigma: 'float') -> 'float'
Map an expected home margin to a home win probability via a normal CDF.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
spread | float | Expected HOME margin (positive = home favored). | |
sigma | float | Margin standard deviation (league-specific, tuned on the harness — e.g. ~13.45 NFL). |
Returns
P(home win) = Phi(spread / sigma).
Example
from sportsdataverse.wexp.market import spread_to_prob
spread_to_prob(7.0, sigma=13.45)
variant_hash
variant_hash(config: 'VariantConfig') -> 'str'
Stable 12-hex identifier for a variant config.
Field-order-insensitive (dataclass fields serialize in declaration
order; params are sorted). Any change to any axis value or tunable
produces a different hash — a re-tuned variant is a new leaderboard row.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
config | VariantConfig | The variant. |
Returns
First 12 hex chars of the SHA-256 of the canonical JSON form.
Example
from sportsdataverse.wexp.variants import VariantConfig, variant_hash
variant_hash(VariantConfig(core="elo_margin", response="raw",
opponent_adjust="none", prior="flat",
wp_map="elo_logistic", hfa="fixed"))
winner_accuracy
winner_accuracy(y_true: 'np.ndarray', p_pred: 'np.ndarray') -> 'float'
Fraction of games where the model's favorite (p >= 0.5) won.
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
The winner accuracy in [0, 1].
Example
import numpy as np
from sportsdataverse.wexp.scoring import winner_accuracy
winner_accuracy(np.array([1, 0]), np.array([0.7, 0.6]))