Upload 22 files
Browse filesFiles changed (22)
- functions/__pycache__/df_update.cpython-39.pycAdded
- functions/__pycache__/pitch_summary_functions.cpython-39.pycAdded
- functions/df_update.pyAdded+472
- functions/pitch_summary_functions.pyAdded+1029
- functions/statcast_2024_grouped.csvAdded+19
- joblib_model/__pycache__/feature_engineering.cpython-39.pycAdded
- joblib_model/barrel_model.joblibAdded+3
- joblib_model/in_zone.joblibAdded+3
- joblib_model/in_zone_model_knn_20240410.joblibAdded+3
- joblib_model/linear_reg_model_x.joblibAdded+3
- joblib_model/linear_reg_model_z.joblibAdded+3
- joblib_model/model_attack_zone.joblibAdded+3
- joblib_model/no_swing.joblibAdded+3
- joblib_model/swing.joblibAdded+3
- joblib_model/xwoba_model.joblibAdded+3
- stuff_model/__pycache__/feature_engineering.cpython-39.pycAdded
- stuff_model/__pycache__/stuff_apply.cpython-39.pycAdded
- stuff_model/feature_engineering.pyAdded+118
- stuff_model/lgbm_model_2020_2023.joblibAdded+3
- stuff_model/stuff_apply.pyAdded+57
- stuff_model/target_stats.txtAdded+2
- stuff_model/tj_stuff_plus_pitch.csvAdded+16
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472import polars as pl
import numpy as np
import joblib
loaded_model = joblib.load('joblib_model/barrel_model.joblib')
in_zone_model = joblib.load('joblib_model/in_zone_model_knn_20240410.joblib')
attack_zone_model = joblib.load('joblib_model/model_attack_zone.joblib')
xwoba_model = joblib.load('joblib_model/xwoba_model.joblib')
px_model = joblib.load('joblib_model/linear_reg_model_x.joblib')
pz_model = joblib.load('joblib_model/linear_reg_model_z.joblib')
class df_update:
def __init__(self):
pass
def update(self, df_clone: pl.DataFrame):
df = df_clone.clone()
# Assuming px_model is defined and df is your DataFrame
hit_codes = ['single',
'double','home_run', 'triple']
ab_codes = ['single', 'strikeout', 'field_out',
'grounded_into_double_play', 'fielders_choice', 'force_out',
'double', 'field_error', 'home_run', 'triple',
'double_play',
'fielders_choice_out', 'strikeout_double_play',
'other_out','triple_play']
obp_true_codes = ['single', 'walk',
'double','home_run', 'triple',
'hit_by_pitch', 'intent_walk']
obp_codes = ['single', 'strikeout', 'walk', 'field_out',
'grounded_into_double_play', 'fielders_choice', 'force_out',
'double', 'sac_fly', 'field_error', 'home_run', 'triple',
'hit_by_pitch', 'double_play', 'intent_walk',
'fielders_choice_out', 'strikeout_double_play',
'sac_fly_double_play',
'other_out','triple_play']
contact_codes = ['In play, no out',
'Foul', 'In play, out(s)',
'In play, run(s)',
'Foul Bunt']
bip_codes = ['In play, no out', 'In play, run(s)','In play, out(s)']
conditions_barrel = [
df['launch_speed'].is_null(),
(df['launch_speed'] * 1.5 - df['launch_angle'] >= 117) &
(df['launch_speed'] + df['launch_angle'] >= 124) &
(df['launch_speed'] >= 98) &
(df['launch_angle'] >= 4) & (df['launch_angle'] <= 50)
]
choices_barrel = [False, True]
conditions_tb = [
(df['event_type'] == 'single'),
(df['event_type'] == 'double'),
(df['event_type'] == 'triple'),
(df['event_type'] == 'home_run')
]
choices_tb = [1, 2, 3, 4]
conditions_woba = [
df['event_type'].is_in(['strikeout', 'field_out', 'sac_fly', 'force_out', 'grounded_into_double_play', 'fielders_choice', 'field_error', 'sac_bunt', 'double_play', 'fielders_choice_out', 'strikeout_double_play', 'sac_fly_double_play', 'other_out']),
df['event_type'] == 'walk',
df['event_type'] == 'hit_by_pitch',
df['event_type'] == 'single',
df['event_type'] == 'double',
df['event_type'] == 'triple',
df['event_type'] == 'home_run'
]
choices_woba = [0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]
woba_codes = ['strikeout', 'field_out', 'single', 'walk', 'hit_by_pitch', 'double', 'sac_fly', 'force_out', 'home_run', 'grounded_into_double_play', 'fielders_choice', 'field_error', 'triple', 'sac_bunt', 'double_play', 'fielders_choice_out', 'strikeout_double_play', 'sac_fly_double_play', 'other_out']
pitch_cat = {'FA': 'Fastball',
'FF': 'Fastball',
'FT': 'Fastball',
'FC': 'Fastball',
'FS': 'Off-Speed',
'FO': 'Off-Speed',
'SI': 'Fastball',
'ST': 'Breaking',
'SL': 'Breaking',
'CU': 'Breaking',
'KC': 'Breaking',
'SC': 'Off-Speed',
'GY': 'Off-Speed',
'SV': 'Breaking',
'CS': 'Breaking',
'CH': 'Off-Speed',
'KN': 'Off-Speed',
'EP': 'Breaking',
'UN': None,
'IN': None,
'PO': None,
'AB': None,
'AS': None,
'NP': None}
df = df.with_columns([
pl.when(df['type_ab'].is_not_null()).then(1).otherwise(0).alias('pa'),
pl.when(df['is_pitch']).then(1).otherwise(0).alias('pitches'),
pl.when(df['sz_top'] == 0).then(None).otherwise(df['sz_top']).alias('sz_top'),
pl.when(df['sz_bot'] == 0).then(None).otherwise(df['sz_bot']).alias('sz_bot'),
pl.when(df['zone'] > 0).then(df['zone'] < 10).otherwise(None).alias('in_zone'),
pl.Series(px_model.predict(df[['x']].fill_null(0).to_numpy())[:, 0]).alias('px_predict'),
pl.Series(pz_model.predict(df[['y']].fill_null(0).to_numpy())[:, 0] + 3.2).alias('pz_predict'),
pl.Series(in_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('in_zone_predict'),
pl.Series(attack_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('attack_zone_predict'),
pl.when(df['event_type'].is_in(hit_codes)).then(True).otherwise(False).alias('hits'),
pl.when(df['event_type'].is_in(ab_codes)).then(True).otherwise(False).alias('ab'),
pl.when(df['event_type'].is_in(obp_true_codes)).then(True).otherwise(False).alias('on_base'),
pl.when(df['event_type'].is_in(obp_codes)).then(True).otherwise(False).alias('obp'),
pl.when(df['play_description'].is_in(bip_codes)).then(True).otherwise(False).alias('bip'),
pl.when(conditions_barrel[0]).then(choices_barrel[0]).when(conditions_barrel[1]).then(choices_barrel[1]).otherwise(None).alias('barrel'),
pl.when(df['launch_angle'].is_null()).then(False).when((df['launch_angle'] >= 8) & (df['launch_angle'] <= 32)).then(True).otherwise(None).alias('sweet_spot'),
pl.when(df['launch_speed'].is_null()).then(False).when(df['launch_speed'] >= 94.5).then(True).otherwise(None).alias('hard_hit'),
pl.when(conditions_tb[0]).then(choices_tb[0]).when(conditions_tb[1]).then(choices_tb[1]).when(conditions_tb[2]).then(choices_tb[2]).when(conditions_tb[3]).then(choices_tb[3]).otherwise(None).alias('tb'),
pl.when(conditions_woba[0]).then(choices_woba[0]).when(conditions_woba[1]).then(choices_woba[1]).when(conditions_woba[2]).then(choices_woba[2]).when(conditions_woba[3]).then(choices_woba[3]).when(conditions_woba[4]).then(choices_woba[4]).when(conditions_woba[5]).then(choices_woba[5]).when(conditions_woba[6]).then(choices_woba[6]).otherwise(None).alias('woba'),
pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T')).then(1).otherwise(0).alias('whiffs'),
pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T') | (df['play_code'] == 'C')).then(1).otherwise(0).alias('csw'),
pl.when(pl.col('is_swing').cast(pl.Boolean)).then(1).otherwise(0).alias('swings'),
pl.col('event_type').is_in(['strikeout','strikeout_double_play']).alias('k'),
pl.col('event_type').is_in(['walk', 'intent_walk']).alias('bb'),
pl.lit(None).alias('attack_zone'),
pl.lit(None).alias('woba_pred'),
pl.lit(None).alias('woba_pred_contact')
])
df = df.with_columns([
pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('woba_codes'),
pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('xwoba_codes'),
pl.when((pl.col('tb') >= 0)).then(df['woba']).otherwise(None).alias('woba_contact'),
pl.when(pl.col('px').is_null()).then(pl.col('px_predict')).otherwise(pl.col('px')).alias('px'),
pl.when(pl.col('pz').is_null()).then(pl.col('pz_predict')).otherwise(pl.col('pz')).alias('pz'),
pl.when(pl.col('in_zone').is_null()).then(pl.col('in_zone_predict')).otherwise(pl.col('in_zone')).alias('in_zone'),
pl.when(df['launch_speed'].is_null()).then(None).otherwise(df['barrel']).alias('barrel'),
pl.lit('average').alias('average'),
pl.when(pl.col('in_zone') == False).then(True).otherwise(False).alias('out_zone'),
pl.when((pl.col('in_zone') == True) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('zone_swing'),
pl.when((pl.col('in_zone') == True) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('zone_contact'),
pl.when((pl.col('in_zone') == False) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('ozone_swing'),
pl.when((pl.col('in_zone') == False) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('ozone_contact'),
pl.when(pl.col('event_type').str.contains('strikeout')).then(True).otherwise(False).alias('k'),
pl.when(pl.col('event_type').is_in(['walk', 'intent_walk'])).then(True).otherwise(False).alias('bb'),
pl.when(pl.col('attack_zone').is_null()).then(pl.col('attack_zone_predict')).otherwise(pl.col('attack_zone')).alias('attack_zone'),
])
df = df.with_columns([
(df['k'].cast(pl.Float32) - df['bb'].cast(pl.Float32)).alias('k_minus_bb'),
(df['bb'].cast(pl.Float32) - df['k'].cast(pl.Float32)).alias('bb_minus_k'),
(df['launch_speed'] > 0).alias('bip_div'),
(df['attack_zone'] == 0).alias('heart'),
(df['attack_zone'] == 1).alias('shadow'),
(df['attack_zone'] == 2).alias('chase'),
(df['attack_zone'] == 3).alias('waste'),
((df['attack_zone'] == 0) & (df['swings'] == 1)).alias('heart_swing'),
((df['attack_zone'] == 1) & (df['swings'] == 1)).alias('shadow_swing'),
((df['attack_zone'] == 2) & (df['swings'] == 1)).alias('chase_swing'),
((df['attack_zone'] == 3) & (df['swings'] == 1)).alias('waste_swing'),
((df['attack_zone'] == 0) & (df['whiffs'] == 1)).alias('heart_whiff'),
((df['attack_zone'] == 1) & (df['whiffs'] == 1)).alias('shadow_whiff'),
((df['attack_zone'] == 2) & (df['whiffs'] == 1)).alias('chase_whiff'),
((df['attack_zone'] == 3) & (df['whiffs'] == 1)).alias('waste_whiff')
])
[0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]
df = df.with_columns([
pl.Series(
[sum(x) for x in xwoba_model.predict_proba(df[['launch_angle', 'launch_speed']].fill_null(0).to_numpy()[:]) * ([0, 0.881, 1.254, 1.589, 2.048])]
).alias('woba_pred_predict')
])
df = df.with_columns([
pl.when(pl.col('event_type').is_in(['walk'])).then(0.689)
.when(pl.col('event_type').is_in(['hit_by_pitch'])).then(0.720)
.when(pl.col('event_type').is_in(['strikeout', 'strikeout_double_play'])).then(0)
.otherwise(pl.col('woba_pred_predict')).alias('woba_pred_predict')
])
df = df.with_columns([
pl.when(pl.col('woba_codes').is_null()).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred'),
pl.when(pl.col('bip')!=1).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred_contact'),
])
df = df.with_columns([
pl.when(pl.col('trajectory').is_in(['bunt_popup'])).then(pl.lit('popup'))
.when(pl.col('trajectory').is_in(['bunt_grounder'])).then(pl.lit('ground_ball'))
.when(pl.col('trajectory').is_in(['bunt_line_drive'])).then(pl.lit('line_drive'))
.when(pl.col('trajectory').is_in([''])).then(pl.lit(None))
.otherwise(pl.col('trajectory')).alias('trajectory')
])
# Create one-hot encoded columns for the trajectory column
dummy_df = df.select(pl.col('trajectory')).to_dummies()
# Rename the one-hot encoded columns
dummy_df = dummy_df.rename({
'trajectory_fly_ball': 'trajectory_fly_ball',
'trajectory_ground_ball': 'trajectory_ground_ball',
'trajectory_line_drive': 'trajectory_line_drive',
'trajectory_popup': 'trajectory_popup'
})
# Ensure the columns are present in the DataFrame
for col in ['trajectory_fly_ball', 'trajectory_ground_ball', 'trajectory_line_drive', 'trajectory_popup']:
if col not in dummy_df.columns:
dummy_df = dummy_df.with_columns(pl.lit(0).alias(col))
# Join the one-hot encoded columns back to the original DataFrame
df = df.hstack(dummy_df)
# Check if 'trajectory_null' column exists and drop it
if 'trajectory_null' in df.columns:
df = df.drop('trajectory_null')
return df
# Assuming df is your Polars DataFrame
def update_summary(self, df: pl.DataFrame, pitcher: bool = True) -> pl.DataFrame:
"""
Update summary statistics for pitchers or batters.
Parameters:
df (pl.DataFrame): The input Polars DataFrame containing player statistics.
pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).
Returns:
pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics.
"""
# Determine the position based on the pitcher flag
if pitcher:
position = 'pitcher'
else:
position = 'batter'
# Group by position_id and position_name, then aggregate various statistics
df_summ = df.group_by([f'{position}_id', f'{position}_name']).agg([
pl.col('pa').sum().alias('pa'),
pl.col('ab').sum().alias('ab'),
pl.col('obp').sum().alias('obp_pa'),
pl.col('hits').sum().alias('hits'),
pl.col('on_base').sum().alias('on_base'),
pl.col('k').sum().alias('k'),
pl.col('bb').sum().alias('bb'),
pl.col('bb_minus_k').sum().alias('bb_minus_k'),
pl.col('csw').sum().alias('csw'),
pl.col('bip').sum().alias('bip'),
pl.col('bip_div').sum().alias('bip_div'),
pl.col('tb').sum().alias('tb'),
pl.col('woba').sum().alias('woba'),
pl.col('woba_contact').sum().alias('woba_contact'),
pl.col('woba_pred').sum().alias('xwoba'),
pl.col('woba_pred_contact').sum().alias('xwoba_contact'),
pl.col('woba_codes').sum().alias('woba_codes'),
pl.col('xwoba_codes').sum().alias('xwoba_codes'),
pl.col('hard_hit').sum().alias('hard_hit'),
pl.col('barrel').sum().alias('barrel'),
pl.col('sweet_spot').sum().alias('sweet_spot'),
pl.col('launch_speed').max().alias('max_launch_speed'),
pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),
pl.col('launch_speed').mean().alias('launch_speed'),
pl.col('launch_angle').mean().alias('launch_angle'),
pl.col('is_pitch').sum().alias('pitches'),
pl.col('swings').sum().alias('swings'),
pl.col('in_zone').sum().alias('in_zone'),
pl.col('out_zone').sum().alias('out_zone'),
pl.col('whiffs').sum().alias('whiffs'),
pl.col('zone_swing').sum().alias('zone_swing'),
pl.col('zone_contact').sum().alias('zone_contact'),
pl.col('ozone_swing').sum().alias('ozone_swing'),
pl.col('ozone_contact').sum().alias('ozone_contact'),
pl.col('trajectory_ground_ball').sum().alias('ground_ball'),
pl.col('trajectory_line_drive').sum().alias('line_drive'),
pl.col('trajectory_fly_ball').sum().alias('fly_ball'),
pl.col('trajectory_popup').sum().alias('pop_up'),
pl.col('attack_zone').count().alias('attack_zone'),
pl.col('heart').sum().alias('heart'),
pl.col('shadow').sum().alias('shadow'),
pl.col('chase').sum().alias('chase'),
pl.col('waste').sum().alias('waste'),
pl.col('heart_swing').sum().alias('heart_swing'),
pl.col('shadow_swing').sum().alias('shadow_swing'),
pl.col('chase_swing').sum().alias('chase_swing'),
pl.col('waste_swing').sum().alias('waste_swing'),
pl.col('heart_whiff').sum().alias('heart_whiff'),
pl.col('shadow_whiff').sum().alias('shadow_whiff'),
pl.col('chase_whiff').sum().alias('chase_whiff'),
pl.col('waste_whiff').sum().alias('waste_whiff')
])
# Add calculated columns to the summary DataFrame
df_summ = df_summ.with_columns([
(pl.col('hits') / pl.col('ab')).alias('avg'),
(pl.col('on_base') / pl.col('obp_pa')).alias('obp'),
(pl.col('tb') / pl.col('ab')).alias('slg'),
(pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),
(pl.col('k') / pl.col('pa')).alias('k_percent'),
(pl.col('bb') / pl.col('pa')).alias('bb_percent'),
(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),
(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),
(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),
(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),
(pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),
(pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),
(pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),
(pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),
(pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),
(pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),
(pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),
(pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),
(pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),
(pl.col('swings') / pl.col('pitches')).alias('swing_percent'),
(pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),
(pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),
(pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),
(pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),
(pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),
(pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),
(pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),
(pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),
(pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),
(pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),
(pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),
(pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),
(pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),
(pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),
(pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),
(pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),
(pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),
(pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),
(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),
(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact')
])
return df_summ
# Assuming df is your Polars DataFrame
def update_summary_select(self, df: pl.DataFrame, selection: list) -> pl.DataFrame:
"""
Update summary statistics for pitchers or batters.
Parameters:
df (pl.DataFrame): The input Polars DataFrame containing player statistics.
pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).
Returns:
pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics.
"""
# Group by position_id and position_name, then aggregate various statistics
df_summ = df.group_by(selection).agg([
pl.col('pa').sum().alias('pa'),
pl.col('ab').sum().alias('ab'),
pl.col('obp').sum().alias('obp_pa'),
pl.col('hits').sum().alias('hits'),
pl.col('on_base').sum().alias('on_base'),
pl.col('k').sum().alias('k'),
pl.col('bb').sum().alias('bb'),
pl.col('bb_minus_k').sum().alias('bb_minus_k'),
pl.col('csw').sum().alias('csw'),
pl.col('bip').sum().alias('bip'),
pl.col('bip_div').sum().alias('bip_div'),
pl.col('tb').sum().alias('tb'),
pl.col('woba').sum().alias('woba'),
pl.col('woba_contact').sum().alias('woba_contact'),
pl.col('woba_pred').sum().alias('xwoba'),
pl.col('woba_pred_contact').sum().alias('xwoba_contact'),
pl.col('woba_codes').sum().alias('woba_codes'),
pl.col('xwoba_codes').sum().alias('xwoba_codes'),
pl.col('hard_hit').sum().alias('hard_hit'),
pl.col('barrel').sum().alias('barrel'),
pl.col('sweet_spot').sum().alias('sweet_spot'),
pl.col('launch_speed').max().alias('max_launch_speed'),
pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),
pl.col('launch_speed').mean().alias('launch_speed'),
pl.col('launch_angle').mean().alias('launch_angle'),
pl.col('is_pitch').sum().alias('pitches'),
pl.col('swings').sum().alias('swings'),
pl.col('in_zone').sum().alias('in_zone'),
pl.col('out_zone').sum().alias('out_zone'),
pl.col('whiffs').sum().alias('whiffs'),
pl.col('zone_swing').sum().alias('zone_swing'),
pl.col('zone_contact').sum().alias('zone_contact'),
pl.col('ozone_swing').sum().alias('ozone_swing'),
pl.col('ozone_contact').sum().alias('ozone_contact'),
pl.col('trajectory_ground_ball').sum().alias('ground_ball'),
pl.col('trajectory_line_drive').sum().alias('line_drive'),
pl.col('trajectory_fly_ball').sum().alias('fly_ball'),
pl.col('trajectory_popup').sum().alias('pop_up'),
pl.col('attack_zone').count().alias('attack_zone'),
pl.col('heart').sum().alias('heart'),
pl.col('shadow').sum().alias('shadow'),
pl.col('chase').sum().alias('chase'),
pl.col('waste').sum().alias('waste'),
pl.col('heart_swing').sum().alias('heart_swing'),
pl.col('shadow_swing').sum().alias('shadow_swing'),
pl.col('chase_swing').sum().alias('chase_swing'),
pl.col('waste_swing').sum().alias('waste_swing'),
pl.col('heart_whiff').sum().alias('heart_whiff'),
pl.col('shadow_whiff').sum().alias('shadow_whiff'),
pl.col('chase_whiff').sum().alias('chase_whiff'),
pl.col('waste_whiff').sum().alias('waste_whiff')
])
# Add calculated columns to the summary DataFrame
df_summ = df_summ.with_columns([
(pl.col('hits') / pl.col('ab')).alias('avg'),
(pl.col('on_base') / pl.col('obp_pa')).alias('obp'),
(pl.col('tb') / pl.col('ab')).alias('slg'),
(pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),
(pl.col('k') / pl.col('pa')).alias('k_percent'),
(pl.col('bb') / pl.col('pa')).alias('bb_percent'),
(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),
(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),
(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),
(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),
(pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),
(pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),
(pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),
(pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),
(pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),
(pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),
(pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),
(pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),
(pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),
(pl.col('swings') / pl.col('pitches')).alias('swing_percent'),
(pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),
(pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),
(pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),
(pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),
(pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),
(pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),
(pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),
(pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),
(pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),
(pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),
(pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),
(pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),
(pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),
(pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),
(pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),
(pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),
(pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),
(pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),
(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),
(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact')
])
return df_summ123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029import pandas as pdimport numpy as npimport jsonfrom matplotlib.ticker import FuncFormatterfrom matplotlib.ticker import MaxNLocatorimport mathfrom matplotlib.patches import Ellipseimport matplotlib.transforms as transformsimport matplotlib.colorsimport matplotlib.colors as mcolorsimport seaborn as snsimport matplotlib.pyplot as pltimport requestsimport polars as plfrom PIL import Imageimport requestsfrom io import BytesIOfrom matplotlib.offsetbox import OffsetImage, AnnotationBboximport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport PIL
### PITCH COLOURS ###
# Dictionary to map pitch types to their corresponding colors and namespitch_colours = { ## Fastballs ## 'FF': {'colour': '#FF007D', 'name': '4-Seam Fastball'}, 'FA': {'colour': '#FF007D', 'name': 'Fastball'}, 'SI': {'colour': '#98165D', 'name': 'Sinker'}, 'FC': {'colour': '#BE5FA0', 'name': 'Cutter'},
## Offspeed ## 'CH': {'colour': '#F79E70', 'name': 'Changeup'}, 'FS': {'colour': '#FE6100', 'name': 'Splitter'}, 'SC': {'colour': '#F08223', 'name': 'Screwball'}, 'FO': {'colour': '#FFB000', 'name': 'Forkball'},
## Sliders ## 'SL': {'colour': '#67E18D', 'name': 'Slider'}, 'ST': {'colour': '#1BB999', 'name': 'Sweeper'}, 'SV': {'colour': '#376748', 'name': 'Slurve'},
## Curveballs ## 'KC': {'colour': '#311D8B', 'name': 'Knuckle Curve'}, 'CU': {'colour': '#3025CE', 'name': 'Curveball'}, 'CS': {'colour': '#274BFC', 'name': 'Slow Curve'}, 'EP': {'colour': '#648FFF', 'name': 'Eephus'},
## Others ## 'KN': {'colour': '#867A08', 'name': 'Knuckleball'}, 'PO': {'colour': '#472C30', 'name': 'Pitch Out'}, 'UN': {'colour': '#9C8975', 'name': 'Unknown'},}
# Create dictionaries for pitch types and their attributesdict_colour = {key: value['colour'] for key, value in pitch_colours.items()}dict_pitch = {key: value['name'] for key, value in pitch_colours.items()}dict_pitch_desc_type = {value['name']: key for key, value in pitch_colours.items()}dict_pitch_desc_type.update({'Four-Seam Fastball':'FF'})dict_pitch_desc_type.update({'All':'All'})dict_pitch_name = {value['name']: value['colour'] for key, value in pitch_colours.items()}dict_pitch_name.update({'Four-Seam Fastball':'#FF007D'})
font_properties = {'family': 'calibi', 'size': 12}font_properties_titles = {'family': 'calibi', 'size': 20}font_properties_axes = {'family': 'calibi', 'size': 16} cmap_sum = matplotlib.colors.LinearSegmentedColormap.from_list("", ['#648FFF','#FFFFFF','#FFB000',])
### FANGRAPHS STATS DICT ###fangraphs_stats_dict = {'IP':{'table_header':'$\\bf{IP}$','format':'.1f',} , 'TBF':{'table_header':'$\\bf{PA}$','format':'.0f',} , 'AVG':{'table_header':'$\\bf{AVG}$','format':'.3f',} , 'K/9':{'table_header':'$\\bf{K\/9}$','format':'.2f',} , 'BB/9':{'table_header':'$\\bf{BB\/9}$','format':'.2f',} , 'K/BB':{'table_header':'$\\bf{K\/BB}$','format':'.2f',} , 'HR/9':{'table_header':'$\\bf{HR\/9}$','format':'.2f',} , 'K%':{'table_header':'$\\bf{K\%}$','format':'.1%',} , 'BB%':{'table_header':'$\\bf{BB\%}$','format':'.1%',} , 'K-BB%':{'table_header':'$\\bf{K-BB\%}$','format':'.1%',} , 'WHIP':{'table_header':'$\\bf{WHIP}$','format':'.2f',} , 'BABIP':{'table_header':'$\\bf{BABIP}$','format':'.3f',} , 'LOB%':{'table_header':'$\\bf{LOB\%}$','format':'.1%',} , 'xFIP':{'table_header':'$\\bf{xFIP}$','format':'.2f',} , 'FIP':{'table_header':'$\\bf{FIP}$','format':'.2f',} , 'H':{'table_header':'$\\bf{H}$','format':'.0f',} , '2B':{'table_header':'$\\bf{2B}$','format':'.0f',} , '3B':{'table_header':'$\\bf{3B}$','format':'.0f',} , 'R':{'table_header':'$\\bf{R}$','format':'.0f',} , 'ER':{'table_header':'$\\bf{ER}$','format':'.0f',} , 'HR':{'table_header':'$\\bf{HR}$','format':'.0f',} , 'BB':{'table_header':'$\\bf{BB}$','format':'.0f',} , 'IBB':{'table_header':'$\\bf{IBB}$','format':'.0f',} , 'HBP':{'table_header':'$\\bf{HBP}$','format':'.0f',} , 'SO':{'table_header':'$\\bf{SO}$','format':'.0f',} , 'OBP':{'table_header':'$\\bf{OBP}$','format':'.0f',} , 'SLG':{'table_header':'$\\bf{SLG}$','format':'.0f',} , 'ERA':{'table_header':'$\\bf{ERA}$','format':'.2f',} , 'wOBA':{'table_header':'$\\bf{wOBA}$','format':'.3f',} , 'G':{'table_header':'$\\bf{G}$','format':'.0f',}, 'strikePercentage':{'table_header':'$\\bf{Strike\%}$','format':'.1%'} }
colour_palette = ['#FFB000','#648FFF','#785EF0', '#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']
### GET COLOURS ###def get_color(value, normalize, cmap_sum): """ Get the color corresponding to a value based on a colormap and normalization.
Parameters ---------- value : float The value to be mapped to a color. normalize : matplotlib.colors.Normalize The normalization function to scale the value. cmap_sum : matplotlib.colors.Colormap The colormap to use for mapping the value to a color.
Returns ------- str The hexadecimal color code corresponding to the value. """ color = cmap_sum(normalize(value)) return mcolors.to_hex(color)
### PITCH ELLIPSE ###def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs): """ Create a plot of the covariance confidence ellipse of *x* and *y*.
Parameters ---------- x, y : array-like, shape (n, ) Input data.
ax : matplotlib.axes.Axes The axes object to draw the ellipse into.
n_std : float The number of standard deviations to determine the ellipse's radiuses.
**kwargs Forwarded to `~matplotlib.patches.Ellipse`
Returns ------- matplotlib.patches.Ellipse """ if len(x) != len(y): raise ValueError("x and y must be the same size") try: cov = np.cov(x, y) pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1]) # Using a special case to obtain the eigenvalues of this # two-dimensional dataset. ell_radius_x = np.sqrt(1 + pearson) ell_radius_y = np.sqrt(1 - pearson) ellipse = Ellipse((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2, facecolor=facecolor,linewidth=2,linestyle='--', **kwargs)
# Calculating the standard deviation of x from # the squareroot of the variance and multiplying # with the given number of standard deviations. scale_x = np.sqrt(cov[0, 0]) * n_std mean_x = x.mean()
# calculating the standard deviation of y ... scale_y = np.sqrt(cov[1, 1]) * n_std mean_y = y.mean()
transf = transforms.Affine2D() \ .rotate_deg(45) \ .scale(scale_x, scale_y) \ .translate(mean_x, mean_y)
ellipse.set_transform(transf + ax.transData) except ValueError: return return ax.add_patch(ellipse) ### VELOCITY KDES ###def velocity_kdes(df: pl.DataFrame, ax: plt.Axes, gs: gridspec.GridSpec, gs_x: list, gs_y: list, fig: plt.Figure): """ Plot the velocity KDEs for different pitch types.
Parameters ---------- df : pl.DataFrame The DataFrame containing pitch data. ax : plt.Axes The axis to plot on. gs : GridSpec The GridSpec for the subplot layout. gs_x : list The x-coordinates for the GridSpec. gs_y : list The y-coordinates for the GridSpec. fig : plt.Figure The figure to plot on. """ # Join the original DataFrame on 'pitch_type' with sorted counts to reorder items_in_order = (df .sort("pitch_count", descending=True)['pitch_type'] .unique(maintain_order=True) .to_numpy() )
# Create the inner subplot inside the outer subplot import matplotlib.gridspec as gridspec ax.axis('off') ax.set_title('Pitch Velocity Distribution', fontdict={'family': 'calibi', 'size': 20})
inner_grid_1 = gridspec.GridSpecFromSubplotSpec(len(items_in_order), 1, subplot_spec=gs[gs_x[0]:gs_x[-1], gs_y[0]:gs_y[-1]]) ax_top = [fig.add_subplot(inner) for inner in inner_grid_1]
for idx, i in enumerate(items_in_order): pitch_data = df.filter(pl.col('pitch_type') == i)['start_speed'] if np.unique(pitch_data).size == 1: # Check if all values are the same ax_top[idx].plot([np.unique(pitch_data), np.unique(pitch_data)], [0, 1], linewidth=4, color=dict_colour[i], zorder=20) else: sns.kdeplot(pitch_data, ax=ax_top[idx], fill=True, clip=(pitch_data.min(), pitch_data.max()), color=dict_colour[i])
# Plot the mean release speed for the current data df_average = df.filter(df['pitch_type'] == i)['start_speed'] ax_top[idx].plot([df_average.mean(), df_average.mean()], [ax_top[idx].get_ylim()[0], ax_top[idx].get_ylim()[1]], color=dict_colour[i], linestyle='--') df_statcast_group = pl.read_csv('functions/statcast_2024_grouped.csv')
# Plot the mean release speed for the statcast group data df_average = df_statcast_group.filter(df_statcast_group['pitch_type'] == i)['release_speed'] ax_top[idx].plot([df_average.mean(), df_average.mean()], [ax_top[idx].get_ylim()[0], ax_top[idx].get_ylim()[1]], color=dict_colour[i], linestyle=':')
ax_top[idx].set_xlim(math.floor(df['start_speed'].min() / 5) * 5, math.ceil(df['start_speed'].max() / 5) * 5) ax_top[idx].set_xlabel('') ax_top[idx].set_ylabel('') if idx < len(items_in_order) - 1: ax_top[idx].spines['top'].set_visible(False) ax_top[idx].spines['right'].set_visible(False) ax_top[idx].spines['left'].set_visible(False) ax_top[idx].tick_params(axis='x', colors='none')
ax_top[idx].set_xticks(range(math.floor(df['start_speed'].min() / 5) * 5, math.ceil(df['start_speed'].max() / 5) * 5, 5)) ax_top[idx].set_yticks([]) ax_top[idx].grid(axis='x', linestyle='--') ax_top[idx].text(-0.01, 0.5, i, transform=ax_top[idx].transAxes, fontsize=14, va='center', ha='right')
ax_top[-1].spines['top'].set_visible(False) ax_top[-1].spines['right'].set_visible(False) ax_top[-1].spines['left'].set_visible(False) ax_top[-1].set_xticks(list(range(math.floor(df['start_speed'].min() / 5) * 5, math.ceil(df['start_speed'].max() / 5) * 5, 5))) ax_top[-1].set_xlabel('Velocity (mph)')
### TJ STUFF+ ROLLING ###def tj_stuff_roling(df: pl.DataFrame, window: int, ax: plt.Axes): """ Plot the rolling average of tjStuff+ for different pitch types.
Parameters ---------- df : pl.DataFrame The DataFrame containing pitch data. window : int The window size for calculating the rolling average. ax : plt.Axes The axis to plot on. """ # Join the original DataFrame on 'pitch_type' with sorted counts to reorder items_in_order = ( df.sort("pitch_count", descending=True)['pitch_type'] .unique(maintain_order=True) .to_numpy() ) # Plot the rolling average for each pitch type for i in items_in_order: if max(df.filter(pl.col('pitch_type') == i)['pitch_count']) >= window: print('LENGTH', len(range(1, max(df.filter(pl.col('pitch_type') == i)['pitch_count']) + 1)), len(df.filter(pl.col('pitch_type') == i)['tj_stuff_plus'].rolling_mean(window))) sns.lineplot( x=range(1, max(df.filter(pl.col('pitch_type') == i)['pitch_count']) + 1), y=df.filter(pl.col('pitch_type') == i)['tj_stuff_plus'].rolling_mean(window), color=dict_colour[i], ax=ax, linewidth=3 )
# Adjust x-axis limits to start from 1 ax.set_xlim(window, max(df['pitch_count'])) ax.set_ylim(70, 130) ax.set_xlabel('Pitches', fontdict=font_properties_axes) ax.set_ylabel('tjStuff+', fontdict=font_properties_axes) ax.set_title(f"{window} Pitch Rolling tjStuff+", fontdict=font_properties_titles) ax.xaxis.set_major_locator(MaxNLocator(integer=True))
### TJ STUFF+ ROLLING ###def tj_stuff_roling_game(df: pl.DataFrame, window: int, ax: plt.Axes): """ Plot the rolling average of tjStuff+ for different pitch types over games.
Parameters ---------- df : pl.DataFrame The DataFrame containing pitch data. window : int The window size for calculating the rolling average. ax : plt.Axes The axis to plot on. """ # Map game_id to sequential numbers date_to_number = {date: i + 1 for i, date in enumerate(df['game_id'].unique(maintain_order=True))}
# Add a column with the sequential game numbers df_plot = df.with_columns( pl.col("game_id").map_elements(lambda x: date_to_number.get(x, x)).alias("start_number") )
# Group by relevant columns and calculate mean tj_stuff_plus plot_game_roll = df_plot.group_by(['start_number', 'game_id', 'game_date', 'pitch_type', 'pitch_description']).agg( pl.col('tj_stuff_plus').mean().alias('tj_stuff_plus') ).sort('start_number', descending=False)
# Get the list of pitch types ordered by frequency sorted_value_counts = df['pitch_type'].value_counts().sort('count', descending=True) items_in_order = sorted_value_counts['pitch_type'].to_list()
# Plot the rolling average for each pitch type for i in items_in_order: df_item = plot_game_roll.filter(pl.col('pitch_type') == i) df_item = df_item.with_columns( pl.col("start_number").cast(pl.Int64) ).join( pl.DataFrame({"start_number": list(date_to_number.values())}), on="start_number", how="outer" ).sort("start_number_right").with_columns([ pl.col("start_number").fill_null(strategy="forward").fill_null(strategy="backward"), pl.col("tj_stuff_plus").fill_null(strategy="forward").fill_null(strategy="backward"), pl.col("pitch_type").fill_null(strategy="forward").fill_null(strategy="backward"), pl.col("pitch_description").fill_null(strategy="forward").fill_null(strategy="backward") ])
sns.lineplot(x=range(1, max(df_item['start_number_right']) + 1), y=df_item.filter(pl.col('pitch_type') == i)['tj_stuff_plus'].rolling_mean(window), color=dict_colour[i], ax=ax, linewidth=3)
# Highlight missing game data points for n in range(len(df_item)): if df_item['game_id'].is_null()[n]: sns.scatterplot(x=[df_item['start_number_right'][n]], y=[df_item['tj_stuff_plus'][n]], color='white', ec='black', ax=ax, zorder=100)
# Adjust x-axis limits to start from 1 ax.set_xlim(window, max(df_item['start_number'])) ax.set_ylim(70, 130) ax.set_xlabel('Games', fontdict=font_properties_axes) ax.set_ylabel('tjStuff+', fontdict=font_properties_axes) ax.set_title(f"{window} Game Rolling tjStuff+", fontdict=font_properties_titles) ax.xaxis.set_major_locator(MaxNLocator(integer=True))
def break_plot(df: pl.DataFrame, ax: plt.Axes): """ Plot the pitch breaks for different pitch types.
Parameters ---------- df : pl.DataFrame The DataFrame containing pitch data. ax : plt.Axes The axis to plot on. """ # Get unique pitch types sorted by pitch count label_labels = df.sort(by=['pitch_count', 'pitch_type'], descending=[False, True])['pitch_type'].unique(maintain_order=True).to_numpy()
# Plot confidence ellipses for each pitch type for idx, label in enumerate(label_labels): subset = df.filter(pl.col('pitch_type') == label) if len(subset) > 4: try: confidence_ellipse(subset['hb'], subset['ivb'], ax=ax, edgecolor=dict_colour[label], n_std=2, facecolor=dict_colour[label], alpha=0.2) except ValueError: return
# Plot scatter plot for pitch breaks if df['pitcher_hand'][0] == 'R': sns.scatterplot(ax=ax, x=df['hb'], y=df['ivb'] * 1, hue=df['pitch_type'], palette=dict_colour, ec='black', alpha=1, zorder=2) if df['pitcher_hand'][0] == 'L': sns.scatterplot(ax=ax, x=df['hb'], y=df['ivb'] * 1, hue=df['pitch_type'], palette=dict_colour, ec='black', alpha=1, zorder=2)
# Set axis limits ax.set_xlim((-25, 25)) ax.set_ylim((-25, 25))
# Add horizontal and vertical lines ax.hlines(y=0, xmin=-50, xmax=50, color=colour_palette[8], alpha=0.5, linestyles='--', zorder=1) ax.vlines(x=0, ymin=-50, ymax=50, color=colour_palette[8], alpha=0.5, linestyles='--', zorder=1)
# Set axis labels and title ax.set_xlabel('Horizontal Break (in)', fontdict=font_properties_axes) ax.set_ylabel('Induced Vertical Break (in)', fontdict=font_properties_axes) ax.set_title("Pitch Breaks", fontdict=font_properties_titles)
# Remove legend ax.get_legend().remove()
# Set tick labels ax.set_xticklabels(ax.get_xticks(), fontdict=font_properties) ax.set_yticklabels(ax.get_yticks(), fontdict=font_properties)
# Add text annotations for glove side and arm side if df['pitcher_hand'][0] == 'R': ax.text(-24.5, -24.5, s='← Glove Side', fontstyle='italic', ha='left', va='bottom', bbox=dict(facecolor='white', edgecolor='black'), fontsize=12, zorder=3) ax.text(24.5, -24.5, s='Arm Side →', fontstyle='italic', ha='right', va='bottom', bbox=dict(facecolor='white', edgecolor='black'), fontsize=12, zorder=3) if df['pitcher_hand'][0] == 'L': ax.invert_xaxis() ax.text(24.5, -24.5, s='← Arm Side', fontstyle='italic', ha='left', va='bottom', bbox=dict(facecolor='white', edgecolor='black'), fontsize=12, zorder=3) ax.text(-24.5, -24.5, s='Glove Side →', fontstyle='italic', ha='right', va='bottom', bbox=dict(facecolor='white', edgecolor='black'), fontsize=12, zorder=3)
# Set aspect ratio and format axis ticks ax.set_aspect('equal', adjustable='box') ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x))) ax.yaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))
# DEFINE STRIKE ZONEstrike_zone = pl.DataFrame({ 'PlateLocSide': [-0.9, -0.9, 0.9, 0.9, -0.9], 'PlateLocHeight': [1.5, 3.5, 3.5, 1.5, 1.5]})
### STRIKE ZONE ###def draw_line(axis, alpha_spot=1, catcher_p=True): """ Draw the strike zone and home plate on the given axis.
Parameters ---------- axis : matplotlib.axes.Axes The axis to draw the strike zone on. alpha_spot : float, optional The transparency level of the lines (default is 1). catcher_p : bool, optional Whether to draw the catcher's perspective (default is True). """ # Draw the strike zone axis.plot(strike_zone['PlateLocSide'].to_list(), strike_zone['PlateLocHeight'].to_list(), color='black', linewidth=1.3, zorder=3, alpha=alpha_spot)
if catcher_p: # Draw home plate from catcher's perspective axis.plot([-0.708, 0.708], [0.15, 0.15], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([-0.708, -0.708], [0.15, 0.3], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([-0.708, 0], [0.3, 0.5], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([0, 0.708], [0.5, 0.3], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([0.708, 0.708], [0.3, 0.15], color='black', linewidth=1, alpha=alpha_spot, zorder=1) else: # Draw home plate from pitcher's perspective axis.plot([-0.708, 0.708], [0.4, 0.4], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([-0.708, -0.9], [0.4, -0.1], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([-0.9, 0], [-0.1, -0.35], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([0, 0.9], [-0.35, -0.1], color='black', linewidth=1, alpha=alpha_spot, zorder=1) axis.plot([0.9, 0.708], [-0.1, 0.4], color='black', linewidth=1, alpha=alpha_spot, zorder=1)
def location_plot(df: pl.DataFrame, ax: plt.Axes, hand: str): """ Plot the pitch locations for different pitch types against a specific batter hand.
Parameters ---------- df : pl.DataFrame The DataFrame containing pitch data. ax : plt.Axes The axis to plot on. hand : str The batter hand ('L' for left-handed, 'R' for right-handed). """ # Get unique pitch types sorted by pitch count label_labels = df.sort(by=['pitch_count', 'pitch_type'], descending=[False, True])['pitch_type'].unique(maintain_order=True).to_numpy()
# Plot confidence ellipses for each pitch type for label in label_labels: subset = df.filter((pl.col('pitch_type') == label) & (pl.col('batter_hand') == hand)) if len(subset) >= 5: confidence_ellipse(subset['px'], subset['pz'], ax=ax, edgecolor=dict_colour[label], n_std=1.5, facecolor=dict_colour[label], alpha=0.3)
# Group pitch locations by pitch type and calculate mean values pitch_location_group = ( df.filter(pl.col("batter_hand") == hand) .group_by("pitch_type") .agg([ pl.col("start_speed").count().alias("pitches"), pl.col("px").mean().alias("px"), pl.col("pz").mean().alias("pz") ]) )
# Calculate pitch percentages total_pitches = pitch_location_group['pitches'].sum() pitch_location_group = pitch_location_group.with_columns( (pl.col("pitches") / total_pitches).alias("pitch_percent") )
# Plot pitch locations sns.scatterplot(ax=ax, x=pitch_location_group['px'], y=pitch_location_group['pz'], hue=pitch_location_group['pitch_type'], palette=dict_colour, ec='black', s=pitch_location_group['pitch_percent'] * 750, linewidth=2, zorder=2)
# Customize plot appearance ax.axis('square') draw_line(ax, alpha_spot=0.75, catcher_p=False) ax.axis('off') ax.set_xlim((-2.75, 2.75)) ax.set_ylim((-0.5, 5)) if len(pitch_location_group['px']) > 0: ax.get_legend().remove() ax.grid(False) ax.set_title(f"Pitch Locations vs {hand}HB\n{pitch_location_group['pitches'].sum()} Pitches", fontdict=font_properties_titles)
def summary_table(df: pl.DataFrame, ax: plt.Axes): """ Create a summary table of pitch data.
Parameters ---------- df : pl.DataFrame The DataFrame containing pitch data. ax : plt.Axes The axis to plot the table on. """ # Aggregate pitch data by pitch description df_agg = df.group_by("pitch_description").agg( pl.col('is_pitch').sum().alias('count'), (pl.col('is_pitch').sum() / df.select(pl.col('is_pitch').sum())).alias('count_percent'), pl.col('start_speed').mean().alias('start_speed'), pl.col('ivb').mean().alias('ivb'), pl.col('hb').mean().alias('hb'), pl.col('spin_rate').mean().alias('spin_rate'), pl.col('vaa').mean().alias('vaa'), pl.col('haa').mean().alias('haa'), pl.col('z0').mean().alias('z0'), pl.col('x0').mean().alias('x0'), pl.col('extension').mean().alias('extension'), (((pl.col('spin_direction').mean() + 180) % 360 // 30) + (((pl.col('spin_direction').mean() + 180) % 360 % 30 / 30 / 100 * 60).round(2) * 10).round(0) // 1.5 / 4) .cast(pl.Float64).map_elements(lambda x: f"{int(x)}:{int((x % 1) * 60):02d}", return_dtype=pl.Utf8).alias('clock_time'), pl.col('tj_stuff_plus').mean().alias('tj_stuff_plus'), pl.col('pitch_grade').mean().alias('pitch_grade'), (pl.col('in_zone').sum() / pl.col('is_pitch').sum()).alias('zone_percent'), (pl.col('ozone_swing').sum() / pl.col('out_zone').sum()).alias('chase_percent'), (pl.col('whiffs').sum() / pl.col('swings').sum()).alias('whiff_percent'), (pl.col('woba_pred_contact').sum() / pl.col('bip').sum()).alias('xwobacon') ).sort("count", descending=True)
# Aggregate all pitch data df_agg_all = df.group_by(pl.lit("All").alias("pitch_description")).agg( pl.col('is_pitch').sum().alias('count'), (pl.col('is_pitch').sum() / df.select(pl.col('is_pitch').sum())).alias('count_percent'), pl.lit(None).alias('start_speed'), pl.lit(None).alias('ivb'), pl.lit(None).alias('hb'), pl.lit(None).alias('spin_rate'), pl.lit(None).alias('vaa'), pl.lit(None).alias('haa'), pl.lit(None).alias('z0'), pl.lit(None).alias('x0'), pl.col('extension').mean().alias('extension'), pl.lit(None).alias('clock_time'), pl.col('tj_stuff_plus').mean().alias('tj_stuff_plus'), pl.lit(None).alias('pitch_grade'), (pl.col('in_zone').sum() / pl.col('is_pitch').sum()).alias('zone_percent'), (pl.col('ozone_swing').sum() / pl.col('out_zone').sum()).alias('chase_percent'), (pl.col('whiffs').sum() / pl.col('swings').sum()).alias('whiff_percent'), (pl.col('woba_pred_contact').sum() / pl.col('bip').sum()).alias('xwobacon') )
# Concatenate aggregated data df_agg = pl.concat([df_agg, df_agg_all]).fill_nan(None)
# Load statcast pitch summary data statcast_pitch_summary = pl.read_csv('functions/statcast_2024_grouped.csv')
# Create table table = ax.table(cellText=df_agg.fill_nan('—').fill_null('—').to_numpy(), colLabels=df_agg.columns, cellLoc='center', colWidths=[2.3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], bbox=[0.0, 0, 1, 0.8])
# Set table properties min_font_size = 14 table.auto_set_font_size(False) table.set_fontsize(min_font_size) table.scale(1, 0.5)
# Set font size for values min_font_size = 18 for i in range(len(df_agg) + 1): for j in range(len(df_agg.columns)): if i > 0: # Skip the header row cell = table.get_celld()[i, j] cell.set_fontsize(min_font_size)
# Define color maps cmap_sum = mcolors.LinearSegmentedColormap.from_list("", ['#648FFF', '#FFFFFF', '#FFB000']) cmap_sum_r = mcolors.LinearSegmentedColormap.from_list("", ['#FFB000', '#FFFFFF', '#648FFF'])
# Update table cells with colors and text properties for i in range(len(df_agg)): pitch_check = dict_pitch_desc_type[df_agg['pitch_description'][i]] cell_text = table.get_celld()[(i + 1, 0)].get_text().get_text()
if cell_text != 'All': table.get_celld()[(i + 1, 0)].set_facecolor(dict_pitch_name[cell_text]) text_props = {'color': '#000000', 'fontweight': 'bold'} if cell_text in ['Split-Finger', 'Slider', 'Changeup'] else {'color': '#ffffff', 'fontweight': 'bold'} table.get_celld()[(i + 1, 0)].set_text_props(**text_props) if cell_text == 'Four-Seam Fastball': table.get_celld()[(i + 1, 0)].get_text().set_text('4-Seam')
select_df = statcast_pitch_summary.filter(statcast_pitch_summary['pitch_type'] == pitch_check)
# Apply color to specific columns based on normalized values columns_to_color = [(3, 'release_speed', 0.95, 1.05), (11, 'release_extension', 0.9, 1.1), (13, None, 80, 120), (14, None, 30, 70), (15, 'in_zone_rate', 0.7, 1.3), (16, 'chase_rate', 0.7, 1.3), (17, 'whiff_rate', 0.7, 1.3), (18, 'xwoba', 0.7, 1.3)]
for col, stat, vmin_factor, vmax_factor in columns_to_color: cell_value = table.get_celld()[(i + 1, col)].get_text().get_text() if cell_value != '—': vmin = select_df[stat].mean() * vmin_factor if stat else vmin_factor vmax = select_df[stat].mean() * vmax_factor if stat else vmax_factor normalize = mcolors.Normalize(vmin=vmin, vmax=vmax) cmap = cmap_sum if col != 18 else cmap_sum_r table.get_celld()[(i + 1, col)].set_facecolor(get_color(float(cell_value.strip('%')), normalize, cmap))
# Set header text properties table.get_celld()[(len(df_agg), 0)].set_text_props(color='#000000', fontweight='bold')
# Update column names new_column_names = ['$\\bf{Pitch\\ Name}$', '$\\bf{Count}$', '$\\bf{Pitch\\%}$', '$\\bf{Velocity}$', '$\\bf{iVB}$', '$\\bf{HB}$', '$\\bf{Spin}$', '$\\bf{VAA}$', '$\\bf{HAA}$', '$\\bf{vRel}$', '$\\bf{hRel}$', '$\\bf{Ext.}$', '$\\bf{Axis}$', '$\\bf{tjStuff+}$', '$\\bf{Grade}$', '$\\bf{Zone\\%}$', '$\\bf{Chase\\%}$', '$\\bf{Whiff\\%}$', '$\\bf{xwOBA}$\n$\\bf{Contact}$']
for i, col_name in enumerate(new_column_names): table.get_celld()[(0, i)].get_text().set_text(col_name)
# Format cell values def format_cells(columns, fmt): for col in columns: col_idx = df_agg.columns.index(col) for row in range(1, len(df_agg) + 1): cell_value = table.get_celld()[(row, col_idx)].get_text().get_text() if cell_value != '—': table.get_celld()[(row, col_idx)].get_text().set_text(fmt.format(float(cell_value.strip('%'))))
format_cells(['start_speed', 'ivb', 'hb', 'vaa', 'haa', 'z0', 'x0', 'extension'], '{:,.1f}') format_cells(['xwobacon'], '{:,.3f}') format_cells(['count_percent', 'zone_percent', 'chase_percent', 'whiff_percent'], '{:,.1%}') format_cells(['tj_stuff_plus', 'pitch_grade', 'spin_rate'], '{:,.0f}')
# Create legend for pitch types items_in_order = (df.sort("pitch_count", descending=True)['pitch_type'].unique(maintain_order=True).to_numpy()) colour_pitches = [dict_colour[x] for x in items_in_order] label = [dict_pitch[x] for x in items_in_order] handles = [plt.scatter([], [], color=color, marker='o', s=100) for color in colour_pitches] if len(label) > 5: ax.legend(handles, label, bbox_to_anchor=(0.1, 0.81, 0.8, 0.14), ncol=5, fancybox=True, loc='lower center', fontsize=16, framealpha=1.0, markerscale=1.7, prop={'family': 'calibi', 'size': 16}) else: ax.legend(handles, label, bbox_to_anchor=(0.1, 0.81, 0.8, 0.14), ncol=5, fancybox=True, loc='lower center', fontsize=20, framealpha=1.0, markerscale=2, prop={'family': 'calibi', 'size': 20}) ax.axis('off')
def plot_footer(ax:plt.Axes): # Add footer text ax.text(0, 1, 'By: @TJStats', ha='left', va='top', fontsize=24) ax.text(0.5, 0.25, ''' Colour Coding Compares to League Average By Pitch tjStuff+ calculates the Expected Run Value (xRV) of a pitch regardless of type tjStuff+ is normally distributed, where 100 is the mean and Standard Deviation is 10 Pitch Grade scales tjStuff+ to the traditional 20-80 Scouting Scale for a given pitch type ''', ha='center', va='bottom', fontsize=16) ax.text(1, 1, 'Data: MLB, Fangraphs\nImages: MLB, ESPN', ha='right', va='top', fontsize=24) ax.axis('off')
# Function to get an image from a URL and display it on the given axisdef player_headshot(player_input: str, ax: plt.Axes, sport_id: int,season: int): # Construct the URL for the player's headshot image print('SPORT ID',sport_id) try: if int(sport_id) == 1: url = f'https://img.mlbstatic.com/mlb-photos/image/'\ f'upload/d_people:generic:headshot:67:current.png'\ f'/w_640,q_auto:best/v1/people/{player_input}/headshot/silo/current.png'
# Send a GET request to the URL response = requests.get(url)
# Open the image from the response content img = Image.open(BytesIO(response.content))
# Display the image on the axis ax.set_xlim(0, 1.3) ax.set_ylim(0, 1) ax.imshow(img, extent=[0, 1, 0, 1], origin='upper') else: url = f'https://img.mlbstatic.com/mlb-photos/image/upload/c_fill,g_auto/w_640/v1/people/{player_input}/headshot/milb/current.png' response = requests.get(url) img = Image.open(BytesIO(response.content)) ax.set_xlim(0, 1.3) ax.set_ylim(0, 1) ax.imshow(img, extent=[1/6, 5/6, 0, 1], origin='upper') except PIL.UnidentifiedImageError as e: ax.axis('off') return
# Turn off the axis ax.axis('off')
def player_bio(pitcher_id: str, ax: plt.Axes,sport_id: int,year_input: int): # Construct the URL to fetch player data url = f"https://statsapi.mlb.com/api/v1/people?personIds={pitcher_id}&hydrate=currentTeam"
# Send a GET request to the URL and parse the JSON response data = requests.get(url).json()
# Extract player information from the JSON data player_name = data['people'][0]['fullName'] pitcher_hand = data['people'][0]['pitchHand']['code'] age = data['people'][0]['currentAge'] height = data['people'][0]['height'] weight = data['people'][0]['weight']
# Display the player's name, handedness, age, height, and weight on the axis ax.text(0.5, 1, f'{player_name}', va='top', ha='center', fontsize=56) ax.text(0.5, 0.7, f'{pitcher_hand}HP, Age:{age}, {height}/{weight}', va='top', ha='center', fontsize=30) ax.text(0.5, 0.45, f'Season Pitching Summary', va='top', ha='center', fontsize=40)
# Make API call to retrieve sports information response = requests.get(url='https://statsapi.mlb.com/api/v1/sports').json() # Convert the JSON response into a Polars DataFrame df_sport_id = pl.DataFrame(response['sports']) abb = df_sport_id.filter(pl.col('id') == sport_id)['abbreviation'][0]
ax.text(0.5, 0.20, f'{year_input} {abb} Season', va='top', ha='center', fontsize=30, fontstyle='italic')
# Turn off the axis ax.axis('off')
def plot_logo(pitcher_id: str, ax: plt.Axes,df_team: pl.DataFrame,df_players : pl.DataFrame):# List of MLB teams and their corresponding ESPN logo URLs mlb_teams = [ {"team": "AZ", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/ari.png&h=500&w=500"}, {"team": "ATL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/atl.png&h=500&w=500"}, {"team": "BAL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/bal.png&h=500&w=500"}, {"team": "BOS", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/bos.png&h=500&w=500"}, {"team": "CHC", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/chc.png&h=500&w=500"}, {"team": "CWS", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/chw.png&h=500&w=500"}, {"team": "CIN", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/cin.png&h=500&w=500"}, {"team": "CLE", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/cle.png&h=500&w=500"}, {"team": "COL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/col.png&h=500&w=500"}, {"team": "DET", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/det.png&h=500&w=500"}, {"team": "HOU", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/hou.png&h=500&w=500"}, {"team": "KC", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/kc.png&h=500&w=500"}, {"team": "LAA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/laa.png&h=500&w=500"}, {"team": "LAD", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/lad.png&h=500&w=500"}, {"team": "MIA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/mia.png&h=500&w=500"}, {"team": "MIL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/mil.png&h=500&w=500"}, {"team": "MIN", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/min.png&h=500&w=500"}, {"team": "NYM", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/nym.png&h=500&w=500"}, {"team": "NYY", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/nyy.png&h=500&w=500"}, {"team": "OAK", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/oak.png&h=500&w=500"}, {"team": "PHI", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/phi.png&h=500&w=500"}, {"team": "PIT", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/pit.png&h=500&w=500"}, {"team": "SD", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sd.png&h=500&w=500"}, {"team": "SF", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sf.png&h=500&w=500"}, {"team": "SEA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sea.png&h=500&w=500"}, {"team": "STL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/stl.png&h=500&w=500"}, {"team": "TB", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tb.png&h=500&w=500"}, {"team": "TEX", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tex.png&h=500&w=500"}, {"team": "TOR", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tor.png&h=500&w=500"}, {"team": "WSH", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/wsh.png&h=500&w=500"}, {"team": "ATH", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/oak.png&h=500&w=500"}, ] try: # Create a DataFrame from the list of dictionaries df_image = pd.DataFrame(mlb_teams) image_dict = df_image.set_index('team')['logo_url'].to_dict() team_id = df_players.filter(pl.col('player_id') == pitcher_id)['team'][0]
# Construct the URL to fetch team data url_team = f'https://statsapi.mlb.com/api/v1/teams/{team_id}'
# Send a GET request to the team URL and parse the JSON response data_team = requests.get(url_team).json()
# Extract the team abbreviation if data_team['teams'][0]['id'] in df_team['parent_org_id']: team_abb = df_team.filter(pl.col('team_id') == data_team['teams'][0]['id'])['parent_org_abbreviation'][0] else: team_abb = df_team.filter(pl.col('parent_org_id') == data_team['teams'][0]['parentOrgId'])['parent_org_abbreviation'][0]
# Get the logo URL from the image dictionary using the team abbreviation logo_url = image_dict[team_abb]
# Send a GET request to the logo URL response = requests.get(logo_url)
# Open the image from the response content img = Image.open(BytesIO(response.content))
# Display the image on the axis ax.set_xlim(0, 1.3) ax.set_ylim(0, 1) ax.imshow(img, extent=[0.3, 1.3, 0, 1], origin='upper')
# Turn off the axis ax.axis('off') except KeyError as e: ax.axis('off') return
splits = { 'All':0, 'LHH':13, 'RHH':14,}
splits_title = {
'All':'', 'LHH':' vs LHH', 'RHH':' vs RHH',
}
def fangraphs_pitching_leaderboards(season: int, split: str, start_date: str = '2024-01-01', end_date: str = '2024-12-31'): """ Fetch pitching leaderboards data from Fangraphs.
Parameters ---------- season : int The season year. split : str The split type (e.g., 'All', 'LHH', 'RHH'). start_date : str, optional The start date for the data (default is '2024-01-01'). end_date : str, optional The end date for the data (default is '2024-12-31').
Returns ------- pl.DataFrame The DataFrame containing the pitching leaderboards data. """ url = f""" https://www.fangraphs.com/api/leaders/major-league/data?age=&pos=all&stats=pit&lg=all&season={season}&season1={season} &startdate={start_date}&enddate={end_date}&ind=0&qual=0&type=8&month={splits[split]}&pageitems=500000 """
data = requests.get(url).json() df = pl.DataFrame(data=data['data'], infer_schema_length=1000) return df
def fangraphs_table(df: pl.DataFrame, ax: plt.Axes, player_input: str, season: int, split: str): """ Create a table of Fangraphs pitching leaderboards data for a specific player.
Parameters ---------- ax : plt.Axes The axis to plot the table on. season : int The season year. split : str The split type (e.g., 'All', 'LHH', 'RHH'). """
start_date = df['game_date'][0] end_date = df['game_date'][-1]
# Fetch Fangraphs pitching leaderboards data df_fangraphs = fangraphs_pitching_leaderboards(season=season, split=split, start_date=start_date, end_date=end_date).filter(pl.col('xMLBAMID') == player_input) df_fangraphs = df_fangraphs.with_columns( ((pl.col('Strikes')/pl.col('Pitches'))).alias('strikePercentage'),
)
# Select relevant columns for the table plot_table = df_fangraphs.select(['IP', 'WHIP', 'ERA', 'TBF', 'FIP', 'K%', 'BB%', 'K-BB%','strikePercentage'])
# Format table values plot_table_values = [format(plot_table[x][0], fangraphs_stats_dict[x]['format']) if plot_table[x][0] != '---' else '---' for x in plot_table.columns] # Create the table table_fg = ax.table(cellText=[plot_table_values], colLabels=plot_table.columns, cellLoc='center', bbox=[0.0, 0.1, 1, 0.7])
# Set font size for the table min_font_size = 20 table_fg.set_fontsize(min_font_size)
# Update column names with formatted headers new_column_names = [fangraphs_stats_dict[col]['table_header'] for col in plot_table.columns] for i, col_name in enumerate(new_column_names): table_fg.get_celld()[(0, i)].get_text().set_text(col_name)
# Set header text properties ax.text(0.5, 0.9, f'{start_date} to {end_date}{splits_title[split]}', va='bottom', ha='center', fontsize=36, fontstyle='italic') ax.axis('off')
def stat_summary_table(df: pl.DataFrame, player_input: int, sport_id: int, ax: plt.Axes, split: str = 'All'): start_date_format = str(pd.to_datetime(df['game_date'][0]).strftime('%m/%d/%Y')) end_date_format = str(pd.to_datetime(df['game_date'][-1]).strftime('%m/%d/%Y'))
if sport_id == 1: appContext = 'majorLeague' else: appContext = 'minorLeague'
pitcher_stats_call = requests.get(f'https://statsapi.mlb.com/api/v1/people/{player_input}?appContext={appContext}&hydrate=stats(group=[pitching],type=[byDateRange],sportId={sport_id},startDate={start_date_format},endDate={end_date_format})').json() pitcher_stats_call_header = [x for x in pitcher_stats_call['people'][0]['stats'][0]['splits'][-1]['stat']] pitcher_stats_call_values = [pitcher_stats_call['people'][0]['stats'][0]['splits'][-1]['stat'][x] for x in pitcher_stats_call['people'][0]['stats'][0]['splits'][-1]['stat']] pitcher_stats_call_df = pl.DataFrame(data=dict(zip(pitcher_stats_call_header,pitcher_stats_call_values)))
pitcher_stats_call_df = pitcher_stats_call_df.with_columns( pl.lit(df['is_whiff'].sum()).alias('whiffs'), (pl.col('strikeOuts')/pl.col('battersFaced')*100).round(1).cast(pl.Utf8).str.concat('%').alias('k_percent'), (pl.col('baseOnBalls')/pl.col('battersFaced')*100).round(1).cast(pl.Utf8).str.concat('%').alias('bb_percent'), ((pl.col('strikeOuts') - pl.col('baseOnBalls'))/pl.col('battersFaced')*100).round(1).cast(pl.Utf8).str.concat('%').alias('k_bb_percent'), (((pl.col('homeRuns')*13 + 3*((pl.col('baseOnBalls'))+(pl.col('hitByPitch')))-2*(pl.col('strikeOuts'))))/((pl.col('outs'))/3)+3.15).round(2).map_elements(lambda x: f"{x:.2f}") .alias('fip'), ((pl.col('strikes')/pl.col('numberOfPitches')*100)).round(1).cast(pl.Utf8).str.concat('%').alias('strikePercentage'), )
if df['game_id'][0] == df['game_id'][-1]: pitcher_stats_call_df_small = pitcher_stats_call_df.select(['inningsPitched','battersFaced','earnedRuns','hits','strikeOuts','baseOnBalls','hitByPitch','homeRuns','strikePercentage','whiffs']) new_column_names = ['$\\bf{IP}$','$\\bf{PA}$','$\\bf{ER}$','$\\bf{H}$','$\\bf{K}$','$\\bf{BB}$','$\\bf{HBP}$','$\\bf{HR}$','$\\bf{Strike\%}$','$\\bf{Whiffs}$'] title = f'{df["game_date"][0]} vs {df["batter_team"][0]}' elif sport_id != 1: pitcher_stats_call_df_small = pitcher_stats_call_df.select(['inningsPitched','battersFaced','whip','era','fip','k_percent','bb_percent','k_bb_percent','strikePercentage']) new_column_names = ['$\\bf{IP}$','$\\bf{PA}$','$\\bf{WHIP}$','$\\bf{ERA}$','$\\bf{FIP}$','$\\bf{K\%}$','$\\bf{BB\%}$','$\\bf{K-BB\%}$','$\\bf{Strike\%}$'] title = f'{df["game_date"][0]} to {df["game_date"][-1]}' else: fangraphs_table(df=df, ax=ax, player_input=player_input, season=2024, split=split) return import matplotlib.pyplot as plt table_fg = ax.table(cellText=pitcher_stats_call_df_small.to_numpy(), colLabels=pitcher_stats_call_df_small.columns, cellLoc='center', bbox=[0.0, 0.1, 1, 0.7])
min_font_size = 20 table_fg.set_fontsize(min_font_size)
# #new_column_names = ['Pitch Name', 'Pitch%', 'Velocity', 'Spin Rate','Exit Velocity', 'Whiff%', 'CSW%'] for i, col_name in enumerate(new_column_names): table_fg.get_celld()[(0, i)].get_text().set_text(col_name) ax.text(0.5, 0.9, title, va='bottom', ha='center', fontsize=36, fontstyle='italic')
ax.axis('off')12345678910111213141516171819pitch_type,pitch,release_speed,pfx_z,pfx_x,release_spin_rate,release_pos_x,release_pos_z,release_extension,delta_run_exp,swing,whiff,in_zone,out_zone,chase,xwoba,pitch_usage,whiff_rate,in_zone_rate,chase_rate,delta_run_exp_per_100,all
CH,74155,85.46226725895522,5.247514143364433,-3.9745011679246045,1803.342540762527,-0.5077629855663421,5.740925968432281,6.449406057002311,204.631,37385,11538,28912,45151,15250,0.28973564881286695,0.10218846333521206,0.30862645446034503,0.38988604949093114,0.3377555314389493,-0.27595037421616886,
CS,22,66.38181818181819,-7.232727272727273,5.176363636363637,2039.2727272727273,-1.7981818181818183,6.5177272727272735,6.0636363636363635,-0.6290000000000001,9,2,10,12,2,0.13466666666666668,3.0316852449257168e-05,0.2222222222222222,0.45454545454545453,0.16666666666666666,2.85909090909091,
CU,47579,79.40938533133989,-9.345106445703216,4.516206279348902,2568.8591051473077,-0.6765712059634863,5.9438438375202685,6.401792908519479,93.57199999999999,19910,6150,20751,26738,7749,0.28049767649520974,0.0655657055765094,0.3088900050226017,0.4361377918829736,0.28981225222529733,-0.1966665966077471,
EP,576,50.51909722222222,16.357291666666665,-3.8287500000000003,1256.7152777777778,-0.9668749999999999,6.647100694444444,4.442013888888889,23.643,252,7,207,369,106,0.3971430703517588,0.0007937503186714604,0.027777777777777776,0.359375,0.2872628726287263,-4.104687500000001,
FA,635,67.81354330708662,15.865511811023623,-3.7226456692913388,1674.0144694533763,-1.1163779527559055,6.317716535433071,4.92488188976378,15.495,284,29,296,339,73,0.43393490999999995,0.0008750546047853774,0.10211267605633803,0.46614173228346456,0.2153392330383481,-2.4401574803149604,
FC,58379,89.56435813713696,8.08895396195288,1.5509243697478992,2389.231715947733,-0.9745362684951281,5.8461769002079365,6.403954996645393,-20.390000000000015,28753,6674,30002,28189,7757,0.34077822947428493,0.08044852405159929,0.23211490974854798,0.5139176758765994,0.2751782610238036,0.034926942907552404,
FF,230412,94.27369496062718,15.720274827472318,-3.1074418968484365,2296.591789895323,-0.7685432927147252,5.821400777026439,6.524392110813926,-80.28400000000002,113157,24741,127386,102722,24808,0.3401256910065045,0.3175166639335565,0.21864312415493517,0.5528618301130149,0.2415062012032476,0.03484367133656234,
FO,168,82.07916666666667,1.7357142857142858,0.1378571428571428,946.8154761904761,-0.5333333333333333,5.8914285714285715,6.666666666666667,2.539,89,29,60,108,43,0.27798747368421056,0.0002315105096125093,0.3258426966292135,0.35714285714285715,0.39814814814814814,-1.511309523809524,
FS,21727,86.31228885718231,2.979608781700189,-8.76550651263405,1302.3992981808108,-1.4640824780227366,5.742066553136651,6.508958525345622,-16.641000000000005,11333,3906,7982,13745,4946,0.2548785060302361,0.02994064787113684,0.34465719579987647,0.3673769963639711,0.3598399417970171,0.07659133796658538,
KC,11916,81.79965592480698,-9.370896273917422,4.895297079556898,2444.1642796967144,-0.8788083249412554,5.940037764350453,6.434007553503986,-12.997000000000003,5312,1860,4858,7058,2316,0.25845137325418993,0.016420709717515837,0.3501506024096386,0.40768714333669015,0.32813828279965995,0.10907183618663985,
KN,971,76.94819773429454,-2.9453759011328526,-5.356498455200824,263.56326987681973,-1.2303398558187437,5.542131822863028,6.45653964984552,12.681,426,113,428,543,130,0.2870389181034483,0.0013380756240103959,0.2652582159624413,0.4407826982492276,0.23941068139963168,-1.3059732234809474,
PO,55,91.24909090909091,13.11709090909091,-6.399272727272727,2195.3818181818183,-1.494181818181818,5.861272727272727,6.305454545454546,0.0,0,0,1,54,0,,7.579213112314292e-05,,0.01818181818181818,0.0,-0.0,
SC,159,81.02264150943397,-3.1056603773584905,-8.001509433962264,2050.5974842767296,-1.0535849056603774,6.110377358490566,6.064150943396227,4.623,58,13,63,96,20,0.35349463636363637,0.0002191081608832677,0.22413793103448276,0.39622641509433965,0.20833333333333334,-2.9075471698113207,
SI,116002,93.34805382235511,7.567078832293412,-6.148476070311284,2147.3631502060834,-0.7671983511070397,5.622119363257688,6.435364206296976,-32.837000000000025,53318,7390,65492,50222,12474,0.3501967420378125,0.15985525080994228,0.13860234817510034,0.5645764728194341,0.2483772052088726,0.028307270564300636,
SL,116390,85.60138786052518,1.5759858803271631,2.7325110632802407,2435.5705519351436,-0.9811034007748601,5.761407576409815,6.433055359327349,-167.41500000000002,56606,19101,52478,63672,20396,0.2818607008786495,0.16038992984404735,0.337437727449387,0.45088065985050263,0.3203291870838045,0.14383967694819144,
ST,43821,81.8580155633144,1.4796932977339632,7.821825152324228,2575.3661920073496,-1.080187124894457,5.4607240820611125,6.40352674793587,-52.96800000000001,20035,6276,19349,24472,7531,0.25978070794500324,0.0603870359626772,0.3132518093336661,0.44154629059126904,0.30773945733899966,0.12087355377558708,
SV,2702,81.67483345669874,-4.788941524796447,7.356861584011844,2470.624858757062,-0.5779570688378979,5.420762398223538,6.227296392711045,0.19299999999999926,1117,339,1138,1564,479,0.2907683709923664,0.0037234606962678577,0.3034914950760967,0.42116950407105846,0.3062659846547315,-0.007142857142857115,
All,725669,89.1521052747817,7.058379139422499,-1.2140087540219224,2255.6768252515376,-0.8282529777063689,5.758824349487279,6.456550518555369,-20.178000000000118,352163,89742,359413,365054,104080,0.3147037524825,1.0,0.25483085957354973,0.4952850404247667,0.28510850449522535,0.002780606585095976,all123version https://git-lfs.github.com/spec/v1oid sha256:9428e89f2a408148377efb3cd169dc8790bcc89df9495cb895b9db5a955e8fb7size 11447123version https://git-lfs.github.com/spec/v1oid sha256:c5300b15a6ccfb1dd1e79c85bd9ea478a1945c454845e6be31cd8815e4063a3esize 54459064123version https://git-lfs.github.com/spec/v1oid sha256:82d6d95be88b006bea7efd4bbf0464a0a50f261f6f65f060bf022114300721edsize 46782024123version https://git-lfs.github.com/spec/v1oid sha256:179663ae0fa65c626b9a941b6934bda1ce58bdf02a69c0daefc28abd28154201size 579123version https://git-lfs.github.com/spec/v1oid sha256:3ceabc302949cdbe5515b428f900bce98d6f6bedf99153c8d8a645cb0240ef8bsize 579123version https://git-lfs.github.com/spec/v1oid sha256:2671d4db2606cfee299dcffba2a94138fce77c1b7ef6ad14695a972a38dda3c8size 50570139123version https://git-lfs.github.com/spec/v1oid sha256:c3da3e7ab2b513b87d05e90ae30c788ac819dfcaa7cc1cd9943fc13d2958a00fsize 279409123version https://git-lfs.github.com/spec/v1oid sha256:4fef4a66363e5f3fdc70ae45c5382bd986c800ff8bf9296a1f9b334461e70fd4size 262137123version https://git-lfs.github.com/spec/v1oid sha256:05bade9c0420657d3f0dfe35f0b1adbd2d5ae25c87a07bdf6629987f29926438size 10684246123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import polars as pl
import numpy as np
def feature_engineering(df: pl.DataFrame) -> pl.DataFrame:
# Extract the year from the game_date column
df = df.with_columns(
pl.col('game_date').str.slice(0, 4).alias('year')
)
df = df.with_columns([
(-(pl.col('vy0')**2 - (2 * pl.col('ay') * (pl.col('y0') - 17/12)))**0.5).alias('vy_f'),
])
df = df.with_columns([
((pl.col('vy_f') - pl.col('vy0')) / pl.col('ay')).alias('t'),
])
df = df.with_columns([
(pl.col('vz0') + (pl.col('az') * pl.col('t'))).alias('vz_f'),
(pl.col('vx0') + (pl.col('ax') * pl.col('t'))).alias('vx_f')
])
df = df.with_columns([
(-np.arctan(pl.col('vz_f') / pl.col('vy_f')) * (180 / np.pi)).alias('vaa'),
(-np.arctan(pl.col('vx_f') / pl.col('vy_f')) * (180 / np.pi)).alias('haa')
])
# Mirror horizontal break for left-handed pitchers
df = df.with_columns(
pl.when(pl.col('pitcher_hand') == 'L')
.then(-pl.col('ax'))
.otherwise(pl.col('ax'))
.alias('ax')
)
# Mirror horizontal break for left-handed pitchers
df = df.with_columns(
pl.when(pl.col('pitcher_hand') == 'L')
.then(-pl.col('hb'))
.otherwise(pl.col('hb'))
.alias('hb')
)
# Mirror horizontal release point for left-handed pitchers
df = df.with_columns(
pl.when(pl.col('pitcher_hand') == 'L')
.then(pl.col('x0'))
.otherwise(-pl.col('x0'))
.alias('x0')
)
# Define the pitch types to be considered
pitch_types = ['SI', 'FF', 'FC']
# Filter the DataFrame to include only the specified pitch types
df_filtered = df.filter(pl.col('pitch_type').is_in(pitch_types))
# Group by pitcher_id and year, then aggregate to calculate average speed and usage percentage
df_agg = df_filtered.group_by(['pitcher_id', 'year', 'pitch_type']).agg([
pl.col('start_speed').mean().alias('avg_fastball_speed'),
pl.col('az').mean().alias('avg_fastball_az'),
pl.col('ax').mean().alias('avg_fastball_ax'),
pl.len().alias('count')
])
# Sort the aggregated data by count and average fastball speed
df_agg = df_agg.sort(['count', 'avg_fastball_speed'], descending=[True, True])
df_agg = df_agg.unique(subset=['pitcher_id', 'year'], keep='first')
# Join the aggregated data with the main DataFrame
df = df.join(df_agg, on=['pitcher_id', 'year'])
# If no fastball, use the fastest pitch for avg_fastball_speed
df = df.with_columns(
pl.when(pl.col('avg_fastball_speed').is_null())
.then(pl.col('start_speed').max().over('pitcher_id'))
.otherwise(pl.col('avg_fastball_speed'))
.alias('avg_fastball_speed')
)
# If no fastball, use the fastest pitch for avg_fastball_az
df = df.with_columns(
pl.when(pl.col('avg_fastball_az').is_null())
.then(pl.col('az').max().over('pitcher_id'))
.otherwise(pl.col('avg_fastball_az'))
.alias('avg_fastball_az')
)
# If no fastball, use the fastest pitch for avg_fastball_ax
df = df.with_columns(
pl.when(pl.col('avg_fastball_ax').is_null())
.then(pl.col('ax').max().over('ax'))
.otherwise(pl.col('avg_fastball_ax'))
.alias('avg_fastball_ax')
)
# Calculate pitch differentials
df = df.with_columns(
(pl.col('start_speed') - pl.col('avg_fastball_speed')).alias('speed_diff'),
(pl.col('az') - pl.col('avg_fastball_az')).alias('az_diff'),
(pl.col('ax') - pl.col('avg_fastball_ax')).abs().alias('ax_diff')
)
# Cast the year column to integer type
df = df.with_columns(
pl.col('year').cast(pl.Int64)
)
df = df.with_columns([
pl.lit('All').alias('all')
])
return df123version https://git-lfs.github.com/spec/v1oid sha256:41001a1acf6ce7dbe247f1b8b7e68a1bb1b112f39d080b7e95a83479e56cb7c1size 3092328123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import polars as pl
import joblib
model = joblib.load('stuff_model/lgbm_model_2020_2023.joblib')
# Read the values from the text file
with open('stuff_model/target_stats.txt', 'r') as file:
lines = file.readlines()
target_mean = float(lines[0].strip())
target_std = float(lines[1].strip())
# Define the features to be used for training
features = ['start_speed',
'spin_rate',
'extension',
'az',
'ax',
'x0',
'z0',
'speed_diff',
'az_diff',
'ax_diff']
def stuff_apply(df:pl.DataFrame) -> pl.DataFrame:
# Filter the dataframe to include only the rows for the year 2024 and drop rows with null values in the specified features and target column
# df_test = df.drop_nulls(subset=features)
df_test = df.clone()
# Predict the target values for the 2024 data using the trained model
df_test = df_test.with_columns(
pl.Series(name="target", values=model.predict(df_test[features].to_numpy()))
)
# Standardize the target column to create a z-score
df_test = df_test.with_columns(
((pl.col('target') - target_mean) / target_std).alias('target_zscore')
)
# Convert the z-score to tj_stuff_plus
df_test = df_test.with_columns(
(100 - (pl.col('target_zscore') * 10)).alias('tj_stuff_plus')
)
df_pitch_types = pl.read_csv('stuff_model/tj_stuff_plus_pitch.csv')
# Join the pitch type statistics with the main DataFrame based on pitch_type
df_pitch_all = df_test.join(df_pitch_types, left_on='pitch_type', right_on='pitch_type')
# Normalize pitch_grade values to a range between -0.5 and 0.5 based on the percentiles
df_pitch_all = df_pitch_all.with_columns(
((pl.col('tj_stuff_plus') - pl.col('mean')) / pl.col('std')).alias('pitch_grade')
)
# Scale the pitch_grade values to a range between 20 and 80
df_pitch_all = df_pitch_all.with_columns(
(pl.col('pitch_grade') * 10 + 50).clip(20, 80)
)
return df_pitch_all120.0034732498406374636
0.00684675274862654812345678910111213141516pitch_type,mean,std,median,min,max,percentile_1,percentile_99
ST,106.44784631565936,5.593943599731136,106.24878922952112,91.18894850636659,125.29541262167034,91.69322149368426,125.25688309207108
SV,103.73183202363764,3.001226780758946,103.50047554089315,93.3173875900245,111.34757479687066,93.32953434698274,111.33689503153641
SL,103.49296290610897,5.265572779780409,103.19144262214559,88.84957017284297,121.88798777026031,89.76670287371176,121.36013955239422
KC,101.8993919341341,4.271694896723436,100.79211889194949,93.69754063161618,119.4933202093256,93.75149298057133,119.38166236091195
All,99.9275100894791,5.01699442232884,99.65265124489378,84.73033633038408,116.94934527087541,86.65905811630736,116.7610246502804
CU,99.88832068607897,4.615228571103906,99.08993373693156,89.84495168337246,119.90089262632986,90.20429983334718,117.89567125997061
FC,98.83449547008738,5.811964883678063,98.54483029899575,83.20928731685326,119.78700324933075,83.34007602984008,118.21186533190846
FS,98.25541635267653,6.898952096824192,98.46204303842217,72.25450024197754,114.88400714657823,73.39595959354874,114.78967217449389
FO,98.15224613640243,1.081819065809178,99.94816563615653,94.0023252668585,100.50624750619224,94.0142169475971,100.50513134245217
FF,97.29024735737988,6.078459125845886,97.09670890504734,81.2230917971995,118.10419744965911,81.32311771953398,117.7938724746093
SC,97.27958020025409,1.2452898498180456,97.27958020025409,93.536223938276,101.02293646223218,93.54371065079995,101.01544974970822
CH,96.35866365133434,6.178939251378385,95.80884625564597,81.28802319264824,121.14136334013493,82.02275793969746,119.09639344796777
SI,95.14161603816645,4.9734372581529955,95.11657827702109,82.5850956341191,112.99618112461533,82.8856383780296,112.72626192694757
CS,93.97853627048322,0.0,93.97853627048322,93.97853627048322,93.97853627048322,93.97853627048322,93.97853627048322
KN,93.41890096234394,0.0,93.41890096234394,93.41890096234394,93.41890096234394,93.41890096234394,93.41890096234394functions/__pycache__/df_update.cpython-39.pycAdded
functions/__pycache__/pitch_summary_functions.cpython-39.pycAdded
functions/df_update.pyAdded+472
functions/pitch_summary_functions.pyAdded+1029
functions/statcast_2024_grouped.csvAdded+19
joblib_model/__pycache__/feature_engineering.cpython-39.pycAdded
joblib_model/barrel_model.joblibAdded+3
joblib_model/in_zone.joblibAdded+3
joblib_model/in_zone_model_knn_20240410.joblibAdded+3
joblib_model/linear_reg_model_x.joblibAdded+3
joblib_model/linear_reg_model_z.joblibAdded+3
joblib_model/model_attack_zone.joblibAdded+3
joblib_model/no_swing.joblibAdded+3
joblib_model/swing.joblibAdded+3
joblib_model/xwoba_model.joblibAdded+3
stuff_model/__pycache__/feature_engineering.cpython-39.pycAdded
stuff_model/__pycache__/stuff_apply.cpython-39.pycAdded
stuff_model/feature_engineering.pyAdded+118
stuff_model/lgbm_model_2020_2023.joblibAdded+3
stuff_model/stuff_apply.pyAdded+57
stuff_model/target_stats.txtAdded+2
stuff_model/tj_stuff_plus_pitch.csvAdded+16