File size: 35,232 Bytes
0ee5ebe 1ebaea5 0ee5ebe dbcb21f 0ee5ebe dbcb21f 0ee5ebe dbcb21f 0ee5ebe 5729f79 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 4ec0563 0ee5ebe 68365d9 dbcb21f 0ee5ebe 2edf337 0ee5ebe 4ec0563 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 56ae43b 0ee5ebe dbcb21f 0ee5ebe 5729f79 2edf337 0ee5ebe dbcb21f 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe dbcb21f 5729f79 2edf337 0ee5ebe dbcb21f 0ee5ebe dbcb21f 0ee5ebe c59164f 0ee5ebe 871761f 0ee5ebe 2edf337 0ee5ebe 2edf337 5c74524 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 68365d9 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 c59164f 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 c59164f 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 c59164f 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 68365d9 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 12a4292 2edf337 0ee5ebe 2edf337 0ee5ebe 5fa8f55 c59164f 0ee5ebe 64de8fe 5fa8f55 64de8fe 23003f7 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 23003f7 64de8fe 23003f7 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 5fa8f55 64de8fe 23003f7 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 5fa8f55 64de8fe 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 5fa8f55 64de8fe 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 5fa8f55 64de8fe 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 5fa8f55 64de8fe 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 2edf337 0ee5ebe 5fa8f55 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 |
import streamlit as st
st.set_page_config(layout="wide")
import numpy as np
import pandas as pd
import gspread
import pymongo
import time
@st.cache_resource
def init_conn():
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = {
"type": "service_account",
"project_id": "model-sheets-connect",
"private_key_id": st.secrets['model_sheets_connect_pk'],
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDiu1v/e6KBKOcK\ncx0KQ23nZK3ZVvADYy8u/RUn/EDI82QKxTd/DizRLIV81JiNQxDJXSzgkbwKYEDm\n48E8zGvupU8+Nk76xNPakrQKy2Y8+VJlq5psBtGchJTuUSHcXU5Mg2JhQsB376PJ\nsCw552K6Pw8fpeMDJDZuxpKSkaJR6k9G5Dhf5q8HDXnC5Rh/PRFuKJ2GGRpX7n+2\nhT/sCax0J8jfdTy/MDGiDfJqfQrOPrMKELtsGHR9Iv6F4vKiDqXpKfqH+02E9ptz\nBk+MNcbZ3m90M8ShfRu28ebebsASfarNMzc3dk7tb3utHOGXKCf4tF8yYKo7x8BZ\noO9X4gSfAgMBAAECggEAU8ByyMpSKlTCF32TJhXnVJi/kS+IhC/Qn5JUDMuk4LXr\naAEWsWO6kV/ZRVXArjmuSzuUVrXumISapM9Ps5Ytbl95CJmGDiLDwRL815nvv6k3\nUyAS8EGKjz74RpoIoH6E7EWCAzxlnUgTn+5oP9Flije97epYk3H+e2f1f5e1Nn1d\nYNe8U+1HqJgILcxA1TAUsARBfoD7+K3z/8DVPHI8IpzAh6kTHqhqC23Rram4XoQ6\nzj/ZdVBjvnKuazETfsD+Vl3jGLQA8cKQVV70xdz3xwLcNeHsbPbpGBpZUoF73c65\nkAXOrjYl0JD5yAk+hmYhXr6H9c6z5AieuZGDrhmlFQKBgQDzV6LRXmjn4854DP/J\nI82oX2GcI4eioDZPRukhiQLzYerMQBmyqZIRC+/LTCAhYQSjNgMa+ZKyvLqv48M0\n/x398op/+n3xTs+8L49SPI48/iV+mnH7k0WI/ycd4OOKh8rrmhl/0EWb9iitwJYe\nMjTV/QxNEpPBEXfR1/mvrN/lVQKBgQDuhomOxUhWVRVH6x03slmyRBn0Oiw4MW+r\nrt1hlNgtVmTc5Mu+4G0USMZwYuOB7F8xG4Foc7rIlwS7Ic83jMJxemtqAelwOLdV\nXRLrLWJfX8+O1z/UE15l2q3SUEnQ4esPHbQnZowHLm0mdL14qSVMl1mu1XfsoZ3z\nJZTQb48CIwKBgEWbzQRtKD8lKDupJEYqSrseRbK/ax43DDITS77/DWwHl33D3FYC\nMblUm8ygwxQpR4VUfwDpYXBlklWcJovzamXpSnsfcYVkkQH47NuOXPXPkXQsw+w+\nDYcJzeu7F/vZqk9I7oBkWHUrrik9zPNoUzrfPvSRGtkAoTDSwibhoc5dAoGBAMHE\nK0T/ANeZQLNuzQps6S7G4eqjwz5W8qeeYxsdZkvWThOgDd/ewt3ijMnJm5X05hOn\ni4XF1euTuvUl7wbqYx76Wv3/1ZojiNNgy7ie4rYlyB/6vlBS97F4ZxJdxMlabbCW\n6b3EMWa4EVVXKoA1sCY7IVDE+yoQ1JYsZmq45YzPAoGBANWWHuVueFGZRDZlkNlK\nh5OmySmA0NdNug3G1upaTthyaTZ+CxGliwBqMHAwpkIRPwxUJpUwBTSEGztGTAxs\nWsUOVWlD2/1JaKSmHE8JbNg6sxLilcG6WEDzxjC5dLL1OrGOXj9WhC9KX3sq6qb6\nF/j9eUXfXjAlb042MphoF3ZC\n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "100369174533302798535",
"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%40model-sheets-connect.iam.gserviceaccount.com"
}
credentials2 = {
"type": "service_account",
"project_id": "sheets-api-connect-378620",
"private_key_id": st.secrets['sheets_api_connect_pk'],
"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"
}
uri = st.secrets['mongo_uri']
client = pymongo.MongoClient(uri, retryWrites=True, serverSelectionTimeoutMS=500000)
db = client["League_of_Legends"]
LOL_Data = st.secrets['LOL_Data']
gc = gspread.service_account_from_dict(credentials)
gc2 = gspread.service_account_from_dict(credentials2)
return gc, gc2, db, LOL_Data
gcservice_account, gcservice_account2, db, LOL_Data = init_conn()
percentages_format = {'Exposure': '{:.2%}'}
freq_format = {'Exposure': '{:.2%}', 'Proj Own': '{:.2%}', 'Edge': '{:.2%}'}
dk_columns = ['CPT', 'TOP', 'JNG', 'MID', 'ADC', 'SUP', 'TEAM', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']
fd_columns = ['CPT', 'TOP', 'JNG', 'MID', 'ADC', 'SUP', 'TEAM', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']
@st.cache_data(ttl = 599)
def init_DK_seed_frames():
collection = db["League_of_Legends_DK_seed_frame"]
cursor = collection.find()
raw_display = pd.DataFrame(list(cursor))
raw_display = raw_display[['CPT', 'TOP', 'JNG', 'MID', 'ADC', 'SUP', 'TEAM', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
raw_display['CPT'] = raw_display['CPT'].astype(str)
raw_display['TOP'] = raw_display['TOP'].astype(str)
raw_display['JNG'] = raw_display['JNG'].astype(str)
raw_display['MID'] = raw_display['MID'].astype(str)
raw_display['ADC'] = raw_display['ADC'].astype(str)
raw_display['SUP'] = raw_display['SUP'].astype(str)
raw_display['TEAM'] = raw_display['TEAM'].astype(str)
DK_seed = raw_display.to_numpy()
return DK_seed
@st.cache_data(ttl = 599)
def init_baselines():
try:
sh = gcservice_account.open_by_url(LOL_Data)
except:
sh = gcservice_account2.open_by_url(LOL_Data)
worksheet = sh.worksheet('ROO')
load_display = pd.DataFrame(worksheet.get_all_records())
load_display.replace('', np.nan, inplace=True)
load_display['Player'] = load_display['Player'].astype(str)
load_display['STDev'] = load_display['Median'] / 4
load_display = load_display.drop_duplicates(subset=['Player'], keep='first')
dk_raw = load_display.dropna(subset=['Median'])
return dk_raw
@st.cache_data
def convert_df(array):
array = pd.DataFrame(array, columns=column_names)
return array.to_csv().encode('utf-8')
@st.cache_data
def calculate_DK_value_frequencies(np_array):
unique, counts = np.unique(np_array[:, :6], return_counts=True)
frequencies = counts / len(np_array) # Normalize by the number of rows
combined_array = np.column_stack((unique, frequencies))
return combined_array
@st.cache_data
def calculate_FD_value_frequencies(np_array):
unique, counts = np.unique(np_array[:, :6], return_counts=True)
frequencies = counts / len(np_array) # Normalize by the number of rows
combined_array = np.column_stack((unique, frequencies))
return combined_array
@st.cache_data
def sim_contest(Sim_size, seed_frame, maps_dict, sharp_split, Contest_Size):
SimVar = 1
Sim_Winners = []
fp_array = seed_frame[:sharp_split, :]
# Pre-vectorize functions
vec_projection_map = np.vectorize(maps_dict['Projection_map'].__getitem__)
vec_stdev_map = np.vectorize(maps_dict['STDev_map'].__getitem__)
st.write('Simulating contest on frames')
while SimVar <= Sim_size:
fp_random = fp_array[np.random.choice(fp_array.shape[0], Contest_Size)]
sample_arrays1 = np.c_[
fp_random,
np.sum(np.random.normal(
loc=vec_projection_map(fp_random[:, :-7]),
scale=vec_stdev_map(fp_random[:, :-7])),
axis=1)
]
sample_arrays = sample_arrays1
final_array = sample_arrays[sample_arrays[:, 7].argsort()[::-1]]
best_lineup = final_array[final_array[:, -1].argsort(kind='stable')[::-1][:1]]
Sim_Winners.append(best_lineup)
SimVar += 1
return Sim_Winners
DK_seed = init_DK_seed_frames()
dk_raw = init_baselines()
tab1, tab2 = st.tabs(['Contest Sims', 'Data Export'])
with tab2:
col1, col2 = st.columns([1, 7])
with col1:
if st.button("Load/Reset Data", key='reset1'):
st.cache_data.clear()
for key in st.session_state.keys():
del st.session_state[key]
DK_seed = init_DK_seed_frames()
dk_raw = init_baselines()
slate_var1 = st.radio("Which data are you loading?", ('LCK', 'LEC', 'LCS'))
site_var1 = st.radio("What site are you working with?", ('Draftkings'))
if site_var1 == 'Draftkings':
raw_baselines = dk_raw[dk_raw['league'] == slate_var1]
column_names = dk_columns
team_var1 = st.radio("Do you want a frame with specific teams?", ('Full Slate', 'Specific Teams'), key='team_var1')
if team_var1 == 'Specific Teams':
team_var2 = st.multiselect('Which teams do you want?', options = dk_raw['Team'].unique())
elif team_var1 == 'Full Slate':
team_var2 = dk_raw.Team.values.tolist()
stack_var1 = st.radio("Do you want a frame with specific stack sizes?", ('Full Slate', 'Specific Stack Sizes'), key='stack_var1')
if stack_var1 == 'Specific Stack Sizes':
stack_var2 = st.multiselect('Which stack sizes do you want?', options = [4, 3, 2, 1, 0])
elif stack_var1 == 'Full Slate':
stack_var2 = [4, 3, 2, 1, 0]
if st.button("Prepare data export", key='data_export'):
data_export = st.session_state.working_seed.copy()
st.download_button(
label="Export optimals set",
data=convert_df(data_export),
file_name='LOL_optimals_export.csv',
mime='text/csv',
)
with col2:
if st.button("Load Data", key='load_data'):
if site_var1 == 'Draftkings':
if 'working_seed' in st.session_state:
st.session_state.working_seed = st.session_state.working_seed[np.isin(st.session_state.working_seed[:, 8], team_var2)]
st.session_state.working_seed = st.session_state.working_seed[np.isin(st.session_state.working_seed[:, 9], stack_var2)]
st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:1000], columns=column_names)
elif 'working_seed' not in st.session_state:
st.session_state.working_seed = DK_seed.copy()
st.session_state.working_seed = st.session_state.working_seed[np.isin(st.session_state.working_seed[:, 8], team_var2)]
st.session_state.working_seed = st.session_state.working_seed[np.isin(st.session_state.working_seed[:, 9], stack_var2)]
st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:1000], columns=column_names)
with st.container():
if 'data_export_display' in st.session_state:
st.dataframe(st.session_state.data_export_display.style.format(freq_format, precision=2), use_container_width = True)
with tab1:
col1, col2 = st.columns([1, 7])
with col1:
if st.button("Load/Reset Data", key='reset2'):
st.cache_data.clear()
for key in st.session_state.keys():
del st.session_state[key]
DK_seed = init_DK_seed_frames()
dk_raw = init_baselines()
sim_slate_var1 = st.radio("Which data are you loading?", ('LCK', 'LEC', 'LCS'), key='sim_slate_var1')
sim_site_var1 = st.radio("What site are you working with?", ('Draftkings'), key='sim_site_var1')
if sim_site_var1 == 'Draftkings':
raw_baselines = dk_raw[dk_raw['league'] == sim_slate_var1]
column_names = dk_columns
contest_var1 = st.selectbox("What contest size are you simulating?", ('Small', 'Medium', 'Large', 'Custom'))
if contest_var1 == 'Small':
Contest_Size = 1000
elif contest_var1 == 'Medium':
Contest_Size = 5000
elif contest_var1 == 'Large':
Contest_Size = 10000
elif contest_var1 == 'Custom':
Contest_Size = st.number_input("Insert contest size", value=100, placeholder="Type a number under 10,000...")
strength_var1 = st.selectbox("How sharp is the field in the contest?", ('Very', 'Above Average', 'Average', 'Below Average', 'Not Very'))
if strength_var1 == 'Not Very':
sharp_split = 500000
elif strength_var1 == 'Below Average':
sharp_split = 400000
elif strength_var1 == 'Average':
sharp_split = 300000
elif strength_var1 == 'Above Average':
sharp_split = 200000
elif strength_var1 == 'Very':
sharp_split = 100000
with col2:
if st.button("Run Contest Sim"):
if 'working_seed' in st.session_state:
maps_dict = {
'Projection_map':dict(zip(raw_baselines.Player,raw_baselines.Median)),
'Salary_map':dict(zip(raw_baselines.Player,raw_baselines.Salary)),
'Pos_map':dict(zip(raw_baselines.Player,raw_baselines.Position)),
'Own_map':dict(zip(raw_baselines.Player,raw_baselines['Own'])),
'Team_map':dict(zip(raw_baselines.Player,raw_baselines.Team)),
'STDev_map':dict(zip(raw_baselines.Player,raw_baselines.STDev))
}
Sim_Winners = sim_contest(1000, st.session_state.working_seed, maps_dict, sharp_split, Contest_Size)
Sim_Winner_Frame = pd.DataFrame(np.concatenate(Sim_Winners))
# Initial setup
Sim_Winner_Frame = pd.DataFrame(np.concatenate(Sim_Winners), columns=column_names + ['Fantasy'])
Sim_Winner_Frame['GPP_Proj'] = (Sim_Winner_Frame['proj'] + Sim_Winner_Frame['Fantasy']) / 2
Sim_Winner_Frame['unique_id'] = Sim_Winner_Frame['proj'].astype(str) + Sim_Winner_Frame['salary'].astype(str) + Sim_Winner_Frame['Team'].astype(str) + Sim_Winner_Frame['Secondary'].astype(str)
Sim_Winner_Frame = Sim_Winner_Frame.assign(win_count=Sim_Winner_Frame['unique_id'].map(Sim_Winner_Frame['unique_id'].value_counts()))
# Type Casting
type_cast_dict = {'salary': int, 'proj': np.float16, 'Fantasy': np.float16, 'GPP_Proj': np.float32, 'Own': np.float32}
Sim_Winner_Frame = Sim_Winner_Frame.astype(type_cast_dict)
# Sorting
st.session_state.Sim_Winner_Frame = Sim_Winner_Frame.sort_values(by=['win_count', 'GPP_Proj'], ascending= [False, False]).copy().drop_duplicates(subset='unique_id').head(100)
st.session_state.Sim_Winner_Frame.drop(columns='unique_id', inplace=True)
# Data Copying
st.session_state.Sim_Winner_Export = Sim_Winner_Frame.copy()
# Data Copying
st.session_state.Sim_Winner_Display = Sim_Winner_Frame.copy()
else:
if sim_site_var1 == 'Draftkings':
st.session_state.working_seed = DK_seed.copy()
maps_dict = {
'Projection_map':dict(zip(raw_baselines.Player,raw_baselines.Median)),
'Salary_map':dict(zip(raw_baselines.Player,raw_baselines.Salary)),
'Pos_map':dict(zip(raw_baselines.Player,raw_baselines.Position)),
'Own_map':dict(zip(raw_baselines.Player,raw_baselines['Own'])),
'Team_map':dict(zip(raw_baselines.Player,raw_baselines.Team)),
'STDev_map':dict(zip(raw_baselines.Player,raw_baselines.STDev))
}
Sim_Winners = sim_contest(1000, st.session_state.working_seed, maps_dict, sharp_split, Contest_Size)
Sim_Winner_Frame = pd.DataFrame(np.concatenate(Sim_Winners))
# Initial setup
Sim_Winner_Frame = pd.DataFrame(np.concatenate(Sim_Winners), columns=column_names + ['Fantasy'])
Sim_Winner_Frame['GPP_Proj'] = (Sim_Winner_Frame['proj'] + Sim_Winner_Frame['Fantasy']) / 2
Sim_Winner_Frame['unique_id'] = Sim_Winner_Frame['proj'].astype(str) + Sim_Winner_Frame['salary'].astype(str) + Sim_Winner_Frame['Team'].astype(str) + Sim_Winner_Frame['Secondary'].astype(str)
Sim_Winner_Frame = Sim_Winner_Frame.assign(win_count=Sim_Winner_Frame['unique_id'].map(Sim_Winner_Frame['unique_id'].value_counts()))
# Type Casting
type_cast_dict = {'salary': int, 'proj': np.float16, 'Fantasy': np.float16, 'GPP_Proj': np.float32, 'Own': np.float32}
Sim_Winner_Frame = Sim_Winner_Frame.astype(type_cast_dict)
# Sorting
st.session_state.Sim_Winner_Frame = Sim_Winner_Frame.sort_values(by=['win_count', 'GPP_Proj'], ascending= [False, False]).copy().drop_duplicates(subset='unique_id').head(100)
st.session_state.Sim_Winner_Frame.drop(columns='unique_id', inplace=True)
# Data Copying
st.session_state.Sim_Winner_Export = Sim_Winner_Frame.copy()
# Data Copying
st.session_state.Sim_Winner_Display = Sim_Winner_Frame.copy()
freq_copy = st.session_state.Sim_Winner_Display
if sim_site_var1 == 'Draftkings':
freq_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,0:7].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
freq_working['Freq'] = freq_working['Freq'].astype(int)
freq_working['Position'] = freq_working['Player'].map(maps_dict['Pos_map'])
freq_working['Salary'] = freq_working['Player'].map(maps_dict['Salary_map'])
freq_working['Proj Own'] = freq_working['Player'].map(maps_dict['Own_map']) / 100
freq_working['Exposure'] = freq_working['Freq']/(1000)
freq_working['Edge'] = freq_working['Exposure'] - freq_working['Proj Own']
freq_working['Team'] = freq_working['Player'].map(maps_dict['Team_map'])
st.session_state.player_freq = freq_working.copy()
if sim_site_var1 == 'Draftkings':
cpt_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,0:1].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
cpt_working['Freq'] = cpt_working['Freq'].astype(int)
cpt_working['Position'] = cpt_working['Player'].map(maps_dict['Pos_map'])
cpt_working['Salary'] = cpt_working['Player'].map(maps_dict['Salary_map'])
cpt_working['Proj Own'] = cpt_working['Player'].map(maps_dict['Own_map']) / 600
cpt_working['Exposure'] = cpt_working['Freq']/(1000)
cpt_working['Edge'] = cpt_working['Exposure'] - cpt_working['Proj Own']
cpt_working['Team'] = cpt_working['Player'].map(maps_dict['Team_map'])
st.session_state.cpt_freq = cpt_working.copy()
if sim_site_var1 == 'Draftkings':
top_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,1:2].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
top_working['Freq'] = top_working['Freq'].astype(int)
top_working['Position'] = top_working['Player'].map(maps_dict['Pos_map'])
top_working['Salary'] = top_working['Player'].map(maps_dict['Salary_map'])
top_working['Proj Own'] = top_working['Player'].map(maps_dict['Own_map']) / 105
top_working['Exposure'] = top_working['Freq']/(1000)
top_working['Edge'] = top_working['Exposure'] - top_working['Proj Own']
top_working['Team'] = top_working['Player'].map(maps_dict['Team_map'])
st.session_state.top_freq = top_working.copy()
if sim_site_var1 == 'Draftkings':
jng_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,2:3].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
jng_working['Freq'] = jng_working['Freq'].astype(int)
jng_working['Position'] = jng_working['Player'].map(maps_dict['Pos_map'])
jng_working['Salary'] = jng_working['Player'].map(maps_dict['Salary_map'])
jng_working['Proj Own'] = jng_working['Player'].map(maps_dict['Own_map']) / 135
jng_working['Exposure'] = jng_working['Freq']/(1000)
jng_working['Edge'] = jng_working['Exposure'] - jng_working['Proj Own']
jng_working['Team'] = jng_working['Player'].map(maps_dict['Team_map'])
st.session_state.jng_freq = jng_working.copy()
if sim_site_var1 == 'Draftkings':
mid_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,3:4].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
mid_working['Freq'] = mid_working['Freq'].astype(int)
mid_working['Position'] = mid_working['Player'].map(maps_dict['Pos_map'])
mid_working['Salary'] = mid_working['Player'].map(maps_dict['Salary_map'])
mid_working['Proj Own'] = mid_working['Player'].map(maps_dict['Own_map']) / 120
mid_working['Exposure'] = mid_working['Freq']/(1000)
mid_working['Edge'] = mid_working['Exposure'] - mid_working['Proj Own']
mid_working['Team'] = mid_working['Player'].map(maps_dict['Team_map'])
st.session_state.mid_freq = mid_working.copy()
if sim_site_var1 == 'Draftkings':
adc_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,4:5].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
adc_working['Freq'] = adc_working['Freq'].astype(int)
adc_working['Position'] = adc_working['Player'].map(maps_dict['Pos_map'])
adc_working['Salary'] = adc_working['Player'].map(maps_dict['Salary_map'])
adc_working['Proj Own'] = adc_working['Player'].map(maps_dict['Own_map']) / 135
adc_working['Exposure'] = adc_working['Freq']/(1000)
adc_working['Edge'] = adc_working['Exposure'] - adc_working['Proj Own']
adc_working['Team'] = adc_working['Player'].map(maps_dict['Team_map'])
st.session_state.adc_freq = adc_working.copy()
if sim_site_var1 == 'Draftkings':
sup_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,5:6].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
sup_working['Freq'] = sup_working['Freq'].astype(int)
sup_working['Position'] = sup_working['Player'].map(maps_dict['Pos_map'])
sup_working['Salary'] = sup_working['Player'].map(maps_dict['Salary_map'])
sup_working['Proj Own'] = sup_working['Player'].map(maps_dict['Own_map']) / 105
sup_working['Exposure'] = sup_working['Freq']/(1000)
sup_working['Edge'] = sup_working['Exposure'] - sup_working['Proj Own']
sup_working['Team'] = sup_working['Player'].map(maps_dict['Team_map'])
st.session_state.sup_freq = sup_working.copy()
if sim_site_var1 == 'Draftkings':
team_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,6:7].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
team_working['Freq'] = team_working['Freq'].astype(int)
team_working['Position'] = team_working['Player'].map(maps_dict['Pos_map'])
team_working['Salary'] = team_working['Player'].map(maps_dict['Salary_map'])
team_working['Proj Own'] = team_working['Player'].map(maps_dict['Own_map']) / 100
team_working['Exposure'] = team_working['Freq']/(1000)
team_working['Edge'] = team_working['Exposure'] - team_working['Proj Own']
team_working['Team'] = team_working['Player'].map(maps_dict['Team_map'])
st.session_state.team_freq = team_working.copy()
if sim_site_var1 == 'Draftkings':
stack_working = pd.DataFrame(np.column_stack(np.unique(freq_copy.iloc[:,9:10].values, return_counts=True)),
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
stack_working['Freq'] = stack_working['Freq'].astype(int)
stack_working['Exposure'] = stack_working['Freq']/(1000)
st.session_state.stack_freq = stack_working.copy()
with st.container():
if st.button("Reset Sim", key='reset_sim'):
for key in st.session_state.keys():
del st.session_state[key]
if 'player_freq' in st.session_state:
player_split_var2 = st.radio("Are you wanting to isolate any lineups with specific players?", ('Full Players', 'Specific Players'), key='player_split_var2')
if player_split_var2 == 'Specific Players':
find_var2 = st.multiselect('Which players must be included in the lineups?', options = st.session_state.player_freq['Player'].unique())
elif player_split_var2 == 'Full Players':
find_var2 = st.session_state.player_freq.Player.values.tolist()
if player_split_var2 == 'Specific Players':
st.session_state.Sim_Winner_Display = st.session_state.Sim_Winner_Frame[np.equal.outer(st.session_state.Sim_Winner_Frame.to_numpy(), find_var2).any(axis=1).all(axis=1)]
if player_split_var2 == 'Full Players':
st.session_state.Sim_Winner_Display = st.session_state.Sim_Winner_Frame
if 'Sim_Winner_Display' in st.session_state:
st.dataframe(st.session_state.Sim_Winner_Display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
if 'Sim_Winner_Export' in st.session_state:
st.download_button(
label="Export Full Frame",
data=st.session_state.Sim_Winner_Export.to_csv().encode('utf-8'),
file_name='LOL_consim_export.csv',
mime='text/csv',
)
with st.container():
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8, tab9 = st.tabs(['Stack Exposures', 'Overall Exposures', 'CPT Exposures', 'TOP Exposures', 'JNG Exposures', 'MID Exposures', 'ADC Exposures', 'SUP Exposures', 'Team Exposures'])
with tab1:
if 'stack_freq' in st.session_state and st.session_state.stack_freq is not None:
st.dataframe(st.session_state.stack_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(percentages_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.stack_freq.to_csv().encode('utf-8'),
file_name='stack_freq.csv',
mime='text/csv',
key='stack'
)
with tab2:
if 'player_freq' in st.session_state and st.session_state.player_freq is not None:
st.dataframe(st.session_state.player_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.player_freq.to_csv().encode('utf-8'),
file_name='player_freq_export.csv',
mime='text/csv',
key='overall'
)
with tab3:
if 'cpt_freq' in st.session_state and st.session_state.cpt_freq is not None:
st.dataframe(st.session_state.cpt_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width=True)
st.download_button(
label="Export Exposures",
data=st.session_state.cpt_freq.to_csv().encode('utf-8'),
file_name='cpt_freq.csv',
mime='text/csv',
key='cpt'
)
with tab4:
if 'top_freq' in st.session_state and st.session_state.top_freq is not None:
st.dataframe(st.session_state.top_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.top_freq.to_csv().encode('utf-8'),
file_name='top_freq.csv',
mime='text/csv',
key='top'
)
with tab5:
if 'jng_freq' in st.session_state and st.session_state.jng_freq is not None:
st.dataframe(st.session_state.jng_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.jng_freq.to_csv().encode('utf-8'),
file_name='jng_freq.csv',
mime='text/csv',
key='jng'
)
with tab6:
if 'mid_freq' in st.session_state and st.session_state.mid_freq is not None:
st.dataframe(st.session_state.mid_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.mid_freq.to_csv().encode('utf-8'),
file_name='mid_freq.csv',
mime='text/csv',
key='mid'
)
with tab7:
if 'adc_freq' in st.session_state and st.session_state.adc_freq is not None:
st.dataframe(st.session_state.adc_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.adc_freq.to_csv().encode('utf-8'),
file_name='adc_freq.csv',
mime='text/csv',
key='adc'
)
with tab8:
if 'sup_freq' in st.session_state and st.session_state.sup_freq is not None:
st.dataframe(st.session_state.sup_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.sup_freq.to_csv().encode('utf-8'),
file_name='sup_freq.csv',
mime='text/csv',
key='sup'
)
with tab9:
if 'team_freq' in st.session_state and st.session_state.team_freq is not None:
st.dataframe(st.session_state.team_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True)
st.download_button(
label="Export Exposures",
data=st.session_state.team_freq.to_csv().encode('utf-8'),
file_name='team_freq.csv',
mime='text/csv',
key='team'
)
|