Skip to main content
Version: 0.2.0

NFL — additional Python functions — Models and calculators: nfl_player–touchback_yardline

nfl_player_projection​

nfl_player_projection(seasons: 'List[int]', target_season: 'int', *, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Marcel-style next-season player projection with delta-method aging.

Loads weekly player stats + rosters, aggregates to season rates, and for every player visible in seasons strictly before target_season (the as-of-date leakage boundary) produces a recency-weighted rate blend regressed toward the volume-weighted position mean by k / (k + reliability), scaled by the position aging-curve ratio aging_mult(proj_age) / aging_mult(current_age). The aging curve is fit only on the same pre-target history.

Parameters

ParameterTypeDefaultDescription
seasonsList[int]History seasons to load (seasons >= target_season are discarded by the leakage split).
target_seasonintThe season being projected.
return_as_pandasboolFalseIf True, returns a pandas dataframe.

Returns

One row per projected player: player_id:Utf8, target_season:Int64, position_group:Utf8, proj_age:Float64, proj_ppg:Float64, proj_volume:Float64, proj_games:Float64, aging_mult:Float64, reliability:Float64 plus proj_<stat>_rate component-rate columns. Empty history returns a zero-row frame.

col_nametypedescription
player_idStringnflverse gsis player id (character join key).
target_seasonInt64The season being projected (features use strictly earlier seasons only - the as-of-date leakage boundary).
position_groupStringnflverse offensive position group (QB/RB/WR/TE plus fringe groups).
proj_ageFloat64Projected age at the target season (age at last visible season + season gap).
proj_ppgFloat64Projected PPR fantasy points per game - recency-weighted rate blend regressed toward the volume-weighted position mean by k/(k + reliability), scaled by the damped aging-curve ratio.
proj_volumeFloat64Projected position-specific opportunity volume (QB = pass attempts, RB = carries + targets, WR/TE = targets).
proj_gamesFloat64Recency-weighted mean of historical games played.
aging_multFloat64Applied aging multiplier - the damped, clamped ratio aging_curve(proj_age) / aging_curve(current_age).
reliabilityFloat64Recency-weighted volume sum - the shrinkage evidence weight.
proj_completions_rateFloat64Projected per-game pass completions (Marcel blend x aging ratio).
proj_attempts_rateFloat64Projected per-game pass attempts (Marcel blend x aging ratio).
proj_passing_yards_rateFloat64Projected per-game passing yards (Marcel blend x aging ratio).
proj_passing_tds_rateFloat64Projected per-game passing touchdowns (Marcel blend x aging ratio).
proj_interceptions_rateFloat64Projected per-game interceptions thrown (Marcel blend x aging ratio).
proj_carries_rateFloat64Projected per-game rush attempts (Marcel blend x aging ratio).
proj_rushing_yards_rateFloat64Projected per-game rushing yards (Marcel blend x aging ratio).
proj_rushing_tds_rateFloat64Projected per-game rushing touchdowns (Marcel blend x aging ratio).
proj_receptions_rateFloat64Projected per-game receptions (Marcel blend x aging ratio).
proj_targets_rateFloat64Projected per-game targets (Marcel blend x aging ratio).
proj_receiving_yards_rateFloat64Projected per-game receiving yards (Marcel blend x aging ratio).
proj_receiving_tds_rateFloat64Projected per-game receiving touchdowns (Marcel blend x aging ratio).
proj_receiving_air_yards_rateFloat64Projected per-game receiving air yards (Marcel blend x aging ratio).
proj_fumbles_lost_rateFloat64Projected per-game fumbles lost (Marcel blend x aging ratio).

Example

from sportsdataverse.nfl.nfl_projection import nfl_player_projection
proj = nfl_player_projection([2021, 2022, 2023], 2024)
proj.sort("proj_ppg", descending=True).head()

# Pandas round-trip

proj_pd = nfl_player_projection([2021, 2022, 2023], 2024, return_as_pandas=True)

nfl_ratings​

nfl_ratings(seasons: 'int | list[int]', *, as_of_date: 'datetime.date | None' = None, config: 'RatingsConfig | None' = None, return_as_pandas: 'bool' = False) -> 'pl.DataFrame | pd.DataFrame'

One row per team: the native NFL ratings spine (off/def/ST EPA).

Public orchestrator over efficiency_ratings + special_teams_ratings. Loads play-by-play + schedule via load_nfl_pbp / load_nfl_schedule, joins each game's gameday onto the plays, optionally applies the as-of-date leakage boundary (only plays from games with gameday < as_of_date are used), then fits both components and reshapes into one wide per-team table with dense ranks and a net z-score.

The loaded pbp is down-selected to the ridge columns before any fit so no market column (spread_line / vegas_wp) can leak into the ratings (the binding non-market boundary).

Parameters

ParameterTypeDefaultDescription
seasonsint | list[int]A single season (e.g. 2023) or a list of seasons pooled into one combined fit.
as_of_datedate | NoneNoneWhen given, only plays from games strictly before this date are used (mirrors what was knowable heading into that date). None (default) uses the full season(s).
configRatingsConfig | NoneNoneTuning knobs forwarded to both component fits; defaults to RatingsConfig.
return_as_pandasboolFalseIf True, returns a pandas DataFrame.

Returns

A DataFrame with one row per team_id: season (Int64 -- the single passed season, null for a pooled multi-season call), team_id (Utf8), adj_off_epa / adj_def_epa / adj_st_epa / adj_net (Float64; adj_net is offense minus defense -- special teams stays a separate column), games (Int64), off_rank / def_rank / net_rank (Int64; def_rank ascends -- fewer EPA allowed ranks better), net_z (Float64). Zero-row, correctly-typed when the seasons have no data or as_of_date filters out every play.

col_nametypedescription
seasonInt64Season the ratings cover (null for a pooled multi-season fit).
team_idStringnflverse team abbreviation (character join key, e.g. "KC").
adj_off_epaFloat64Opponent-adjusted offensive EPA per play (higher is better); competitive-play ridge fit.
adj_def_epaFloat64Opponent-adjusted defensive EPA allowed per play (lower is better); competitive-play ridge fit.
adj_st_epaFloat64Opponent-adjusted special-teams EPA per play (ridge on special==1 plays; 0.0 for teams with no special-teams plays in the window).
adj_netFloat64Opponent-adjusted net efficiency (adj_off_epa minus adj_def_epa; special teams not folded in).
gamesInt64Number of games the team played in the fitted window.
off_rankInt64Dense rank on adj_off_epa descending (best offense = 1).
def_rankInt64Dense rank on adj_def_epa ascending (fewer EPA allowed ranks better).
net_rankInt64Dense rank on adj_net descending (best net rating = 1).
net_zFloat64Z-score of adj_net across the 32 teams.

Example

from sportsdataverse.nfl import nfl_ratings
ratings = nfl_ratings(2023)
ratings.sort("net_rank").head()

# As-of-date leakage boundary

import datetime as dt
week6 = nfl_ratings(2023, as_of_date=dt.date(2023, 10, 12))

nfl_simulations​

nfl_simulations(games: 'pl.DataFrame', compute_results: 'Optional[ComputeResultsFn]' = None, *, simulations: 'int' = 10000, playoff_seeds: 'int' = 7, byes_per_conf: 'int' = 1, tiebreaker_depth: 'str' = 'SOS', sim_include: 'str' = 'DRAFT', seed: 'Optional[int]' = None, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "Dict[str, Union[pl.DataFrame, 'pd.DataFrame']]"

Simulate an NFL season from a schedule with (partially) missing results.

Faithful port of nflseedR::nfl_simulations() + simulate_chunk() (simulations.R L140-409, simulations_simulate_chunks.R L1-284). Missing regular season results are filled week by week via compute_results; standings, division ranks and playoff seeds are then computed with the full NFL tiebreakers, the postseason is simulated round by round (with reseeding and byes_per_conf byes), and the draft order is derived. nflseedR's furrr chunking is replaced by one vectorized pass over all simulated seasons, so there is no chunks argument; reproducibility comes from seed.

Parameters

ParameterTypeDefaultDescription
gamesDataFrameSchedule frame for ONE season with columns sim or season, game_type, week, away_team, home_team, away_rest, home_rest, location, and result (home margin; missing = not yet played).
compute_resultsOptional[ComputeResultsFn]NoneFunction filling results for one week, called as compute_results(teams, games, week_num, rng=rng, **kwargs) and returning {"teams": ..., "games": ...}. Defaults to nfl_compute_results (dynamic ELO + Normal(estimate, 13) margins). Must only fill results where week == week_num and result is missing, and must not produce postseason ties.
simulationsint10000Number of seasons to simulate.
playoff_seedsint7Number of playoff seeds per conference.
byes_per_confint1First-round byes per conference (drives the number of wildcard games).
tiebreaker_depthstr'SOS''SOS' (default), 'PRE-SOV', or 'RANDOM' ('POINTS' is unavailable because simulated games carry margins, not scores).
sim_includestr'DRAFT''REG' (standings/seeds only), 'POST' (+ postseason), or 'DRAFT' (default; + draft order).
seedOptional[int]NoneSeed for the numpy RNG driving results and coin tosses.
return_as_pandasboolFalseIf True, return pandas DataFrames.

Returns

Dict of frames mirroring the nflseedR simulation list: standings (one row per sim x team), games (all simulated games), overall (per-team probabilities: wins, playoff, div1, seed1, won_conf, won_sb, draft1, draft5), team_wins (over/under probabilities vs. half-win lines), and game_summary (per-matchup home/away win rates).

col_nametypedescription
standings.simInt64Simulated season identifier (1 through simulations).
standings.confStringConference of the team (AFC or NFC).
standings.divisionStringDivision of the team (e.g. "AFC East").
standings.teamStringTeam abbreviation.
standings.gamesInt64Number of regular season games played in the simulated season.
standings.winsFloat64Regular season wins in the simulated season with ties counted as half a win.
standings.true_winsInt64Regular season wins in the simulated season excluding ties.
standings.lossesInt64Regular season losses in the simulated season.
standings.tiesInt64Regular season ties in the simulated season.
standings.win_pctFloat64Regular season win percentage in the simulated season with ties counted as half a win.
standings.div_pctFloat64Win percentage against division opponents in the simulated season (0 when no division games).
standings.conf_pctFloat64Win percentage against conference opponents in the simulated season (0 when no conference games).
standings.sovFloat64Strength of victory in the simulated season - combined win percentage of all defeated opponents.
standings.sosFloat64Strength of schedule in the simulated season - combined win percentage of all opponents faced.
standings.div_rankInt64Division rank (1-4) in the simulated season after the NFL division tiebreakers.
standings.div_tie_broken_byStringTiebreaker step that resolved the division rank in this simulated season; null when no tiebreaker was needed.
standings.conf_rankInt64Conference rank (playoff seed) in the simulated season after the NFL conference tiebreakers; null beyond playoff_seeds.
standings.conf_tie_broken_byStringTiebreaker step that resolved the conference rank in this simulated season; null when no tiebreaker was needed.
standings.exitStringRound of the team's final game in the simulated season - REG, WC, DIV, CON, SB, or SB_WIN for the Super Bowl winner.
standings.draft_rankInt64Draft pick position (1 = first overall) in the simulated season (present when sim_include="DRAFT").
standings.draft_tie_broken_byStringTiebreaker step that resolved the draft rank in this simulated season; null when no tiebreaker was needed.
games.simInt64Simulated season identifier the game row belongs to.
games.game_typeStringGame type - REG for regular season or the playoff round (WC, DIV, CON, SB).
games.weekInt64Week number of the game; simulated playoff rounds are numbered from the last regular season week (+1 for WC through +4 for SB).
games.away_teamStringTeam abbreviation of the away team (simulated playoff matchups are filled by seed).
games.home_teamStringTeam abbreviation of the home team (simulated playoff matchups are filled by seed).
games.away_restInt64Days of rest for the away team before the game.
games.home_restInt64Days of rest for the home team before the game (14 for the top seed's divisional round game).
games.locationStringGame site indicator - "Home" or "Neutral" (Super Bowl).
games.resultInt64Home margin (home score minus away score); real where the input schedule had one, simulated otherwise.
overall.confStringConference of the team (AFC or NFC).
overall.divisionStringDivision of the team (e.g. "AFC East").
overall.teamStringTeam abbreviation.
overall.winsFloat64Mean regular season wins across all simulated seasons (ties counted as half a win).
overall.playoffFloat64Share of simulated seasons in which the team made the playoffs (conference rank within playoff_seeds).
overall.div1Float64Share of simulated seasons in which the team won its division.
overall.seed1Float64Share of simulated seasons in which the team earned the conference number one seed.
overall.won_confFloat64Share of simulated seasons in which the team won the conference championship; null when sim_include="REG".
overall.won_sbFloat64Share of simulated seasons in which the team won the Super Bowl; null when sim_include="REG".
overall.draft1Float64Share of simulated seasons in which the team held the first overall draft pick; null unless sim_include="DRAFT".
overall.draft5Float64Share of simulated seasons in which the team held a top-five draft pick; null unless sim_include="DRAFT".
team_wins.teamStringTeam abbreviation.
team_wins.winsFloat64Half-win line the over/under probabilities are evaluated against (0, 0.5, ... up to the number of regular season games).
team_wins.over_probFloat64Probability across simulated seasons that the team's outright win total exceeds the line.
team_wins.under_probFloat64Probability across simulated seasons that the team's outright win total falls below the line (exact pushes are the remainder).
game_summary.game_typeStringGame type of the matchup - REG for regular season or the playoff round (WC, DIV, CON, SB).
game_summary.weekInt64Week number of the matchup.
game_summary.away_teamStringTeam abbreviation of the away team in the matchup.
game_summary.home_teamStringTeam abbreviation of the home team in the matchup.
game_summary.away_winsInt64Number of simulated seasons in which the away team won the matchup.
game_summary.home_winsInt64Number of simulated seasons in which the home team won the matchup.
game_summary.tiesInt64Number of simulated seasons in which the matchup ended in a tie.
game_summary.resultFloat64Mean home margin of the matchup across the simulated seasons in which it was played.
game_summary.games_playedInt64Number of simulated seasons in which this exact matchup occurred (playoff pairings only arise in the simulations that produce them).
game_summary.away_percentageFloat64Share of played simulations won by the away team, with ties counted as half a win.
game_summary.home_percentageFloat64Share of played simulations won by the home team, with ties counted as half a win.

Raises

ExceptionDescription
ValueErrorOn missing columns, more than one season, no games to simulate, or invalid argument values.

Example

import sportsdataverse.nfl as nfl
games = nfl.load_schedules([2024])
sim = nfl.nfl_simulations(games, simulations=1000, seed=42)
print(sim["overall"].head())

# Custom initial ELO ratings

sim = nfl.nfl_simulations(games, simulations=500, seed=1,
elo={"KC": 1700, "BUF": 1650})

# Pipeline next step (one line)

sim["overall"].sort("won_sb", descending=True).head()

nfl_usage_projection​

nfl_usage_projection(seasons: 'List[int]', target_season: 'int', *, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Project next-season target share, air-yards share, and WOPR.

Projects each player's shares via the shared Marcel blend (sportsdataverse.nfl.nfl_projection._marcel_blend — the same recency/shrinkage engine as the rate projection), assigns each player to their most recent team, renormalizes shares within each projected team to sum to 1.0 (the share invariant), and converts shares to volumes with a team-level carry-forward of pass attempts (team targets) and air yards. As-of-date clean: only seasons strictly before target_season are used.

Parameters

ParameterTypeDefaultDescription
seasonsList[int]History seasons to load.
target_seasonintThe season being projected.
return_as_pandasboolFalseIf True, returns a pandas dataframe.

Returns

player_id:Utf8, target_season:Int64, position_group:Utf8, proj_team:Utf8, proj_target_share:Float64, proj_air_yards_share:Float64, proj_wopr:Float64, proj_targets:Float64, proj_air_yards:Float64. Empty history returns a zero-row frame.

col_nametypedescription
player_idStringnflverse gsis player id (character join key).
target_seasonInt64The season being projected (features use strictly earlier seasons only).
position_groupStringnflverse offensive position group.
proj_teamStringMost recent team (max season, tiebreak most targets) - the renormalization group.
proj_target_shareFloat64Projected share of team targets - Marcel share blend renormalized to sum to 1.0 within proj_team.
proj_air_yards_shareFloat64Projected share of team air yards, renormalized within proj_team.
proj_woprFloat64Projected weighted opportunity rating - 1.5 x proj_target_share + 0.7 x proj_air_yards_share.
proj_targetsFloat64Projected targets - proj_target_share x team pass-target carry-forward.
proj_air_yardsFloat64Projected receiving air yards - proj_air_yards_share x team air-yards carry-forward.

Example

from sportsdataverse.nfl.nfl_usage_projection import nfl_usage_projection
usage = nfl_usage_projection([2021, 2022, 2023], 2024)
usage.sort("proj_wopr", descending=True).head()

opponent_adjusted_ridge​

opponent_adjusted_ridge(plays: 'pl.DataFrame', *, off_col: 'str', def_col: 'str', home_col: 'str', resp_col: 'str', lam: 'float', penalize_home: 'bool | float' = False, hfa_col: 'str | None' = None, weight_col: 'str | None' = None) -> 'tuple[pl.DataFrame, float, float]'

Ridge-regress resp_col on offense + defense team indicators + HFA.

League-agnostic (column names are arguments): builds the full offense/defense-indicator + intercept + home design and solves the ridge normal equations beta = (X'WX + lam*R)^-1 X'Wy. Only team coefficients are penalised; the intercept (and, unless penalize_home, the home term) is free. Moved (T7.2) from sportsdataverse.nfl.nfl_ratings. Callers: NFL ratings, CFB adjusted EPA (via hfa_col) and basketball team strength (via weight_col); cfb_ratings uses the different dropped_level_ridge.

Parameters

ParameterTypeDefaultDescription
playsDataFrameOne row per play. Rows with a null off_col / def_col / resp_col must be filtered by the caller.
off_colstrColumn naming the offense (possession) team.
def_colstrColumn naming the defense team.
home_colstrColumn naming the home team (HFA indicator is off_col == home_col).
resp_colstrNumeric response column (e.g. epa).
lamfloatRidge penalty applied to the team coefficients.
penalize_homebool | floatFalseAlso penalise the home-field coefficient (default False): True by lam, a number by that penalty (to shrink it toward h, subtract h times the home regressor from the response and add h back).
hfa_colstr | NoneNoneNumeric column used as the home regressor as-is (e.g. CFB's +1 home offense / 0 neutral site / -1 away), in place of the off_col == home_col indicator, which then goes unused. Must not contain nulls (raises ValueError).
weight_colstr | NoneNoneOptional per-row weight W (each finite and > 0, else ValueError): a row standing for that many identical rows, with resp_col their mean, gives the uncollapsed fit's coefficients.

Returns

A (frame, intercept, home_coef) tuple: frame has one row per team (team_id Utf8, off_coef / def_coef Float64); intercept is the league baseline; home_coef the fitted HFA in response units. Zero-row frame + (0.0, 0.0) on empty input.

Example

from sportsdataverse.nfl.nfl_ratings import opponent_adjusted_ridge
frame, intercept, hfa = opponent_adjusted_ridge(
plays, off_col="posteam", def_col="defteam",
home_col="home_team", resp_col="epa", lam=200.0,
)
frame.sort("off_coef", descending=True).head()

pressure_pairs​

pressure_pairs(pbp: 'pl.DataFrame') -> 'pl.DataFrame'

Per (season, off_team, def_team) dropbacks + pressures (matchup grid).

Parameters

ParameterTypeDefaultDescription
pbpDataFramenflverse play-by-play with season, posteam, defteam and the dropback / pressure flags.

Returns

One row per (season, off_team, def_team) matchup, with dropbacks and pressures (Int64), sorted by season and teams. A zero-row frame with that schema when the input has no dropbacks.

col_nametypedescription
seasonInt64Season of the matchup aggregate.
off_teamStringOffense team abbreviation.
def_teamStringDefense team abbreviation.
dropbacksInt64Offense dropbacks in the matchup.
pressuresInt64Sacks plus QB hits in the matchup.

special_teams_ratings​

special_teams_ratings(plays: 'pl.DataFrame', *, config: 'RatingsConfig | None' = None) -> 'pl.DataFrame'

One row per team: opponent-adjusted special-teams EPA per play.

Reuses opponent_adjusted_ridge (no forked solver) restricted to special == 1 plays with resp_col="epa"; adj_st_epa is the off_coef (the special-teams unit acting as "offense" on the play). Teams appearing anywhere in plays but on no special-teams play get the documented neutral fill adj_st_epa = 0.0.

Parameters

ParameterTypeDefaultDescription
playsDataFrameAn load_nfl_pbp-schema frame carrying posteam, defteam, home_team, epa, special. Not pre-filtered -- this function selects the ST plays itself.
configRatingsConfig | NoneNoneTuning knobs (only ridge_lambda is consulted); defaults to RatingsConfig.

Returns

One row per team_id (Utf8) with adj_st_epa (Float64). Zero-row, correctly-typed when plays is empty.

col_nametypedescription
team_idString
adj_st_epaFloat64

Example

from sportsdataverse.nfl.nfl_ratings import special_teams_ratings
st = special_teams_ratings(pbp)
st.sort("adj_st_epa", descending=True).head()

team_pressure_rates​

team_pressure_rates(pbp: 'pl.DataFrame') -> 'pl.DataFrame'

Per (season, team) raw pressure rates, both sides of the ball.

Parameters

ParameterTypeDefaultDescription
pbpDataFramenflverse-format pbp with season / posteam / defteam / qb_dropback / sack / qb_hit.

Returns

Per (season, team): dropbacks_off, pressures_allowed, pressure_rate_allowed, dropbacks_def, pressures_generated, pressure_rate_generated. Empty input yields a zero-row frame.

col_nametypedescription
seasonInt64Season of the aggregate.
teamStringTeam abbreviation.
dropbacks_offInt64Offensive dropbacks (qb_dropback plays).
pressures_allowedInt64Sacks plus QB hits allowed on the team's own dropbacks.
pressure_rate_allowedFloat64pressures_allowed / dropbacks_off.
dropbacks_defInt64Opponent dropbacks faced on defense.
pressures_generatedInt64Sacks plus QB hits generated against opponent dropbacks.
pressure_rate_generatedFloat64pressures_generated / dropbacks_def.

Example

from sportsdataverse.nfl import load_nfl_pbp
from sportsdataverse.nfl.nfl_line_grades import team_pressure_rates
rates = team_pressure_rates(load_nfl_pbp([2023]))
print(rates.sort("pressure_rate_generated", descending=True).head())

touchback_yardline_expr​

touchback_yardline_expr(season: 'pl.Expr') -> 'pl.Expr'

Polars form of touchback_yardline for a season column expression.

Parameters

ParameterTypeDefaultDescription
seasonExprInteger season expression (pl.col("season")).

Returns

An Int64 expression of the touchback yards-to-endzone per row.

Example

import polars as pl
from sportsdataverse.nfl.model_vars import touchback_yardline_expr

df = pl.DataFrame({"season": [2015, 2016, 2024, 2025]})
print(df.select(touchback_yardline_expr(pl.col("season"))).to_series().to_list())