Skip to main content
Version: 0.0.72

MLB — additional Python functions

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

Play-by-play, schedule & rosters

espn_mlb_game_rosters(game_id: 'int', raw: 'bool' = False, return_as_pandas: 'bool' = False, **kwargs)

espn_mlb_game_rosters - pull the active game rosters for both teams.

Parameters

ParameterTypeDefaultDescription
game_idintESPN game id.
rawboolFalseWhen True, returns the merged competitor + roster payload dict.
return_as_pandasboolFalseWhen True, returns a pandas dataframe; otherwise polars.

Returns

One row per (game × team × athlete) with columns game_id, team_id, home_away, athlete_id, athlete_full_name, athlete_jersey, athlete_position_id, athlete_position_abbreviation, athlete_starter.

Example

from sportsdataverse.mlb import espn_mlb_game_rosters
ros = espn_mlb_game_rosters(game_id=401569461)
print(ros.shape)
ros.group_by("home_away").len()

espn_mlb_pbp(game_id: 'int', raw: 'bool' = False, **kwargs) -> 'Dict'

espn_mlb_pbp - pull the full ESPN game-summary payload for one MLB game.

Parameters

ParameterTypeDefaultDescription
game_idintESPN game id (the "event id"). Obtainable from espn_mlb_schedule.
rawboolFalseWhen True, returns the full nested payload unchanged. When False (default), the same payload is returned for now — full parsing into a tidy plays / boxscore dict is not yet implemented; see the TODO below.

Returns

The Site v2 summary payload. Top-level keys typically include header, boxscore, plays, leaders, scoringPlays, gameInfo, winprobability, pickcenter, news, videos, standings, article, seasonseries, broadcasts, predictor.

Example

from sportsdataverse.mlb import espn_mlb_pbp
game = espn_mlb_pbp(game_id=401569461, raw=True)
sorted(game.keys())
print(game.get("header", {}).get("competitions", [{}])[0].get("date"))

# Iterate the plays array

plays = game.get("plays") or []
print(f"{len(plays)} plays")
for p in plays[:3]:
print(p.get("text"))

espn_mlb_player_stats(athlete_id: 'int', season: 'int', *, season_type: 'str' = 'regular', total: 'bool' = False, raw: 'bool' = False, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame | dict[str, Any]'

Pull an MLB athlete's ESPN season stat line as one wide row.

See sportsdataverse.wbb.espn_wbb_player_stats for full documentation of the wide return shape, the {category}_{stat} stat columns (for baseball: batting_*, pitching_*, fielding_*), the athlete / team metadata blocks, and the season_type / total parameters. For the richer multi-category web-v3 payload use sportsdataverse.mlb.espn_mlb_player_stats_v3.

Parameters

ParameterTypeDefaultDescription
athlete_idintESPN MLB athlete identifier (e.g. 33192 for Aaron Judge).
seasonintSeason year, used in the core-v2 path.
season_typestr'regular'"regular" (type 2) or "postseason" (type 3).
totalboolFalseForward-compat totals passthrough.
rawboolFalseIf True, returns the raw core-v2 statistics JSON dict.
return_as_pandasboolFalseIf True, returns a pandas DataFrame; else polars.

Returns

A single-row wide DataFrame (polars by default). When raw=True returns the raw statistics JSON dict.

col_nametypedescription
seasonintegerSeason year.
season_typecharacterSeason-type id.
totallogicalTotal.
athlete_idintegerUnique ESPN athlete identifier.
athlete_uidcharacterAthlete uid.
athlete_guidcharacterAthlete guid.
athlete_typecharacterAthlete type.
first_namecharacterPlayer first name.
last_namecharacterPlayer last name.
full_namecharacterPlayer's full name.
display_namecharacterDisplay name.
short_namecharacterShort display name.
weightdoubleWeight in pounds.
display_weightcharacterDisplay weight.
heightdoubleHeight (feet and inches).
display_heightcharacterDisplay height.
ageintegerPlayer age (in years).
date_of_birthcharacterDate of birth.
jerseycharacterJersey number worn by the player.
slugcharacterURL-safe identifier.
activelogicalWhether the player is currently active.
position_idintegerUnique position identifier.
position_namecharacterPosition name.
position_display_namecharacterPosition display name.
position_abbreviationcharacterPosition abbreviation.
college_namecharacterCollege name.
status_idintegerStatus id.
status_namecharacterGame status (e.g. 'STATUS_FINAL').
batting_games_playeddoubleTeam batting: batting games played.
batting_team_games_playeddoubleTeam batting: batting team games played.
batting_hit_by_pitchdoubleTeam batting: batting hit by pitch.
batting_ground_ballsdoubleTeam batting: batting ground balls.
batting_strikeoutsdoubleTeam batting: batting strikeouts.
batting_rb_isdoubleTeam batting: batting rb is.
batting_sac_hitsdoubleTeam batting: batting sac hits.
batting_hitsdoubleTeam batting: batting hits.
batting_stolen_basesdoubleTeam batting: batting stolen bases.
batting_walksdoubleTeam batting: batting walks.
batting_catcher_interferencedoubleTeam batting: batting catcher interference.
batting_runsdoubleTeam batting: batting runs.
batting_gid_psdoubleTeam batting: batting gid ps.
batting_sac_fliesdoubleTeam batting: batting sac flies.
batting_at_batsdoubleTeam batting: batting at bats.
batting_home_runsdoubleTeam batting: batting home runs.
batting_grand_slam_home_runsdoubleTeam batting: batting grand slam home runs.
batting_runners_left_on_basedoubleTeam batting: batting runners left on base.
batting_triplesdoubleTeam batting: batting triples.
batting_game_winning_rb_isdoubleTeam batting: batting game winning rb is.
batting_intentional_walksdoubleTeam batting: batting intentional walks.
batting_doublesdoubleTeam batting: batting doubles.
batting_fly_ballsdoubleTeam batting: batting fly balls.
batting_caught_stealingdoubleTeam batting: batting caught stealing.
batting_pitchesdoubleTeam batting: batting pitches.
batting_games_starteddoubleTeam batting: batting games started.
batting_pinch_at_batsdoubleTeam batting: batting pinch at bats.
batting_pinch_hitsdoubleTeam batting: batting pinch hits.
batting_player_ratingdoubleTeam batting: batting player rating.
batting_is_qualifieddoubleTeam batting: batting is qualified.
batting_is_qualified_stealsdoubleTeam batting: batting is qualified steals.
batting_total_basesdoubleTeam batting: batting total bases.
batting_plate_appearancesdoubleTeam batting: batting plate appearances.
batting_projected_home_runsdoubleTeam batting: batting projected home runs.
batting_extra_base_hitsdoubleTeam batting: batting extra base hits.
batting_runs_createddoubleTeam batting: batting runs created.
batting_avgdoubleTeam batting: batting average.
batting_pinch_avgdoubleTeam batting: batting pinch avg.
batting_slug_avgdoubleTeam batting: batting slug avg.
batting_secondary_avgdoubleTeam batting: batting secondary avg.
batting_on_base_pctdoubleTeam batting: batting on base pct.
batting_opsdoubleTeam batting: batting ops.
batting_ground_to_fly_ratiodoubleTeam batting: batting ground to fly ratio.
batting_runs_created_per27_outsdoubleBill James Runs Created per 27 outs, estimating how many runs a lineup of this batter would score per game.
batting_batter_ratingdoubleTeam batting: batting batter rating.
batting_at_bats_per_home_rundoubleTeam batting: batting at bats per home run.
batting_stolen_base_pctdoubleTeam batting: batting stolen base pct.
batting_pitches_per_plate_appearancedoubleTeam batting: batting pitches per plate appearance.
batting_isolated_powerdoubleTeam batting: batting isolated power.
batting_walk_to_strikeout_ratiodoubleTeam batting: batting walk to strikeout ratio.
batting_walks_per_plate_appearancedoubleTeam batting: batting walks per plate appearance.
batting_secondary_avg_minus_badoubleTeam batting: batting secondary avg minus ba.
batting_runs_produceddoubleTeam batting: batting runs produced.
batting_runs_ratiodoubleTeam batting: batting runs ratio.
batting_patience_ratiodoubleRatio of walks to strikeouts, measuring a batter's plate discipline and ability to work counts.
batting_bipadoubleBatting average on balls in the air (fly balls and line drives), measuring in-play success on airborne contact.
batting_mlb_ratingdoubleESPN's composite MLB rating for the batter reflecting overall offensive performance.
batting_off_warbrdoubleOffensive Wins Above Replacement (Baseball Reference methodology) attributable to the batter's hitting contributions.
batting_warbrdoubleTotal Wins Above Replacement (Baseball Reference methodology) for the batter including offense and baserunning.
fielding_games_playeddoubleNumber of games in which the player appeared defensively at their position.
fielding_team_games_playeddoubleNumber of games the player's team played while the player was on the active roster.
fielding_double_playsdoubleNumber of double plays the fielder participated in during the season.
fielding_opportunitiesdoubleTotal fielding opportunities defined as putouts plus assists plus errors for the player.
fielding_errorsdoubleNumber of fielding errors charged to the player during the season.
fielding_passed_ballsdoubleNumber of pitches ruled as passed balls charged to the catcher during the season.
fielding_assistsdoubleNumber of assists recorded by the fielder when a thrown ball contributes to an out.
fielding_outfield_assistsdoubleNumber of outfield assists, recorded when an outfielder throws out a runner.
fielding_pickoffsdoubleNumber of baserunners picked off by pitchers while this catcher was behind the plate or this fielder was at their position.
fielding_putoutsdoubleNumber of putouts recorded by the fielder where they made the final play to retire a batter or runner.
fielding_outs_on_fielddoubleTotal outs recorded across all innings the player was present on the field.
fielding_triple_playsdoubleNumber of triple plays in which the fielder participated during the season.
fielding_balls_in_zonedoubleNumber of batted balls that entered the fielder's defined defensive zone.
fielding_extra_basesdoubleExtra bases allowed by the outfielder due to errors or misplays on balls hit into their zone.
fielding_outs_madedoubleTotal outs the fielder was directly responsible for recording during the season.
fielding_hitsdoubleNumber of hits recorded while this fielder was positioned, relevant for zone-rating calculations.
fielding_total_basesdoubleTotal bases allowed by the outfielder on balls hit into their zone, used in advanced defensive metrics.
fielding_games_starteddoubleNumber of games the player started at their primary defensive position.
fielding_catcher_third_innings_playeddoubleTotal one-third innings played behind the plate by the catcher, expressed in thirds.
fielding_catcher_caught_stealingdoubleNumber of opposing baserunners thrown out attempting to steal a base by this catcher.
fielding_catcher_stolen_bases_alloweddoubleNumber of successful stolen bases allowed by the catcher during the season.
fielding_catcher_earned_runsdoubleEarned runs allowed while this catcher was behind the plate, used in catcher ERA calculations.
fielding_is_qualifieddoubleIndicator flag for whether the player meets minimum innings requirements to qualify for fielding rate stats.
fielding_is_qualified_catcherdoubleIndicator flag for whether the catcher meets the minimum innings threshold to qualify for catcher-specific rate stats.
fielding_is_qualified_pitcherdoubleIndicator flag for whether the pitcher qualifies for pitcher fielding rate statistics.
fielding_successful_chancesdoubleTotal successful fielding chances defined as putouts plus assists (errors excluded).
fielding_total_chancesdoubleTotal fielding chances (putouts + assists + errors) offered to the player during the season.
fielding_full_innings_playeddoubleNumber of complete innings (three outs per side) the player appeared in the field.
fielding_part_innings_playeddoubleNumber of fractional (partial) innings the player appeared in the field, expressed as a count of thirds.
fielding_fielding_pctdoubleFielding percentage calculated as successful chances divided by total chances (putouts + assists + errors).
fielding_range_factordoubleRange factor per nine innings (putouts + assists) / innings * 9, measuring a fielder's defensive range.
fielding_zone_ratingdoublePercentage of batted balls in the fielder's defined zone that were successfully converted into outs.
fielding_catcher_caught_stealing_pctdoublePercentage of opposing stolen base attempts that resulted in the catcher throwing out the runner.
fielding_catcher_eradoubleERA of pitchers while this specific catcher was behind the plate over the season.
fielding_def_warbrdoubleDefensive Wins Above Replacement (Baseball Reference methodology) attributable to the player's fielding.
team_idintegerUnique ESPN team identifier.
team_uidcharacterESPN universal team identifier (UID).
team_guidcharacterESPN team GUID.
team_slugcharacterURL-safe team identifier.
team_locationcharacterTeam city / location.
team_namecharacterTeam name.
team_abbreviationcharacterShort team abbreviation (e.g. 'NYY').
team_display_namecharacterFull team display name (e.g. 'New York Yankees').
team_short_display_namecharacterShort team display name.
team_colorcharacterTeam primary color (hex, no leading '#').
team_alternate_colorcharacterTeam alternate color (hex).
team_is_activelogicalTeam is active.
team_logo_hrefcharacterDefault team logo URL; team_detail = TRUE only.

Example

from sportsdataverse.mlb import espn_mlb_player_stats
df = espn_mlb_player_stats(athlete_id=33192, season=2023)
df.select(["full_name", "team_display_name", "batting_home_runs"])

espn_mlb_schedule(dates=None, season_type=None, limit=500, return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_mlb_schedule - look up the MLB schedule for a given date or season-year.

Parameters

ParameterTypeDefaultDescription
datesintNoneDate filter. Either a calendar date as YYYYMMDD or a season-year (e.g. 2024). When a 4-digit year is passed, the call returns the full season slate (paginated by limit).
season_typeintNoneSeason type — 1 = spring training, 2 = regular, 3 = postseason, 4 = all-star.
limitint500Number of records to return. Default 500.
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False (default), returns a polars dataframe.

Returns

Polars dataframe containing the schedule. Returns None if no games.

col_nametypedescription
game_idcharacterUnique ESPN game/event identifier.
datecharacterDate in YYYY-MM-DD format.
season_yearintegerSeason year string ('YYYY-YY' format).
season_typeintegerSeason-type id.
status_type_statecharacterStatus state (pre/in/post).
status_type_completedlogicalWhether the game is complete.
status_type_descriptioncharacterStatus type description.
venue_idcharacterMLBAM venue ID.
venue_full_namecharacterVenue full name.
venue_citycharacterVenue city.
venue_statecharacterVenue state / province.
home_idcharacterUnique identifier for home.
home_namecharacterHome team display name.
home_abbreviationcharacterHome team's abbreviation.
home_display_namecharacterHome team display name.
home_scorecharacterHome team run total after the play.
home_winnerlogicalWhether the home team won.
away_idcharacterUnique identifier for away.
away_namecharacterAway team display name.
away_abbreviationcharacterAway team's abbreviation.
away_display_namecharacterAway team display name.
away_scorecharacterAway team run total after the play.
away_winnerlogicalWhether the away team won.

Example

from sportsdataverse.mlb import espn_mlb_schedule
sched = espn_mlb_schedule(dates=20240328)
print(sched.shape)
sched.select(["game_id", "home_name", "away_name", "status_type_description"]).head()

# Pull a regular-season slate from a season-year

reg = espn_mlb_schedule(dates=2024, season_type=2, limit=500)
reg.group_by("status_type_description").len().sort("len", descending=True)

# Pandas round-trip for one date

espn_mlb_schedule(dates=20240328, return_as_pandas=True).head()

Utilities & helpers

most_recent_mlb_season() -> 'int'

most_recent_mlb_season - return the most recent / current MLB season year.

MLB seasons run calendar-year. Before April we still consider the previous year the "most recent" season (since spring training only starts in late February).

Returns

The most recent MLB season year (e.g. 2024).

Other

add_sequence_features(feats: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Add within-game sequence, times-through-order, and workload features.

Consumes the output of pitch_features. Within each plate appearance (game_pk, pitcher, at_bat_number, sorted by pitch_number), adds prev_pitch_type/prev_release_pos_x/ prev_release_pos_z/prev_plate_x/prev_plate_z via shift(1). Within each game (game_pk, pitcher, sorted by at_bat_number then pitch_number), adds cum_pitches_game (running pitch count), batter_faced_index (distinct-at_bat_number rank), and times_through_order (min(3, (batter_faced_index-1)//9+1)). Every lag/rank is .over(...) scoped to avoid cross-game leakage.

Parameters

ParameterTypeDefaultDescription
featsDataFrameOutput of pitch_features.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

feats plus the sequence/TTO/workload columns described above. Empty input returns a zero-row frame carrying the full schema.

col_nametypedescription
prev_pitch_typecharacterPitch type of the previous pitch in the same plate appearance (null on the first pitch).
prev_release_pos_xdoubleHorizontal release position of the previous pitch in the same plate appearance.
prev_release_pos_zdoubleVertical release position of the previous pitch in the same plate appearance.
prev_plate_xdoubleHorizontal plate location of the previous pitch in the same plate appearance.
prev_plate_zdoubleVertical plate location of the previous pitch in the same plate appearance.
cum_pitches_gameintegerRunning count of pitches thrown by this pitcher so far in this game (inclusive of the current pitch).
batter_faced_indexintegerDense rank of this plate appearance's at_bat_number within the game (1 = first batter faced).
times_through_orderintegerTimes through the batting order, min(3, (batter_faced_index-1)//9 + 1).

Example

from sportsdataverse.mlb.mlb_pitch_features import pitch_features, add_sequence_features
feats = add_sequence_features(pitch_features(raw))
print(feats.select("times_through_order", "cum_pitches_game").tail())

advancement_opportunities(events: "'pl.DataFrame'") -> "'pl.DataFrame'"

Extract first-to-third / second-to-home / tag-up opportunities and outcomes.

One plate-appearance row (the terminal, non-null-events pitch of each (game_pk, at_bat_number)) is matched against the next plate appearance's pre-play occupancy (on_1b/on_2b/on_3b, shifted within game_pk) to read the post-play base state.

Parameters

ParameterTypeDefaultDescription
eventsDataFramePitch-level frame (a sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search output) with game_pk, at_bat_number, on_1b, on_2b, on_3b, events.

Returns

one row per detected opportunity. | Column | Type | Description | |---|---|---| | runner_id | Utf8 | MLBAM id of the runner facing the advancement decision | | opp_type | Utf8 | first_to_third | second_to_home | tag_up | | took_extra | Int8 | 1 if the runner advanced the extra base, else 0 |

Example

from sportsdataverse.mlb.mlb_baserunning import advancement_opportunities
opps = advancement_opportunities(pitches)

as_of_split(events: "'pl.DataFrame'", cutoff_date: 'Any', *, date_col: 'str' = 'game_date') -> "'pl.DataFrame'"

Leakage boundary: rows strictly before cutoff_date only.

The predictive path of the stolen-base (and, where predictive, baserunning) model must derive runner/catcher features only from data known before the event being scored -- this helper is the one place that boundary is enforced, so every predictive caller shares it.

Parameters

ParameterTypeDefaultDescription
eventsDataFrameAny frame carrying a date column.
cutoff_dateAnyExclusive upper bound (rows with date_col < cutoff_date are kept).
date_colstr'game_date'Name of the date column. Defaults to "game_date".

Returns

the filtered frame (unchanged if empty or missing date_col).

Example

from sportsdataverse.mlb.mlb_run_values import as_of_split
history = as_of_split(events, cutoff_date=dt.date(2024, 6, 15))

bip_trajectory_features(bip: "'pl.DataFrame'") -> "'pl.DataFrame'"

Add spray angle / hit distance / launch-angle bin / out label / position.

spray_angle = atan2(hc_x - 125.42, 198.27 - hc_y) (Savant's standard hc_x/hc_y transform, home plate at the origin, positive = toward first base).

Parameters

ParameterTypeDefaultDescription
bipDataFrameBalls-in-play frame (hc_x, hc_y, hit_distance_sc, launch_angle, events, hit_location).

Returns

bip with added spray_angle (Float64), hit_dist (Float64), la_bin (Int64), is_out (Int8), position (Int64).

Example

from sportsdataverse.mlb.mlb_fielding_oaa import bip_trajectory_features
feats = bip_trajectory_features(bip)

build_we_table(states: 'pl.DataFrame', results: 'pl.DataFrame', *, laplace: 'float' = 1.0) -> 'pl.DataFrame'

Empirical, Laplace-smoothed home win-expectancy table.

Parameters

ParameterTypeDefaultDescription
statesDataFrameOutput of pbp_base_out_states.
resultsDataFrameGame-level results with game_id (same dtype as states), home_score, away_score.
laplacefloat1.0Additive smoothing constant (default 1.0).

Returns

one row per observed state bucket. | Column | Type | Description | |---|---|---| | inning_capped | Int64 | Inning, capped at 9 | | half | Utf8 | "top" or "bottom" | | base_state | Utf8 | 3-char base occupancy | | outs_start | Int64 | Outs before the play (0-2) | | score_diff_bucket | Int64 | home - away score, clipped to [-6, 6] | | home_win_exp | Float64 | Laplace-smoothed P(home wins | state) | | n | Int64 | Plate appearances observed in this bucket |

col_nametypedescription
inning_cappedintegerInning number, capped at 9 (extra innings pooled with the 9th).
halfcharacterHalf-inning ("top" or "bottom").
base_statecharacter3-char base occupancy code.
outs_startintegerOuts before the play (0-2).
score_diff_bucketintegerhome minus away score, clipped to [-6, 6].
home_win_expdoubleLaplace-smoothed empirical P(home team wins | state bucket).
nintegerPlate appearances observed in this state bucket.

Example

from sportsdataverse.mlb.mlb_run_expectancy import pbp_base_out_states
from sportsdataverse.mlb.mlb_win_expectancy import build_we_table
states = pbp_base_out_states(pbp)
table = build_we_table(states, results)

called_strike_prob_grid(pitches: "'pl.DataFrame'", *, x_bin: 'float' = 0.1, z_bin: 'float' = 0.1, alpha: 'float' = 1.0) -> "'pl.DataFrame'"

Empirical called-strike-probability grid over (stand, plate_x, pz_norm).

Pitch height is normalized within the batter's strike zone (pz_norm = (plate_z - sz_bot) / (sz_top - sz_bot)) so the grid is zone-relative and comparable across batters; plate_x is kept raw (feet from the plate's center). Rate per bin is Laplace-smoothed: (strikes + alpha) / (n + 2 * alpha).

Parameters

ParameterTypeDefaultDescription
pitchesDataFramePitch-level takes frame (plate_x, plate_z, sz_top, sz_bot, stand, description).
x_binfloat0.1Bin width for plate_x, in feet. Defaults to 0.1.
z_binfloat0.1Bin width for zone-normalized height. Defaults to 0.1.
alphafloat1.0Laplace smoothing strength. Defaults to 1.0.

Returns

one row per observed (stand, px_bin, pz_bin). | Column | Type | Description | |---|---|---| | stand | Utf8 | Batter handedness (L/R) | | px_bin | Int64 | Horizontal plate-location bin index | | pz_bin | Int64 | Zone-normalized vertical bin index | | p_strike | Float64 | Laplace-smoothed empirical called-strike probability | | n | Int64 | Takes observed in this bin |

Example

from sportsdataverse.mlb.mlb_catcher_framing import called_strike_prob_grid
grid = called_strike_prob_grid(pitches, alpha=1.0)

catch_prob_surface(bip: "'pl.DataFrame'", *, dist_bin: 'float' = 10.0, spray_bin: 'float' = 0.1, alpha: 'float' = 2.0) -> "'pl.DataFrame'"

Empirical catch-probability surface over (position, distance, spray, launch angle).

Rate per bin is Laplace-smoothed: (outs + alpha) / (n + 2 * alpha).

Parameters

ParameterTypeDefaultDescription
bipDataFrameBalls-in-play frame (see bip_trajectory_features).
dist_binfloat10.0Bin width for hit distance, in feet. Defaults to 10.0.
spray_binfloat0.1Bin width for spray angle, in radians. Defaults to 0.1.
alphafloat2.0Laplace smoothing strength. Defaults to 2.0.

Returns

one row per observed (position, dist_b, spray_b, la_bin). | Column | Type | Description | |---|---|---| | position | Int64 | Responsible fielder position (Savant hit_location, 1-9) | | dist_b | Int64 | Hit-distance bin index | | spray_b | Int64 | Spray-angle bin index | | la_bin | Int64 | Launch-angle bin index (hang-time proxy) | | p_catch | Float64 | Laplace-smoothed empirical out (catch) probability | | n | Int64 | Balls in play observed in this bin |

Example

from sportsdataverse.mlb.mlb_fielding_oaa import catch_prob_surface
surface = catch_prob_surface(bip, alpha=2.0)

count_strike_run_value(pitches: "'pl.DataFrame'") -> "'pl.DataFrame'"

Ball-to-strike run-expectancy delta per count, from delta_run_exp.

strike_run_value is positive = runs saved by the defense per stolen strike, since a called strike carries negative delta_run_exp for the batting team relative to a ball in the same count: strike_run_value = -(E[delta_run_exp | called_strike, count] - E[delta_run_exp | ball, count]).

Parameters

ParameterTypeDefaultDescription
pitchesDataFramePitch-level frame with balls, strikes, description, and delta_run_exp columns (a sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search frame). Rows other than called_strike/ball are ignored.

Returns

one row per observed count. | Column | Type | Description | |---|---|---| | balls | Int64 | Ball count (0-3) entering the pitch | | strikes | Int64 | Strike count (0-2) entering the pitch | | strike_run_value | Float64 | Runs saved by the defense per called strike vs. a ball in this count |

Example

from sportsdataverse.mlb.mlb_run_values import count_strike_run_value
rv = count_strike_run_value(pitches)

espn_mlb_teams(return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_mlb_teams - look up MLB teams from ESPN's Site v2 API.

Parameters

ParameterTypeDefaultDescription
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False (default), returns a polars dataframe.

Returns

Polars dataframe containing teams for MLB. This function caches by default, so if you want to refresh the data, use sportsdataverse.mlb.espn_mlb_teams.cache_clear().

col_nametypedescription
team_abbreviationcharacterShort team abbreviation (e.g. 'NYY').
team_alternate_colorcharacterTeam alternate color (hex).
team_colorcharacterTeam primary color (hex, no leading '#').
team_display_namecharacterFull team display name (e.g. 'New York Yankees').
team_idcharacterUnique ESPN team identifier.
team_is_activelogicalTeam is active.
team_is_all_starlogicalTeam is all star.
team_locationcharacterTeam city / location.
team_logosintegerTeam logo metadata.
team_namecharacterTeam name.
team_nicknamecharacterTeam nickname.
team_short_display_namecharacterShort team display name.
team_slugcharacterURL-safe team identifier.
team_uidcharacterESPN universal team identifier (UID).

Example

from sportsdataverse.mlb import espn_mlb_teams
teams = espn_mlb_teams()
print(teams.shape)
teams.select(["team_id", "team_abbreviation", "team_display_name"]).head()

# Find Los Angeles Dodgers (team_id 19)

import polars as pl
teams.filter(pl.col("team_id") == "19").to_dicts()

# Refresh the cache (the call is ``lru_cache``'d) and round-trip to pandas

espn_mlb_teams.cache_clear()
teams_pd = espn_mlb_teams(return_as_pandas=True)
teams_pd[["team_id", "team_abbreviation", "team_display_name"]].head()

event_run_value(pitches: "'pl.DataFrame'", events: "'List[str]'") -> 'float'

Empirical run value of an event set, from mean delta_run_exp.

Parameters

ParameterTypeDefaultDescription
pitchesDataFramePitch-level frame with an events column and delta_run_exp.
eventsList[str]Statcast events values to average over (e.g. ["stolen_base_2b"]).

Returns

Mean delta_run_exp over rows whose events is in events. 0.0 if the frame is empty, lacks delta_run_exp, or no rows match.

Example

from sportsdataverse.mlb.mlb_run_values import event_run_value
rv_sb = event_run_value(pitches, ["stolen_base_2b", "stolen_base_3b"])

fit_zone_model(pitches: 'pl.DataFrame') -> 'Dict[str, Any]'

Fit a logistic P(called strike | zone coordinates) on called pitches.

Compute-on-demand -- no artifact is bundled or cached to disk. L2-regularized (1e-4) mean log-loss, minimized via scipy.optimize.minimize(method="L-BFGS-B").

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameFrame of pitches with description (filtered to {"called_strike", "ball"}), plate_x, plate_z, sz_top, sz_bot.

Returns

{"coef": list[float] (7,), "intercept": float, "features": list[str]}. {"coef": [], "intercept": 0.0, "features": [...]} if fewer than 2 called pitches are available (degenerate fit).

Example

from sportsdataverse.mlb.mlb_umpire_zone import fit_zone_model
model = fit_zone_model(pitches)

fox_mlb_league_leaders(category: 'str' = 'batting', who: 'str' = 'player', page: 'int' = 0, *, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "Union[pl.DataFrame, 'pd.DataFrame', Dict[str, Any]]"

MLB statistical leaders (stats-con); who=player|team.

Parameters

ParameterTypeDefaultDescription
categorystr'batting'Stat category. Defaults to "batting".
whostr'player'"player" or "team". Defaults to "player".
pageint00-based result page. Defaults to 0.
return_parsedboolTrueIf True (default) flatten the leader tables to a DataFrame; if False return the raw JSON dict.
return_as_pandasboolFalseIf True return a pandas DataFrame; otherwise polars. Ignored when return_parsed=False.

Returns

A polars DataFrame (default), a pandas DataFrame when return_as_pandas=True, or the raw JSON dict when return_parsed=False.

Example

from sportsdataverse.mlb import fox_mlb_league_leaders
df = fox_mlb_league_leaders("batting")

fox_mlb_odds(game_id: 'Union[int, str]', *, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "Union[pl.DataFrame, 'pd.DataFrame', Dict[str, Any]]"

MLB game odds six-pack (run line / to-win / total per team).

Parameters

ParameterTypeDefaultDescription
game_idUnion[int, str]Fox Bifrost event id.
return_parsedboolTrueIf True (default) flatten the six-pack market to a DataFrame; if False return the raw JSON dict.
return_as_pandasboolFalseIf True return a pandas DataFrame; otherwise polars. Ignored when return_parsed=False.

Returns

A polars DataFrame (default), a pandas DataFrame when return_as_pandas=True, or the raw JSON dict when return_parsed=False.

Example

from sportsdataverse.mlb import fox_mlb_odds
df = fox_mlb_odds("...")

fox_mlb_standings(team_id: 'Union[int, str]', *, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "Union[pl.DataFrame, 'pd.DataFrame', Dict[str, Any]]"

MLB standings for a team's division/league.

Parameters

ParameterTypeDefaultDescription
team_idUnion[int, str]Fox Bifrost team id.
return_parsedboolTrueIf True (default) flatten the standings tables to a DataFrame; if False return the raw JSON dict.
return_as_pandasboolFalseIf True return a pandas DataFrame; otherwise polars. Ignored when return_parsed=False.

Returns

A polars DataFrame (default), a pandas DataFrame when return_as_pandas=True, or the raw JSON dict when return_parsed=False.

Example

from sportsdataverse.mlb import fox_mlb_standings
df = fox_mlb_standings("...")

fox_mlb_team_gamelog(team_id: 'Union[int, str]', *, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "Union[pl.DataFrame, 'pd.DataFrame', Dict[str, Any]]"

MLB team game log (long: one row per game-stat).

Parameters

ParameterTypeDefaultDescription
team_idUnion[int, str]Fox Bifrost team id.
return_parsedboolTrueIf True (default) flatten to long form; if False return the raw JSON dict.
return_as_pandasboolFalseIf True return a pandas DataFrame; otherwise polars. Ignored when return_parsed=False.

Returns

A polars DataFrame (default), a pandas DataFrame when return_as_pandas=True, or the raw JSON dict when return_parsed=False.

Example

from sportsdataverse.mlb import fox_mlb_team_gamelog
df = fox_mlb_team_gamelog("...")

fox_mlb_team_roster(team_id: 'Union[int, str]', *, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "Union[pl.DataFrame, 'pd.DataFrame', Dict[str, Any]]"

MLB team roster (one row per player).

Parameters

ParameterTypeDefaultDescription
team_idUnion[int, str]Fox Bifrost team id.
return_parsedboolTrueIf True (default) flatten the position-group tables to a DataFrame; if False return the raw JSON dict.
return_as_pandasboolFalseIf True return a pandas DataFrame; otherwise polars. Ignored when return_parsed=False.

Returns

A polars DataFrame (default), a pandas DataFrame when return_as_pandas=True, or the raw JSON dict when return_parsed=False.

Example

from sportsdataverse.mlb import fox_mlb_team_roster
df = fox_mlb_team_roster("...")

fox_mlb_team_stats(team_id: 'Union[int, str]', *, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "Union[pl.DataFrame, 'pd.DataFrame', Dict[str, Any]]"

MLB team stat leaders by category.

Parameters

ParameterTypeDefaultDescription
team_idUnion[int, str]Fox Bifrost team id.
return_parsedboolTrueIf True (default) flatten the leader sections to a DataFrame; if False return the raw JSON dict.
return_as_pandasboolFalseIf True return a pandas DataFrame; otherwise polars. Ignored when return_parsed=False.

Returns

A polars DataFrame (default), a pandas DataFrame when return_as_pandas=True, or the raw JSON dict when return_parsed=False.

Example

from sportsdataverse.mlb import fox_mlb_team_stats
df = fox_mlb_team_stats("...")

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

mlb_attendance(team_id: 'Optional[int]' = None, league_id: 'Optional[Union[int, str]]' = None, season: 'Optional[Union[int, str]]' = None, league_list_id: 'Optional[str]' = None, game_type: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/attendance — game attendance figures.

Parameters

ParameterTypeDefaultDescription
team_idOptional[int]None
league_idOptional[Union[int, str]]None
seasonOptional[Union[int, str]]None
league_list_idOptional[str]None
game_typeOptional[str]None

mlb_baserunning_value(events: "'pl.DataFrame'", sprint_speed: "'pl.DataFrame'", *, speed_bin: 'float' = 1.0, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-runner baserunning runs from extra-bases-taken above expected.

Expected extra-base probability is an empirical rate by (opp_type, speed_bin); baserunning_runs = extra_bases_above_expected * RUN_VALUES["extra_base"].

Parameters

ParameterTypeDefaultDescription
eventsDataFramePitch-level frame passed to advancement_opportunities. MiLB feeds run through the same function -- there is no Savant baserunning leaderboard oracle for MiLB.
sprint_speedDataFrameA sportsdataverse.mlb.mlb_statcast.mlb_statcast_leaderboard_sprint_speed frame with runner_id (Utf8) and sprint_speed.
speed_binfloat1.0Bin width (ft/sec) for the sprint-speed bucket. Defaults to 1.0.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

one row per runner. | Column | Type | Description | |---|---|---| | runner_id | Utf8 | Runner MLBAM id | | opportunities | Int64 | Advancement opportunities faced | | extra_bases_above_expected | Float64 | Sum of (took_extra - expected rate) | | baserunning_runs | Float64 | extra_bases_above_expected x RUN_VALUES["extra_base"] |

Example

from sportsdataverse.mlb.mlb_baserunning import mlb_baserunning_value
baserunning = mlb_baserunning_value(pitches, sprint_speed)

mlb_batter_projection(target_season: 'int', *, history: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Next-season xwOBA projection (Marcel + delta-method aging) for every batter.

If history is None, builds player-season xwOBA history via sportsdataverse.mlb.mlb_expected_stats.mlb_expected_stats across the three seasons before target_season (ages must already be present on a supplied history frame -- this convenience path is intended for callers who already maintain an age-joined roster history).

Parameters

ParameterTypeDefaultDescription
target_seasonintThe season being projected.
historyOptional[DataFrame]NonePre-built player-season history (batter, season, age, xwoba, pa). If None, uses mlb_expected_stats over target_season - 3 .. target_season - 1.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per batter: age, proj_xwoba, proj_pa. Empty history returns a zero-row frame with the documented schema.

col_nametypedescription
batterintegerMLBAM batter id.
ageintegerBatter's projected age in target_season (last known age plus one).
proj_xwobadoubleMarcel-style weighted, PA-regressed, aging-curve-adjusted xwOBA projection for target_season.
proj_padoubleSum of plate appearances across the weighted lookback seasons used to build the projection.

Example

from sportsdataverse.mlb.mlb_batter_projection import mlb_batter_projection

proj = mlb_batter_projection(2024, history=player_season_history)
print(proj.shape)

# Pipeline next step (one line)

proj.sort("proj_xwoba", descending=True).head()

mlb_catcher_blocking(pitches: "'pl.DataFrame'", *, dirt_bin_width: 'float' = 0.2, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-catcher blocking runs from a dirt-pitch block-probability model.

A block opportunity is a pitch below the strike zone (pz_norm < 0) with a runner on base, or a pitch whose des narrates a wild pitch/passed ball (see module docstring for why des, not events). Expected block probability is the empirical block rate within the pitch's dirt-depth bin; blocking_runs = blocks_above_expected * RUN_VALUES["wp_pb"] (the documented fallback constant -- the narrating row's delta_run_exp bundles the primary batter outcome with the WP/PB and cannot isolate the latter's value).

Parameters

ParameterTypeDefaultDescription
pitchesDataFramePitch-level frame with plate_z/sz_top/sz_bot, fielder_2, des (or events as a fallback), and (if present) on_1b/on_2b/on_3b. MiLB feeds (e.g. sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search_minors) run through the same function -- there is no Savant blocking leaderboard oracle for MiLB.
dirt_bin_widthfloat0.2Bin width for the below-zone depth bucket. Defaults to 0.2 (zone-normalized units).
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

one row per catcher. | Column | Type | Description | |---|---|---| | catcher_id | Utf8 | Catcher MLBAM id (Savant fielder_2) | | block_opps | Int64 | Dirt-pitch block opportunities faced | | blocks_above_expected | Float64 | Sum of (blocked - expected block rate) | | blocking_runs | Float64 | blocks_above_expected x RUN_VALUES["wp_pb"] |

Example

from sportsdataverse.mlb.mlb_catcher_defense import mlb_catcher_blocking
blocking = mlb_catcher_blocking(pitches)

# Pipeline next step (one line)

blocking.filter(pl.col("block_opps") >= 50).sort("blocking_runs", descending=True)

mlb_catcher_framing(pitches: "'pl.DataFrame'", *, shadow_lo: 'float' = 0.1, shadow_hi: 'float' = 0.9, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-catcher framing runs from a smooth called-strike logistic (Savant method).

A logistic P(called strike | zone location) is fit on all takes (the T6.4 zone model, sportsdataverse.mlb.mlb_umpire_zone.mlb_umpire_called_strike_prob); then, over shadow-zone takes only -- those with shadow_lo <= P_strike <= shadow_hi, i.e. near the rulebook edge where receiving actually moves the call -- framing_run = (actual_strike - P_strike) * strike_run_value(count). strike_run_value is the count's defensive run value from sportsdataverse.mlb.mlb_run_values.count_strike_run_value. Summed per catcher (Savant's fielder_2, cast Utf8 at the boundary). The takes column counts all takes handled (workload), while the runs sum only over the frameable shadow-zone subset.

Parameters

ParameterTypeDefaultDescription
pitchesDataFramePitch-level frame with the take columns (plate_x/plate_z/sz_top/sz_bot/stand/ description/balls/strikes/delta_run_exp/ fielder_2). MiLB feeds (e.g. sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search_minors) run through the same function -- there is simply no Savant leaderboard oracle to gate MiLB output against.
shadow_lofloat0.1Lower P(strike) bound of the frameable shadow zone. Defaults to 0.1.
shadow_hifloat0.9Upper P(strike) bound of the frameable shadow zone. Defaults to 0.9.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

one row per catcher. | Column | Type | Description | |---|---|---| | catcher_id | Utf8 | Catcher MLBAM id (Savant fielder_2) | | takes | Int64 | Called-strike + ball takes caught (all, workload) | | framing_runs | Float64 | Sum over shadow-zone takes of (actual - P_strike) x count run-value | | strikes_gained | Float64 | Sum over shadow-zone takes of (actual - P_strike), run-value-free |

Example

from sportsdataverse.mlb.mlb_catcher_framing import mlb_catcher_framing
framing = mlb_catcher_framing(pitches)

# Useful parameter combination

framing_pd = mlb_catcher_framing(pitches, shadow_lo=0.15, shadow_hi=0.85, return_as_pandas=True)

# Pipeline next step (one line)

framing.filter(pl.col("takes") >= 500).sort("framing_runs", descending=True)

mlb_catcher_throwing(sb_attempts: "'pl.DataFrame'", poptime: "'Optional[pl.DataFrame]'" = None, *, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-catcher caught-stealing (throwing) value = caught-stealing above average.

Mirrors Savant's catcher_stealing_runs leaderboard: throwing_runs = cs_above_expected * |RUN_VALUES["cs"] - RUN_VALUES["sb"]| where cs_above_expected sums (caught - expected CS rate) over the catcher's attempts. The expected CS rate is catcher-INDEPENDENT -- the empirical league CS rate for the attempt's difficulty stratum (the attempted base, since a steal of 3rd is caught far more often than a steal of 2nd), NOT a function of the catcher's own pop time. The catcher's arm/pop time/exchange is the skill that produces caught-stealings above that baseline; the prior implementation conditioned the expectation on the catcher's own binned pop time, which cancelled exactly the signal Savant measures (it correlated ~0 / slightly negative with the leaderboard -- the fixed model correlates positively).

Run value uses the documented RUN_VALUES fallback constants (see sportsdataverse.mlb.mlb_stolen_base for why a real-capture attempt's delta_run_exp cannot isolate the steal's own run value from the bundled primary batter outcome it is narrated alongside).

Parameters

ParameterTypeDefaultDescription
sb_attemptsDataFrameOne row per stolen-base attempt (see sportsdataverse.mlb.mlb_stolen_base.sb_attempts_from_pitches), with catcher_id (Utf8), outcome ("success" \
poptimeOptional[DataFrame]NoneAccepted for call-site compatibility and not used -- pop time is the catcher's own skill (the mechanism producing above-average CS), so it must never enter the expected CS model.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

one row per catcher. | Column | Type | Description | |---|---|---| | catcher_id | Utf8 | Catcher MLBAM id | | attempts | Int64 | Stolen-base attempts caught behind the plate | | cs_above_expected | Float64 | Sum of (caught - per-base league CS rate) | | throwing_runs | Float64 | cs_above_expected x |RUN_VALUES["cs"] - RUN_VALUES["sb"]| |

Example

from sportsdataverse.mlb.mlb_catcher_defense import mlb_catcher_throwing
throwing = mlb_catcher_throwing(sb_attempts)

mlb_command_plus(pitches: 'pl.DataFrame', *, level: 'str' = 'pitch', return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Score pitches with the bundled Command+/Location+ (②) run-value model.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameOutput of sportsdataverse.mlb.mlb_pitch_features.pitch_features (needs plate_x_abs, plate_z_norm, in_zone, dist_from_heart, balls, strikes, stand, p_throws, pitch_type).
levelstr'pitch'"pitch" (default) for per-pitch output, or "pitcher" for a per-pitcher mean.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

level="pitch": pitcher, pitch_type, location_rv_hat, command_plus. level="pitcher": pitcher, location_rv_hat, command_plus (per-pitcher mean). Empty input returns a zero-row frame with the documented schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
pitch_typecharacterStatcast pitch-type abbreviation.
location_rv_hatdoublePredicted per-pitch run value from the bundled Command+/Location+ xgboost model (location + count/handedness/pitch-type features only).
command_plusdoublePlus-scale Command+/Location+ score, 100 = league average, higher = better.

Example

from sportsdataverse.mlb.mlb_pitch_features import pitch_features
from sportsdataverse.mlb.mlb_command_plus import mlb_command_plus
feats = pitch_features(raw_pitches)
out = mlb_command_plus(feats)
print(out.select("pitcher", "command_plus").head())

# Pipeline next step

out.group_by("pitcher").agg(pl.col("command_plus").mean()).sort("command_plus", descending=True)

mlb_divisions(sport_id: 'int' = 1, league_id: 'Optional[Union[int, str]]' = None, division_id: 'Optional[int]' = None, **kwargs) -> 'Dict'

GET /api/v1/divisions — list divisions.

Parameters

ParameterTypeDefaultDescription
sport_idint1
league_idOptional[Union[int, str]]None
division_idOptional[int]None

mlb_draft_prospects(year: 'Union[int, str]', scouting_report: 'Optional[bool]' = None, limit: 'int' = 100, **kwargs) -> 'Dict'

GET /api/v1/draft/prospects/{year} — draft prospect list for a year.

Parameters

ParameterTypeDefaultDescription
yearUnion[int, str]
scouting_reportOptional[bool]None
limitint100

mlb_expected_home_runs(start_dt: 'str', end_dt: 'str', *, puller: 'Optional[Callable[..., pl.DataFrame]]' = None, park_factors: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Per player-season park-neutral xHR, park-adjusted xHR, and HR-above-expected.

Pulls batted balls via puller(start_dt, end_dt, player_type="batter"), builds the EV x LA x spray HR-probability grid from the pull's own batted balls (season-agnostic algorithm, per-pull empirical constants), predicts each ball's HR probability with the EV x LA-marginal fallback, park-adjusts via hr_factor (index 100 = neutral, joined on the Statcast home_team abbreviation -> MLBAM team id), then aggregates per batter.

Parameters

ParameterTypeDefaultDescription
start_dtstrPull start date, YYYY-MM-DD.
end_dtstrPull end date, YYYY-MM-DD.
pullerOptional[Callable[..., DataFrame]]NoneInjectable Statcast search callable -- defaults to sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search.
park_factorsOptional[DataFrame]NonePre-fetched park-factors frame (team_id, hr_factor); if None, fetched via sportsdataverse.mlb.mlb_statcast.mlb_statcast_leaderboard_park_factors.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per (batter, season): hr, xhr_neutral, xhr_park_adj, hr_above_expected (hr - xhr_neutral). Empty pull returns a zero-row frame with the documented schema.

col_nametypedescription
batterintegerMLBAM batter id (join key into Savant's home-runs leaderboard as player_id).
seasonintegerFour-digit season year derived from game_year/game_date.
hrintegerRealized home runs in the pulled window.
xhr_neutraldoublePark-neutral expected home runs from the EV x LA x spray probability grid.
xhr_park_adjdoublePark-adjusted expected home runs (xhr_neutral cell probabilities scaled by each batted ball's home-park HR factor / 100).
hr_above_expecteddoublehr minus xhr_neutral -- positive means the batter over-performed the park-neutral HR model.

Example

from sportsdataverse.mlb.mlb_expected_home_runs import mlb_expected_home_runs

df = mlb_expected_home_runs("2024-06-01", "2024-06-21")
print(df.shape)

# Pipeline next step (one line)

df.sort("hr_above_expected", descending=True).head()

mlb_expected_stats(start_dt: 'str', end_dt: 'str', *, puller: 'Optional[Callable[..., pl.DataFrame]]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Per player-season xwOBA/xBA/xSLG from an on-the-fly EV x LA empirical grid.

Pulls pitches via puller(start_dt, end_dt, player_type="batter"), builds the outcome grid from the pull's own batted balls (season-agnostic algorithm, per-pull empirical constants -- see CLAUDE.md), predicts contact woba/ba/slg per batted ball with the launch-angle- marginal fallback, then aggregates:

  • xwoba = (sum(predicted_woba over balls in play) + sum(woba_value over non-batted-ball PA outcomes)) / sum(woba_denom)
  • xba = sum(predicted_ba over balls in play) / ab
  • xslg = sum(predicted_tb over balls in play) / ab

Parameters

ParameterTypeDefaultDescription
start_dtstrPull start date, YYYY-MM-DD.
end_dtstrPull end date, YYYY-MM-DD.
pullerOptional[Callable[..., DataFrame]]NoneInjectable Statcast search callable -- defaults to sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per (batter, season): pa, ab, xwoba, xba, xslg. Empty pull returns a zero-row frame with the documented schema.

col_nametypedescription
batterintegerMLBAM batter id (join key into Savant's expected-stats leaderboard as player_id).
seasonintegerFour-digit season year derived from game_year/game_date.
paintegerPlate appearances in the pulled window.
abintegerAt-bats (PA minus walks, HBP, and sacrifices) in the pulled window.
xwobadoubleExpected wOBA from the EV x LA empirical grid (contact) plus realized non-contact outcome value, divided by wOBA denominator.
xbadoubleExpected batting average from the EV x LA empirical grid's hit-indicator cell means.
xslgdoubleExpected slugging percentage from the EV x LA empirical grid's total-bases cell means.

Example

from sportsdataverse.mlb.mlb_expected_stats import mlb_expected_stats

df = mlb_expected_stats("2024-06-01", "2024-06-21")
print(df.shape)

# Pipeline next step (one line)

df.sort("xwoba", descending=True).head()

mlb_fielding_oaa(bip: "'pl.DataFrame'", *, l2: 'float' = 0.0001, min_fit: 'int' = 50, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-fielder outs above average from a per-position catch-probability logistic.

oaa = sum(is_out - p_catch) per (fielder_id, position), where p_catch is a smooth per-position logistic P(out | landing distance, launch angle, exit velocity, spray angle) (exit velocity x launch angle proxy the hang time). A position with fewer than min_fit balls in play falls back to its mean out rate. This replaced a coarse empirical bin surface, roughly halving the gap to Savant's leaderboard (full-season Pearson ~0.40 -> ~0.60). The fielder id is resolved dynamically from the responsible position's fielder_{position} column (cast Utf8 at the boundary).

Parameters

ParameterTypeDefaultDescription
bipDataFrameBalls-in-play frame with hc_x/hc_y, hit_distance_sc, launch_angle, launch_speed, hit_location, events, and the fielder_1..fielder_9 responsible-player columns. MiLB input (e.g. sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search_minors) runs through the same function -- there is no Savant OAA leaderboard oracle for MiLB.
l2float0.0001L2 penalty for the per-position logistic. Defaults to 1e-4.
min_fitint50Minimum balls in play for a position to fit its own logistic; below this the position's mean out rate is used. Defaults to 50.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

one row per (fielder_id, position). | Column | Type | Description | |---|---|---| | fielder_id | Utf8 | Responsible fielder's MLBAM id | | position | Int64 | Position (Savant hit_location, 1-9) | | opportunities | Int64 | Balls in play charged to this fielder | | oaa | Float64 | Sum of (out - expected catch probability) |

Example

from sportsdataverse.mlb.mlb_fielding_oaa import mlb_fielding_oaa
oaa = mlb_fielding_oaa(bip)

# Pipeline next step (one line)

oaa.filter(pl.col("opportunities") >= 100).sort("oaa", descending=True)

mlb_injury_risk(pitches: 'pl.DataFrame', *, as_of_date: 'Optional[dt.date]' = None, window: 'int' = 5, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Composite pitcher injury-risk index from leakage-safe trailing trends.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameRaw pitch frame (from sportsdataverse.mlb.mlb_statcast_search).
as_of_dateOptional[date]NoneWhen given, restricts input to game_date < as_of_date via sportsdataverse.mlb.mlb_pitching_constants.as_of_split before computing trends (an additional leakage boundary on top of the per-appearance trailing-window logic).
windowint5Trailing-window size passed to pitcher_appearance_trends.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

pitcher, game_pk, game_date, injury_risk_index — equal-weighted sum of standardized adverse features (-velo_trend, -velo_drop, trailing_workload, -days_rest; higher = more risk). Empty input returns a zero-row frame with this schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
game_pkintegerGame identifier.
game_datedateCalendar date of the game (YYYY-MM-DD).
injury_risk_indexdoubleEqual-weighted composite of standardized adverse trailing features (higher = more risk).

Example

from sportsdataverse.mlb.mlb_pitch_injury import mlb_injury_risk
out = mlb_injury_risk(raw_pitches)
print(out.sort("injury_risk_index", descending=True).head())

mlb_pbp_diff(game_pk: 'int', start_timecode: 'str', end_timecode: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/game/{gamePk}/feed/live/diffPatch — JSON-patch diff of the live feed.

Replays of in-game state for low-bandwidth clients.

Parameters

ParameterTypeDefaultDescription
game_pkint
start_timecodestr
end_timecodeOptional[str]None

mlb_pbp_live(game_pk: 'int', language: 'Optional[str]' = None, timecode: 'Optional[str]' = None, hydrate: 'Optional[str]' = None, fields: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1.1/game/{gamePk}/feed/live — live firehose (v1.1).

Top-level keys: copyright, gamePk, link, metaData, gameData, liveData. Includes Statcast metrics where available. The historical name mlb_pbp is preserved as an alias in the generated module.

Parameters

ParameterTypeDefaultDescription
game_pkint
languageOptional[str]None
timecodeOptional[str]None
hydrateOptional[str]None
fieldsOptional[str]None

mlb_person_stats(person_id: 'int', stats: 'str', group: 'str' = 'hitting', season: 'Optional[Union[int, str]]' = None, season_type: 'Optional[str]' = None, sport_ids: 'Optional[Union[int, List[int]]]' = None, game_type: 'Optional[str]' = None, fields: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/people/{personId}/stats — player aggregate stats.

stats: season, career, yearByYear, vsTeam, vsPlayer, byMonth, byDayOfWeek, homeAndAway, gameLog, lastXGames, …

Parameters

ParameterTypeDefaultDescription
person_idint
statsstr
groupstr'hitting'
seasonOptional[Union[int, str]]None
season_typeOptional[str]None
sport_idsOptional[Union[int, List[int]]]None
game_typeOptional[str]None
fieldsOptional[str]None

mlb_pitch_classify(pitches: 'pl.DataFrame', *, max_components: 'int' = 6, seed: 'int' = 0, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-pitcher Gaussian-mixture pitch reclassification.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameOutput of sportsdataverse.mlb.mlb_pitch_features.pitch_features (needs velo_z, spin_z, pfx_x_z, pfx_z_z).
max_componentsint6Cap on GMM components considered per pitcher (BIC picks the best 1..min(max_components, n_pitch_types)).
seedint0Random seed for reproducible cluster labels.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

pitcher, pitch_type, pitch_type_reclass, reclass_confidence (max posterior cluster responsibility). Pitchers with fewer than MIN_PITCHES_FOR_CLUSTERING pitches pass through the Savant label unchanged with reclass_confidence = 1.0. Empty input returns a zero-row frame with this schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
pitch_typecharacterSavant-reported pitch-type abbreviation.
pitch_type_reclasscharacterReclassified pitch-type label from the per-pitcher GMM clustering (may differ from pitch_type).
reclass_confidencedoubleMax posterior cluster responsibility (1.0 for low-volume pitchers passed through unchanged).

Example

from sportsdataverse.mlb.mlb_pitch_features import pitch_features
from sportsdataverse.mlb.mlb_pitch_classify import mlb_pitch_classify
feats = pitch_features(raw_pitches)
out = mlb_pitch_classify(feats, seed=0)
print(out.filter(out["pitch_type"] != out["pitch_type_reclass"]).head())

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

Combined xERA + SIERA-like estimator (model ③).

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameRaw pitch frame (from sportsdataverse.mlb.mlb_statcast_search).
seasonsintSeason year.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

pitcher, season, x_woba, x_era, k_pct, bb_pct, gb_pct, siera_like. Empty input returns a zero-row frame with this schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
seasonintegerMLB season (4-digit start year).
x_wobadoubleMean estimated_woba_using_speedangle allowed on batted balls.
x_eradoubleParametric xERA converted from x_woba via the season's league baselines.
k_pctdoubleStrikeout rate (strikeouts / batters faced).
bb_pctdoubleWalk rate (walks + HBP / batters faced).
gb_pctdoubleGround-ball rate among batted balls.
siera_likedoubleSIERA-like ERA estimate from the fitted K%/BB%/GB% OLS coefficients.

Example

from sportsdataverse.mlb.mlb_pitch_era import mlb_pitch_era
out = mlb_pitch_era(raw_pitches, 2024)
print(out.select("pitcher", "x_era", "siera_like").head())

mlb_pitch_tunneling(pitches: 'pl.DataFrame', *, eps: 'float' = 0.01, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-pitch release/plate distance from the previous pitch + tunnel ratio.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameOutput of sportsdataverse.mlb.mlb_pitch_features.add_sequence_features (needs release_pos_x/release_pos_z, prev_release_pos_x/ prev_release_pos_z, plate_x/plate_z, prev_plate_x/prev_plate_z).
epsfloat0.01Minimum release_dist denominator (avoids divide-by-zero).
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

pitcher, game_pk, at_bat_number, pitch_number, release_dist, plate_dist, tunnel_ratio. First pitch of a plate appearance (no previous pitch) has null geometry. Empty input returns a zero-row frame with this schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
game_pkintegerGame identifier.
at_bat_numberintegerGame-level plate-appearance sequence number.
pitch_numberintegerPitch sequence number within the plate appearance.
release_distdoubleEuclidean distance between this pitch's release point and the previous pitch's release point.
plate_distdoubleEuclidean distance between this pitch's plate location and the previous pitch's plate location.
tunnel_ratiodoubleplate_dist / max(release_dist, eps) -- higher means better tunneling (similar release, different result).

Example

from sportsdataverse.mlb.mlb_pitch_features import pitch_features, add_sequence_features
from sportsdataverse.mlb.mlb_pitch_sequencing import mlb_pitch_tunneling
feats = add_sequence_features(pitch_features(raw_pitches))
out = mlb_pitch_tunneling(feats)
print(out.select("tunnel_ratio").describe())

mlb_prop_strikeouts(team_k9: 'float', opp_k_rate: 'float', lg_k_rate: 'float', *, innings: 'float' = 9.0) -> 'float'

Expected pitcher/team strikeouts via a K/9-and-opponent-K-rate blend.

team_k9 / 9 * innings * (opp_k_rate / lg_k_rate).

Parameters

ParameterTypeDefaultDescription
team_k9floatTeam/pitcher strikeouts per 9 innings pitched.
opp_k_ratefloatOpponent's own strikeout rate (K per PA).
lg_k_ratefloatLeague-average strikeout rate.
inningsfloat9.0Innings pitched in this outing (default 9.0).

Returns

expected strikeouts.

Example

from sportsdataverse.mlb.mlb_prop_projection import mlb_prop_strikeouts
mlb_prop_strikeouts(9.0, 0.22, 0.22)

mlb_prop_team_runs(home_off: 'float', away_def: 'float', lg_rpg: 'float', *, park_factor: 'float' = 1.0) -> 'float'

Expected team runs via a log5-style rate blend.

lg_rpg * (home_off / lg_rpg) * (away_def / lg_rpg) * park_factor.

Parameters

ParameterTypeDefaultDescription
home_offfloatTeam's own runs-scored-per-game rate.
away_deffloatOpponent's runs-allowed-per-game rate.
lg_rpgfloatLeague-average runs-per-game rate.
park_factorfloat1.0Park run-scoring multiplier (default neutral 1.0; a real park-factor table is a documented follow-on).

Returns

expected runs for the team in this matchup.

Example

from sportsdataverse.mlb.mlb_prop_projection import mlb_prop_team_runs
mlb_prop_team_runs(5.5, 5.0, 4.5)

mlb_props(matchups: 'pl.DataFrame', ratings: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Expected team runs + strikeouts for a slate of matchups.

Parameters

ParameterTypeDefaultDescription
matchupsDataFrameOne row per game: game_id, home_team_id, away_team_id.
ratingsDataFramePer-team as-of-date rate table: team_id, off_rpg (runs scored/game), def_rpg (runs allowed/game), and optionally k9 + k_rate (see the module docstring -- strikeout columns are null without them). team_id must share a dtype with matchups' team-id columns.
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per matchup. | Column | Type | Description | |---|---|---| | game_id | Utf8 | Game identifier | | home_team_id | Utf8 | Home team identifier | | away_team_id | Utf8 | Away team identifier | | exp_runs_home | Float64 | Expected home-team runs | | exp_runs_away | Float64 | Expected away-team runs | | exp_strikeouts_home | Float64 | Expected home-pitcher strikeouts (null if ratings lacks k9/k_rate) | | exp_strikeouts_away | Float64 | Expected away-pitcher strikeouts (null if ratings lacks k9/k_rate) |

col_nametypedescription
game_idcharacterGame identifier.
home_team_idcharacterHome team identifier.
away_team_idcharacterAway team identifier.
exp_runs_homedoubleExpected home-team runs (log5-style rate blend).
exp_runs_awaydoubleExpected away-team runs (log5-style rate blend).
exp_strikeouts_homedoubleExpected home-pitcher strikeouts (null when the ratings input lacks k9/k_rate).
exp_strikeouts_awaydoubleExpected away-pitcher strikeouts (null when the ratings input lacks k9/k_rate).

Example

from sportsdataverse.mlb.mlb_prop_projection import mlb_props
props = mlb_props(matchups, ratings)

mlb_pythagenpat(runs_scored: 'float', runs_allowed: 'float', games: 'int', *, exponent: 'float' = 0.287) -> 'float'

Pythagenpat expected win percentage (Smyth-Patriot, run-environment adaptive exponent).

x = ((runs_scored + runs_allowed) / games) ** exponent; win_pct = runs_scored**x / (runs_scored**x + runs_allowed**x).

Parameters

ParameterTypeDefaultDescription
runs_scoredfloatTotal runs scored.
runs_allowedfloatTotal runs allowed.
gamesintGames played.
exponentfloat0.287Run-environment exponent (default the published 0.287).

Returns

expected win percentage in [0, 1]. Returns 0.5 when games == 0 or runs_scored + runs_allowed == 0 (guard against a zero-division/degenerate input).

Example

from sportsdataverse.mlb.mlb_team_projection import mlb_pythagenpat
mlb_pythagenpat(800, 600, 162)

mlb_pythagenpat_table(results: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Per-(season, team) pythagenpat table from game-level results.

This is a same-window estimator, not a forward-looking prediction: pythagenpat smooths a team's already-known run differential into an implied "true-talent" win rate over that same window (the classic Bill James validation is exactly "does the formula's win% track the actual win% over the same season"). To use it predictively for a future game, pre-filter results to games strictly before that date with sportsdataverse.mlb.mlb_game_state_constants.as_of_split first -- this function does not do that filtering itself.

Parameters

ParameterTypeDefaultDescription
resultsDataFrameGame-level results (season, home_team_id, away_team_id, home_score, away_score).
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per (season, team). | Column | Type | Description | |---|---|---| | season | Int64 | Season | | team_id | Utf8 | Team identifier | | runs_scored | Int64 | Total runs scored | | runs_allowed | Int64 | Total runs allowed | | games | Int64 | Games played | | win_pct | Float64 | Realized win percentage | | pythag_win_pct | Float64 | Pythagenpat expected win percentage |

col_nametypedescription
seasonintegerMLB season (4-digit start year).
team_idcharacterTeam identifier (statsapi team id, stringified).
runs_scoredintegerTotal runs scored across the covered games.
runs_allowedintegerTotal runs allowed across the covered games.
gamesintegerCount of games played in the season.
win_pctdoubleRealized win percentage.
pythag_win_pctdoublePythagenpat expected win percentage (exponent 0.287).

Example

from sportsdataverse.mlb.mlb_team_projection import mlb_pythagenpat_table
table = mlb_pythagenpat_table(results)

mlb_run_expectancy_matrix(seasons: 'Union[int, List[int], None]' = None, *, pbp: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Empirical RE24 run-expectancy matrix by base-out state.

re[base_state, outs] = mean(runs_rest_of_inning) over all plate appearances starting in that state, excluding the bottom of the 9th inning and beyond (the standard RE24 exclusion -- those half-innings are only played while the home team trails or is tied, a score-differential selection bias that would otherwise distort the matrix). Computed on demand from statsapi play-by-play; no bundled artifact.

Parameters

ParameterTypeDefaultDescription
seasonsUnion[int, List[int], None]NoneOne season (int) or a list of seasons to collect via sportsdataverse.mlb.mlb_api_extra.mlb_schedule. Ignored when pbp is supplied.
pbpOptional[DataFrame]NonePre-collected parsed play-by-play frame (skips the network collector -- primarily for tests / offline reuse).
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

up to 24 rows (base_state x outs). | Column | Type | Description | |---|---|---| | base_state | Utf8 | 3-char base occupancy (e.g. "1_3") | | outs | Int64 | Outs at the start of the state (0-2) | | re | Float64 | Mean runs scored through the end of the half-inning | | n | Int64 | Number of plate appearances observed in this state |

col_nametypedescription
base_statecharacter3-char base occupancy code ("_" = empty, "1"/"2"/"3" = occupied), e.g. "1_3" for runners on first and third.
outsintegerOuts at the start of the base-out state (0-2).
redoubleEmpirical mean runs scored from this state through the end of the half-inning (RE24).
nintegerNumber of plate appearances observed starting in this base-out state.

Example

from sportsdataverse.mlb.mlb_run_expectancy import mlb_run_expectancy_matrix
matrix = mlb_run_expectancy_matrix(pbp=pbp)

# Pipeline next step (one line)

matrix.filter(pl.col("base_state") == "___").sort("outs")

mlb_schedule(date: 'Optional[str]' = None, start_date: 'Optional[str]' = None, end_date: 'Optional[str]' = None, team_id: 'Optional[int]' = None, opponent_id: 'Optional[int]' = None, season: 'Optional[Union[int, str]]' = None, sport_id: 'int' = 1, game_type: 'Optional[str]' = None, league_id: 'Optional[Union[int, str]]' = None, hydrate: 'Optional[str]' = None, fields: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/schedule — schedule of games for a date, range, team, or season.

Response: dates[].games[].

Parameters

ParameterTypeDefaultDescription
dateOptional[str]None
start_dateOptional[str]None
end_dateOptional[str]None
team_idOptional[int]None
opponent_idOptional[int]None
seasonOptional[Union[int, str]]None
sport_idint1
game_typeOptional[str]None
league_idOptional[Union[int, str]]None
hydrateOptional[str]None
fieldsOptional[str]None

mlb_seasons(sport_id: 'int' = 1, season: 'Optional[Union[int, str]]' = None, all_seasons: 'bool' = False, **kwargs) -> 'Dict'

GET /api/v1/seasons — list of seasons for a sport.

Parameters

ParameterTypeDefaultDescription
sport_idint1
seasonOptional[Union[int, str]]None
all_seasonsboolFalse

mlb_sequence_run_value(pitches: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Mean run value grouped by the ordered (prev_pitch_type, pitch_type) sequence.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameOutput of sportsdataverse.mlb.mlb_pitch_features.add_sequence_features (needs prev_pitch_type, pitch_type, run_value / delta_run_exp).
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

prev_pitch_type, pitch_type, mean_run_value, n — one row per observed ordered pair (rows with a null prev_pitch_type, i.e. the first pitch of a PA, are dropped). Empty input returns a zero-row frame with this schema.

col_nametypedescription
prev_pitch_typecharacterPitch type of the preceding pitch in the sequence.
pitch_typecharacterPitch type of the current pitch.
mean_run_valuedoubleMean run value of the current pitch, grouped by the ordered (prev_pitch_type, pitch_type) pair.
nintegerNumber of pitches observed for this ordered pair.

Example

from sportsdataverse.mlb.mlb_pitch_sequencing import mlb_sequence_run_value
out = mlb_sequence_run_value(feats)
print(out.sort("mean_run_value").head())

mlb_standings(league_id: 'Union[int, str, List[int]]' = '103,104', season: 'Optional[Union[int, str]]' = None, date: 'Optional[str]' = None, standings_types: 'Optional[str]' = None, hydrate: 'Optional[str]' = None, fields: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/standings — league standings.

league_id: 103 AL, 104 NL (comma-separated for both, the default). standings_types e.g. regularSeason, wildCard, divisionLeaders.

Parameters

ParameterTypeDefaultDescription
league_idUnion[int, str, List[int]]'103,104'
seasonOptional[Union[int, str]]None
dateOptional[str]None
standings_typesOptional[str]None
hydrateOptional[str]None
fieldsOptional[str]None

mlb_statcast_player(player_id: 'int', stats: 'Optional[str]' = None, *, section: 'str' = 'statcast', raw: 'bool' = False, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> "'Union[pl.DataFrame, pd.DataFrame, str]'"

GET /savant-player/{player_id} and parse one embedded table into a tidy frame.

Returns a tidy frame by default (the parsed Statcast page); pass raw=True to get the underlying HTML string instead (the page embeds ~12 other tables you can mine yourself, or feed to sportsdataverse.mlb.parse_mlb_statcast_player with a different section).

Parameters

ParameterTypeDefaultDescription
player_idintMLBAM player id (shared with the Stats API personId).
statsOptional[str]Noneoptional stats query value to scope the embedded payload.
sectionstr'statcast'which embedded serverVals table to flatten (default "statcast", the seasonal aggregate; e.g. "statcastGameLogs").
rawboolFalsereturn the raw page HTML string instead of a parsed frame.
return_as_pandasboolFalsereturn a pandas DataFrame instead of polars.

Returns

A polars (or pandas) DataFrame of the player's Statcast metrics by default (zero rows when the page/section is absent); the raw HTML str when raw=True.

col_nametypedescription
aggregateintegerAggregate.
yearintegerSeason year.
yearhiddenintegerYearhidden.
player_idintegerMLBAM player id.
ageintegerPlayer age.
bat_sidecharacterBatter side (R/L/S).
pitch_handcharacterPitcher handedness (R/L).
monthcharacterMonth.
grouping_codecharacterGrouping code.
grouping_catcharacterGrouping cat.
pitch_countintegerPitch count.
in_zone_percentnumericIn zone rate.
out_zone_percentnumericOut zone rate.
edge_percentnumericEdge rate.
z_swing_percentnumericZ swing rate.
oz_swing_percentnumericOz swing rate.
iz_contact_percentnumericIz contact rate.
oz_contact_percentnumericOz contact rate.
whiff_percentnumericWhiff rate (swings and misses / swings).
f_strike_percentnumericF strike rate.
f_swing_percentnumericF swing rate.
swing_percentnumericSwing rate.
meatball_swing_percentintegerMeatball swing rate.
meatball_percentnumericMeatball rate.
z_swing_miss_percentnumericZ swing miss rate.
oz_swing_miss_percentnumericOz swing miss rate.
in_zoneintegerIn zone.
out_zoneintegerOut zone.
edgeintegerEdge.
popupsintegerPopups.
flyballsintegerFlyballs.
linedrivesintegerLinedrives.
groundballsintegerGroundballs.
airballsintegerAirballs.
popups_percentnumericPopups rate.
flyballs_percentnumericFlyballs rate.
linedrives_percentnumericLinedrives rate.
groundballs_percentnumericGroundballs rate.
airballs_percentnumericAirballs rate.
pull_percentnumericPull rate.
straightaway_percentnumericStraightaway rate.
opposite_percentnumericOpposite rate.
pull_percent_airballsnumericPull percent airballs.
straightaway_percent_airballsnumericStraightaway percent airballs.
opposite_percent_airballsintegerOpposite percent airballs.
pull_percent_groundballsnumericPull percent groundballs.
straightaway_percent_groundballsnumericStraightaway percent groundballs.
opposite_percent_groundballsnumericOpposite percent groundballs.
pull_percent_popupsnumericPull percent popups.
straightaway_percent_popupsnumericStraightaway percent popups.
opposite_percent_popupsnumericOpposite percent popups.
pull_percent_flyballsnumericPull percent flyballs.
straightaway_percent_flyballsnumericStraightaway percent flyballs.
opposite_percent_flyballsnumericOpposite percent flyballs.
pull_percent_linedrivesintegerPull percent linedrives.
straightaway_percent_linedrivesintegerStraightaway percent linedrives.
opposite_percent_linedrivesintegerOpposite percent linedrives.
poorlyweak_percentintegerPoorlyweak rate.
poorlytopped_percentnumericPoorlytopped rate.
poorlyunder_percentnumericPoorlyunder rate.
flareburner_percentnumericFlareburner rate.
solidcontact_percentnumericSolidcontact rate.
hr_flyballs_percentnumericHr flyballs rate.
in_zone_swingintegerIn zone swing.
out_zone_swingintegerOut zone swing.
in_zone_swing_missintegerIn zone swing miss.
out_zone_swing_missintegerOut zone swing miss.
pitch_count_fastballintegerPitch count fastball.
pitch_count_offspeedintegerPitch count offspeed.
pitch_count_breakingintegerPitch count breaking.
paintegerPlate appearances.
abintegerAt-bats.
hitintegerHit.
singleintegerSingles.
doubleintegerDoubles.
tripleintegerTriples.
home_runintegerHome run.
walkintegerWalk.
strikeoutintegerStrikeout.
hbpintegerHbp.
k_percentnumericStrikeout rate.
bb_percentnumericWalk rate.
sz_judgenumericSz judge.
batted_ballintegerBatted ball.
barrelintegerBarrel.
barrel_batted_ratenumericBarrels per batted ball.
barrels_per_panumericBarrels per pa.
launch_angle_avgnumericLaunch angle avg.
exit_velocity_avgnumericExit velocity avg.
exit_velocity_maxnumericExit velocity max.
hard_hit_percentnumericHard-hit rate (95+ mph EV).
sweet_spot_percentnumericSweet-spot rate (8-32 deg launch angle).
banumericBatting average.
xbanumericExpected batting average.
baconnumericBacon.
xbaconnumericExpected batting average on contact.
babipnumericBABIP.
obpnumericOn-base percentage.
slgnumericSlugging percentage.
xobpnumericExpected on-base percentage.
xslgnumericExpected slugging.
isonumericIsolated power.
xisonumericExpected isolated power.
wobanumericWeighted on-base average.
xwobanumericExpected wOBA.
wobaconnumericWobacon.
xwobaconnumericXwobacon.
xbadiffnumericXbadiff.
xslgdiffnumericXslgdiff.
wobadiffnumericWobadiff.
player_typecharacterPlayer type.
eracharacterEra.
xeracharacterExpected ERA.
avg_hyper_speednumericAvg hyper speed.
avg_best_speednumericAvg best speed.
distance_hr_avgintegerDistance hr avg.
sprint_speednumericSprint speed (ft/sec, top 50% of competitive runs).
pop_2bcharacterPop 2b.
arm_cs_2bcharacterArm cs 2b.
strike_ratecharacterCalled-strike rate.
outs_above_averageintegerOuts Above Average.
jump_v_avgintegerJump v avg.
max_arm_strengthcharacterMax arm strength (mph).
arm_overallcharacterArm overall.
xhrnumericXhr.
swing_take_run_valueintegerSwing take run value.
blocks_above_averagecharacterBlocks above average.
cs_above_averagecharacterCs above average.
fastball_velocharacterFastball velo.
fastball_spincharacterFastball spin.
fastball_extensioncharacterFastball extension.
curveball_spincharacterCurveball spin.
pitch_run_value_fastballnumericPitch run value fastball.
pitch_run_value_breakingnumericPitch run value breaking.
pitch_run_value_offspeednumericPitch run value offspeed.
group_fastball_velonumericGroup fastball velo.
group_breaking_velonumericGroup breaking velo.
group_offspeed_velonumericGroup offspeed velo.
pitch_usage_fastballnumericPitch usage fastball.
pitch_usage_breakingnumericPitch usage breaking.
pitch_usage_offspeednumericPitch usage offspeed.
fielding_run_valueintegerFielding run value.
runner_run_valueintegerRunner run value.
fielding_run_value_armintegerFielding run value arm.
fielding_run_value_framingcharacterFielding run value framing.
runner_runs_sbintegerRunner runs sb.
runner_runs_xbintegerRunner runs xb.
net_bases_runnerintegerNet bases runner.
net_bases_pitchercharacterNet bases pitcher.
fast_swing_ratecharacterFast-swing rate (>=75 mph).
squared_up_contactcharacterSquared up contact.
squared_up_swingcharacterSquared up swing.
blasts_contactcharacterBlasts contact.
blasts_swingcharacterBlasts swing.
swordscharacterSwords.
avg_swing_speedcharacterAvg swing speed.
avg_swing_lengthcharacterAvg swing length.
attack_anglecharacterAttack angle (deg, bat path at contact).
vertical_swing_pathcharacterVertical swing path.
accelerationcharacterAcceleration.
horizontal_swing_pathcharacterHorizontal swing path.
attack_directioncharacterAttack direction (deg, pull/oppo).
ideal_angle_ratecharacterIdeal angle rate.
n_squared_upcharacterNumber of squared up.
n_blastscharacterNumber of blasts.
arm_anglecharacterArm angle.
is_qualifiedintegerIs qualified.
percent_rank_barrel_unroundedcharacterPercent rank barrel unrounded.
percent_rank_barrel_batted_rate_unroundedcharacterPercent rank barrel batted rate unrounded.
percent_rank_exit_velocity_avg_unroundedcharacterPercent rank exit velocity avg unrounded.
percent_rank_exit_velocity_max_unroundednumericPercent rank exit velocity max unrounded.
percent_rank_launch_angle_avg_unroundedcharacterPercent rank launch angle avg unrounded.
percent_rank_xba_unroundedcharacterPercent rank xba unrounded.
percent_rank_xslg_unroundedcharacterPercent rank xslg unrounded.
percent_rank_xwoba_unroundedcharacterPercent rank xwoba unrounded.
percent_rank_woba_unroundedcharacterPercent rank woba unrounded.
percent_rank_hard_hit_percent_unroundedcharacterPercent rank hard hit percent unrounded.
percent_rank_xwobacon_unroundedcharacterPercent rank xwobacon unrounded.
percent_rank_wobacon_unroundedcharacterPercent rank wobacon unrounded.
percent_rank_k_percent_unroundedcharacterPercent rank k percent unrounded.
percent_rank_bb_percent_unroundedcharacterPercent rank bb percent unrounded.
percent_rank_sz_judge_unroundedcharacterPercent rank sz judge unrounded.
percent_rank_whiff_percent_unroundedcharacterPercent rank whiff percent unrounded.
percent_rank_chase_percent_unroundedcharacterPercent rank chase percent unrounded.
percent_rank_ba_unroundedcharacterPercent rank ba unrounded.
percent_rank_bacon_unroundedcharacterPercent rank bacon unrounded.
percent_rank_xbacon_unroundedcharacterPercent rank xbacon unrounded.
percent_rank_babip_unroundedcharacterPercent rank babip unrounded.
percent_rank_obp_unroundedcharacterPercent rank obp unrounded.
percent_rank_slg_unroundedcharacterPercent rank slg unrounded.
percent_rank_xobp_unroundedcharacterPercent rank xobp unrounded.
percent_rank_iso_unroundedcharacterPercent rank iso unrounded.
percent_rank_xiso_unroundedcharacterPercent rank xiso unrounded.
percent_rank_sweet_spot_percent_unroundedcharacterPercent rank sweet spot percent unrounded.
percent_rank_distance_hr_avg_unroundedcharacterPercent rank distance hr avg unrounded.
percent_rank_groundballs_percent_unroundedcharacterPercent rank groundballs percent unrounded.
percent_rank_airballs_percent_unroundedcharacterPercent rank airballs percent unrounded.
percent_rank_avg_hyper_speed_unroundedcharacterPercent rank avg hyper speed unrounded.
percent_rank_avg_best_speed_unroundedcharacterPercent rank avg best speed unrounded.
percent_rank_pitch_run_value_fastball_unroundedcharacterPercent rank pitch run value fastball unrounded.
percent_rank_pitch_run_value_breaking_unroundedcharacterPercent rank pitch run value breaking unrounded.
percent_rank_pitch_run_value_offspeed_unroundedcharacterPercent rank pitch run value offspeed unrounded.
percent_rank_barrelcharacterPercent rank barrel.
percent_rank_barrel_batted_ratecharacterPercent rank barrel batted rate.
percent_rank_exit_velocity_avgcharacterPercent rank exit velocity avg.
percent_rank_exit_velocity_maxintegerPercent rank exit velocity max.
percent_rank_launch_angle_avgcharacterPercent rank launch angle avg.
percent_rank_xbacharacterPercent rank xba.
percent_rank_xslgcharacterPercent rank xslg.
percent_rank_xwobacharacterPercent rank xwoba.
percent_rank_wobacharacterPercent rank woba.
percent_rank_hard_hit_percentcharacterPercent rank hard hit rate.
percent_rank_xwobaconcharacterPercent rank xwobacon.
percent_rank_wobaconcharacterPercent rank wobacon.
percent_rank_k_percentcharacterPercent rank k rate.
percent_rank_bb_percentcharacterPercent rank bb rate.
percent_rank_sz_judgecharacterPercent rank sz judge.
percent_rank_whiff_percentcharacterPercent rank whiff rate.
percent_rank_chase_percentcharacterPercent rank chase rate.
percent_rank_bacharacterPercent rank ba.
percent_rank_baconcharacterPercent rank bacon.
percent_rank_xbaconcharacterPercent rank xbacon.
percent_rank_babipcharacterPercent rank babip.
percent_rank_obpcharacterPercent rank obp.
percent_rank_slgcharacterPercent rank slg.
percent_rank_xobpcharacterPercent rank xobp.
percent_rank_isocharacterPercent rank iso.
percent_rank_xisocharacterPercent rank xiso.
percent_rank_sweet_spot_percentcharacterPercent rank sweet spot rate.
percent_rank_distance_hr_avgcharacterPercent rank distance hr avg.
percent_rank_groundballs_percentcharacterPercent rank groundballs rate.
percent_rank_airballs_percentcharacterPercent rank airballs rate.
percent_rank_avg_hyper_speedcharacterPercent rank avg hyper speed.
percent_rank_avg_best_speedcharacterPercent rank avg best speed.
percent_rank_pitch_run_value_fastballcharacterPercent rank pitch run value fastball.
percent_rank_pitch_run_value_breakingcharacterPercent rank pitch run value breaking.
percent_rank_pitch_run_value_offspeedcharacterPercent rank pitch run value offspeed.
percent_speed_orderintegerPercent speed order.
percent_rank_speed_orderintegerPercent rank speed order.
percent_rank_pop_2bcharacterPercent rank pop 2b.
percent_rank_arm_cs_2bcharacterPercent rank arm cs 2b.
percent_rank_oaacharacterPercent rank oaa.
percent_rank_framingcharacterPercent rank framing.
percent_rank_jumpcharacterPercent rank jump.
percent_rank_fastball_velocharacterPercent rank fastball velo.
percent_rank_fastball_spincharacterPercent rank fastball spin.
percent_rank_fastball_extensioncharacterPercent rank fastball extension.
percent_rank_cu_spincharacterPercent rank cu spin.
percent_rank_xeracharacterPercent rank xera.
percent_rank_arm_maxcharacterPercent rank arm max.
percent_rank_arm_overallcharacterPercent rank arm overall.
percent_rank_xhrcharacterPercent rank xhr.
percent_rank_swing_take_run_valuecharacterPercent rank swing take run value.
percent_rank_blocks_above_averagecharacterPercent rank blocks above average.
percent_rank_cs_above_averagecharacterPercent rank cs above average.
percent_rank_fielding_run_valuecharacterPercent rank fielding run value.
percent_rank_runner_run_valuecharacterPercent rank runner run value.
percent_rank_fielding_run_value_armcharacterPercent rank fielding run value arm.
percent_rank_fielding_run_value_framingcharacterPercent rank fielding run value framing.
percent_rank_swing_speedcharacterPercent rank swing speed.
percent_rank_swing_lengthcharacterPercent rank swing length.
percent_rank_squared_up_swingcharacterPercent rank squared up swing.
percent_rank_attack_anglecharacterPercent rank attack angle.
percent_rank_vertical_swing_pathcharacterPercent rank vertical swing path.
percent_rank_accelerationcharacterPercent rank acceleration.
percent_rank_ideal_angle_ratecharacterPercent rank ideal angle rate.

Example

from sportsdataverse.mlb import mlb_statcast_player
df = mlb_statcast_player(592450)
html = mlb_statcast_player(592450, raw=True)

Pitch-by-pitch MLB Statcast search (/statcast_search/csv), date-chunked.

Savant caps a single /statcast_search/csv response at 25,000 rows with no pagination. This splits the date range into chunk_days windows, halving any window that hits the cap, and stitches the chunks back together.

Parameters

ParameterTypeDefaultDescription
start_dtstr
end_dtstr
player_typestr'batter'"batter" (default) or "pitcher".
chunk_daysint7initial window size in days.
return_as_pandasboolFalsereturn a pandas DataFrame instead of polars.

Returns

A polars (or pandas) DataFrame, one row per pitch.

col_nametypedescription
pitch_typecharacterPitch type code.
game_datecharacterGame date.
release_speednumericRelease speed.
release_pos_xnumericRelease pos x.
release_pos_znumericRelease pos z.
player_namecharacterPlayer name.
batterintegerMLBAM id of the batter.
pitcherintegerMLBAM id of the pitcher.
eventscharacterEvents.
descriptioncharacterDescription.
spin_dircharacterSpin dir.
spin_rate_deprecatedcharacterSpin rate deprecated.
break_angle_deprecatedcharacterBreak angle deprecated.
break_length_deprecatedcharacterBreak length deprecated.
zoneintegerZone.
descharacterDes.
game_typecharacterGame type.
standcharacterBatter stance side (R/L).
p_throwscharacterPitcher throwing hand (R/L).
home_teamcharacterHome team.
away_teamcharacterAway team.
typecharacterRecord/pitch type.
hit_locationintegerHit location.
bb_typecharacterBb type.
ballsintegerBalls.
strikesintegerStrikes.
game_yearintegerGame year.
pfx_xnumericHorizontal movement (in, pitcher perspective).
pfx_znumericInduced vertical movement (in).
plate_xnumericPlate x.
plate_znumericPlate z.
on_3bcharacterOn 3b.
on_2bcharacterOn 2b.
on_1bcharacterOn 1b.
outs_when_upintegerOuts when up.
inningintegerInning.
inning_topbotcharacterInning topbot.
hc_xnumericHc x.
hc_ynumericHc y.
tfs_deprecatedcharacterTfs deprecated.
tfs_zulu_deprecatedcharacterTfs zulu deprecated.
umpirecharacterUmpire.
sv_idcharacterSv id.
vx0numericVx0.
vy0numericVy0.
vz0numericVz0.
axnumericAx.
aynumericAy.
aznumericAz.
sz_topnumericSz top.
sz_botnumericSz bot.
hit_distance_scintegerHit distance sc.
launch_speednumericExit velocity of the batted ball (mph).
launch_angleintegerLaunch angle (deg).
effective_speedintegerEffective speed.
release_spin_rateintegerRelease spin rate.
release_extensionnumericRelease extension.
game_pkintegerMLBAM game id.
fielder_2integerFielder 2.
fielder_3integerFielder 3.
fielder_4integerFielder 4.
fielder_5integerFielder 5.
fielder_6integerFielder 6.
fielder_7integerFielder 7.
fielder_8integerFielder 8.
fielder_9integerFielder 9.
release_pos_ynumericRelease pos y.
estimated_ba_using_speedanglenumericEstimated ba using speedangle.
estimated_woba_using_speedanglenumericEstimated woba using speedangle.
woba_valueintegerWoba value.
woba_denomintegerWoba denom.
babip_valueintegerBabip value.
iso_valueintegerIso value.
launch_speed_angleintegerLaunch speed angle.
at_bat_numberintegerAt bat number.
pitch_numberintegerPitch number.
pitch_namecharacterPitch type name.
home_scoreintegerHome score.
away_scoreintegerAway score.
bat_scoreintegerBat score.
fld_scoreintegerFld score.
post_away_scoreintegerPost away score.
post_home_scoreintegerPost home score.
post_bat_scoreintegerPost bat score.
post_fld_scoreintegerPost fld score.
if_fielding_alignmentcharacterIf fielding alignment.
of_fielding_alignmentcharacterOf fielding alignment.
spin_axisintegerSpin axis.
delta_home_win_expnumericDelta home win exp.
delta_run_expnumericDelta run exp.
bat_speednumericBat speed (mph).
swing_lengthnumericSwing length (ft, head travel).
miss_distancecharacterAverage miss distance (in) on swings.
estimated_slg_using_speedanglenumericEstimated slg using speedangle.
delta_pitcher_run_expnumericDelta pitcher run exp.
hyper_speednumericHyper speed.
home_score_diffintegerHome score diff.
bat_score_diffintegerBat score diff.
home_win_expnumericHome win exp.
bat_win_expnumericBat win exp.
age_pit_legacyintegerAge pit legacy.
age_bat_legacyintegerAge bat legacy.
age_pitintegerAge pit.
age_batintegerAge bat.
n_thruorder_pitcherintegerNumber of thruorder pitcher.
n_priorpa_thisgame_player_at_batintegerNumber of priorpa thisgame player at bat.
pitcher_days_since_prev_gameintegerPitcher days since prev game.
batter_days_since_prev_gameintegerBatter days since prev game.
pitcher_days_until_next_gameintegerPitcher days until next game.
batter_days_until_next_gameintegerBatter days until next game.
api_break_z_with_gravitynumericApi break z with gravity.
api_break_x_armnumericApi break x arm.
api_break_x_batter_innumericApi break x batter in.
arm_anglenumericArm angle.
attack_anglenumericAttack angle (deg, bat path at contact).
attack_directionnumericAttack direction (deg, pull/oppo).
swing_path_tiltnumericSwing-path tilt (deg).
intercept_ball_minus_batter_pos_x_inchesnumericIntercept ball minus batter pos x inches.
intercept_ball_minus_batter_pos_y_inchesnumericIntercept ball minus batter pos y inches.

Example

from sportsdataverse.mlb import mlb_statcast_search
df = mlb_statcast_search("2024-06-15", "2024-06-16", batters_lookup=592450)

mlb_statcast_search_minors(start_dt: 'str', end_dt: 'str', *, player_type: 'str' = 'batter', chunk_days: 'int' = 7, return_as_pandas: 'bool' = False, **filters: 'Any') -> "'Union[pl.DataFrame, pd.DataFrame]'"

Minor-league Statcast search (/statcast-search-minors/csv), date-chunked.

Same shape, columns, and 25,000-row chunking as mlb_statcast_search, but against the MiLB CSV route. Scope with hfLevel (Triple-A/Double-A/…) and hfSea filters.

Parameters

ParameterTypeDefaultDescription
start_dtstr
end_dtstr
player_typestr'batter'"batter" (default) or "pitcher".
chunk_daysint7initial window size in days.
return_as_pandasboolFalsereturn a pandas DataFrame instead of polars.

Returns

A polars (or pandas) DataFrame, one row per minor-league pitch.

col_nametypedescription
pitch_typecharacterPitch type code.
game_datecharacterGame date.
release_speednumericRelease speed.
release_pos_xnumericRelease pos x.
release_pos_znumericRelease pos z.
player_namecharacterPlayer name.
batterintegerMLBAM id of the batter.
pitcherintegerMLBAM id of the pitcher.
eventscharacterEvents.
descriptioncharacterDescription.
spin_dircharacterSpin dir.
spin_rate_deprecatedcharacterSpin rate deprecated.
break_angle_deprecatedcharacterBreak angle deprecated.
break_length_deprecatedcharacterBreak length deprecated.
zoneintegerZone.
descharacterDes.
game_typecharacterGame type.
standcharacterBatter stance side (R/L).
p_throwscharacterPitcher throwing hand (R/L).
home_teamcharacterHome team.
away_teamcharacterAway team.
typecharacterRecord/pitch type.
hit_locationintegerHit location.
bb_typecharacterBb type.
ballsintegerBalls.
strikesintegerStrikes.
game_yearintegerGame year.
pfx_xnumericHorizontal movement (in, pitcher perspective).
pfx_znumericInduced vertical movement (in).
plate_xnumericPlate x.
plate_znumericPlate z.
on_3bcharacterOn 3b.
on_2bcharacterOn 2b.
on_1bcharacterOn 1b.
outs_when_upintegerOuts when up.
inningintegerInning.
inning_topbotcharacterInning topbot.
hc_xnumericHc x.
hc_ynumericHc y.
tfs_deprecatedcharacterTfs deprecated.
tfs_zulu_deprecatedcharacterTfs zulu deprecated.
umpirecharacterUmpire.
sv_idcharacterSv id.
vx0numericVx0.
vy0numericVy0.
vz0numericVz0.
axnumericAx.
aynumericAy.
aznumericAz.
sz_topnumericSz top.
sz_botnumericSz bot.
hit_distance_scintegerHit distance sc.
launch_speednumericExit velocity of the batted ball (mph).
launch_angleintegerLaunch angle (deg).
effective_speedintegerEffective speed.
release_spin_rateintegerRelease spin rate.
release_extensionnumericRelease extension.
game_pkintegerMLBAM game id.
fielder_2integerFielder 2.
fielder_3integerFielder 3.
fielder_4integerFielder 4.
fielder_5integerFielder 5.
fielder_6integerFielder 6.
fielder_7integerFielder 7.
fielder_8integerFielder 8.
fielder_9integerFielder 9.
release_pos_ynumericRelease pos y.
estimated_ba_using_speedanglenumericEstimated ba using speedangle.
estimated_woba_using_speedanglenumericEstimated woba using speedangle.
woba_valueintegerWoba value.
woba_denomintegerWoba denom.
babip_valueintegerBabip value.
iso_valueintegerIso value.
launch_speed_angleintegerLaunch speed angle.
at_bat_numberintegerAt bat number.
pitch_numberintegerPitch number.
pitch_namecharacterPitch type name.
home_scoreintegerHome score.
away_scoreintegerAway score.
bat_scoreintegerBat score.
fld_scoreintegerFld score.
post_away_scoreintegerPost away score.
post_home_scoreintegerPost home score.
post_bat_scoreintegerPost bat score.
post_fld_scoreintegerPost fld score.
if_fielding_alignmentcharacterIf fielding alignment.
of_fielding_alignmentcharacterOf fielding alignment.
spin_axisintegerSpin axis.
delta_home_win_expnumericDelta home win exp.
delta_run_expnumericDelta run exp.
bat_speednumericBat speed (mph).
swing_lengthnumericSwing length (ft, head travel).
miss_distancecharacterAverage miss distance (in) on swings.
estimated_slg_using_speedanglenumericEstimated slg using speedangle.
delta_pitcher_run_expnumericDelta pitcher run exp.
hyper_speednumericHyper speed.
home_score_diffintegerHome score diff.
bat_score_diffintegerBat score diff.
home_win_expnumericHome win exp.
bat_win_expnumericBat win exp.
age_pit_legacyintegerAge pit legacy.
age_bat_legacyintegerAge bat legacy.
age_pitintegerAge pit.
age_batintegerAge bat.
n_thruorder_pitcherintegerNumber of thruorder pitcher.
n_priorpa_thisgame_player_at_batintegerNumber of priorpa thisgame player at bat.
pitcher_days_since_prev_gameintegerPitcher days since prev game.
batter_days_since_prev_gameintegerBatter days since prev game.
pitcher_days_until_next_gameintegerPitcher days until next game.
batter_days_until_next_gameintegerBatter days until next game.
api_break_z_with_gravitynumericApi break z with gravity.
api_break_x_armnumericApi break x arm.
api_break_x_batter_innumericApi break x batter in.
arm_anglenumericArm angle.
attack_anglenumericAttack angle (deg, bat path at contact).
attack_directionnumericAttack direction (deg, pull/oppo).
swing_path_tiltnumericSwing-path tilt (deg).
intercept_ball_minus_batter_pos_x_inchesnumericIntercept ball minus batter pos x inches.
intercept_ball_minus_batter_pos_y_inchesnumericIntercept ball minus batter pos y inches.

Example

from sportsdataverse.mlb import mlb_statcast_search_minors
df = mlb_statcast_search_minors("2024-06-01", "2024-06-02")

mlb_statcast_search_wbc(start_dt: 'str', end_dt: 'str', *, player_type: 'str' = 'batter', chunk_days: 'int' = 7, return_as_pandas: 'bool' = False, **filters: 'Any') -> "'Union[pl.DataFrame, pd.DataFrame]'"

World Baseball Classic Statcast search (/statcast-search-world-baseball-classic/csv).

Same shape, columns, and 25,000-row chunking as mlb_statcast_search, against the WBC CSV route. Pass WBC date windows (e.g. March of a WBC year).

Parameters

ParameterTypeDefaultDescription
start_dtstr
end_dtstr
player_typestr'batter'"batter" (default) or "pitcher".
chunk_daysint7initial window size in days.
return_as_pandasboolFalsereturn a pandas DataFrame instead of polars.

Returns

A polars (or pandas) DataFrame, one row per WBC pitch.

col_nametypedescription
pitch_typecharacterPitch type code.
game_datecharacterGame date.
release_speednumericRelease speed.
release_pos_xnumericRelease pos x.
release_pos_znumericRelease pos z.
player_namecharacterPlayer name.
batterintegerMLBAM id of the batter.
pitcherintegerMLBAM id of the pitcher.
eventscharacterEvents.
descriptioncharacterDescription.
spin_dircharacterSpin dir.
spin_rate_deprecatedcharacterSpin rate deprecated.
break_angle_deprecatedcharacterBreak angle deprecated.
break_length_deprecatedcharacterBreak length deprecated.
zoneintegerZone.
descharacterDes.
game_typecharacterGame type.
standcharacterBatter stance side (R/L).
p_throwscharacterPitcher throwing hand (R/L).
home_teamcharacterHome team.
away_teamcharacterAway team.
typecharacterRecord/pitch type.
hit_locationintegerHit location.
bb_typecharacterBb type.
ballsintegerBalls.
strikesintegerStrikes.
game_yearintegerGame year.
pfx_xnumericHorizontal movement (in, pitcher perspective).
pfx_znumericInduced vertical movement (in).
plate_xnumericPlate x.
plate_znumericPlate z.
on_3bcharacterOn 3b.
on_2bcharacterOn 2b.
on_1bcharacterOn 1b.
outs_when_upintegerOuts when up.
inningintegerInning.
inning_topbotcharacterInning topbot.
hc_xnumericHc x.
hc_ynumericHc y.
tfs_deprecatedcharacterTfs deprecated.
tfs_zulu_deprecatedcharacterTfs zulu deprecated.
umpirecharacterUmpire.
sv_idcharacterSv id.
vx0numericVx0.
vy0numericVy0.
vz0numericVz0.
axnumericAx.
aynumericAy.
aznumericAz.
sz_topnumericSz top.
sz_botnumericSz bot.
hit_distance_scintegerHit distance sc.
launch_speednumericExit velocity of the batted ball (mph).
launch_angleintegerLaunch angle (deg).
effective_speedintegerEffective speed.
release_spin_rateintegerRelease spin rate.
release_extensionnumericRelease extension.
game_pkintegerMLBAM game id.
fielder_2integerFielder 2.
fielder_3integerFielder 3.
fielder_4integerFielder 4.
fielder_5integerFielder 5.
fielder_6integerFielder 6.
fielder_7integerFielder 7.
fielder_8integerFielder 8.
fielder_9integerFielder 9.
release_pos_ynumericRelease pos y.
estimated_ba_using_speedanglenumericEstimated ba using speedangle.
estimated_woba_using_speedanglenumericEstimated woba using speedangle.
woba_valueintegerWoba value.
woba_denomintegerWoba denom.
babip_valueintegerBabip value.
iso_valueintegerIso value.
launch_speed_angleintegerLaunch speed angle.
at_bat_numberintegerAt bat number.
pitch_numberintegerPitch number.
pitch_namecharacterPitch type name.
home_scoreintegerHome score.
away_scoreintegerAway score.
bat_scoreintegerBat score.
fld_scoreintegerFld score.
post_away_scoreintegerPost away score.
post_home_scoreintegerPost home score.
post_bat_scoreintegerPost bat score.
post_fld_scoreintegerPost fld score.
if_fielding_alignmentcharacterIf fielding alignment.
of_fielding_alignmentcharacterOf fielding alignment.
spin_axisintegerSpin axis.
delta_home_win_expnumericDelta home win exp.
delta_run_expnumericDelta run exp.
bat_speednumericBat speed (mph).
swing_lengthnumericSwing length (ft, head travel).
miss_distancecharacterAverage miss distance (in) on swings.
estimated_slg_using_speedanglenumericEstimated slg using speedangle.
delta_pitcher_run_expnumericDelta pitcher run exp.
hyper_speednumericHyper speed.
home_score_diffintegerHome score diff.
bat_score_diffintegerBat score diff.
home_win_expnumericHome win exp.
bat_win_expnumericBat win exp.
age_pit_legacyintegerAge pit legacy.
age_bat_legacyintegerAge bat legacy.
age_pitintegerAge pit.
age_batintegerAge bat.
n_thruorder_pitcherintegerNumber of thruorder pitcher.
n_priorpa_thisgame_player_at_batintegerNumber of priorpa thisgame player at bat.
pitcher_days_since_prev_gameintegerPitcher days since prev game.
batter_days_since_prev_gameintegerBatter days since prev game.
pitcher_days_until_next_gameintegerPitcher days until next game.
batter_days_until_next_gameintegerBatter days until next game.
api_break_z_with_gravitynumericApi break z with gravity.
api_break_x_armnumericApi break x arm.
api_break_x_batter_innumericApi break x batter in.
arm_anglenumericArm angle.
attack_anglenumericAttack angle (deg, bat path at contact).
attack_directionnumericAttack direction (deg, pull/oppo).
swing_path_tiltnumericSwing-path tilt (deg).
intercept_ball_minus_batter_pos_x_inchesnumericIntercept ball minus batter pos x inches.
intercept_ball_minus_batter_pos_y_inchesnumericIntercept ball minus batter pos y inches.

Example

from sportsdataverse.mlb import mlb_statcast_search_wbc
df = mlb_statcast_search_wbc("2023-03-08", "2023-03-22")

mlb_stats(stats: 'str', group: 'str', season: 'Optional[Union[int, str]]' = None, sport_id: 'int' = 1, league_id: 'Optional[Union[int, str]]' = None, team_id: 'Optional[int]' = None, player_pool: 'Optional[str]' = None, game_type: 'Optional[str]' = None, limit: 'int' = 50, offset: 'int' = 0, fields: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/stats — generic stats query.

stats selects the slice (season, career, yearByYear, …) and group selects the stat group (hitting, pitching, fielding). Filters: season, team_id, league_id, game_type, player_pool.

Parameters

ParameterTypeDefaultDescription
statsstr
groupstr
seasonOptional[Union[int, str]]None
sport_idint1
league_idOptional[Union[int, str]]None
team_idOptional[int]None
player_poolOptional[str]None
game_typeOptional[str]None
limitint50
offsetint0
fieldsOptional[str]None

mlb_stats_leaders(leader_categories: 'str', season: 'Optional[Union[int, str]]' = None, leader_game_types: 'Optional[str]' = None, stat_group: 'Optional[str]' = None, league_id: 'Optional[Union[int, str]]' = None, sport_id: 'int' = 1, limit: 'int' = 10, **kwargs) -> 'Dict'

GET /api/v1/stats/leaders — top-N leaders for a stat category.

Parameters

ParameterTypeDefaultDescription
leader_categoriesstr
seasonOptional[Union[int, str]]None
leader_game_typesOptional[str]None
stat_groupOptional[str]None
league_idOptional[Union[int, str]]None
sport_idint1
limitint10

mlb_stats_streaks(streak_type: 'str', streak_threshold: 'int' = 1, season: 'Optional[Union[int, str]]' = None, stat_group: 'Optional[str]' = None, active_streak: 'Optional[bool]' = None, sport_id: 'int' = 1, **kwargs) -> 'Dict'

GET /api/v1/stats/streaks — active or historical streaks.

streak_type e.g. hittingStreakOverall, onBaseOverall.

Parameters

ParameterTypeDefaultDescription
streak_typestr
streak_thresholdint1
seasonOptional[Union[int, str]]None
stat_groupOptional[str]None
active_streakOptional[bool]None
sport_idint1

mlb_stolen_base_value(sb_attempts: "'pl.DataFrame'", sprint_speed: "'pl.DataFrame'", poptime: "'pl.DataFrame'", *, speed_bin: 'float' = 0.5, pop_bin: 'float' = 0.05, pop_col: 'str' = 'pop_2b_sba', alpha: 'float' = 2.0, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-runner stolen-base run value: realized-vs-expected run contribution.

sb_run_value = sum(p_success * RUN_VALUES["sb"] + (1 - p_success) * RUN_VALUES["cs"]) per attempt -- the documented fallback constants (see module docstring for why, not sportsdataverse.mlb.mlb_run_values.event_run_value on these bundled-des rows), weighted by the surface's modeled success probability for that attempt's bin.

Parameters

ParameterTypeDefaultDescription
sb_attemptsDataFrameOne row per attempt (see sb_attempts_from_pitches). MiLB feeds run through the same function -- there is no Savant basestealing leaderboard oracle for MiLB.
sprint_speedDataFrameSprint-speed leaderboard frame (runner_id, sprint_speed).
poptimeDataFramePop-time leaderboard frame (catcher_id, pop_col).
speed_binfloat0.5Sprint-speed bin width. Defaults to 0.5.
pop_binfloat0.05Pop-time bin width. Defaults to 0.05.
pop_colstr'pop_2b_sba'Pop-time column name in poptime. Defaults to "pop_2b_sba".
alphafloat2.0Laplace smoothing strength for the surface. Defaults to 2.0.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

one row per runner. | Column | Type | Description | |---|---|---| | runner_id | Utf8 | Runner MLBAM id | | attempts | Int64 | Stolen-base attempts | | p_success_mean | Float64 | Mean modeled success probability across attempts | | sb_run_value | Float64 | Sum of realized-vs-expected run contribution |

Example

from sportsdataverse.mlb.mlb_stolen_base import mlb_stolen_base_value
sb_value = mlb_stolen_base_value(sb_attempts, sprint_speed, poptime)

mlb_stuff_plus(pitches: 'pl.DataFrame', *, level: 'str' = 'pitch', return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Score pitches with the bundled Stuff+ (①) run-value model.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameOutput of sportsdataverse.mlb.mlb_pitch_features.pitch_features (needs velo_z, spin_z, pfx_x_z, pfx_z_z, release_pos_x_z, release_pos_z_z, extension_z).
levelstr'pitch'"pitch" (default) for per-pitch output, or "arsenal" for a per (pitcher, pitch_type) mean.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

pitcher, pitch_type, stuff_rv_hat, stuff_plus — one row per pitch (level="pitch") or per pitcher-pitchtype (level="arsenal"). Empty input returns a zero-row frame with the documented schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
pitch_typecharacterStatcast pitch-type abbreviation.
stuff_rv_hatdoublePredicted per-pitch run value from the bundled Stuff+ xgboost model (physics + fastball-relative features only).
stuff_plusdoublePlus-scale Stuff+ score, 100 = league average, higher = better (sign-inverted from stuff_rv_hat).

Example

from sportsdataverse.mlb.mlb_pitch_features import pitch_features
from sportsdataverse.mlb.mlb_stuff_plus import mlb_stuff_plus
feats = pitch_features(raw_pitches)
out = mlb_stuff_plus(feats, level="arsenal")
print(out.sort("stuff_plus", descending=True).head())

# Pipeline next step

out.filter(pl.col("pitch_type") == "FF").sort("stuff_plus", descending=True)

mlb_swing_decision(start_dt: 'str', end_dt: 'str', *, puller: 'Optional[Callable[..., pl.DataFrame]]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Per player-season swing/take run value + selective-aggression (SEAGER analog).

Pulls pitches via puller(start_dt, end_dt, player_type="batter"), builds the RV(swing)/RV(take) zone x count surfaces (and the league swing-rate table) from the pull itself, then per batter:

  • swing_take_runs = sum of the actual per-pitch delta_run_exp credited to the batter's swing/take decisions (matching Savant's swing/take run-value definition -- the run value of what actually happened on each pitch, not a league-average lookup).
  • selective_agg = sum of rv_chosen - rv_neutral, where rv_neutral = swing_rate * rv_swing + (1 - swing_rate) * rv_take uses the league swing rate for that zone x count cell -- positive means the batter swings at hittable pitches and takes bad ones more than a league-average decision-maker would.
  • chase_rate = swings / pitches seen in the waste/chase zones (zone in {11,12,13,14}).

Parameters

ParameterTypeDefaultDescription
start_dtstrPull start date, YYYY-MM-DD.
end_dtstrPull end date, YYYY-MM-DD.
pullerOptional[Callable[..., DataFrame]]NoneInjectable Statcast search callable -- defaults to sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per (batter, season): pitches, swing_take_runs, selective_agg, chase_rate, n_swings. Empty pull returns a zero-row frame with the documented schema.

col_nametypedescription
batterintegerMLBAM batter id (join key into Savant's swing/take leaderboard as player_id).
seasonintegerFour-digit season year derived from game_year/game_date.
pitchesintegerTotal pitches seen with a non-null zone/decision in the pulled window.
swing_take_runsdoubleSum of the run value of the batter's actual swing/take decisions (delta_run_exp of the chosen decision at that zone x count).
selective_aggdoubleSEAGER-analog selective-aggression score -- sum of (chosen run value minus the league-neutral-rate run value) per pitch.
chase_ratedoubleShare of pitches in the waste/chase attack zones (11-14) that the batter swung at.
n_swingsintegerCount of pitches the batter swung at.

Example

from sportsdataverse.mlb.mlb_swing_decision import mlb_swing_decision

df = mlb_swing_decision("2024-06-01", "2024-06-21")
print(df.shape)

# Pipeline next step (one line)

df.sort("selective_agg", descending=True).head()

mlb_team_elo(results: 'pl.DataFrame', *, k: 'float' = 4.0, hfa: 'float' = 24.0, init: 'float' = 1500.0, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

As-of-date iterative Elo run-differential rating.

Games are folded in date order (ties broken by game_id); each team's rating updates only after its game is scored, so the home_rating/away_rating columns are strictly as-of-date (no leakage from later games). home_win_prob_elo uses the standard logistic Elo formula with a home-field-advantage offset.

Parameters

ParameterTypeDefaultDescription
resultsDataFrameGame-level results (game_id, date, home_team_id, away_team_id, home_score, away_score).
kfloat4.0Elo K-factor (rating-update step size).
hfafloat24.0Home-field-advantage Elo-point offset.
initfloat1500.0Initial rating for a team with no prior games.
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per game, in date order. | Column | Type | Description | |---|---|---| | game_id | Utf8 | Game identifier | | date | Date | Game date | | home_team_id | Utf8 | Home team identifier | | away_team_id | Utf8 | Away team identifier | | home_rating | Float64 | Home team's rating before this game | | away_rating | Float64 | Away team's rating before this game | | home_win_prob_elo | Float64 | Elo-implied P(home wins) before this game | | home_rating_post | Float64 | Home team's rating after this game | | away_rating_post | Float64 | Away team's rating after this game |

col_nametypedescription
game_idcharacterGame identifier (statsapi gamePk, stringified).
datedateCalendar date of the game (YYYY-MM-DD).
home_team_idcharacterHome team identifier.
away_team_idcharacterAway team identifier.
home_ratingdoubleHome team's Elo rating before this game (as-of-date).
away_ratingdoubleAway team's Elo rating before this game (as-of-date).
home_win_prob_elodoubleElo-implied P(home team wins) before this game.
home_rating_postdoubleHome team's Elo rating after this game.
away_rating_postdoubleAway team's Elo rating after this game.

Example

from sportsdataverse.mlb.mlb_team_projection import mlb_team_elo
elo = mlb_team_elo(results)

# Pipeline next step (one line)

elo.group_by("home_team_id").agg(pl.col("home_rating_post").last())

mlb_team_leaders(team_id: 'int', leader_categories: 'str', season: 'Optional[Union[int, str]]' = None, leader_game_types: 'Optional[str]' = None, limit: 'int' = 10, **kwargs) -> 'Dict'

GET /api/v1/teams/{teamId}/leaders — team leaders.

leader_categories e.g. homeRuns, battingAverage, wins, earnedRunAverage (comma-separated for multi).

Parameters

ParameterTypeDefaultDescription
team_idint
leader_categoriesstr
seasonOptional[Union[int, str]]None
leader_game_typesOptional[str]None
limitint10

mlb_team_projection(seasons: 'Union[int, List[int], None]' = None, *, results: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Combined pythagenpat + Elo team projection.

Parameters

ParameterTypeDefaultDescription
seasonsUnion[int, List[int], None]NoneReserved for a future network-collector path (currently unused -- pass results directly; see sportsdataverse.mlb.mlb_run_expectancy.mlb_run_expectancy_matrix for the collector pattern this will follow once wired).
resultsOptional[DataFrame]NoneGame-level results (see mlb_pythagenpat_table and mlb_team_elo for the required columns).
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per (season, team). | Column | Type | Description | |---|---|---| | season | Int64 | Season | | team_id | Utf8 | Team identifier | | win_pct | Float64 | Realized win percentage | | pythag_win_pct | Float64 | Pythagenpat expected win percentage | | rating | Float64 | Final (as of the last observed game) Elo rating | | exp_margin | Float64 | Elo-implied expected run margin vs a league-average opponent |

col_nametypedescription
seasonintegerMLB season (4-digit start year).
team_idcharacterTeam identifier (statsapi team id, stringified).
win_pctdoubleRealized win percentage.
pythag_win_pctdoublePythagenpat expected win percentage.
ratingdoubleFinal (as of the last observed game) Elo rating.
exp_margindoubleElo-implied expected run margin vs a league-average opponent.

Example

from sportsdataverse.mlb.mlb_team_projection import mlb_team_projection
projection = mlb_team_projection(results=results)

mlb_team_stats(team_id: 'int', season: 'Union[int, str]', stats: 'str' = 'season', group: 'str' = 'hitting', sport_ids: 'Optional[Union[int, List[int]]]' = None, game_type: 'Optional[str]' = None, fields: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/teams/{teamId}/stats — team-level stats.

stats: season, career, yearByYear, byMonth, byDayOfWeek, … group: hitting, pitching, fielding.

Parameters

ParameterTypeDefaultDescription
team_idint
seasonUnion[int, str]
statsstr'season'
groupstr'hitting'
sport_idsOptional[Union[int, List[int]]]None
game_typeOptional[str]None
fieldsOptional[str]None

mlb_teams(season: 'Optional[Union[int, str]]' = None, sport_id: 'int' = 1, league_ids: 'Optional[Union[int, List[int], str]]' = None, active_status: 'Optional[str]' = None, all_star_statuses: 'Optional[str]' = None, hydrate: 'Optional[str]' = None, fields: 'Optional[str]' = None, **kwargs) -> 'Dict'

GET /api/v1/teams — list teams. sport_id=1 = MLB.

Parameters

ParameterTypeDefaultDescription
seasonOptional[Union[int, str]]None
sport_idint1
league_idsOptional[Union[int, List[int], str]]None
active_statusOptional[str]None
all_star_statusesOptional[str]None
hydrateOptional[str]None
fieldsOptional[str]None

mlb_times_through_order(pitches: 'pl.DataFrame', *, season: 'int' = 2024, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Per-pitch fitted times-through-order fatigue adjustment.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameOutput of sportsdataverse.mlb.mlb_pitch_features.add_sequence_features (needs times_through_order).
seasonint2024Season year, selects the fitted tto_penalty coefficients via sportsdataverse.mlb.mlb_pitching_constants.get_baselines.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

pitcher, game_pk, at_bat_number, pitch_number, times_through_order, fatigue_rv_adj (the fitted marginal penalty for that TTO level). Empty input returns a zero-row frame with this schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
game_pkintegerGame identifier.
at_bat_numberintegerGame-level plate-appearance sequence number.
pitch_numberintegerPitch sequence number within the plate appearance.
times_through_orderintegerTimes through the batting order (1-3).
fatigue_rv_adjdoubleFitted per-TTO run-value marginal (mlb_pitching_constants.tto_penalty) for this pitch's TTO level.

Example

from sportsdataverse.mlb.mlb_pitch_features import pitch_features, add_sequence_features
from sportsdataverse.mlb.mlb_pitch_fatigue import mlb_times_through_order
feats = add_sequence_features(pitch_features(raw_pitches))
out = mlb_times_through_order(feats, season=2024)
print(out.select("times_through_order", "fatigue_rv_adj").unique())

mlb_umpire_bias(pitches: 'pl.DataFrame', *, model: 'Optional[Dict[str, Any]]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Per-umpire called-strike bias residual (observed minus expected).

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameCalled pitches with umpire_id, description, plate_x, plate_z, sz_top, sz_bot.
modelOptional[Dict[str, Any]]NonePre-fit model dict from fit_zone_model; fits on pitches itself when None.
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per umpire. | Column | Type | Description | |---|---|---| | umpire_id | Utf8 | Umpire identifier | | n_called | Int64 | Called pitches observed for this umpire | | obs_strike_rate | Float64 | Realized called-strike rate | | exp_strike_rate | Float64 | Mean model-predicted called-strike probability | | bias | Float64 | obs_strike_rate - exp_strike_rate (positive = strike-generous) |

col_nametypedescription
umpire_idcharacterUmpire identifier (statsapi people id, stringified).
n_calledintegerCalled pitches (strike or ball) observed for this umpire.
obs_strike_ratedoubleRealized called-strike rate for this umpire.
exp_strike_ratedoubleMean model-predicted called-strike probability for this umpire's pitches.
biasdoubleobs_strike_rate minus exp_strike_rate (positive = strike-generous).

Example

from sportsdataverse.mlb.mlb_umpire_zone import mlb_umpire_bias
bias = mlb_umpire_bias(pitches)

mlb_umpire_called_strike_prob(pitches: 'pl.DataFrame', *, model: 'Optional[Dict[str, Any]]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

P(called strike) per pitch from the zone logistic.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameFrame with plate_x, plate_z, sz_top, sz_bot (one row per pitch, not required to be called pitches only).
modelOptional[Dict[str, Any]]NonePre-fit model dict from fit_zone_model; fits on pitches itself when None (using only its called pitches).
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per input pitch. | Column | Type | Description | |---|---|---| | called_strike_prob | Float64 | P(called strike | pitch location) |

col_nametypedescription
called_strike_probdoubleP(called strike | pitch location) from the standardized zone-coordinate logistic.

Example

from sportsdataverse.mlb.mlb_umpire_zone import mlb_umpire_called_strike_prob
prob = mlb_umpire_called_strike_prob(pitches)

mlb_win_expectancy(pbp: 'pl.DataFrame', results: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Per-play home win expectancy from the empirical state table.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameParsed mlb_play_by_play frame (see sportsdataverse.mlb.mlb_run_expectancy.pbp_base_out_states).
resultsDataFrameGame-level results (game_id, home_score, away_score).
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per plate appearance, plus one terminal "game over" row per game (at_bat_index = last real PA's index + 1, home_win_exp pinned to the actual final outcome: 1.0 if home won, 0.0 otherwise). Without this anchor, the last real play's own WPA swing (e.g. a walk-off) would never be captured by mlb_win_probability_added's per-game diff, and the game-level WPA sum would not telescope to the exact +-0.5 identity. | Column | Type | Description | |---|---|---| | game_id | Utf8 | Game identifier | | at_bat_index | Int64 | Game-global sequential PA index (last row is a synthetic terminal marker) | | half | Utf8 | "top" or "bottom" (offense side); the terminal row repeats the last real half | | home_win_exp | Float64 | P(home team wins | state before the play); 1.0/0.0 on the terminal row |

col_nametypedescription
game_idcharacterGame identifier (statsapi gamePk, stringified).
at_bat_indexintegerGame-global sequential plate-appearance index.
halfcharacterHalf-inning ("top" or "bottom") -- which side is on offense.
home_win_expdoubleEmpirical P(home team wins | base-out-score-inning state before the play).

Example

from sportsdataverse.mlb.mlb_win_expectancy import mlb_win_expectancy
we = mlb_win_expectancy(pbp, results)

# Pipeline next step (one line)

we.filter(pl.col("game_id") == "716390").sort("at_bat_index")

mlb_win_probability_added(we: 'pl.DataFrame', *, perspective: 'str' = 'home', return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Per-play win-probability-added from a mlb_win_expectancy frame.

wpa_i = home_win_exp_i - home_win_exp_{i-1} within each game (the first play of a game is measured against the neutral 0.5 baseline).

Parameters

ParameterTypeDefaultDescription
weDataFrameOutput of mlb_win_expectancy (needs game_id, at_bat_index, home_win_exp).
perspectivestr'home'"home" (default) returns home-team WPA; any other value (e.g. "away") returns the sign-flipped (away-team) WPA.
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

one row per plate appearance. | Column | Type | Description | |---|---|---| | game_id | Utf8 | Game identifier | | at_bat_index | Int64 | Game-global sequential PA index | | wpa | Float64 | Win-probability added, from perspective |

col_nametypedescription
game_idcharacterGame identifier (statsapi gamePk, stringified).
at_bat_indexintegerGame-global sequential plate-appearance index.
wpadoubleWin-probability added on this play, from the requested perspective.

Example

from sportsdataverse.mlb.mlb_win_expectancy import mlb_win_probability_added
wpa = mlb_win_probability_added(we)

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

Reconstruct pre-play base-out state from statsapi play-by-play.

Within each (game_id, inning, half) half-inning, ordered by the game-global at_bat_index: base_state/outs_start before PA i are the post-occupancy / out-count of PA i-1 (empty/0 at the half's first PA -- occupancy and outs both genuinely reset at every half-inning boundary). runs_on_play is the score delta since the previous PA in the game (over("game_id"), not reset per half-inning -- the score itself carries across the half-inning boundary even though outs/bases do not). runs_rest_of_inning is the suffix-sum of runs_on_play within the half.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameParsed mlb_play_by_play frame (optionally concatenated across games), carrying game_id, about_inning, about_half_inning, about_at_bat_index, count_outs, result_home_score, result_away_score, matchup_post_on_{first,second,third}_id.

Returns

one row per plate appearance. | Column | Type | Description | |---|---|---| | game_id | Utf8 | Game identifier | | inning | Int64 | Inning number | | half | Utf8 | "top" or "bottom" | | at_bat_index | Int64 | Game-global sequential PA index | | base_state | Utf8 | 3-char occupancy before the PA ("1_3" etc.) | | outs_start | Int64 | Outs before the PA (0-2) | | runs_on_play | Int64 | Runs scored on this PA | | runs_rest_of_inning | Int64 | Runs scored from this PA through the half's end | | score_diff | Int64 | home - away score at the start of the PA |

Example

from sportsdataverse.mlb.mlb_run_expectancy import pbp_base_out_states
states = pbp_base_out_states(pbp)

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

Pearson correlation coefficient between two 1-D arrays.

Parameters

ParameterTypeDefaultDescription
andarrayFirst sample array.
bndarraySecond sample array, same length as a.

Returns

Pearson's r. nan if either input has zero variance.

Example

from sportsdataverse.mlb.mlb_run_values import pearson_corr
r = pearson_corr(mine["framing_runs"].to_numpy(), sav["runs_extra_strikes"].to_numpy())

pitch_features(pitches: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Build the per-pitch feature substrate every pitching model consumes.

Standardizes physics (velocity/spin/movement/release/extension) within pitcher, derives strike-zone-relative location features, pins id columns to Int64, and passes Savant's per-pitch delta_run_exp through unchanged as run_value (the single run-value label used by Stuff+/Command+/TTO/tunneling).

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameRaw Savant pitch frame (e.g. from sportsdataverse.mlb.mlb_statcast_search), one row per pitch, carrying pitcher, release_speed, release_spin_rate, pfx_x, pfx_z, release_pos_x, release_pos_z, release_extension, plate_x, plate_z, sz_top, sz_bot, delta_run_exp.
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

One row per pitch with the input columns plus velo_z, spin_z, pfx_x_z, pfx_z_z, release_pos_x_z, release_pos_z_z, extension_z (standardized within pitcher), plate_z_norm, plate_x_abs, in_zone, dist_from_heart, and run_value. Empty/malformed input returns a zero-row frame carrying the added schema.

col_nametypedescription
velo_zdoubleRelease speed standardized (z-score) within pitcher.
spin_zdoubleRelease spin rate standardized (z-score) within pitcher.
pfx_x_zdoubleHorizontal movement (pfx_x) standardized (z-score) within pitcher.
pfx_z_zdoubleVertical movement (pfx_z) standardized (z-score) within pitcher.
release_pos_x_zdoubleHorizontal release position standardized (z-score) within pitcher.
release_pos_z_zdoubleVertical release position standardized (z-score) within pitcher.
extension_zdoubleRelease extension standardized (z-score) within pitcher.
run_valuedoubleSavant per-pitch delta_run_exp, passed through unchanged as the spine's single run-value label.
plate_x_absdoubleAbsolute horizontal plate location (distance from the center of the zone).
plate_z_normdoubleVertical plate location normalized to the batter's own strike zone, 0 = bottom, 1 = top.
in_zoneinteger1 if the pitch crossed the strike zone (normalized location + horizontal bound), else 0.
dist_from_heartdoubleEuclidean distance from the normalized zone center (0, 0.5) -- lower is more hittable.

Example

from sportsdataverse.mlb import mlb_statcast_search
from sportsdataverse.mlb.mlb_pitch_features import pitch_features
raw = mlb_statcast_search("2024-06-15", "2024-06-15", player_type="pitcher")
feats = pitch_features(raw)
print(feats.select("pitch_type", "in_zone", "run_value").head())

# Pipeline next step

feats.filter(pl.col("in_zone") == 1).group_by("pitch_type").agg(pl.col("run_value").mean())

Leakage-safe per-appearance trailing velocity/workload trends.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameRaw (or feature-substrate) pitch frame carrying pitcher, game_pk, game_date, pitch_type, release_speed.
windowint5Number of trailing PRIOR appearances used for the rolling statistics (never includes the current appearance).
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

Per (pitcher, game_pk, game_date): fb_velo (this game's mean fastball release_speed), velo_trend (OLS slope of fb_velo over the trailing window prior appearances), velo_drop (trailing-baseline mean minus this game's fb_velo), pitches_game, trailing_workload (mean pitches_game over the trailing window), days_rest. The first appearance for a pitcher has null trailing stats (no prior data). Empty input returns a zero-row frame with this schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
game_pkintegerGame identifier.
game_datedateCalendar date of the game (YYYY-MM-DD).
fb_velodoubleMean fastball release speed for this appearance.
velo_trenddoubleOLS slope of fb_velo over the trailing prior appearances (leakage-safe).
velo_dropdoubleTrailing-baseline mean fb_velo minus this appearance's fb_velo.
pitches_gameintegerPitches thrown in this appearance.
trailing_workloaddoubleMean pitches_game over the trailing prior appearances (leakage-safe).
days_restdoubleDays since the pitcher's previous appearance.

Example

from sportsdataverse.mlb.mlb_pitch_injury import pitcher_appearance_trends
out = pitcher_appearance_trends(raw_pitches, window=5)
print(out.select("game_date", "velo_drop", "days_rest").tail())

predict_sb_success(upcoming: "'pl.DataFrame'", history: "'pl.DataFrame'", cutoff_date: 'Any', *, speed_bin: 'float' = 0.5, pop_bin: 'float' = 0.05, pop_col: 'str' = 'pop_2b_sba', alpha: 'float' = 2.0, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

As-of-date predictive P(success): the surface is fit on history strictly before cutoff_date.

The leakage boundary: sportsdataverse.mlb.mlb_run_values.as_of_split drops every history row with game_date >= cutoff_date before the success-rate grid is built, so upcoming attempts are scored only against what was knowable at that date.

Parameters

ParameterTypeDefaultDescription
upcomingDataFrameAttempts to score, each carrying runner_id, base, sprint_speed, and the pop_col pop-time column.
historyDataFramePrior attempts with game_date, outcome, sprint_speed, and pop_col -- used to fit the surface via as_of_split.
cutoff_dateAnyExclusive upper bound on history["game_date"].
speed_binfloat0.5Sprint-speed bin width. Defaults to 0.5.
pop_binfloat0.05Pop-time bin width. Defaults to 0.05.
pop_colstr'pop_2b_sba'Pop-time column name. Defaults to "pop_2b_sba".
alphafloat2.0Laplace smoothing strength. Defaults to 2.0.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

one row per scored attempt. | Column | Type | Description | |---|---|---| | runner_id | Utf8 | Runner MLBAM id | | base | Utf8 | Attempted base | | p_success | Float64 | Modeled success probability, as-of cutoff_date |

Example

from sportsdataverse.mlb.mlb_stolen_base import predict_sb_success
preds = predict_sb_success(upcoming, history, cutoff_date=dt.date(2024, 6, 15))

prop_over_prob(line: 'float', expected: 'float') -> 'float'

P(realized count > line) under a Poisson(expected) model.

1 - poisson.cdf(floor(line), expected).

Parameters

ParameterTypeDefaultDescription
linefloatThe prop betting line (e.g. 8.5 runs).
expectedfloatThe Poisson mean (expected runs/strikeouts/etc.).

Returns

P(over), in [0, 1].

Example

from sportsdataverse.mlb.mlb_prop_projection import prop_over_prob
prop_over_prob(3.5, 4.5)

sb_attempts_from_pitches(pitches: "'pl.DataFrame'") -> "'pl.DataFrame'"

Extract stolen-base / caught-stealing attempts from pitch-level Statcast rows.

Detects attempts via a des regex (see module docstring for why -- the events column does not carry these in the flat per-pitch search) and reads the attempting runner off the pre-play occupancy column implied by the attempted base (2B attempt -> on_1b, 3B -> on_2b, home -> on_3b).

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameA sportsdataverse.mlb.mlb_statcast_extra.mlb_statcast_search frame with des, fielder_2, on_1b/on_2b/on_3b, and (if present) game_date.

Returns

one row per attempt. | Column | Type | Description | |---|---|---| | game_date | Date | Game date (if present in the input) | | runner_id | Utf8 | Attempting runner's MLBAM id | | catcher_id | Utf8 | Catcher MLBAM id (Savant fielder_2) | | base | Utf8 | 2B | 3B | HOME | | outcome | Utf8 | success | caught |

Example

from sportsdataverse.mlb.mlb_stolen_base import sb_attempts_from_pitches
sb_attempts = sb_attempts_from_pitches(pitches)

sb_success_surface(sb_attempts: "'pl.DataFrame'", sprint_speed: "'pl.DataFrame'", poptime: "'pl.DataFrame'", *, speed_bin: 'float' = 0.5, pop_bin: 'float' = 0.05, pop_col: 'str' = 'pop_2b_sba', alpha: 'float' = 2.0) -> "'pl.DataFrame'"

Empirical P(stolen-base success) surface over (sprint speed, pop time, base).

Rate per bin is Laplace-smoothed: (successes + alpha) / (n + 2 * alpha).

Parameters

ParameterTypeDefaultDescription
sb_attemptsDataFrameOne row per attempt (runner_id, catcher_id, base, outcome).
sprint_speedDataFrameA sportsdataverse.mlb.mlb_statcast.mlb_statcast_leaderboard_sprint_speed frame with runner_id (Utf8) and sprint_speed.
poptimeDataFrameA sportsdataverse.mlb.mlb_statcast.mlb_statcast_leaderboard_poptime frame with catcher_id (Utf8) and the pop-time column named by pop_col.
speed_binfloat0.5Bin width (ft/sec) for sprint speed. Defaults to 0.5.
pop_binfloat0.05Bin width (seconds) for pop time. Defaults to 0.05.
pop_colstr'pop_2b_sba'Name of the pop-time column in poptime. Defaults to "pop_2b_sba".
alphafloat2.0Laplace smoothing strength. Defaults to 2.0.

Returns

one row per observed (speed_b, pop_b, base). | Column | Type | Description | |---|---|---| | speed_b | Int64 | Sprint-speed bin index | | pop_b | Int64 | Pop-time bin index | | base | Utf8 | Attempted base | | p_success | Float64 | Laplace-smoothed empirical success probability | | n | Int64 | Attempts observed in this bin |

Example

from sportsdataverse.mlb.mlb_stolen_base import sb_success_surface
surface = sb_success_surface(sb_attempts, sprint_speed, poptime)

siera_like(pitches: 'pl.DataFrame', season: 'int', *, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

SIERA-like ERA estimator from K%/BB%/GB% (experimental / provisional).

Evaluates the published SIERA functional form with mlb_pitching_constants.siera_coef, which are SEEDED literature placeholders (not yet OLS-fitted — the Task-4.2 next-season-ERA fit has not landed). Treat the output as directionally indicative, not a calibrated ERA; use x_era (oracle-gated vs Savant's xERA) for a fitted number.

Parameters

ParameterTypeDefaultDescription
pitchesDataFrameRaw pitch frame carrying pitcher, events, and (optionally) bb_type.
seasonintSeason year (unused in the formula itself, carried through for join convenience with x_era).
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

pitcher, season, k_pct, bb_pct, gb_pct, siera_like. Empty input returns a zero-row frame with this schema.

col_nametypedescription
pitcherintegerMLB Advanced Media (MLBAM) id for the pitcher.
seasonintegerSeason year (carried through for join convenience with x_era).
k_pctdoubleStrikeout rate (strikeouts / batters faced).
bb_pctdoubleWalk rate (walks + HBP / batters faced).
gb_pctdoubleGround-ball rate among batted balls.
siera_likedoubleSIERA-like ERA estimate from the fitted K%/BB%/GB% OLS coefficients.

Example

from sportsdataverse.mlb.mlb_pitch_era import siera_like
out = siera_like(raw_pitches, 2024)
print(out.sort("siera_like").head())

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

tto_penalty_table(feats: 'pl.DataFrame', *, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Observed mean run value by times-through-order, with the penalty vs TTO=1.

Parameters

ParameterTypeDefaultDescription
featsDataFrameOutput of sportsdataverse.mlb.mlb_pitch_features.add_sequence_features (needs times_through_order and run_value).
return_as_pandasboolFalseWhen True, return a pandas.DataFrame.

Returns

times_through_order, mean_run_value, penalty_vs_first (mean_run_value minus the TTO=1 mean run value), n. Empty input returns a zero-row frame with this schema.

col_nametypedescription
times_through_orderintegerTimes through the batting order (1-3).
mean_run_valuedoubleMean observed run value for pitches at this TTO level.
penalty_vs_firstdoublemean_run_value minus the TTO=1 mean run value.
nintegerNumber of pitches observed at this TTO level.

Example

from sportsdataverse.mlb.mlb_pitch_features import pitch_features, add_sequence_features
from sportsdataverse.mlb.mlb_pitch_fatigue import tto_penalty_table
feats = add_sequence_features(pitch_features(raw_pitches))
out = tto_penalty_table(feats)
print(out.sort("times_through_order"))