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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pulp
|
2 |
+
import numpy as np
|
3 |
+
import pandas as pd
|
4 |
+
import random
|
5 |
+
import sys
|
6 |
+
import openpyxl
|
7 |
+
import re
|
8 |
+
import time
|
9 |
+
import streamlit as st
|
10 |
+
import matplotlib
|
11 |
+
from matplotlib.colors import LinearSegmentedColormap
|
12 |
+
from st_aggrid import GridOptionsBuilder, AgGrid, GridUpdateMode, DataReturnMode
|
13 |
+
import json
|
14 |
+
import requests
|
15 |
+
import gspread
|
16 |
+
import plotly.figure_factory as ff
|
17 |
+
|
18 |
+
scope = ['https://www.googleapis.com/auth/spreadsheets',
|
19 |
+
"https://www.googleapis.com/auth/drive"]
|
20 |
+
|
21 |
+
credentials = {
|
22 |
+
"type": "service_account",
|
23 |
+
"project_id": "sheets-api-connect-378620",
|
24 |
+
"private_key_id": "1005124050c80d085e2c5b344345715978dd9cc9",
|
25 |
+
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtKa01beXwc88R\nnPZVQTNPVQuBnbwoOfc66gW3547ja/UEyIGAF112dt/VqHprRafkKGmlg55jqJNt\na4zceLKV+wTm7vBu7lDISTJfGzCf2TrxQYNqwMKE2LOjI69dBM8u4Dcb4k0wcp9v\ntW1ZzLVVuwTvmrg7JBHjiSaB+x5wxm/r3FOiJDXdlAgFlytzqgcyeZMJVKKBQHyJ\njEGg/1720A0numuOCt71w/2G0bDmijuj1e6tH32MwRWcvRNZ19K9ssyDz2S9p68s\nYDhIxX69OWxwScTIHLY6J2t8txf/XMivL/636fPlD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mPCsQqAy6E2p6RcK+Xa+omxvSnVhq0x1AoGAKr8GdkCl4CF6rieLMAQ7\nLNBuuoYGaHoh8l5E2uOQpzwxVy/nMBcAv+2+KqHEzHryUv1owOi6pMLv7A9mTFoS\n18B0QRLuz5fSOsVnmldfC9fpUc6H8cH1SINZpzajqQA74bPwELJjnzrCnH79TnHG\nJuElxA33rFEjbgbzdyrE768=\n-----END PRIVATE KEY-----\n",
|
26 |
+
"client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
|
27 |
+
"client_id": "106625872877651920064",
|
28 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
29 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
30 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
31 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
|
32 |
+
}
|
33 |
+
|
34 |
+
gc = gspread.service_account_from_dict(credentials)
|
35 |
+
|
36 |
+
st.set_page_config(layout="wide")
|
37 |
+
|
38 |
+
game_format = {'Win Percentage': '{:.2%}','Cover Spread Percentage': '{:.2%}', 'First Inning Lead Percentage': '{:.2%}',
|
39 |
+
'Fifth Inning Lead Percentage': '{:.2%}'}
|
40 |
+
american_format = {'First Inning Lead Percentage': '{:.2%}', 'Fifth Inning Lead Percentage': '{:.2%}'}
|
41 |
+
|
42 |
+
master_hold = 'https://docs.google.com/spreadsheets/d/1f42Ergav8K1VsOLOK9MUn7DM_MLMvv4GR2Fy7EfnZTc/edit#gid=340831852'
|
43 |
+
|
44 |
+
@st.cache_data
|
45 |
+
def load_pitcher_props():
|
46 |
+
sh = gc.open_by_url(master_hold)
|
47 |
+
worksheet = sh.worksheet('Pitcher_Stats')
|
48 |
+
props_frame_hold = pd.DataFrame(worksheet.get_all_records())
|
49 |
+
props_frame_hold.rename(columns={"Names": "Player"}, inplace = True)
|
50 |
+
props_frame_hold = props_frame_hold[['Player', 'Team', 'BB', 'Hits', 'HRs', 'ERs', 'Ks', 'Outs', 'Fantasy', 'FD_Fantasy', 'PrizePicks']]
|
51 |
+
props_frame_hold = props_frame_hold.drop_duplicates(subset='Player')
|
52 |
+
|
53 |
+
return props_frame_hold
|
54 |
+
|
55 |
+
@st.cache_data
|
56 |
+
def load_time():
|
57 |
+
sh = gc.open_by_url(master_hold)
|
58 |
+
worksheet = sh.worksheet('Timestamp')
|
59 |
+
raw_stamp = worksheet.acell('a1').value
|
60 |
+
|
61 |
+
t_stamp = f"Last update was at {raw_stamp}"
|
62 |
+
|
63 |
+
return t_stamp
|
64 |
+
|
65 |
+
@st.cache_data
|
66 |
+
def load_hitter_props():
|
67 |
+
sh = gc.open_by_url(master_hold)
|
68 |
+
worksheet = sh.worksheet('Hitter_Stats')
|
69 |
+
props_frame_hold = pd.DataFrame(worksheet.get_all_records())
|
70 |
+
props_frame_hold.rename(columns={"Names": "Player"}, inplace = True)
|
71 |
+
props_frame_hold = props_frame_hold[['Player', 'Team', 'Walks', 'Steals', 'Hits', 'Singles', 'Doubles', 'HRs', 'RBIs', 'Runs', 'Fantasy', 'FD_Fantasy', 'PrizePicks']]
|
72 |
+
props_frame_hold['Total Bases'] = props_frame_hold['Singles'] + (props_frame_hold['Doubles'] * 2) + (props_frame_hold['HRs'] * 4)
|
73 |
+
props_frame_hold['Hits + Runs + RBIs'] = props_frame_hold['Hits'] + props_frame_hold['Runs'] + props_frame_hold['RBIs']
|
74 |
+
props_frame_hold = props_frame_hold.drop_duplicates(subset='Player')
|
75 |
+
|
76 |
+
return props_frame_hold
|
77 |
+
|
78 |
+
@st.cache_data
|
79 |
+
def load_team_table():
|
80 |
+
sh = gc.open_by_url(master_hold)
|
81 |
+
worksheet = sh.worksheet('Game_Betting_Model')
|
82 |
+
team_frame = pd.DataFrame(worksheet.get_all_records())
|
83 |
+
team_frame = team_frame.drop_duplicates(subset='Names')
|
84 |
+
team_frame['Win Percentage'] = team_frame['Win Percentage'].str.replace('%', '').astype('float')/100
|
85 |
+
team_frame['Cover Spread Percentage'] = team_frame['Cover Spread Percentage'].str.replace('%', '').astype('float')/100
|
86 |
+
|
87 |
+
return team_frame
|
88 |
+
|
89 |
+
@st.cache_data
|
90 |
+
def load_strikeout_props():
|
91 |
+
sh = gc.open_by_url(master_hold)
|
92 |
+
worksheet = sh.worksheet('Strikeout_Props')
|
93 |
+
prop_type_frame = pd.DataFrame(worksheet.get_all_records())
|
94 |
+
prop_type_frame = prop_type_frame.drop_duplicates(subset='Player')
|
95 |
+
|
96 |
+
return prop_type_frame
|
97 |
+
|
98 |
+
@st.cache_data
|
99 |
+
def load_total_outs_props():
|
100 |
+
sh = gc.open_by_url(master_hold)
|
101 |
+
worksheet = sh.worksheet('Total_Outs_Props')
|
102 |
+
prop_type_frame = pd.DataFrame(worksheet.get_all_records())
|
103 |
+
prop_type_frame = prop_type_frame.drop_duplicates(subset='Player')
|
104 |
+
|
105 |
+
return prop_type_frame
|
106 |
+
|
107 |
+
@st.cache_data
|
108 |
+
def load_total_bases_props():
|
109 |
+
sh = gc.open_by_url(master_hold)
|
110 |
+
worksheet = sh.worksheet('Total_Base_Props')
|
111 |
+
prop_type_frame = pd.DataFrame(worksheet.get_all_records())
|
112 |
+
prop_type_frame = prop_type_frame.drop_duplicates(subset='Player')
|
113 |
+
|
114 |
+
return prop_type_frame
|
115 |
+
|
116 |
+
@st.cache_data
|
117 |
+
def load_stolen_bases_props():
|
118 |
+
sh = gc.open_by_url(master_hold)
|
119 |
+
worksheet = sh.worksheet('SB_Props')
|
120 |
+
prop_type_frame = pd.DataFrame(worksheet.get_all_records())
|
121 |
+
prop_type_frame = prop_type_frame.drop_duplicates(subset='Player')
|
122 |
+
|
123 |
+
return prop_type_frame
|
124 |
+
|
125 |
+
pitcher_frame_hold = load_pitcher_props()
|
126 |
+
hitter_frame_hold = load_hitter_props()
|
127 |
+
team_frame_hold = load_team_table()
|
128 |
+
t_stamp = load_time()
|
129 |
+
|
130 |
+
tab1, tab2, tab3, tab4, tab5 = st.tabs(["Game Betting Model", "Pitcher Prop Projections", "Hitter Prop Projections", "Player Prop Simulations", "Stat Specific Simulations"])
|
131 |
+
|
132 |
+
def convert_df_to_csv(df):
|
133 |
+
return df.to_csv().encode('utf-8')
|
134 |
+
|
135 |
+
with tab1:
|
136 |
+
st.info(t_stamp)
|
137 |
+
if st.button("Reset Data", key='reset1'):
|
138 |
+
st.cache_data.clear()
|
139 |
+
pitcher_frame_hold = load_pitcher_props()
|
140 |
+
hitter_frame_hold = load_hitter_props()
|
141 |
+
team_frame_hold = load_team_table()
|
142 |
+
t_stamp = load_time()
|
143 |
+
line_var1 = st.radio('How would you like to display odds?', options = ['Percentage', 'American'], key='line_var1')
|
144 |
+
team_frame = team_frame_hold
|
145 |
+
if line_var1 == 'Percentage':
|
146 |
+
team_frame = team_frame[['Names', 'Game', 'Win Percentage', 'Spread', 'Cover Spread Percentage', 'Avg Score', 'Game Total', 'Avg Fifth Inning', 'Fifth Inning Lead Percentage']]
|
147 |
+
team_frame = team_frame.set_index('Names')
|
148 |
+
st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(game_format, precision=2), use_container_width = True)
|
149 |
+
if line_var1 == 'American':
|
150 |
+
team_frame = team_frame[['Names', 'Game', 'American ML', 'Spread', 'American Cover', 'Avg Score', 'Game Total', 'Avg Fifth Inning', 'Fifth Inning Lead Percentage']]
|
151 |
+
team_frame.rename(columns={"American ML": "Win Percentage", "American Cover": "Cover Spread Percentage"}, inplace = True)
|
152 |
+
team_frame = team_frame.set_index('Names')
|
153 |
+
st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(american_format, precision=2), use_container_width = True)
|
154 |
+
|
155 |
+
st.download_button(
|
156 |
+
label="Export Team Model",
|
157 |
+
data=convert_df_to_csv(team_frame),
|
158 |
+
file_name='MLB_team_betting_export.csv',
|
159 |
+
mime='text/csv',
|
160 |
+
key='team_export',
|
161 |
+
)
|
162 |
+
|
163 |
+
with tab2:
|
164 |
+
st.info(t_stamp)
|
165 |
+
if st.button("Reset Data", key='reset2'):
|
166 |
+
st.cache_data.clear()
|
167 |
+
pitcher_frame_hold = load_pitcher_props()
|
168 |
+
hitter_frame_hold = load_hitter_props()
|
169 |
+
team_frame_hold = load_team_table()
|
170 |
+
t_stamp = load_time()
|
171 |
+
split_var1 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var1')
|
172 |
+
if split_var1 == 'Specific Teams':
|
173 |
+
team_var1 = st.multiselect('Which teams would you like to include in the tables?', options = pitcher_frame_hold['Team'].unique(), key='team_var1')
|
174 |
+
elif split_var1 == 'All':
|
175 |
+
team_var1 = pitcher_frame_hold.Team.values.tolist()
|
176 |
+
pitcher_frame_hold = pitcher_frame_hold[pitcher_frame_hold['Team'].isin(team_var1)]
|
177 |
+
pitcher_frame = pitcher_frame_hold.set_index('Player')
|
178 |
+
pitcher_frame = pitcher_frame.sort_values(by='Ks', ascending=False)
|
179 |
+
st.dataframe(pitcher_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
|
180 |
+
st.download_button(
|
181 |
+
label="Export Prop Model",
|
182 |
+
data=convert_df_to_csv(pitcher_frame),
|
183 |
+
file_name='MLB_pitcher_prop_export.csv',
|
184 |
+
mime='text/csv',
|
185 |
+
key='pitcher_prop_export',
|
186 |
+
)
|
187 |
+
|
188 |
+
with tab3:
|
189 |
+
st.info(t_stamp)
|
190 |
+
if st.button("Reset Data", key='reset3'):
|
191 |
+
st.cache_data.clear()
|
192 |
+
pitcher_frame_hold = load_pitcher_props()
|
193 |
+
hitter_frame_hold = load_hitter_props()
|
194 |
+
team_frame_hold = load_team_table()
|
195 |
+
t_stamp = load_time()
|
196 |
+
split_var2 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var2')
|
197 |
+
if split_var2 == 'Specific Teams':
|
198 |
+
team_var2 = st.multiselect('Which teams would you like to include in the tables?', options = hitter_frame_hold['Team'].unique(), key='team_var2')
|
199 |
+
elif split_var2 == 'All':
|
200 |
+
team_var2 = hitter_frame_hold.Team.values.tolist()
|
201 |
+
hitter_frame_hold = hitter_frame_hold[hitter_frame_hold['Team'].isin(team_var2)]
|
202 |
+
hitter_frame = hitter_frame_hold.set_index('Player')
|
203 |
+
hitter_frame = hitter_frame.sort_values(by='Hits + Runs + RBIs', ascending=False)
|
204 |
+
st.dataframe(hitter_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
|
205 |
+
st.download_button(
|
206 |
+
label="Export Prop Model",
|
207 |
+
data=convert_df_to_csv(hitter_frame),
|
208 |
+
file_name='MLB_hitter_prop_export.csv',
|
209 |
+
mime='text/csv',
|
210 |
+
key='hitter_prop_export',
|
211 |
+
)
|
212 |
+
|
213 |
+
with tab4:
|
214 |
+
st.info(t_stamp)
|
215 |
+
if st.button("Reset Data", key='reset4'):
|
216 |
+
st.cache_data.clear()
|
217 |
+
pitcher_frame_hold = load_pitcher_props()
|
218 |
+
hitter_frame_hold = load_hitter_props()
|
219 |
+
team_frame_hold = load_team_table()
|
220 |
+
t_stamp = load_time()
|
221 |
+
col1, col2 = st.columns([1, 5])
|
222 |
+
|
223 |
+
with col2:
|
224 |
+
df_hold_container = st.empty()
|
225 |
+
info_hold_container = st.empty()
|
226 |
+
plot_hold_container = st.empty()
|
227 |
+
|
228 |
+
with col1:
|
229 |
+
prop_group_var = st.selectbox('What kind of props are you simulating?', options = ['Pitchers', 'Hitters'])
|
230 |
+
if prop_group_var == 'Pitchers':
|
231 |
+
player_check = st.selectbox('Select player to simulate props', options = pitcher_frame_hold['Player'].unique())
|
232 |
+
prop_type_var = st.selectbox('Select type of prop to simulate', options = ['Strikeouts', 'Walks', 'Hits', 'Homeruns', 'Earned Runs', 'Outs', 'Fantasy', 'FD_Fantasy', 'PrizePicks'])
|
233 |
+
elif prop_group_var == 'Hitters':
|
234 |
+
player_check = st.selectbox('Select player to simulate props', options = hitter_frame_hold['Player'].unique())
|
235 |
+
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'])
|
236 |
+
|
237 |
+
ou_var = st.selectbox('Select wether it is an over or under', options = ['Over', 'Under'])
|
238 |
+
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)
|
239 |
+
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)
|
240 |
+
line_var = line_var + 1
|
241 |
+
|
242 |
+
if st.button('Simulate Prop'):
|
243 |
+
with col2:
|
244 |
+
|
245 |
+
with df_hold_container.container():
|
246 |
+
|
247 |
+
if prop_group_var == 'Pitchers':
|
248 |
+
df = pitcher_frame_hold
|
249 |
+
elif prop_group_var == 'Hitters':
|
250 |
+
df = hitter_frame_hold
|
251 |
+
|
252 |
+
total_sims = 1000
|
253 |
+
|
254 |
+
df.replace("", 0, inplace=True)
|
255 |
+
|
256 |
+
player_var = df.loc[df['Player'] == player_check]
|
257 |
+
player_var = player_var.reset_index()
|
258 |
+
|
259 |
+
if prop_group_var == 'Pitchers':
|
260 |
+
if prop_type_var == "Walks":
|
261 |
+
df['Median'] = df['BB']
|
262 |
+
elif prop_type_var == "Hits":
|
263 |
+
df['Median'] = df['Hits']
|
264 |
+
elif prop_type_var == "Homeruns":
|
265 |
+
df['Median'] = df['HRs']
|
266 |
+
elif prop_type_var == "Earned Runs":
|
267 |
+
df['Median'] = df['ERs']
|
268 |
+
elif prop_type_var == "Strikeouts":
|
269 |
+
df['Median'] = df['Ks']
|
270 |
+
elif prop_type_var == "Outs":
|
271 |
+
df['Median'] = df['Outs']
|
272 |
+
elif prop_type_var == "Fantasy":
|
273 |
+
df['Median'] = df['Fantasy']
|
274 |
+
elif prop_type_var == "FD_Fantasy":
|
275 |
+
df['Median'] = df['FD_Fantasy']
|
276 |
+
elif prop_type_var == "PrizePicks":
|
277 |
+
df['Median'] = df['PrizePicks']
|
278 |
+
elif prop_group_var == 'Hitters':
|
279 |
+
if prop_type_var == "Walks":
|
280 |
+
df['Median'] = df['Walks']
|
281 |
+
elif prop_type_var == "Total Bases":
|
282 |
+
df['Median'] = df['Total Bases']
|
283 |
+
elif prop_type_var == "Hits + Runs + RBIs":
|
284 |
+
df['Median'] = df['Hits + Runs + RBIs']
|
285 |
+
elif prop_type_var == "Steals":
|
286 |
+
df['Median'] = df['Steals']
|
287 |
+
elif prop_type_var == "Hits":
|
288 |
+
df['Median'] = df['Hits']
|
289 |
+
elif prop_type_var == "Singles":
|
290 |
+
df['Median'] = df['Singles']
|
291 |
+
elif prop_type_var == "Doubles":
|
292 |
+
df['Median'] = df['Doubles']
|
293 |
+
elif prop_type_var == "Homeruns":
|
294 |
+
df['Median'] = df['HRs']
|
295 |
+
elif prop_type_var == "RBIs":
|
296 |
+
df['Median'] = df['RBIs']
|
297 |
+
elif prop_type_var == "Runs":
|
298 |
+
df['Median'] = df['Runs']
|
299 |
+
elif prop_type_var == "Fantasy":
|
300 |
+
df['Median'] = df['Fantasy']
|
301 |
+
elif prop_type_var == "FD_Fantasy":
|
302 |
+
df['Median'] = df['FD_Fantasy']
|
303 |
+
elif prop_type_var == "PrizePicks":
|
304 |
+
df['Median'] = df['PrizePicks']
|
305 |
+
|
306 |
+
flex_file = df
|
307 |
+
if prop_group_var == 'Pitchers':
|
308 |
+
flex_file['Floor'] = flex_file['Median'] * .20
|
309 |
+
flex_file['Ceiling'] = flex_file['Median'] + (flex_file['Median'] * .80)
|
310 |
+
flex_file['STD'] = flex_file['Median'] / 4
|
311 |
+
flex_file = flex_file[['Player', 'Floor', 'Median', 'Ceiling', 'STD']]
|
312 |
+
|
313 |
+
elif prop_group_var == 'Hitters':
|
314 |
+
flex_file['Floor'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * .20, 0)
|
315 |
+
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)
|
316 |
+
flex_file['STD'] = flex_file['Median'] / 1.5
|
317 |
+
flex_file = flex_file[['Player', 'Floor', 'Median', 'Ceiling', 'STD']]
|
318 |
+
|
319 |
+
hold_file = flex_file
|
320 |
+
overall_file = flex_file
|
321 |
+
salary_file = flex_file
|
322 |
+
|
323 |
+
overall_players = overall_file[['Player']]
|
324 |
+
|
325 |
+
for x in range(0,total_sims):
|
326 |
+
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
|
327 |
+
|
328 |
+
overall_file=overall_file.drop(['Player', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
|
329 |
+
overall_file.astype('int').dtypes
|
330 |
+
|
331 |
+
players_only = hold_file[['Player']]
|
332 |
+
|
333 |
+
player_outcomes = pd.merge(players_only, overall_file, left_index=True, right_index=True)
|
334 |
+
|
335 |
+
players_only['Mean_Outcome'] = overall_file.mean(axis=1)
|
336 |
+
players_only['10%'] = overall_file.quantile(0.1, axis=1)
|
337 |
+
players_only['90%'] = overall_file.quantile(0.9, axis=1)
|
338 |
+
if ou_var == 'Over':
|
339 |
+
players_only['beat_prop'] = overall_file[overall_file > prop_var].count(axis=1)/float(total_sims)
|
340 |
+
elif ou_var == 'Under':
|
341 |
+
players_only['beat_prop'] = (overall_file[overall_file < prop_var].count(axis=1)/float(total_sims))
|
342 |
+
|
343 |
+
players_only['implied_odds'] = np.where(line_var <= 0, (-(line_var)/((-(line_var))+100)), 100/(line_var+100))
|
344 |
+
|
345 |
+
players_only['Player'] = hold_file[['Player']]
|
346 |
+
|
347 |
+
final_outcomes = players_only[['Player', '10%', 'Mean_Outcome', '90%', 'implied_odds', 'beat_prop']]
|
348 |
+
final_outcomes['Bet?'] = np.where(final_outcomes['beat_prop'] - final_outcomes['implied_odds'] >= .10, "Bet", "No Bet")
|
349 |
+
final_outcomes = final_outcomes.loc[final_outcomes['Player'] == player_check]
|
350 |
+
player_outcomes = player_outcomes.loc[player_outcomes['Player'] == player_check]
|
351 |
+
player_outcomes = player_outcomes.drop(columns=['Player']).transpose()
|
352 |
+
player_outcomes = player_outcomes.reset_index()
|
353 |
+
player_outcomes.columns = ['Instance', 'Outcome']
|
354 |
+
|
355 |
+
x1 = player_outcomes.Outcome.to_numpy()
|
356 |
+
|
357 |
+
print(x1)
|
358 |
+
|
359 |
+
hist_data = [x1]
|
360 |
+
|
361 |
+
group_labels = ['player outcomes']
|
362 |
+
|
363 |
+
fig = ff.create_distplot(
|
364 |
+
hist_data, group_labels, bin_size=[.05])
|
365 |
+
fig.add_vline(x=prop_var, line_dash="dash", line_color="green")
|
366 |
+
|
367 |
+
with df_hold_container:
|
368 |
+
df_hold_container = st.empty()
|
369 |
+
format_dict = {'10%': '{:.2f}', 'Mean_Outcome': '{:.2f}','90%': '{:.2f}', 'beat_prop': '{:.2%}','implied_odds': '{:.2%}'}
|
370 |
+
st.dataframe(final_outcomes.style.format(format_dict), use_container_width = True)
|
371 |
+
|
372 |
+
with info_hold_container:
|
373 |
+
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.')
|
374 |
+
|
375 |
+
with plot_hold_container:
|
376 |
+
st.dataframe(player_outcomes, use_container_width = True)
|
377 |
+
plot_hold_container = st.empty()
|
378 |
+
st.plotly_chart(fig, use_container_width=True)
|
379 |
+
|
380 |
+
with tab5:
|
381 |
+
st.info(t_stamp)
|
382 |
+
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.')
|
383 |
+
if st.button("Reset Data/Load Data", key='reset5'):
|
384 |
+
# Clear values from *all* all in-memory and on-disk data caches:
|
385 |
+
# i.e. clear values from both square and cube
|
386 |
+
st.cache_data.clear()
|
387 |
+
t_stamp = load_time()
|
388 |
+
col1, col2 = st.columns([1, 5])
|
389 |
+
|
390 |
+
with col2:
|
391 |
+
df_hold_container = st.empty()
|
392 |
+
info_hold_container = st.empty()
|
393 |
+
plot_hold_container = st.empty()
|
394 |
+
export_container = st.empty()
|
395 |
+
|
396 |
+
with col1:
|
397 |
+
prop_type_var = st.selectbox('Select prop category', options = ['Strikeouts (Pitchers)', 'Total Outs (Pitchers)'])
|
398 |
+
|
399 |
+
if st.button('Simulate Prop Category'):
|
400 |
+
with col2:
|
401 |
+
|
402 |
+
with df_hold_container.container():
|
403 |
+
|
404 |
+
if prop_type_var == "Strikeouts (Pitchers)":
|
405 |
+
player_df = pitcher_frame_hold
|
406 |
+
prop_df = load_strikeout_props()
|
407 |
+
prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']]
|
408 |
+
prop_df.rename(columns={"over_prop": "Prop"}, inplace = True)
|
409 |
+
prop_df = prop_df.loc[prop_df['Prop'] != 0]
|
410 |
+
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))
|
411 |
+
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))
|
412 |
+
df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player'])
|
413 |
+
elif prop_type_var == "Total Outs (Pitchers)":
|
414 |
+
player_df = pitcher_frame_hold
|
415 |
+
prop_df = load_total_outs_props()
|
416 |
+
prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']]
|
417 |
+
prop_df.rename(columns={"over_prop": "Prop"}, inplace = True)
|
418 |
+
prop_df = prop_df.loc[prop_df['Prop'] != 0]
|
419 |
+
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))
|
420 |
+
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))
|
421 |
+
df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player'])
|
422 |
+
elif prop_type_var == "Total Bases (Hitters)":
|
423 |
+
player_df = hitter_frame_hold
|
424 |
+
prop_df = load_total_bases_props()
|
425 |
+
prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']]
|
426 |
+
prop_df.rename(columns={"over_prop": "Prop"}, inplace = True)
|
427 |
+
prop_df = prop_df.loc[prop_df['Prop'] != 0]
|
428 |
+
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))
|
429 |
+
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))
|
430 |
+
df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player'])
|
431 |
+
elif prop_type_var == "Stolen Bases (Hitters)":
|
432 |
+
player_df = hitter_frame_hold
|
433 |
+
prop_df = load_stolen_base_props()
|
434 |
+
prop_df = prop_df[['Player', 'over_prop', 'over_line', 'under_line']]
|
435 |
+
prop_df.rename(columns={"over_prop": "Prop"}, inplace = True)
|
436 |
+
prop_df = prop_df.loc[prop_df['Prop'] != 0]
|
437 |
+
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))
|
438 |
+
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))
|
439 |
+
df = pd.merge(player_df, prop_df, how='left', left_on=['Player'], right_on = ['Player'])
|
440 |
+
|
441 |
+
prop_dict = dict(zip(df.Player, df.Prop))
|
442 |
+
over_dict = dict(zip(df.Player, df.Over))
|
443 |
+
under_dict = dict(zip(df.Player, df.Under))
|
444 |
+
|
445 |
+
total_sims = 1000
|
446 |
+
|
447 |
+
df.replace("", 0, inplace=True)
|
448 |
+
|
449 |
+
if prop_type_var == "Strikeouts (Pitchers)":
|
450 |
+
df['Median'] = df['Ks']
|
451 |
+
elif prop_type_var == "Total Outs (Pitchers)":
|
452 |
+
df['Median'] = df['Outs']
|
453 |
+
elif prop_type_var == "Total Bases (Hitters)":
|
454 |
+
df['Median'] = df['Total Bases']
|
455 |
+
elif prop_type_var == "Stolen Bases (Hitters)":
|
456 |
+
df['Median'] = df['Stolen Bases (Hitters)']
|
457 |
+
|
458 |
+
flex_file = df
|
459 |
+
if prop_type_var == 'Strikeouts (Pitchers)':
|
460 |
+
flex_file['Floor'] = flex_file['Median'] * .20
|
461 |
+
flex_file['Ceiling'] = flex_file['Median'] + (flex_file['Median'] * .80)
|
462 |
+
flex_file['STD'] = flex_file['Median'] / 4
|
463 |
+
flex_file['Prop'] = flex_file['Player'].map(prop_dict)
|
464 |
+
flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']]
|
465 |
+
|
466 |
+
elif prop_type_var == 'Total Outs (Pitchers)':
|
467 |
+
flex_file['Floor'] = flex_file['Median'] * .20
|
468 |
+
flex_file['Ceiling'] = flex_file['Median'] + (flex_file['Median'] * .80)
|
469 |
+
flex_file['STD'] = flex_file['Median'] / 4
|
470 |
+
flex_file['Prop'] = flex_file['Player'].map(prop_dict)
|
471 |
+
flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']]
|
472 |
+
|
473 |
+
elif prop_type_var == 'Total Bases (Hitters)':
|
474 |
+
flex_file['Floor'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * .20, 0)
|
475 |
+
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)
|
476 |
+
flex_file['STD'] = flex_file['Median'] / 1.5
|
477 |
+
flex_file['Prop'] = flex_file['Player'].map(prop_dict)
|
478 |
+
flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']]
|
479 |
+
|
480 |
+
elif prop_type_var == 'Stolen Bases (Hitters)':
|
481 |
+
flex_file['Floor'] = np.where((prop_type_var == "Fantasy") | (prop_type_var == "FD_Fantasy") | (prop_type_var == "PrizePicks"), flex_file['Median'] * .20, 0)
|
482 |
+
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)
|
483 |
+
flex_file['STD'] = flex_file['Median'] / 1.5
|
484 |
+
flex_file['Prop'] = flex_file['Player'].map(prop_dict)
|
485 |
+
flex_file = flex_file[['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']]
|
486 |
+
|
487 |
+
hold_file = flex_file
|
488 |
+
overall_file = flex_file
|
489 |
+
prop_file = flex_file
|
490 |
+
|
491 |
+
overall_players = overall_file[['Player']]
|
492 |
+
|
493 |
+
for x in range(0,total_sims):
|
494 |
+
prop_file[x] = prop_file['Prop']
|
495 |
+
|
496 |
+
prop_file = prop_file.drop(['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
|
497 |
+
|
498 |
+
for x in range(0,total_sims):
|
499 |
+
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
|
500 |
+
|
501 |
+
overall_file=overall_file.drop(['Player', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
|
502 |
+
|
503 |
+
players_only = hold_file[['Player']]
|
504 |
+
|
505 |
+
player_outcomes = pd.merge(players_only, overall_file, left_index=True, right_index=True)
|
506 |
+
|
507 |
+
prop_check = (overall_file - prop_file)
|
508 |
+
|
509 |
+
players_only['Mean_Outcome'] = overall_file.mean(axis=1)
|
510 |
+
players_only['10%'] = overall_file.quantile(0.1, axis=1)
|
511 |
+
players_only['90%'] = overall_file.quantile(0.9, axis=1)
|
512 |
+
players_only['Over'] = prop_check[prop_check > 0].count(axis=1)/float(total_sims)
|
513 |
+
players_only['Imp Over'] = players_only['Player'].map(over_dict)
|
514 |
+
players_only['Over%'] = players_only[["Over", "Imp Over"]].mean(axis=1)
|
515 |
+
players_only['Under'] = prop_check[prop_check < 0].count(axis=1)/float(total_sims)
|
516 |
+
players_only['Imp Under'] = players_only['Player'].map(under_dict)
|
517 |
+
players_only['Under%'] = players_only[["Under", "Imp Under"]].mean(axis=1)
|
518 |
+
players_only['Prop'] = players_only['Player'].map(prop_dict)
|
519 |
+
players_only['Prop_avg'] = players_only['Prop'].mean() / 100
|
520 |
+
players_only['prop_threshold'] = .10
|
521 |
+
players_only = players_only.loc[players_only['Mean_Outcome'] > 0]
|
522 |
+
players_only['Over_diff'] = players_only['Over%'] - players_only['Imp Over']
|
523 |
+
players_only['Under_diff'] = players_only['Under%'] - players_only['Imp Under']
|
524 |
+
players_only['Bet_check'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], players_only['Over_diff'] , players_only['Under_diff'])
|
525 |
+
players_only['Bet_suggest'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], "Over" , "Under")
|
526 |
+
players_only['Bet?'] = np.where(players_only['Bet_check'] >= players_only['prop_threshold'], players_only['Bet_suggest'], "No Bet")
|
527 |
+
players_only['Edge'] = players_only['Bet_check']
|
528 |
+
|
529 |
+
players_only['Player'] = hold_file[['Player']]
|
530 |
+
|
531 |
+
final_outcomes = players_only[['Player', 'Prop', 'Mean_Outcome', 'Imp Over', 'Over%', 'Imp Under', 'Under%', 'Bet?', 'Edge']]
|
532 |
+
|
533 |
+
final_outcomes = final_outcomes.sort_values(by='Edge', ascending=False)
|
534 |
+
|
535 |
+
final_outcomes = final_outcomes.set_index('Player')
|
536 |
+
|
537 |
+
with df_hold_container:
|
538 |
+
df_hold_container = st.empty()
|
539 |
+
st.dataframe(final_outcomes.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
|
540 |
+
with export_container:
|
541 |
+
export_container = st.empty()
|
542 |
+
st.download_button(
|
543 |
+
label="Export Projections",
|
544 |
+
data=convert_df_to_csv(final_outcomes),
|
545 |
+
file_name='MLB_DFS_prop_proj.csv',
|
546 |
+
mime='text/csv',
|
547 |
+
key='prop_proj',
|
548 |
+
)
|
549 |
+
|