Skip to main content
Version: 0.0.72

PWHL — additional Python functions

Hand-written wrappers, loaders, and helpers in sportsdataverse.pwhl not covered by the generated API-endpoint reference above.

Dataset loaders

load_pwhl_games(return_as_pandas: 'bool' = False)

Load the PWHL games-in-data-repo manifest (no seasons argument).

Mirrors fastRhockey (R) load_pwhl_games() which reads a manifest of every PWHL game that has processed data in the data repository.

Tries the sportsdataverse-data release asset first; falls back to the raw fastRhockey-data GitHub path.

Parameters

ParameterTypeDefaultDescription
return_as_pandasboolFalsereturn a pandas DataFrame instead of polars.

Returns

A polars (or pandas) DataFrame of all games in the data repository.

col_nametypedescription
game_idcharacterUnique game identifier.
seasonintegerSeason year (echoed from arg).
game_datecharacterGame date.
game_statuscharacterGame status text.
home_teamcharacterHome team name.
home_team_idcharacterHome team identifier.
away_teamcharacterAway team name.
away_team_idcharacterAway team identifier.
home_scorecharacterHome team final score.
away_scorecharacterAway team final score.
winnercharacterWhether this competitor won the game.
venuecharacterVenue where the game was played.
venue_urlcharacterURL for the venue.
game_typecharacterGame type the row belongs to.
game_jsonlogicalWhether processed game JSON is available.
game_json_urlcharacterURL to the processed game JSON.
PBPlogicalWhether play-by-play data is available.
player_boxlogicalWhether player box score data is available.
skater_boxlogicalWhether skater box data is available.
goalie_boxlogicalWhether goalie box data is available.
team_boxlogicalWhether team box score data is available.
game_infologicalWhether game info data is available.
game_rosterslogicalWhether game rosters data is available.
scoring_summarylogicalWhether scoring summary data is available.
penalty_summarylogicalWhether penalty summary data is available.
three_starslogicalWhether three stars data is available.
officialslogicalWhether officials data is available.
shots_by_periodlogicalWhether shots-by-period data is available.
shootoutlogicalWhether shootout data is available.

Example

load_pwhl_games()

load_pwhl_goalie_box(seasons, return_as_pandas: 'bool' = False)

Alias of load_pwhl_goalie_boxscores() for naming parity with fastRhockey (R).

Parameters

ParameterTypeDefaultDescription
seasons
return_as_pandasboolFalse

load_pwhl_player_box(seasons, return_as_pandas: 'bool' = False)

Alias of load_pwhl_player_boxscores() for naming parity with fastRhockey (R).

Parameters

ParameterTypeDefaultDescription
seasons
return_as_pandasboolFalse

load_pwhl_schedule(seasons, return_as_pandas: 'bool' = False)

Alias of load_pwhl_schedules() for naming parity with fastRhockey (R).

Parameters

ParameterTypeDefaultDescription
seasons
return_as_pandasboolFalse

load_pwhl_skater_box(seasons, return_as_pandas: 'bool' = False)

Alias of load_pwhl_skater_boxscores() for naming parity with fastRhockey (R).

Parameters

ParameterTypeDefaultDescription
seasons
return_as_pandasboolFalse

load_pwhl_team_box(seasons, return_as_pandas: 'bool' = False)

Alias of load_pwhl_team_boxscores() for naming parity with fastRhockey (R).

Parameters

ParameterTypeDefaultDescription
seasons
return_as_pandasboolFalse

Utilities & helpers

most_recent_pwhl_season() -> 'int'

Most-recent PWHL season as an end-year integer (max season_yr).

Other

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') -> None

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

Parameters

ParameterTypeDefaultDescription
hfafloathome-ice edge, expected-goals units.
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 total goals per game.
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.

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.

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(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(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).

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(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(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_game_corsi(game_id: 'int', return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Player-level on-ice Corsi and Fenwick for a single PWHL game.

Computes shot-attempt counts for every player found on ice during a shot/blocked_shot/goal event, then joins their time-on-ice so per-60 rates are available.

Corsi/Fenwick note: the HockeyTech feed has no missed-shot event, so both metrics are proxies that count only shot + blocked_shot + goal. Every output row carries corsi_includes_missed = False.

Parameters

ParameterTypeDefaultDescription
game_idintHockeyTech game identifier (integer or string).
return_as_pandasboolFalseIf True, return a pandas.DataFrame instead of a polars.DataFrame.

Returns

One row per on-ice player with columns: - player_id (Utf8) - corsi_for, corsi_against (Int64) - corsi_for_pct (Float64) - fenwick_for, fenwick_against (Int64) - fenwick_for_pct (Float64) - toi_seconds (Int64, from shifts; null if player not in shift data) - corsi_for_per60 (Float64) - corsi_includes_missed (Boolean, always False)

col_nametypedescription
player_idcharacterUnique player identifier.
corsi_forintegerTotal shot attempts (on goal, missed, and blocked) directed toward the opponent by this team while at the tracked strength in the PWHL game.
corsi_againstintegerTotal shot attempts (on goal, missed, and blocked) directed against this team while at the tracked strength in the PWHL game.
corsi_for_pctdoubleShare of all tracked shot attempts belonging to this team, expressed as a decimal (Corsi For percentage).
fenwick_forintegerUnblocked shot attempts (on goal and missed only) directed toward the opponent by this team at the tracked strength in the PWHL game.
fenwick_againstintegerUnblocked shot attempts (on goal and missed only) directed against this team at the tracked strength in the PWHL game.
fenwick_for_pctdoubleShare of all unblocked shot attempts belonging to this team, expressed as a decimal (Fenwick For percentage).
corsi_includes_missedlogicalBoolean flag indicating whether missed shots are included in the Corsi totals for this record.
toi_secondsdoubleTotal time on ice in seconds for this team at the tracked strength during the PWHL game.
corsi_for_per60doubleThis team's Corsi For rate projected to a full 60 minutes of ice time.

pwhl_game_shifts(game_id: 'int', return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Parsed shift stints for a single PWHL game.

Calls the HockeyTech modulekit/gameshifts endpoint and returns one row per player-shift stint via ~sportsdataverse.hockeytech._parsers.parse_shifts.

Parameters

ParameterTypeDefaultDescription
game_idintHockeyTech game identifier (integer or string).
return_as_pandasboolFalseIf True, return a pandas.DataFrame instead of a polars.DataFrame.

Returns

Columns include player_id, first_name, last_name, home, period, start_time, end_time, start_s, end_s, goal_on_shift, penalty_on_shift.

col_nametypedescription
game_idintegerUnique game identifier.
player_idintegerUnique player identifier.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
jersey_numbercharacterJersey number.
homeintegerWhether the player's team was home.
periodintegerPeriod number.
start_timecharacterShift start time (MM:SS countdown clock).
end_timecharacterShift end time (MM:SS countdown clock).
lengthcharacterLength of the streak in games.
start_sintegerShift start time in seconds elapsed from the start of the period.
end_sdoubleShift end time in seconds elapsed from the start of the period.
goal_on_shiftintegerNumber of goals scored while this shift was active (0 or 1 in most cases).
penalty_on_shiftintegerNumber of penalties called while this shift was active.

pwhl_game_summary(game_id: 'int') -> 'dict'

PWHL game summary — dict of frames (game/goals/penalties/shots_by_period/three_stars).

Parameters

ParameterTypeDefaultDescription
game_idint

pwhl_game_total(games: 'Any', ratings: 'Any', *, league: 'str' = 'pwhl', **kwargs: 'Any') -> 'Any'

PWHL per-game expected total goals (re-export of the expected-goals helper).

Delegates to sportsdataverse.nhl.nhl_player_props.nhl_game_total with league="pwhl" defaulted.

Parameters

ParameterTypeDefaultDescription
gamesAnya schedule-shaped frame.
ratingsAnya pwhl_team_ratings-shaped frame.
leaguestr'pwhl'league key (defaults to "pwhl").

Returns

The NHL core's game_id/exp_total frame, computed with PWHL constants.

Example

from sportsdataverse.pwhl.pwhl_player_props import pwhl_game_total
totals = pwhl_game_total(games, ratings)

pwhl_in_game_win_prob(pbp: 'Any', pregame_home_prob: 'float', *, league: 'str' = 'pwhl', **kwargs: 'Any') -> 'Any'

PWHL per-play live home win probability from the bundled in-game model.

Delegates to sportsdataverse.nhl.nhl_market.nhl_in_game_win_prob with league="pwhl" defaulted. NOTE: requires a committed pwhl_in_game_wp artifact, deferred until PWHL data lands (see module docstring); calling it before then raises a clear FileNotFoundError from the artifact loader, not a silent bad result.

Parameters

ParameterTypeDefaultDescription
pbpAnya play-by-play frame shaped like load_nhl_pbp_full.
pregame_home_probfloatthe pregame home win probability anchor.
leaguestr'pwhl'league key (defaults to "pwhl").

Returns

The NHL core's per-play home_win_prob frame.

Example

from sportsdataverse.pwhl.pwhl_market import pwhl_in_game_win_prob
wp = pwhl_in_game_win_prob(pbp, pregame_home_prob=0.5)

pwhl_leaders(season: 'Optional[int]' = None, season_id: 'Optional[int]' = None, return_as_pandas: 'bool' = False) -> 'Any'

PWHL statistical leaders for a given season.

NOTE: the leadersExtended endpoint uses season_id (integer) to filter by season, not season (name string). The resolved integer is passed as the season_id param so historical-season requests return results.

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]None
season_idOptional[int]None
return_as_pandasboolFalse

Returns

col_nametypedescription
rankintegerRank of the streak.
player_idcharacterUnique player identifier.
jersey_numbercharacterJersey number.
namecharacterTeam mascot name.
team_idcharacterUnique team identifier.
team_namecharacterTeam name.
team_codecharacterTeam abbreviation.
team_logocharacterURL to the team logo image.
team_logo_smallcharacterURL of the small-format team logo image for the PWHL leader-board entry.
stat_formattedcharacterHuman-readable string representation of the player's leading statistic value (e.g., "22G", "0.95").
type_formattedcharacterHuman-readable label for the statistical category driving the leader-board ranking (e.g., "Goals", "Save Percentage").
photocharacterURL to the player photo.
photo_smallcharacterURL of the small-format headshot image for the PWHL leader-board player.
positioncharacterPlayer position.
divisioncharacterDivision identifier.

pwhl_player_box(game_id: 'int', return_as_pandas: 'bool' = False) -> 'Any'

PWHL player box score for a single game.

NOTE: returns an empty frame pending a captured fixture + correct endpoint wiring (A1.8 follow-up); not yet functional.

Parameters

ParameterTypeDefaultDescription
game_idint
return_as_pandasboolFalse

pwhl_player_game_log(player_id: 'int', return_as_pandas: 'bool' = False) -> 'Any'

PWHL player game-by-game log.

Parameters

ParameterTypeDefaultDescription
player_idint
return_as_pandasboolFalse

pwhl_player_info(player_id: 'int', return_as_pandas: 'bool' = False) -> 'Any'

PWHL player biographical info.

NOTE: returns an empty frame pending a captured fixture + correct endpoint wiring (A1.8 follow-up); not yet functional.

Parameters

ParameterTypeDefaultDescription
player_idint
return_as_pandasboolFalse

pwhl_player_props(seasons: 'Any', *, league: 'str' = 'pwhl', **kwargs: 'Any') -> 'Any'

PWHL empirical-Bayes shots/points player-prop projections.

Delegates to sportsdataverse.nhl.nhl_player_props.nhl_player_props with league="pwhl" defaulted.

Parameters

ParameterTypeDefaultDescription
seasonsAnyan int or iterable of seasons.
leaguestr'pwhl'league key (defaults to "pwhl").

Returns

The NHL core's per-(player, game, stat) projection frame.

Example

from sportsdataverse.pwhl.pwhl_player_props import pwhl_player_props
props = pwhl_player_props(2024)

Search for PWHL players by name.

Parameters

ParameterTypeDefaultDescription
namestr
return_as_pandasboolFalse

Returns

col_nametypedescription
person_idcharacterUnique person identifier.
player_idcharacterUnique player identifier.
activecharacterWhether athlete is currently active.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
phonetic_namecharacterPhonetic spelling of the player name.
shootscharacterShooting hand.
catchescharacterCatching hand (goalies).
heightcharacterPlayer height in inches.
weightcharacterPlayer weight in pounds.
rawbirthdatecharacterPlayer's birth date as a raw string in the format returned by the PWHL HockeyTech API, typically YYYY-MM-DD.
birthdatecharacterDate of birth.
birthtowncharacterPlayer birth town.
birthprovcharacterPlayer birth province/state.
birthcntrycharacterPlayer birth country.
team_idcharacterUnique team identifier.
jersey_numbercharacterJersey number.
role_idcharacterNumeric identifier for the player's primary positional role in the PWHL HockeyTech system (e.g., skater, goalie).
season_idcharacterSeason identifier.
role_namecharacterHuman-readable label for the player's primary positional role in the PWHL HockeyTech system (e.g., 'Forward', 'Defense', 'Goalie').
all_rolescharacterPipe- or comma-delimited string listing every positional or roster role associated with the player in the PWHL HockeyTech system.
last_team_namecharacterFull name of the PWHL team on which the player most recently appeared.
last_team_codecharacterShort abbreviation code for the PWHL team on which the player most recently appeared.
divisioncharacterDivision identifier.
positioncharacterPlayer position.
profile_imagecharacterURL of the player's official profile photograph from the PWHL HockeyTech feed.
scorecharacterFinal score string.
last_active_datecharacterISO-formatted date string of the player's most recent recorded activity or roster transaction in the PWHL HockeyTech system.

pwhl_player_stats(player_id: 'int', return_as_pandas: 'bool' = False) -> 'Any'

PWHL player season stats across all seasons.

Parameters

ParameterTypeDefaultDescription
player_idint
return_as_pandasboolFalse

Returns

col_nametypedescription
season_idcharacterSeason identifier.
season_namecharacterFull season name (e.g., "2024-25 Regular Season").
shortnamecharacterPlayer short name.
playoffcharacterWhether the row is playoff statistics.
careercharacterWhether this is a career-stats season.
sopt_track_faceoffscharacterFlag indicating whether faceoff tracking is enabled for this player's statistical record in the HockeyTech system.
max_start_datecharacterLatest game start date for the season.
veteran_statuscharacterPlayer veteran status.
veterancharacterWhether the player is a veteran.
jersey_numbercharacterJersey number.
goalscharacterGoals scored.
games_playedcharacterGames played.
assistscharacterAssists.
pointscharacterTotal points (goals + assists).
plus_minuscharacterPlus/minus rating.
penalty_minutescharacterPenalty minutes.
power_play_goalscharacterPower-play goals.
power_play_assistscharacterPower-play assists.
shotscharacterShots on goal.
shootout_attemptscharacterShootout attempts.
shootout_goalscharacterShootout goals.
shootout_percentagecharacterShootout scoring percentage.
shooting_percentagecharacterShooting percentage.
shootout_winning_goalscharacterShootout game-winning goals.
points_per_gamecharacterPoints per game.
short_handed_goalscharacterShort-handed goals.
short_handed_assistscharacterShort-handed assists.
game_winning_goalscharacterGame-winning goals.
game_tieing_goalscharacterGame-tying goals.
faceoff_winscharacterFaceoff wins.
faceoff_attemptscharacterFaceoff attempts.
faceoff_pctcharacterFaceoff win percentage.
hitscharacterHits.
team_namecharacterTeam name.
team_codecharacterTeam abbreviation.
team_citycharacterTeam city.
team_nicknamecharacterTeam nickname.
team_idcharacterUnique team identifier.
activecharacterWhether athlete is currently active.
first_goalscharacterFirst goals of a game.
insurance_goalscharacterInsurance goals.
overtime_goalscharacterOvertime goals.
unassisted_goalscharacterUnassisted goals.
empty_net_goalscharacterEmpty-net goals.
penalty_minutes_per_gamecharacterPenalty minutes per game.
divisioncharacterDivision identifier.
ice_timecharacterTotal ice time.
ice_time_minutes_secondscharacterIce time in minutes and seconds.
shots_blocked_by_playercharacterShots blocked by the player.
stat_typecharacterStatistic type ("regular"/"playoff").

pwhl_player_toi(game_id: 'int', return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-player time-on-ice totals for a single PWHL game.

Fetches shifts via pwhl_game_shifts then aggregates via ~sportsdataverse.hockeytech._analytics.player_toi.

Parameters

ParameterTypeDefaultDescription
game_idintHockeyTech game identifier (integer or string).
return_as_pandasboolFalseIf True, return a pandas.DataFrame instead of a polars.DataFrame.

Returns

One row per player with player_id, first_name, last_name, toi_seconds, num_shifts, avg_shift_s, sorted by toi_seconds descending.

col_nametypedescription
player_idintegerUnique player identifier.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
toi_secondsdoubleTotal time on ice for the PWHL player during the game or reporting period, recorded in seconds.
num_shiftsintegerTotal number of shifts the player took during the game or reporting period.
avg_shift_sdoubleAverage duration of a single shift for the player during the game or reporting period, measured in seconds.

pwhl_playoff_bracket(season: 'Optional[int]' = None, season_id: 'Optional[int]' = None, return_as_pandas: 'bool' = False) -> 'Any'

PWHL playoff bracket for a given season.

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]None
season_idOptional[int]None
return_as_pandasboolFalse

pwhl_predict_games(games: 'Any', ratings: 'Any', *, league: 'str' = 'pwhl', **kwargs: 'Any') -> 'Any'

PWHL vectorized pregame margin/win-prob/total (+ market edge).

Delegates to sportsdataverse.nhl.nhl_market.nhl_predict_games with league="pwhl" defaulted.

Parameters

ParameterTypeDefaultDescription
gamesAnya schedule-shaped frame (game_id, home_team, away_team, neutral_site).
ratingsAnya pwhl_team_ratings-shaped frame.
leaguestr'pwhl'league key (defaults to "pwhl").

Returns

The NHL core's per-game prediction frame, computed with PWHL constants.

Example

from sportsdataverse.pwhl.pwhl_market import pwhl_predict_games
preds = pwhl_predict_games(games, ratings)

pwhl_schedule(season: 'Optional[int]' = None, season_id: 'Optional[int]' = None, return_as_pandas: 'bool' = False) -> 'Any'

PWHL schedule — one row per game (matches fastRhockey pwhl_schedule).

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]None
season_idOptional[int]None
return_as_pandasboolFalse

Returns

col_nametypedescription
game_idcharacterUnique game identifier.
game_datecharacterGame date.
game_statuscharacterGame status text.
home_teamcharacterHome team name.
home_team_idcharacterHome team identifier.
home_scorecharacterHome team final score.
away_teamcharacterAway team name.
away_team_idcharacterAway team identifier.
away_scorecharacterAway team final score.
venuecharacterVenue where the game was played.
season_idcharacterSeason identifier.
game_typecharacterGame type the row belongs to.

pwhl_scorebar(return_as_pandas: 'bool' = False) -> 'Any'

PWHL live scorebar (today ± 3 days).

Parameters

ParameterTypeDefaultDescription
return_as_pandasboolFalse

Returns

col_nametypedescription
idcharacterUnique player identifier.
season_idcharacterSeason identifier.
league_idcharacterLeague identifier of the team.
game_numbercharacterGame number within the schedule.
game_lettercharacterSingle-letter suffix appended to the game number to distinguish doubleheader or rescheduled games.
game_typecharacterGame type the row belongs to.
quick_scorecharacterCompact score string summarizing the current or final score of the game (e.g., "3-2").
datecharacterGame date (ISO 8601 datetime string).
flo_core_event_idcharacterFloSports core event identifier linking this PWHL game to its FloSports broadcast event record.
flo_live_event_idcharacterFloSports live-stream event identifier for this PWHL game.
game_datecharacterGame date.
game_date_iso8601characterGame date formatted as an ISO 8601 string (e.g., "2024-02-10T00:00:00") for timezone-aware parsing.
scheduled_timecharacterRaw scheduled start time for the game as returned by the HockeyTech feed, typically in HH:MM:SS format.
scheduled_formatted_timecharacterHuman-readable local game start time string formatted for display (e.g., "7:00 PM ET").
timezonecharacterTime zone of the transaction.
ticket_urlcharacterURL to the official ticketing page where fans can purchase tickets for this game.
home_idcharacterHome team ESPN identifier.
home_codecharacterShort team code (abbreviation) for the home team (e.g., "BOS", "MIN").
home_citycharacterHometown of the athlete.
home_nicknamecharacterFranchise nickname for the home team (e.g., "Fleet", "Frost").
home_long_namecharacterFull name including city and franchise for the home team (e.g., "Boston Fleet").
home_divisioncharacterHome team division.
home_goalscharacterHome goals in the period.
home_audio_urlcharacterURL of the home-team radio or audio broadcast stream for this game.
home_video_urlcharacterURL of the home-team video broadcast stream for this game.
home_webcast_urlcharacterURL of the home-team webcast for online viewing of this game.
visitor_idcharacterHockeyTech team identifier for the visiting team in this game.
visitor_codecharacterShort team code (abbreviation) for the visiting team (e.g., "NYR", "OTT").
visitor_citycharacterCity name of the visiting team (e.g., "New York", "Ottawa").
visitor_nicknamecharacterFranchise nickname for the visiting team (e.g., "Charge", "Sceptres").
visitor_long_namecharacterFull name including city and franchise for the visiting team (e.g., "Ottawa Charge").
visiting_divisioncharacterVisiting team division.
visitor_goalscharacterNumber of goals scored by the visiting team at the current point in the game.
visitor_audio_urlcharacterURL of the visiting-team radio or audio broadcast stream for this game.
visitor_video_urlcharacterURL of the visiting-team video broadcast stream for this game.
visitor_webcast_urlcharacterURL of the visiting-team webcast for online viewing of this game.
periodcharacterPeriod number.
period_name_shortcharacterAbbreviated name of the current or final game period (e.g., "3rd", "OT").
period_name_longcharacterVerbose name of the current or final game period (e.g., "Third Period", "Overtime").
game_clockcharacterGame clock.
game_summary_urlcharacterURL to the official PWHL game summary page for this contest.
home_winscharacterWins at home.
home_regulation_lossescharacterNumber of regulation losses accumulated by the home team at the time of this game in the current standings.
home_ot_lossescharacterHome overtime losses.
home_shootout_lossescharacterNumber of shootout losses accumulated by the home team at the time of this game in the current standings.
visitor_winscharacterNumber of wins accumulated by the visiting team at the time of this game in the current standings.
visitor_regulation_lossescharacterNumber of regulation losses accumulated by the visiting team at the time of this game in the current standings.
visitor_ot_lossescharacterNumber of overtime losses accumulated by the visiting team at the time of this game in the current standings.
visitor_shootout_lossescharacterNumber of shootout losses accumulated by the visiting team at the time of this game in the current standings.
game_statuscharacterGame status text.
intermissioncharacterFlag or string indicating whether the game is currently in an intermission period.
game_status_stringcharacterShort status label for the game's current state (e.g., "Final", "In Progress", "Scheduled").
game_status_string_longcharacterVerbose status description for the game's current state, including period or overtime context.
ordcharacterOrdinal sort key used by the HockeyTech scorebar feed to order games within a day.
venue_namecharacterName of the venue.
venue_locationcharacterCity and/or arena name indicating the physical location where the game is played.
league_namecharacterLeague name.
league_codecharacterShort code identifying the league for this scorebar record (e.g., "PWHL").
timezone_shortcharacterAbbreviated timezone label for the game's scheduled start time (e.g., "ET", "CT").
home_logocharacterHome team logo URL.
visitor_logocharacterURL of the logo image for the visiting team.
flo_hockey_urlcharacterURL to the FloHockey streaming page for this PWHL game.
combined_client_codecharacterCombined league-and-client identifier string used by the HockeyTech feed to distinguish multi-tenant deployments.

pwhl_season_id(return_as_pandas: 'bool' = False) -> 'Any'

All PWHL seasons with end-year + game-type labels (HockeyTech seasons).

Parameters

ParameterTypeDefaultDescription
return_as_pandasboolFalse

Returns

col_nametypedescription
season_idintegerSeason identifier.
season_namecharacterFull season name (e.g., "2024-25 Regular Season").
season_shortcharacterShort season name.
careercharacterWhether this is a career-stats season.
playoffcharacterWhether the row is playoff statistics.
start_datecharacterSeason start date.
end_datecharacterSeason end date.
season_yrintegerYear derived from the season name (concluding year).
game_type_labelcharacterGame type: "preseason", "regular", or "playoffs".

pwhl_skater_rapm(pbp: 'pl.DataFrame', shifts: 'pl.DataFrame', *, model_dir: "'str | None'" = None, **kwargs: 'Any') -> "'pl.DataFrame | pd.DataFrame'"

② PWHL skater xG RAPM -- shim over nhl_skater_rapm with league='pwhl'.

Guards on PWHL shift-chart coverage (see the module docstring); returns a documented empty frame + cli_warn rather than fitting a degenerate ridge when shifts is too thin.

Parameters

ParameterTypeDefaultDescription
pbpDataFramea PWHL play-by-play frame shaped like load_nhl_pbp_full.
shiftsDataFramea PWHL shift-chart frame shaped like load_nhl_shifts.
model_dirstr | NoneNonebooster directory passed through to the borrowed NHL xG boosters.

Returns

Same schema as nhl_skater_rapm: player_id:Int64, xg_rapm_off:Float64, xg_rapm_def:Float64, xg_rapm:Float64, toi_minutes:Float64. A zero-row frame with this schema (+ a cli_warn) when PWHL shift coverage is insufficient.

Example

from sportsdataverse.pwhl.pwhl_player_impact import pwhl_skater_rapm
rapm = pwhl_skater_rapm(pbp, shifts)

pwhl_skater_war(pbp: 'pl.DataFrame', shifts: 'pl.DataFrame', *, model_dir: "'str | None'" = None, **kwargs: 'Any') -> "'pl.DataFrame | pd.DataFrame'"

③ PWHL GAR/WAR composite -- shim over nhl_skater_war with league='pwhl'.

Guards on PWHL shift-chart coverage (see the module docstring).

Parameters

ParameterTypeDefaultDescription
pbpDataFramea PWHL play-by-play frame shaped like load_nhl_pbp_full.
shiftsDataFramea PWHL shift-chart frame shaped like load_nhl_shifts.
model_dirstr | NoneNonebooster directory passed through to the borrowed NHL xG boosters.

Returns

Same schema as nhl_skater_war: player_id:Int64, ev_off:Float64, ev_def:Float64, pp:Float64, pk:Float64, pens:Float64, faceoffs:Float64, gar:Float64, war:Float64. A zero-row frame with this schema (+ a cli_warn) when PWHL shift coverage is insufficient.

Example

from sportsdataverse.pwhl.pwhl_player_impact import pwhl_skater_war
war = pwhl_skater_war(pbp, shifts)

pwhl_special_teams_value(pbp: 'pl.DataFrame', shifts: 'pl.DataFrame', *, model_dir: "'str | None'" = None, **kwargs: 'Any') -> "'pl.DataFrame | pd.DataFrame'"

⑥ PWHL special-teams value -- shim over nhl_special_teams_value with league='pwhl'.

Guards on PWHL shift-chart coverage (see the module docstring).

Parameters

ParameterTypeDefaultDescription
pbpDataFramea PWHL play-by-play frame shaped like load_nhl_pbp_full.
shiftsDataFramea PWHL shift-chart frame shaped like load_nhl_shifts.
model_dirstr | NoneNonebooster directory passed through to the borrowed NHL xG boosters.

Returns

Same schema as nhl_special_teams_value: player_id:Int64, pp_toi_minutes:Float64, pk_toi_minutes:Float64, pp_value:Float64, pk_value:Float64. A zero-row frame with this schema (+ a cli_warn) when PWHL shift coverage is insufficient.

Example

from sportsdataverse.pwhl.pwhl_player_impact import pwhl_special_teams_value
st = pwhl_special_teams_value(pbp, shifts)

pwhl_standings(season: 'Optional[int]' = None, season_id: 'Optional[int]' = None, return_as_pandas: 'bool' = False) -> 'Any'

PWHL standings — one row per team.

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]None
season_idOptional[int]None
return_as_pandasboolFalse

Returns

col_nametypedescription
team_codecharacterTeam abbreviation.
lossescharacterLosses.
regulation_winscharacterWins in regulation.
pointscharacterTotal points (goals + assists).
goals_forcharacterGoals for.
goals_againstcharacterGoals against.
non_reg_winscharacterNon-regulation wins.
non_reg_lossescharacterNon-regulation losses.
games_remainingcharacterGames remaining in the season.
percentagecharacterPoints percentage earned by the PWHL team (points divided by maximum possible points), expressed as a decimal between 0 and 1.
overall_rankcharacterOverall recruit ranking (top recruits only; may be NA).
games_playedcharacterGames played.
team_rankintegerTeam rank in the standings.
teamcharacterTeam name.
winsintegerWins.

pwhl_stats(season: 'Optional[int]' = None, season_id: 'Optional[int]' = None, position: 'str' = 'skaters', return_as_pandas: 'bool' = False) -> 'Any'

PWHL aggregate stats by season and position.

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]None
season_idOptional[int]None
positionstr'skaters'
return_as_pandasboolFalse

Returns

col_nametypedescription
player_idcharacterUnique player identifier.
shortnamecharacterPlayer short name.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
namecharacterTeam mascot name.
phonetic_namecharacterPhonetic spelling of the player name.
activecharacterWhether athlete is currently active.
heightcharacterPlayer height in inches.
weightcharacterPlayer weight in pounds.
last_years_clubcharacterPlayer's club in the previous season.
agecharacterPlayer age.
shootscharacterShooting hand.
positioncharacterPlayer position.
suspension_games_remainingcharacterSuspension games remaining.
suspension_indefinitecharacterWhether the suspension is indefinite.
rookiecharacterWhether the player is a rookie.
veterancharacterWhether the player is a veteran.
draft_eligiblecharacterWhether the player is draft eligible.
jersey_numbercharacterJersey number.
team_namecharacterTeam name.
team_codecharacterTeam abbreviation.
team_idcharacterUnique team identifier.
divisioncharacterDivision identifier.
birthdatecharacterDate of birth.
birthdate_yearcharacterPlayer birth year.
hometowncharacterProspect hometown.
homeprovcharacterPlayer home province/state.
homecntrycharacterPlayer home country.
birthtowncharacterPlayer birth town.
birthprovcharacterPlayer birth province/state.
birthcntrycharacterPlayer birth country.
hometownprovcharacterPlayer hometown and province/state.
homeplacecharacterPlayer home place description.
games_playedcharacterGames played.
game_winning_goalscharacterGame-winning goals.
game_tieing_goalscharacterGame-tying goals.
first_goalscharacterFirst goals of a game.
insurance_goalscharacterInsurance goals.
unassisted_goalscharacterUnassisted goals.
empty_net_goalscharacterEmpty-net goals.
overtime_goalscharacterOvertime goals.
ice_timecharacterTotal ice time.
ice_time_avgcharacterAverage ice time.
goalscharacterGoals scored.
shotscharacterShots on goal.
loose_ball_recoveriescharacterLoose ball recoveries.
caused_turnoverscharacterTurnovers caused.
turnoverscharacterTurnovers committed.
hitscharacterHits.
shots_blocked_by_playercharacterShots blocked by the player.
ice_time_minutes_secondscharacterIce time in minutes and seconds.
shooting_percentagecharacterShooting percentage.
assistscharacterAssists.
pointscharacterTotal points (goals + assists).
points_per_gamecharacterPoints per game.
plus_minuscharacterPlus/minus rating.
penalty_minutescharacterPenalty minutes.
penalty_minutes_per_gamecharacterPenalty minutes per game.
ice_time_per_game_avgcharacterAverage ice time per game.
hits_per_game_avgcharacterAverage hits per game.
minor_penaltiescharacterMinor penalties.
major_penaltiescharacterMajor penalties.
power_play_goalscharacterPower-play goals.
power_play_assistscharacterPower-play assists.
power_play_pointscharacterPower play points.
short_handed_goalscharacterShort-handed goals.
short_handed_assistscharacterShort-handed assists.
short_handed_pointscharacterShort-handed points.
shootout_goalscharacterShootout goals.
shootout_attemptscharacterShootout attempts.
shootout_winning_goalscharacterShootout game-winning goals.
shootout_games_playedcharacterGames played that went to a shootout.
faceoff_attemptscharacterFaceoff attempts.
faceoff_winscharacterFaceoff wins.
faceoff_pctcharacterFaceoff win percentage.
faceoff_wacharacterFaceoff wins-to-attempts metric.
shots_oncharacterShots on goal count.
shootout_percentagecharacterShootout scoring percentage.
latest_team_idcharacterMost recent team identifier.
num_teamscharacterNumber of teams the player has played for.
logocharacterURL to the team logo.
rankintegerRank of the streak.
player_page_linkcharacterURL to the player page.
player_imagecharacterURL to the player's headshot image as served by the HockeyTech/PWHL data feed.
namelinkcharacterHTML link for the player name.
teamlinkcharacterHTML link for the team.
team_breakdownintegerPer-team statistical breakdown.
is_totaldoubleWhether the row is a season total.

pwhl_streaks(return_as_pandas: 'bool' = False) -> 'Any'

Current PWHL player/team streaks.

Parameters

ParameterTypeDefaultDescription
return_as_pandasboolFalse

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

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

Delegates to sportsdataverse.nhl.nhl_team_ratings.nhl_team_ratings with league="pwhl" defaulted. Oracle gate deferred (no xG-bearing PWHL pbp yet -- see module docstring).

Parameters

ParameterTypeDefaultDescription
seasonsAnyan int or iterable of seasons.
leaguestr'pwhl'league key (defaults to "pwhl").

Returns

The NHL core's ratings frame, computed with PWHL constants.

Example

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

pwhl_team_roster(team_id: 'int', season: 'Optional[int]' = None, season_id: 'Optional[int]' = None, return_as_pandas: 'bool' = False) -> 'Any'

PWHL team roster for a given team + season.

Parameters

ParameterTypeDefaultDescription
team_idint
seasonOptional[int]None
season_idOptional[int]None
return_as_pandasboolFalse

Returns

col_nametypedescription
idcharacterUnique player identifier.
person_idcharacterUnique person identifier.
activecharacterWhether athlete is currently active.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
phonetic_namecharacterPhonetic spelling of the player name.
display_namecharacterPlayer display name.
shootscharacterShooting hand.
hometowncharacterProspect hometown.
homeprovcharacterPlayer home province/state.
homecntrycharacterPlayer home country.
homeplacecharacterPlayer home place description.
birthtowncharacterPlayer birth town.
birthprovcharacterPlayer birth province/state.
birthcntrycharacterPlayer birth country.
birthplacecharacterCity, province/state, or country where the player was born, as recorded in the PWHL HockeyTech roster.
heightcharacterPlayer height in inches.
weightcharacterPlayer weight in pounds.
height_hyphenatedcharacterPlayer's height formatted as feet-inches with a hyphen separator (e.g., '5-9'), as supplied by the PWHL HockeyTech API.
hiddencharacterFlag indicating whether the player's roster entry is suppressed from public-facing displays in the PWHL HockeyTech system.
current_teamcharacterName or identifier of the PWHL team to which the player is currently rostered.
player_idcharacterUnique player identifier.
statuscharacterStatus string (e.g. captain markers).
birthdatecharacterDate of birth.
birthdate_yearcharacterPlayer birth year.
rawbirthdatecharacterPlayer's birth date as a raw string in the format returned by the PWHL HockeyTech API, typically YYYY-MM-DD.
latest_team_idcharacterMost recent team identifier.
veteran_statuscharacterPlayer veteran status.
veteran_descriptioncharacterText label or descriptor indicating the player's veteran status or experience classification in the PWHL.
team_namecharacterTeam name.
divisioncharacterDivision identifier.
tp_jersey_numbercharacterJersey number assigned to the player on the current PWHL team roster, as provided by the HockeyTech feed.
rookiecharacterWhether the player is a rookie.
position_idcharacterOfficial position identifier.
positioncharacterPlayer position.
nhlteamcharacterName or identifier of the NHL organization that holds the player's NHL rights, if applicable.
player_id_1characterAlternate or secondary HockeyTech player identifier, distinct from the primary person_id and player_id fields.
is_rookiecharacterWhether the player is a rookie.
hcharacterHits.
wcharacterWins.
draft_statuscharacterText description of the player's draft history or eligibility status (e.g., undrafted, drafted year and round).
namecharacterTeam mascot name.
player_imagecharacterURL of the player's official roster photograph from the PWHL HockeyTech feed.
catchescharacterCatching hand (goalies).

pwhl_teams(season: 'Optional[int]' = None, season_id: 'Optional[int]' = None, return_as_pandas: 'bool' = False) -> 'Any'

PWHL teams for a given season.

Parameters

ParameterTypeDefaultDescription
seasonOptional[int]None
season_idOptional[int]None
return_as_pandasboolFalse

Returns

col_nametypedescription
team_namecharacterTeam name.
team_idcharacterUnique team identifier.
team_codecharacterTeam abbreviation.
team_nicknamecharacterTeam nickname.
team_labelcharacterShort city label.
divisioncharacterDivision identifier.
team_logocharacterURL to the team logo image.

pwhl_transactions(return_as_pandas: 'bool' = False) -> 'Any'

PWHL roster transactions.

Parameters

ParameterTypeDefaultDescription
return_as_pandasboolFalse

pwhl_unit_ratings(pbp: 'pl.DataFrame', shifts: 'pl.DataFrame', *, model_dir: "'str | None'" = None, **kwargs: 'Any') -> "'pl.DataFrame | pd.DataFrame'"

⑤ PWHL line/pair ratings -- shim over nhl_unit_ratings with league='pwhl'.

Guards on PWHL shift-chart coverage (see the module docstring).

Parameters

ParameterTypeDefaultDescription
pbpDataFramea PWHL play-by-play frame shaped like load_nhl_pbp_full.
shiftsDataFramea PWHL shift-chart frame shaped like load_nhl_shifts.
model_dirstr | NoneNonebooster directory passed through to the borrowed NHL xG boosters.

Returns

Same schema as nhl_unit_ratings: team:Utf8, unit_ids:Utf8, unit_players:Utf8, toi_minutes:Float64, on_ice_xgf:Float64, on_ice_xga:Float64, on_ice_xgf_pct:Float64, summed_rapm:Float64, unit_value:Float64. A zero-row frame with this schema (+ a cli_warn) when PWHL shift coverage is insufficient.

Example

from sportsdataverse.pwhl.pwhl_player_impact import pwhl_unit_ratings
units = pwhl_unit_ratings(pbp, shifts)

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