Skip to main content

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

ParameterTypeDefaultDescription
leaguestrLeague slug ("nfl" / "cfb").
model_idstrStable model family identifier.
variant_hashstrStable hash of the full variant config.
vintage_policystrKnowledge-cycle vintage ("V0".."V3").
seasonintSeason being scored.
week_slicestrGame slice label ("all", "wk1-3", ...).
erastrEra label ("covid", "post2017", ...).
metricsdict[str, float]Mapping of metric name to value.
nintNumber of games scored.

Returns

A polars.DataFrame matching RESULT_SCHEMA.

col_nametypedescription
leagueStringLeague slug ("nfl" or "cfb").
model_idStringModel identifier (a baseline's column name without the p_ prefix for score_baselines).
variant_hashStringStable hash of the full variant configuration.
vintage_policyStringKnowledge-cycle vintage label of the run.
seasonInt32Season scored; -1 for the row pooled over every season.
week_sliceStringGame-slice label ("all", "wk1-3", ...; "lined" for the rows scored only on games with a closing market line).
eraStringEra label the run was scored under ("all" unless the caller passes one).
metricStringMetric name (brier, log_loss, winner_accuracy, ece).
valueFloat64The metric's value for this model, season and slice.
nInt64Games 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

  1. emit no rows. Neutral-site games carry no HFA indicator in the fit.

Parameters

ParameterTypeDefaultDescription
oracleDataFrameMarket-oracle frame (module contract columns).
lamfloatRidge penalty on the team coefficients.
resp_colstr'home_margin'Response column (default "home_margin"; a team-game EPA margin column slots in unchanged).
capOptional[float]NoneAxis B2 capped response — clip the response to [-cap, cap] before the fit (blowout damping). None = raw (B1).
close_filterOptional[float]NoneAxis 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_seasonsint0Prior 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_decayfloat0.5Per-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_nametypedescription
seasonInt32Season of the vintage.
as_of_weekInt32Week 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_idStringThe 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_coefFloat64Team's offensive coefficient in margin points.
def_coefFloat64Team's defensive coefficient in margin points; expected home margin is home off_coef + away def_coef + intercept (+ hfa).
interceptFloat64Fitted intercept of the vintage, the same on every row of it.
hfaFloat64Home-field advantage in margin points for the vintage, the same on every row of it.
lamFloat64Ridge penalty the vintage was fit with.
capFloat64Response cap applied before the fit (|response| clipped to it); null when no cap was set.
close_filterFloat64Games 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

ParameterTypeDefaultDescription
oracleDataFrameMarket-oracle frame (one row per game, unique game_id).
predictWeekPredictorWeek predictor returning one P(home) per slate row (nulls allowed for games the engine declines to rate).
model_idstrStable model family identifier for the result rows.
variantOptional[VariantConfig]NoneVariant config; its hash keys the result rows ("none" when omitted).
storeOptional[VintageStore]NoneVintage feature store handed to the engine each week.
vintage_policystr'observed'Vintage label for the result rows.
week_slicestr'all'Game-slice label.
erastr'all'Era label.
pathOptional[Union[str, Path]]NoneIf 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

ExceptionDescription
ValueErrorOn 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

ParameterTypeDefaultDescription
probsDataFrameOutput of baseline_probs.
vintage_policystr'observed'Vintage label for the result rows.
week_slicestr'all'Game-slice label.
erastr'all'Era label.
pathstr | Path | NoneNoneIf given, rows are appended to this leaderboard parquet.

Returns

The result rows (long format, RESULT_SCHEMA).

col_nametypedescription
leagueStringLeague slug ("nfl" or "cfb").
model_idStringModel identifier (a baseline's column name without the p_ prefix for score_baselines).
variant_hashStringStable hash of the full variant configuration.
vintage_policyStringKnowledge-cycle vintage label of the run.
seasonInt32Season scored; -1 for the row pooled over every season.
week_sliceStringGame-slice label ("all", "wk1-3", ...; "lined" for the rows scored only on games with a closing market line).
eraStringEra label the run was scored under ("all" unless the caller passes one).
metricStringMetric name (brier, log_loss, winner_accuracy, ece).
valueFloat64The metric's value for this model, season and slice.
nInt64Games 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

ParameterTypeDefaultDescription
frameDataFrameFrame with season, home_win, and prob_col.
prob_colstrThe probability column to score.
leaguestrLeague slug for the result rows.
model_idstrStable model family identifier.
variant_hashstrStable hash of the variant config.
vintage_policystrVintage label for the result rows.
week_slicestr'all'Game-slice label.
erastr'all'Era label.

Returns

Result rows (long format, RESULT_SCHEMA); empty frame with that schema if no season has a scorable game.

col_nametypedescription
leagueStringLeague slug ("nfl" or "cfb").
model_idStringModel identifier (a baseline's column name without the p_ prefix for score_baselines).
variant_hashStringStable hash of the full variant configuration.
vintage_policyStringKnowledge-cycle vintage label of the run.
seasonInt32Season scored; -1 for the row pooled over every season.
week_sliceStringGame-slice label ("all", "wk1-3", ...; "lined" for the rows scored only on games with a closing market line).
eraStringEra label the run was scored under ("all" unless the caller passes one).
metricStringMetric name (brier, log_loss, winner_accuracy, ece).
valueFloat64The metric's value for this model, season and slice.
nInt64Games 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

ParameterTypeDefaultDescription
oracleDataFrameMarket-oracle frame (contract columns incl. team ids, home_win and neutral_site).
ratingsDataFrameTidy vintage ratings — season, as_of_week, team_id (Utf8) and rating in MARGIN points (e.g. off_coef - def_coef, or adj_net).
sigmafloat15.5Margin SD for the expected-wins normal link.
hfafloat3.0Home-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_nametypedescription
seasonInt32Season of the vintage.
as_of_weekInt32Week the vintage is for; only games from weeks strictly before it count.
team_idStringTeam id as text.
sos_playedFloat64Mean rating of the opponents already faced.
sos_remainingFloat64Mean 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.
sorFloat64Strength of record, wins taken minus the wins a league-average team would expect from the same games.
games_playedUInt32Completed 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

ParameterTypeDefaultDescription
andarrayFirst array of values.
bndarraySecond 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

ParameterTypeDefaultDescription
spreadfloatExpected HOME margin (positive = home favored).
sigmafloatMargin 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

ParameterTypeDefaultDescription
configVariantConfigThe 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

ParameterTypeDefaultDescription
y_truendarrayArray of binary home-win outcomes (0/1).
p_predndarrayArray 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]))