import numpy as np import pandas as pd import streamlit as st import gspread import plotly.figure_factory as ff scope = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive"] credentials = { "type": "service_account", "project_id": "sheets-api-connect-378620", "private_key_id": "1005124050c80d085e2c5b344345715978dd9cc9", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtKa01beXwc88R\nnPZVQTNPVQuBnbwoOfc66gW3547ja/UEyIGAF112dt/VqHprRafkKGmlg55jqJNt\na4zceLKV+wTm7vBu7lDISTJfGzCf2TrxQYNqwMKE2LOjI69dBM8u4Dcb4k0wcp9v\ntW1ZzLVVuwTvmrg7JBHjiSaB+x5wxm/r3FOiJDXdlAgFlytzqgcyeZMJVKKBQHyJ\njEGg/1720A0numuOCt71w/2G0bDmijuj1e6tH32MwRWcvRNZ19K9ssyDz2S9p68s\nYDhIxX69OWxwScTIHLY6J2t8txf/XMivL/636fPlDADvBEVTdlT606n8CcKUVQeq\npUVdG+lfAgMBAAECggEAP38SUA7B69eTfRpo658ycOs3Amr0JW4H/bb1rNeAul0K\nZhwd/HnU4E07y81xQmey5kN5ZeNrD5EvqkZvSyMJHV0EEahZStwhjCfnDB/cxyix\nZ+kFhv4y9eK+kFpUAhBy5nX6T0O+2T6WvzAwbmbVsZ+X8kJyPuF9m8ldcPlD0sce\ntj8NwVq1ys52eosqs7zi2vjt+eMcaY393l4ls+vNq8Yf27cfyFw45W45CH/97/Nu\n5AmuzlCOAfFF+z4OC5g4rei4E/Qgpxa7/uom+BVfv9G0DIGW/tU6Sne0+37uoGKt\nW6DzhgtebUtoYkG7ZJ05BTXGp2lwgVcNRoPwnKJDxQKBgQDT5wYPUBDW+FHbvZSp\nd1m1UQuXyerqOTA9smFaM8sr/UraeH85DJPEIEk8qsntMBVMhvD3Pw8uIUeFNMYj\naLmZFObsL+WctepXrVo5NB6RtLB/jZYxiKMatMLUJIYtcKIp+2z/YtKiWcLnwotB\nWdCjVnPTxpkurmF2fWP/eewZ+wKBgQDRMtJg7etjvKyjYNQ5fARnCc+XsI3gkBe1\nX9oeXfhyfZFeBXWnZzN1ITgFHplDznmBdxAyYGiQdbbkdKQSghviUQ0igBvoDMYy\n1rWcy+a17Mj98uyNEfmb3X2cC6WpvOZaGHwg9+GY67BThwI3FqHIbyk6Ko09WlTX\nQpRQjMzU7QKBgAfi1iflu+q0LR+3a3vvFCiaToskmZiD7latd9AKk2ocsBd3Woy9\n+hXXecJHPOKV4oUJlJgvAZqe5HGBqEoTEK0wyPNLSQlO/9ypd+0fEnArwFHO7CMF\nycQprAKHJXM1eOOFFuZeQCaInqdPZy1UcV5Szla4UmUZWkk1m24blHzXAoGBAMcA\nyH4qdbxX9AYrC1dvsSRvgcnzytMvX05LU0uF6tzGtG0zVlub4ahvpEHCfNuy44UT\nxRWW/oFFaWjjyFxO5sWggpUqNuHEnRopg3QXx22SRRTGbN45li/+QAocTkgsiRh1\nqEcYZsO4mPCsQqAy6E2p6RcK+Xa+omxvSnVhq0x1AoGAKr8GdkCl4CF6rieLMAQ7\nLNBuuoYGaHoh8l5E2uOQpzwxVy/nMBcAv+2+KqHEzHryUv1owOi6pMLv7A9mTFoS\n18B0QRLuz5fSOsVnmldfC9fpUc6H8cH1SINZpzajqQA74bPwELJjnzrCnH79TnHG\nJuElxA33rFEjbgbzdyrE768=\n-----END PRIVATE KEY-----\n", "client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com", "client_id": "106625872877651920064", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com" } gc = gspread.service_account_from_dict(credentials) st.set_page_config(layout="wide") game_format = {'Win Percentage': '{:.2%}','Cover Spread Percentage': '{:.2%}', 'First Inning Lead Percentage': '{:.2%}', 'Fifth Inning Lead Percentage': '{:.2%}'} american_format = {'First Inning Lead Percentage': '{:.2%}', 'Fifth Inning Lead Percentage': '{:.2%}'} master_hold = 'https://docs.google.com/spreadsheets/d/1f42Ergav8K1VsOLOK9MUn7DM_MLMvv4GR2Fy7EfnZTc/edit#gid=340831852' @st.cache_resource(ttl = 300) def init_baselines(): sh = gc.open_by_url(master_hold) worksheet = sh.worksheet('Pitcher_Stats') props_frame_hold = pd.DataFrame(worksheet.get_all_records()) props_frame_hold.rename(columns={"Names": "Player"}, inplace = True) props_frame_hold = props_frame_hold[['Player', 'Team', 'BB', 'Hits', 'HRs', 'ERs', 'Ks', 'Outs', 'Fantasy', 'FD_Fantasy', 'PrizePicks']] pitcher_stats = props_frame_hold.drop_duplicates(subset='Player') worksheet = sh.worksheet('Timestamp') raw_stamp = worksheet.acell('a1').value t_stamp = f"Last update was at {raw_stamp}" worksheet = sh.worksheet('Hitter_Stats') props_frame_hold = pd.DataFrame(worksheet.get_all_records()) props_frame_hold.rename(columns={"Names": "Player"}, inplace = True) props_frame_hold = props_frame_hold[['Player', 'Team', 'Walks', 'Steals', 'Hits', 'Singles', 'Doubles', 'HRs', 'RBIs', 'Runs', 'Fantasy', 'FD_Fantasy', 'PrizePicks']] props_frame_hold['Total Bases'] = props_frame_hold['Singles'] + (props_frame_hold['Doubles'] * 2) + (props_frame_hold['HRs'] * 4) props_frame_hold['Hits + Runs + RBIs'] = props_frame_hold['Hits'] + props_frame_hold['Runs'] + props_frame_hold['RBIs'] hitter_stats = props_frame_hold.drop_duplicates(subset='Player') worksheet = sh.worksheet('Game_Betting_Model') team_frame = pd.DataFrame(worksheet.get_all_records()) team_frame = team_frame.drop_duplicates(subset='Names') team_frame['Win Percentage'] = team_frame['Win Percentage'].str.replace('%', '').astype('float')/100 team_frame['Cover Spread Percentage'] = team_frame['Cover Spread Percentage'].str.replace('%', '').astype('float')/100 team_frame['ML_Value'] = team_frame['ML_Value'].str.replace('%', '').astype('float')/100 team_frame['Spread_Value'] = team_frame['Spread_Value'].str.replace('%', '').astype('float')/100 worksheet = sh.worksheet('prop_frame') raw_display = pd.DataFrame(worksheet.get_all_records()) raw_display.replace('', np.nan, inplace=True) prop_frame = raw_display.dropna(subset='Team') worksheet = sh.worksheet('Prop_results') raw_display = pd.DataFrame(worksheet.get_all_records()) raw_display.replace('', np.nan, inplace=True) betsheet_frame = raw_display.dropna(subset='proj') worksheet = sh.worksheet('Pick6_ingest') raw_display = pd.DataFrame(worksheet.get_all_records()) raw_display.replace('', np.nan, inplace=True) pick_frame = raw_display.dropna(subset='Player') return pitcher_stats, hitter_stats, team_frame, prop_frame, betsheet_frame, pick_frame, t_stamp pitcher_stats, hitter_stats, team_frame, prop_frame, betsheet_frame, pick_frame, t_stamp = init_baselines() tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["Game Betting Model", "Pitcher Prop Projections", "Hitter Prop Projections", "Player Prop Simulations", "Stat Specific Simulations", "Bet Sheet"]) def convert_df_to_csv(df): return df.to_csv().encode('utf-8') with tab1: st.info(t_stamp) if st.button("Reset Data", key='reset1'): st.cache_data.clear() pitcher_stats, hitter_stats, team_frame, prop_frame, betsheet_frame, pick_frame, t_stamp = init_baselines() line_var1 = st.radio('How would you like to display odds?', options = ['Percentage', 'American'], key='line_var1') if line_var1 == 'Percentage': team_frame = team_frame[['Names', 'Game', 'Moneyline', 'Win Percentage', 'ML_Value', 'Spread', 'Cover Spread Percentage', 'Spread_Value', 'Avg Score', 'Game Total', 'Avg Fifth Inning', 'Fifth Inning Lead Percentage']] team_frame = team_frame.set_index('Names') st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(game_format, precision=2), use_container_width = True) if line_var1 == 'American': team_frame = team_frame[['Names', 'Game', 'Moneyline', 'American ML', 'ML_Value', 'Spread', 'American Cover', 'Spread_Value', 'Avg Score', 'Game Total', 'Avg Fifth Inning', 'Fifth Inning Lead Percentage']] team_frame.rename(columns={"American ML": "Win Percentage", "American Cover": "Cover Spread Percentage"}, inplace = True) team_frame = team_frame.set_index('Names') st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(american_format, precision=2), use_container_width = True) st.download_button( label="Export Team Model", data=convert_df_to_csv(team_frame), file_name='MLB_team_betting_export.csv', mime='text/csv', key='team_export', ) with tab2: st.info(t_stamp) if st.button("Reset Data", key='reset2'): st.cache_data.clear() pitcher_stats, hitter_stats, team_frame, prop_frame, betsheet_frame, pick_frame, t_stamp = init_baselines() split_var1 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var1') if split_var1 == 'Specific Teams': team_var1 = st.multiselect('Which teams would you like to include in the tables?', options = pitcher_stats['Team'].unique(), key='team_var1') elif split_var1 == 'All': team_var1 = pitcher_stats.Team.values.tolist() pitcher_stats = pitcher_stats[pitcher_stats['Team'].isin(team_var1)] pitcher_frame = pitcher_stats.set_index('Player') pitcher_frame = pitcher_frame.sort_values(by='Ks', ascending=False) st.dataframe(pitcher_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) st.download_button( label="Export Prop Model", data=convert_df_to_csv(pitcher_frame), file_name='MLB_pitcher_prop_export.csv', mime='text/csv', key='pitcher_prop_export', ) with tab3: st.info(t_stamp) if st.button("Reset Data", key='reset3'): st.cache_data.clear() pitcher_stats, hitter_stats, team_frame, prop_frame, betsheet_frame, pick_frame, t_stamp = init_baselines() split_var2 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var2') if split_var2 == 'Specific Teams': team_var2 = st.multiselect('Which teams would you like to include in the tables?', options = hitter_stats['Team'].unique(), key='team_var2') elif split_var2 == 'All': team_var2 = hitter_stats.Team.values.tolist() hitter_stats = hitter_stats[hitter_stats['Team'].isin(team_var2)] hitter_frame = hitter_stats.set_index('Player') hitter_frame = hitter_frame.sort_values(by='Hits + Runs + RBIs', ascending=False) st.dataframe(hitter_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) st.download_button( label="Export Prop Model", data=convert_df_to_csv(hitter_frame), file_name='MLB_hitter_prop_export.csv', mime='text/csv', key='hitter_prop_export', ) with tab4: st.info(t_stamp) if st.button("Reset Data", key='reset4'): st.cache_data.clear() pitcher_stats, hitter_stats, team_frame, prop_frame, betsheet_frame, pick_frame, t_stamp = init_baselines() col1, col2 = st.columns([1, 5]) with col2: df_hold_container = st.empty() info_hold_container = st.empty() plot_hold_container = st.empty() with col1: prop_group_var = st.selectbox('What kind of props are you simulating?', options = ['Pitchers', 'Hitters']) if prop_group_var == 'Pitchers': player_check = st.selectbox('Select player to simulate props', options = pitcher_stats['Player'].unique()) prop_type_var = st.selectbox('Select type of prop to simulate', options = ['Strikeouts', 'Walks', 'Hits', 'Homeruns', 'Earned Runs', 'Outs', 'Fantasy', 'FD_Fantasy', 'PrizePicks']) elif prop_group_var == 'Hitters': player_check = st.selectbox('Select player to simulate props', options = hitter_stats['Player'].unique()) prop_type_var = st.selectbox('Select type of prop to simulate', options = ['Total Bases', 'Walks', 'Steals', 'Hits', 'Singles', 'Doubles', 'Homeruns', 'RBIs', 'Runs', 'Hits + Runs + RBIs', 'Fantasy', 'FD_Fantasy', 'PrizePicks']) ou_var = st.selectbox('Select wether it is an over or under', options = ['Over', 'Under']) prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 50.5, value = 5.5, step = .5) line_var = st.number_input('Type in the line on the prop (i.e. -120)', min_value = -1000, max_value = 1000, value = -150, step = 1) line_var = line_var + 1 if st.button('Simulate Prop'): with col2: with df_hold_container.container(): if prop_group_var == 'Pitchers': df = pitcher_stats elif prop_group_var == 'Hitters': df = hitter_stats total_sims = 1000 df.replace("", 0, inplace=True) player_var = df.loc[df['Player'] == player_check] player_var = player_var.reset_index() if prop_group_var == 'Pitchers': if prop_type_var == "Walks": df['Median'] = df['BB'] elif prop_type_var == "Hits": df['Median'] = df['Hits'] elif prop_type_var == "Homeruns": df['Median'] = df['HRs'] elif prop_type_var == "Earned Runs": df['Median'] = df['ERs'] elif prop_type_var == "Strikeouts": df['Median'] = df['Ks'] elif prop_type_var == "Outs": df['Median'] = df['Outs'] elif prop_type_var == "Fantasy": df['Median'] = df['Fantasy'] elif prop_type_var == "FD_Fantasy": df['Median'] = df['FD_Fantasy'] elif prop_type_var == "PrizePicks": df['Median'] = df['PrizePicks'] elif prop_group_var == 'Hitters': if prop_type_var == "Walks": df['Median'] = df['Walks'] elif prop_type_var == "Total Bases": df['Median'] = df['Total Bases'] elif prop_type_var == "Hits + Runs + RBIs": df['Median'] = df['Hits + Runs + RBIs'] elif prop_type_var == "Steals": df['Median'] = df['Steals'] elif prop_type_var == "Hits": df['Median'] = df['Hits'] elif prop_type_var == "Singles": df['Median'] = df['Singles'] elif prop_type_var == "Doubles": df['Median'] = df['Doubles'] elif prop_type_var == "Homeruns": df['Median'] = df['HRs'] elif prop_type_var == "RBIs": df['Median'] = df['RBIs'] elif prop_type_var == "Runs": df['Median'] = df['Runs'] elif prop_type_var == "Fantasy": df['Median'] = df['Fantasy'] elif prop_type_var == "FD_Fantasy": df['Median'] = df['FD_Fantasy'] elif prop_type_var == "PrizePicks": df['Median'] = df['PrizePicks'] flex_file = df if prop_group_var == 'Pitchers': flex_file['Floor'] = flex_file['Median'] * .20 flex_file['Ceiling'] = flex_file['Median'] + (flex_file['Median'] * .80) flex_file['STD'] = flex_file['Median'] / 4 flex_file = flex_file[['Player', 'Floor', 'Median', 'Ceiling', 'STD']] elif prop_group_var == 'Hitters': flex_file['Floor'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * .20, 0) flex_file['Ceiling'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] + (flex_file['Median'] * .80), flex_file['Median'] * 4) flex_file['STD'] = flex_file['Median'] / 1.5 flex_file = flex_file[['Player', 'Floor', 'Median', 'Ceiling', 'STD']] hold_file = flex_file overall_file = flex_file salary_file = flex_file overall_players = overall_file[['Player']] for x in range(0,total_sims): overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD']) overall_file=overall_file.drop(['Player', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1) overall_file.astype('int').dtypes players_only = hold_file[['Player']] player_outcomes = pd.merge(players_only, overall_file, left_index=True, right_index=True) players_only['Mean_Outcome'] = overall_file.mean(axis=1) players_only['10%'] = overall_file.quantile(0.1, axis=1) players_only['90%'] = overall_file.quantile(0.9, axis=1) if ou_var == 'Over': players_only['beat_prop'] = overall_file[overall_file > prop_var].count(axis=1)/float(total_sims) elif ou_var == 'Under': players_only['beat_prop'] = (overall_file[overall_file < prop_var].count(axis=1)/float(total_sims)) players_only['implied_odds'] = np.where(line_var <= 0, (-(line_var)/((-(line_var))+100)), 100/(line_var+100)) players_only['Player'] = hold_file[['Player']] final_outcomes = players_only[['Player', '10%', 'Mean_Outcome', '90%', 'implied_odds', 'beat_prop']] final_outcomes['Bet?'] = np.where(final_outcomes['beat_prop'] - final_outcomes['implied_odds'] >= .10, "Bet", "No Bet") final_outcomes = final_outcomes.loc[final_outcomes['Player'] == player_check] player_outcomes = player_outcomes.loc[player_outcomes['Player'] == player_check] player_outcomes = player_outcomes.drop(columns=['Player']).transpose() player_outcomes = player_outcomes.reset_index() player_outcomes.columns = ['Instance', 'Outcome'] x1 = player_outcomes.Outcome.to_numpy() print(x1) hist_data = [x1] group_labels = ['player outcomes'] fig = ff.create_distplot( hist_data, group_labels, bin_size=[.05]) fig.add_vline(x=prop_var, line_dash="dash", line_color="green") with df_hold_container: df_hold_container = st.empty() format_dict = {'10%': '{:.2f}', 'Mean_Outcome': '{:.2f}','90%': '{:.2f}', 'beat_prop': '{:.2%}','implied_odds': '{:.2%}'} st.dataframe(final_outcomes.style.format(format_dict), use_container_width = True) with info_hold_container: st.info('The Y-axis is the percent of times in simulations that the player reaches certain thresholds, while the X-axis is the threshold to be met. The Green dotted line is the prop you entered. You can hover over any spot and see the percent to reach that mark.') with plot_hold_container: st.dataframe(player_outcomes, use_container_width = True) plot_hold_container = st.empty() st.plotly_chart(fig, use_container_width=True) with tab5: st.info(t_stamp) st.info('The Over and Under percentages are a compositve percentage based on simulations, historical performance, and implied probabilities, and may be different than you would expect based purely on the median projection. Likewise, the Edge of a bet is not the only indicator of if you should make the bet or not as the suggestion is using a base acceptable threshold to determine how much edge you should have for each stat category.') if st.button("Reset Data/Load Data", key='reset5'): # Clear values from *all* all in-memory and on-disk data caches: # i.e. clear values from both square and cube st.cache_data.clear() pitcher_stats, hitter_stats, team_frame, prop_frame, pick_frame, t_stamp = init_baselines() col1, col2 = st.columns([1, 5]) with col2: df_hold_container = st.empty() info_hold_container = st.empty() plot_hold_container = st.empty() export_container = st.empty() with col1: game_select_var = st.selectbox('Select prop source', options = ['Draftkings', 'Pick6']) if game_select_var == 'Draftkings': prop_df = prop_frame[['Player', 'over_prop', 'over_line', 'under_line', 'prop_type']] working_source = prop_frame.copy elif game_select_var == 'Pick6': prop_df = pick_frame[['Player', 'over_prop', 'over_line', 'under_line', 'prop_type']] working_source = pick_frame.copy() st.download_button( label="Download Prop Source", data=convert_df_to_csv(prop_df), file_name='MLB_prop_source.csv', mime='text/csv', key='prop_source', ) prop_type_var = st.selectbox('Select prop category', options = ['Strikeouts (Pitchers)', 'Total Outs (Pitchers)', 'Earned Runs (Pitchers)', 'Hits Against (Pitchers)', 'Walks Allowed (Pitchers)', 'Total Bases (Hitters)', 'Stolen Bases (Hitters)']) if st.button('Simulate Prop Category'): with col2: with df_hold_container.container(): if prop_type_var == "Strikeouts (Pitchers)": player_df = pitcher_stats prop_df = prop_frame[prop_frame['prop_type'] == 'pitcher_strikeouts'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) elif prop_type_var == "Total Outs (Pitchers)": player_df = pitcher_stats prop_df = prop_frame[prop_frame['prop_type'] == 'pitcher_outs'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) elif prop_type_var == "Earned Runs (Pitchers)": player_df = pitcher_stats prop_df = prop_frame[prop_frame['prop_type'] == 'pitcher_earned_runs'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) elif prop_type_var == "Hits Against (Pitchers)": player_df = pitcher_stats prop_df = prop_frame[prop_frame['prop_type'] == 'pitcher_hits_allowed'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) elif prop_type_var == "Walks Allowed (Pitchers)": player_df = pitcher_stats prop_df = prop_frame[prop_frame['prop_type'] == 'pitcher_walks'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) elif prop_type_var == "Total Bases (Hitters)": player_df = hitter_stats prop_df = prop_frame[prop_frame['prop_type'] == 'batter_total_bases'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) elif prop_type_var == "Stolen Bases (Hitters)": player_df = hitter_stats prop_df = prop_frame[prop_frame['prop_type'] == 'batter_stolen_bases'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) elif prop_type_var == "Hits (Hitters)": player_df = hitter_stats prop_df = prop_frame[prop_frame['prop_type'] == 'batter_hits'] prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']] prop_df.rename(columns={"over_prop": "Prop"}, inplace = True) prop_df = prop_df.loc[prop_df['Prop'] != 0] prop_df['Over'] = np.where(prop_df['over_line'] < 0, (-(prop_df['over_line'])/((-(prop_df['over_line']))+100)), 100/(prop_df['over_line']+100)) prop_df['Under'] = np.where(prop_df['under_line'] < 0, (-(prop_df['under_line'])/((-(prop_df['under_line']))+100)), 100/(prop_df['under_line']+100)) df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player']) prop_dict = dict(zip(df.Player, df.Prop)) over_dict = dict(zip(df.Player, df.Over)) under_dict = dict(zip(df.Player, df.Under)) total_sims = 1000 df.replace("", 0, inplace=True) if prop_type_var == "Strikeouts (Pitchers)": df['Median'] = df['Ks'] elif prop_type_var == "Earned Runs (Pitchers)": df['Median'] = df['ERs'] elif prop_type_var == "Total Outs (Pitchers)": df['Median'] = df['Outs'] elif prop_type_var == "Hits Against (Pitchers)": df['Median'] = df['Hits'] elif prop_type_var == "Walks Allowed (Pitchers)": df['Median'] = df['BB'] elif prop_type_var == "Total Bases (Hitters)": df['Median'] = df['Total Bases'] elif prop_type_var == "Stolen Bases (Hitters)": df['Median'] = df['Stolen Bases (Hitters)'] flex_file = df if prop_type_var == 'Strikeouts (Pitchers)': flex_file['Floor'] = flex_file['Median'] * .20 flex_file['Ceiling'] = flex_file['Median'] * 1.8 flex_file['STD'] = flex_file['Median'] / 4 flex_file['Prop'] = flex_file['Player'].map(prop_dict) flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']] elif prop_type_var == 'Total Outs (Pitchers)': flex_file['Floor'] = flex_file['Median'] * .20 flex_file['Ceiling'] = flex_file['Median'] * 1.8 flex_file['STD'] = flex_file['Median'] / 4 flex_file['Prop'] = flex_file['Player'].map(prop_dict) flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']] elif prop_type_var == 'Earned Runs (Pitchers)': flex_file['Floor'] = flex_file['Median'] * .20 flex_file['Ceiling'] = flex_file['Median'] * 1.8 flex_file['STD'] = flex_file['Median'] / 4 flex_file['Prop'] = flex_file['Player'].map(prop_dict) flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']] elif prop_type_var == 'Hits Against (Pitchers)': flex_file['Floor'] = flex_file['Median'] * .20 flex_file['Ceiling'] = flex_file['Median'] * 1.8 flex_file['STD'] = flex_file['Median'] / 4 flex_file['Prop'] = flex_file['Player'].map(prop_dict) flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']] elif prop_type_var == 'Walks Allowed (Pitchers)': flex_file['Floor'] = flex_file['Median'] * .20 flex_file['Ceiling'] = flex_file['Median'] * 1.8 flex_file['STD'] = flex_file['Median'] / 4 flex_file['Prop'] = flex_file['Player'].map(prop_dict) flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']] elif prop_type_var == 'Total Bases (Hitters)': flex_file['Floor'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * .20, 0) flex_file['Ceiling'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * 1.8, flex_file['Median'] * 4) flex_file['STD'] = flex_file['Median'] / 1.5 flex_file['Prop'] = flex_file['Player'].map(prop_dict) flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']] elif prop_type_var == 'Stolen Bases (Hitters)': flex_file['Floor'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * .20, 0) flex_file['Ceiling'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * 1.8, flex_file['Median'] * 4) flex_file['STD'] = flex_file['Median'] / 1.5 flex_file['Prop'] = flex_file['Player'].map(prop_dict) flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']] hold_file = flex_file overall_file = flex_file prop_file = flex_file overall_players = overall_file[['Player']] for x in range(0,total_sims): prop_file[x] = prop_file['Prop'] prop_file = prop_file.drop(['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1) for x in range(0,total_sims): overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD']) overall_file=overall_file.drop(['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1) players_only = hold_file[['Player']] player_outcomes = pd.merge(players_only, overall_file, left_index=True, right_index=True) prop_check = (overall_file - prop_file) players_only['Mean_Outcome'] = overall_file.mean(axis=1) players_only['10%'] = overall_file.quantile(0.1, axis=1) players_only['90%'] = overall_file.quantile(0.9, axis=1) players_only['Over'] = prop_check[prop_check > 0].count(axis=1)/float(total_sims) players_only['Imp Over'] = players_only['Player'].map(over_dict) players_only['Over%'] = players_only[["Over", "Imp Over"]].mean(axis=1) players_only['Under'] = prop_check[prop_check < 0].count(axis=1)/float(total_sims) players_only['Imp Under'] = players_only['Player'].map(under_dict) players_only['Under%'] = players_only[["Under", "Imp Under"]].mean(axis=1) players_only['Prop'] = players_only['Player'].map(prop_dict) players_only['Prop_avg'] = players_only['Prop'].mean() / 100 players_only['prop_threshold'] = .10 players_only = players_only.loc[players_only['Mean_Outcome'] > 0] players_only['Over_diff'] = players_only['Over%'] - players_only['Imp Over'] players_only['Under_diff'] = players_only['Under%'] - players_only['Imp Under'] players_only['Bet_check'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], players_only['Over_diff'] , players_only['Under_diff']) players_only['Bet_suggest'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], "Over" , "Under") players_only['Bet?'] = np.where(players_only['Bet_check'] >= players_only['prop_threshold'], players_only['Bet_suggest'], "No Bet") players_only['Edge'] = players_only['Bet_check'] players_only['Player'] = hold_file[['Player']] final_outcomes = players_only[['Player', 'Prop', 'Mean_Outcome', 'Imp Over', 'Over%', 'Imp Under', 'Under%', 'Bet?', 'Edge']] final_outcomes = final_outcomes.sort_values(by='Edge', ascending=False) final_outcomes = final_outcomes.set_index('Player') with df_hold_container: df_hold_container = st.empty() st.dataframe(final_outcomes.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) with export_container: export_container = st.empty() st.download_button( label="Export Projections", data=convert_df_to_csv(final_outcomes), file_name='MLB_DFS_prop_proj.csv', mime='text/csv', key='prop_proj', ) with tab6: col1, col2, col3 = st.columns([2, 2, 2]) st.info(t_stamp) st.info('This sheet is more or less a static represenation of the Stat Specific Simulations. ROR is rate of return based on hit rate and payout. Use the over and under EDGEs to place bets. 20%+ should be considered a 1 unit bet, 15-20% is .75 units, 10-15% is .50 units, 5-10% is .25 units, and 0-5% is .1 units.') if st.button("Reset Data", key='reset6'): st.cache_data.clear() pitcher_stats, hitter_stats, team_frame, prop_frame, betsheet_frame, pick_frame, t_stamp = init_baselines() with col1: split_var6 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var6') if split_var6 == 'Specific Teams': team_var6 = st.multiselect('Which teams would you like to include in the tables?', options = betsheet_frame['Team'].unique(), key='team_var6') elif split_var6 == 'All': team_var6 = betsheet_frame.Team.values.tolist() with col2: prop_choice_var6 = st.radio("Would you like to view all prop types or specific ones?", ('All', 'Specific Props'), key='prop_choice_var6') if prop_choice_var6 == 'Specific Props': prop_var6 = st.multiselect('Which props would you like to include in the tables?', options = betsheet_frame['prop_type'].unique(), key='prop_var6') elif prop_choice_var6 == 'All': prop_var6 = betsheet_frame.prop_type.values.tolist() with col3: player_choice_var6 = st.radio("Would you like to view all players props or specific ones?", ('All', 'Specific Players'), key='player_choice_var6') if player_choice_var6 == 'Specific Players': player_var6 = st.multiselect('Which players would you like to include in the tables?', options = betsheet_frame['Player'].unique(), key='player_var6') elif player_choice_var6 == 'All': player_var6 = betsheet_frame.Player.values.tolist() betsheet_disp = betsheet_frame.copy() betsheet_disp = betsheet_disp[betsheet_disp['Team'].isin(team_var6)] betsheet_disp = betsheet_disp[betsheet_disp['prop_type'].isin(prop_var6)] betsheet_disp = betsheet_disp[betsheet_disp['Player'].isin(player_var6)] betsheet_disp = betsheet_disp.sort_values(by='over_EDGE', ascending=False) st.dataframe(betsheet_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), height=750, use_container_width = True) st.download_button( label="Export Betsheet", data=convert_df_to_csv(betsheet_disp), file_name='MLB_Betsheet_export.csv', mime='text/csv', key='MLB_Betsheet_export', )