Skip to main content
Version: 0.2.0

PWHL — additional Python functions — Models and calculators

LeagueConstants​

LeagueConstants(hfa: 'float', margin_sd: 'float', avg_xgf: 'float', avg_total_goals: 'float', total_scale: 'float', shrink_k: 'float', prop_kappa: 'dict', pos_priors: 'dict', prop_team_volume_slope: 'float', in_game_wp_artifact: 'str', min_season: 'int', reg_draw_inflation: 'float', avg_shots_against: 'float', league_shots_k: 'float', shots_hfa: 'float', starter_shot_share: 'float', save_pct_prior: 'float', save_pct_kappa: 'float', shots_nb_size: 'float') -> None

Fitted, league-specific constants for the NHL/PWHL prediction spine.

Parameters

ParameterTypeDefaultDescription
hfafloathome-ice edge on exp_margin's own (shrunk-rating) scale. NHL: fitted jointly with margin_sd, so smaller than the real-goal home edge. PWHL: a seeded placeholder.
margin_sdfloatstandard deviation of the final goal margin (deliberately WIDE for hockey).
avg_xgffloatleague mean even-strength xG-for, per game.
avg_total_goalsfloatleague mean settled total goals per game (a shootout counts one goal), the level of every predicted total.
total_scalefloatmultiplier converting rating differential to total-goals deviation.
shrink_kfloatgames-played prior strength for rating shrinkage.
prop_kappadictempirical-Bayes shrinkage strength per player-prop stat family.
pos_priorsdictper-position (F/D) per-stat-family prior rates.
prop_team_volume_slopefloatgame-script tilt on a player-prop projection (favored team -> fewer late shots-for). SEEDED PLACEHOLDER (~0.04), not yet fitted -- a future prop-fit task should estimate it from the realized shots-vs-exp_margin slope, mirroring how fit_props.py fits prop_kappa/pos_priors.
in_game_wp_artifactstrfilename of the bundled in-game win-probability model under sportsdataverse/nhl/models/.
min_seasonintearliest season this league's prediction spine supports.
reg_draw_inflationfloatmultiplier minus one on every tied cell of the regulation score grid (~sportsdataverse.nhl.nhl_market.regulation_goal_means). Independent Poissons under-predict 60-minute ties.
avg_shots_againstfloatseed for the league's in-season shots-on-goal per team-game, before any game of the season is played (~sportsdataverse.nhl.nhl_player_props.nhl_goalie_saves).
league_shots_kfloatteam-games of weight on avg_shots_against in the in-season league mean. SEEDED (two games a team), not fitted.
shots_hfafloathow many more shots on goal the home team takes than the away team.
starter_shot_sharefloatthe starting goalie's share of his team's expected shots against (he is sometimes relieved).
save_pct_priorfloatleague save percentage a goalie's own record is shrunk toward.
save_pct_kappafloatshots of weight on save_pct_prior in a goalie's shrunk save percentage.
shots_nb_sizefloatnegative-binomial size of a starter's shots against; his saves then follow a negative binomial with the same size (binomial thinning).

as_of_ratings_split​

as_of_ratings_split(df: 'pl.DataFrame', cutoff_date: '_dt.date', *, date_col: 'str' = 'date') -> 'pl.DataFrame'

Filter a frame to rows strictly before cutoff_date (the leakage boundary).

Parameters

ParameterTypeDefaultDescription
dfDataFramea polars DataFrame with a date column.
cutoff_datedatethe game date being predicted; only strictly-earlier rows are kept.
date_colstr'date'name of the date column (default "date").

Returns

The subset of df with df[date_col] < cutoff_date.

col_nametypedescription
game_idStringUnique game identifier.
seasonInt64Season year (echoed from arg).
dateDateGame date (ISO 8601 datetime string).
teamStringTeam name.
opp_teamString
is_homeBooleanHome-team flag.
neutral_siteBooleanWhether the game is at a neutral site.
xgfFloat64
xgaFloat64
gfInt64
gaInt64Goals against (goalies).

Example

import datetime as dt
import polars as pl
from sportsdataverse.nhl.nhl_prediction_constants import as_of_ratings_split
df = pl.DataFrame({"date": [dt.date(2023, 1, 1), dt.date(2023, 1, 2)]})
as_of_ratings_split(df, dt.date(2023, 1, 2))

brier_score​

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

Mean squared error between predicted probabilities and binary outcomes.

Parameters

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

Returns

The Brier score (0.0 is a perfect forecast).

Example

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

calibration_table​

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

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

Parameters

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

Returns

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

col_nametypedescription
bin_midFloat64Midpoint of the equal-width predicted-probability bin (0.05, 0.15, ... with the default 10 bins).
mean_predFloat64Mean predicted probability of the rows in the bin.
mean_actualFloat64Observed outcome rate of the rows in the bin; a calibrated model has it close to mean_pred.
nInt64Rows 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]))

log_loss_score​

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

Binary cross-entropy loss between predicted probabilities and outcomes.

Parameters

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

Returns

The mean log loss.

Example

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

mae​

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

Mean absolute error between two arrays.

Parameters

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

Returns

The mean absolute error.

Example

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

pwhl_team_ratings​

pwhl_team_ratings(seasons: 'Any', *, league: 'Any' = None, **kwargs: 'Any') -> 'Any'

PWHL opponent-adjusted, shrunk even-strength xG team ratings.

Delegates to sportsdataverse.pwhl.pwhl_xg_proxy.pwhl_ratings_from_proxy, which loads PWHL pbp, schedules and game info only.

Parameters

ParameterTypeDefaultDescription
seasonsAnyan int or iterable of PWHL season end-years (>= 2024).
leagueAnyNonedeprecated and ignored (the ratings are always PWHL); passing it warns. Removed in 0.4.0.

Returns

One row per (season, team), the sportsdataverse.nhl.nhl_team_ratings.nhl_team_ratings schema (season, team, adj_xgf, adj_xga, adj_xg_net, adj_gf, adj_ga, games, off_rank, def_rank, net_rank, net_z).

Raises

ExceptionDescription
DeprecationWarningAs a warning, when league is passed.

Example

from sportsdataverse.pwhl.pwhl_team_ratings import pwhl_team_ratings
ratings = pwhl_team_ratings(2025)

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]))