Spaces:
Sleeping
Sleeping
File size: 57,288 Bytes
d932cbf e4b01fa d932cbf 557a15a d932cbf e4b01fa d932cbf 557a15a d932cbf e4b01fa d932cbf e4b01fa d932cbf e4b01fa d932cbf |
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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 |
import pulp
import numpy as np
import pandas as pd
import streamlit as st
import gspread
st.set_page_config(layout="wide")
@st.cache_resource
def init_conn():
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)
return gc
gc = init_conn()
wrong_acro = ['WSH', 'AZ', 'CHW']
right_acro = ['WAS', 'ARI', 'CWS']
game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}',
'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'}
team_roo_format = {'Top Score%': '{:.2%}','0 Runs': '{:.2%}', '1 Run': '{:.2%}', '2 Runs': '{:.2%}', '3 Runs': '{:.2%}', '4 Runs': '{:.2%}',
'5 Runs': '{:.2%}','6 Runs': '{:.2%}', '7 Runs': '{:.2%}', '8 Runs': '{:.2%}', '9 Runs': '{:.2%}', '10 Runs': '{:.2%}'}
dk_player_projections = 'https://docs.google.com/spreadsheets/d/1MdzPFqIT0MFid2IhegWf39VNR8IXUyo_Fb5dolOSt3o/edit#gid=340831852'
fd_player_projections = 'https://docs.google.com/spreadsheets/d/1MdzPFqIT0MFid2IhegWf39VNR8IXUyo_Fb5dolOSt3o/edit#gid=340831852'
secondary_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1lP4t8N7UhjR94MEwPn6powRyLl_cQBDUMSCs6cbL9ms/edit#gid=340831852'
secondary_fd_player_projections = 'https://docs.google.com/spreadsheets/d/1lP4t8N7UhjR94MEwPn6powRyLl_cQBDUMSCs6cbL9ms/edit#gid=340831852'
all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1f42Ergav8K1VsOLOK9MUn7DM_MLMvv4GR2Fy7EfnZTc/edit#gid=500994479'
all_fd_player_projections = 'https://docs.google.com/spreadsheets/d/1f42Ergav8K1VsOLOK9MUn7DM_MLMvv4GR2Fy7EfnZTc/edit#gid=500994479'
final_Proj = 0
@st.cache_resource(ttl=600)
def load_time():
sh = gc.open_by_url(dk_player_projections)
worksheet = sh.worksheet('Timestamp')
raw_stamp = worksheet.acell('a1').value
t_stamp = f"Last update was at {raw_stamp}"
return t_stamp
@st.cache_resource(ttl=600)
def load_dk_player_projections(URL):
sh = gc.open_by_url(URL)
worksheet = sh.worksheet('DK_Projections')
load_display = pd.DataFrame(worksheet.get_all_records())
load_display.replace('', np.nan, inplace=True)
load_display = load_display.drop_duplicates(subset='Player')
raw_display = load_display.dropna()
for checkVar in range(len(wrong_acro)):
raw_display['Team'] = raw_display['Team'].replace(wrong_acro, right_acro)
return raw_display
@st.cache_resource(ttl=600)
def load_fd_player_projections(URL):
sh = gc.open_by_url(URL)
worksheet = sh.worksheet('FD_Projections')
load_display = pd.DataFrame(worksheet.get_all_records())
load_display.replace('', np.nan, inplace=True)
load_display = load_display.drop_duplicates(subset='Player')
raw_display = load_display.dropna()
for checkVar in range(len(wrong_acro)):
raw_display['Team'] = raw_display['Team'].replace(wrong_acro, right_acro)
return raw_display
@st.cache_resource(ttl=600)
def set_slate_teams():
sh = gc.open_by_url(all_dk_player_projections)
worksheet = sh.worksheet('Site_Info')
raw_display = pd.DataFrame(worksheet.get_all_records())
for checkVar in range(len(wrong_acro)):
raw_display['DK Main'] = raw_display['DK Main'].replace(wrong_acro, right_acro)
for checkVar in range(len(wrong_acro)):
raw_display['DK Secondary'] = raw_display['DK Secondary'].replace(wrong_acro, right_acro)
for checkVar in range(len(wrong_acro)):
raw_display['DK Overall'] = raw_display['DK Overall'].replace(wrong_acro, right_acro)
for checkVar in range(len(wrong_acro)):
raw_display['FD Main'] = raw_display['FD Main'].replace(wrong_acro, right_acro)
for checkVar in range(len(wrong_acro)):
raw_display['FD Secondary'] = raw_display['FD Secondary'].replace(wrong_acro, right_acro)
for checkVar in range(len(wrong_acro)):
raw_display['FD Overall'] = raw_display['FD Overall'].replace(wrong_acro, right_acro)
return raw_display
@st.cache_resource(ttl=600)
def load_scoring_percentages(URL):
sh = gc.open_by_url(URL)
worksheet = sh.worksheet('Scoring_Percentages')
raw_display = pd.DataFrame(worksheet.get_all_records())
raw_display['8+ runs'] = raw_display['8+ runs'].str.replace('%', '').astype(float)/100
raw_display['Win Percentage'] = raw_display['Win Percentage'].str.replace('%', '').astype(float)/100
raw_display['DK LevX'] = raw_display['DK LevX'].str.replace('%', '').astype(float)/100
raw_display['FD LevX'] = raw_display['FD LevX'].str.replace('%', '').astype(float)/100
for checkVar in range(len(wrong_acro)):
raw_display['Names'] = raw_display['Names'].replace(wrong_acro, right_acro)
return raw_display
@st.cache_data
def convert_df_to_csv(df):
return df.to_csv().encode('utf-8')
t_stamp = load_time()
site_slates = set_slate_teams()
col1, col2 = st.columns([1, 5])
with col1:
st.info(t_stamp)
if st.button("Load/Reset Data", key='reset5'):
st.cache_data.clear()
raw_baselines = load_dk_player_projections(all_dk_player_projections)
team_baselines = load_scoring_percentages(all_dk_player_projections)
slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'All Games'), key='slate_var1')
site_var5 = st.radio("What site are you working with?", ('Draftkings', 'Fanduel'), key='site_var5')
if slate_var1 == 'Main Slate':
if site_var5 == 'Draftkings':
slate_teams = site_slates['DK Main'].values.tolist()
raw_baselines = load_dk_player_projections(all_dk_player_projections)
raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
team_baselines = load_scoring_percentages(all_dk_player_projections)
team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
elif site_var5 == 'Fanduel':
slate_teams = site_slates['FD Main'].values.tolist()
raw_baselines = load_fd_player_projections(all_fd_player_projections)
raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
team_baselines = load_scoring_percentages(all_fd_player_projections)
team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
elif slate_var1 == 'Secondary Slate':
if site_var5 == 'Draftkings':
slate_teams = site_slates['DK Secondary'].values.tolist()
raw_baselines = load_dk_player_projections(all_dk_player_projections)
raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
team_baselines = load_scoring_percentages(all_dk_player_projections)
team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
elif site_var5 == 'Fanduel':
slate_teams = site_slates['FD Secondary'].values.tolist()
raw_baselines = load_fd_player_projections(all_fd_player_projections)
raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
team_baselines = load_scoring_percentages(all_fd_player_projections)
team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
elif slate_var1 == 'All Games':
if site_var5 == 'Draftkings':
slate_teams = site_slates['DK Overall'].values.tolist()
raw_baselines = load_dk_player_projections(all_dk_player_projections)
raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
team_baselines = load_scoring_percentages(all_dk_player_projections)
team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
elif site_var5 == 'Fanduel':
slate_teams = site_slates['FD Overall'].values.tolist()
raw_baselines = load_fd_player_projections(all_fd_player_projections)
raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
team_baselines = load_scoring_percentages(all_fd_player_projections)
team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
contest_var5 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var5')
if contest_var5 == 'Small Field GPP':
opto_var5 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var5')
if opto_var5 == "Manual":
stack_var5 = st.selectbox('Which teams are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var5')
elif opto_var5 == "Pivot Optimal":
stack_var5 = Max_Rank[0]
elif contest_var5 == 'Large Field GPP':
opto_var5 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var5')
if opto_var5 == "Manual":
stack_var5 = st.selectbox('Which team are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var5')
ministack_var5 = st.selectbox('Which team is your secondary stack?', options = raw_baselines['Team'].unique(), key='ministack_var5')
elif opto_var5 == "Pivot Optimal":
stack_var5 = Max_Upside[0]
ministack_var5 = Max_Rank[0]
split_var5 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var5')
if split_var5 == 'Specific Games':
team_var5 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var5')
elif split_var5 == 'Full Slate Run':
team_var5 = raw_baselines.Team.values.tolist()
lock_var5 = st.multiselect("Are there any players you want to use in all lineups (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var5')
avoid_var5 = st.multiselect("Are there any players you want to remove from the pool (Drop Button)?", options = raw_baselines['Player'].unique(), key='avoid_var5')
linenum_var5 = st.number_input("How many lineups would you like to produce?", min_value = 1, max_value = 300, value = 20, step = 1, key='linenum_var5')
if site_var5 == 'Draftkings':
min_sal5 = st.number_input('Min Salary', min_value = 35000, max_value = 49900, value = 49000, step = 100, key='min_sal5')
max_sal5 = st.number_input('Max Salary', min_value = 35000, max_value = 50000, value = 50000, step = 100, key='max_sal5')
elif site_var5 == 'Fanduel':
min_sal5 = st.number_input('Min Salary', min_value = 25000, max_value = 34900, value = 34000, step = 100, key='min_sal5')
max_sal5 = st.number_input('Max Salary', min_value = 25000, max_value = 35000, value = 35000, step = 100, key='max_sal5')
with col2:
raw_baselines = raw_baselines[raw_baselines['Team'].isin(team_var5)]
raw_baselines = raw_baselines[~raw_baselines['Player'].isin(avoid_var5)]
if contest_var5 == 'Small Field GPP':
if site_var5 == 'Draftkings':
raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean(), raw_baselines['Own'])
raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (10 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean(), raw_baselines['Own%'])
raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
elif site_var5 == 'Fanduel':
raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean())/50) + raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean(), raw_baselines['Own'])
raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (10 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean())/150) + raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean(), raw_baselines['Own%'])
raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
elif contest_var5 == 'Large Field GPP':
if site_var5 == 'Draftkings':
raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (2.5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean(), raw_baselines['Own'])
raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean(), raw_baselines['Own%'])
raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
elif site_var5 == 'Fanduel':
raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (2.5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean())/50) + raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean(), raw_baselines['Own'])
raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean())/150) + raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean(), raw_baselines['Own%'])
raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
elif contest_var5 == 'Cash':
if site_var5 == 'Draftkings':
raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (6 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean(), raw_baselines['Own'])
raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (11 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean(), raw_baselines['Own%'])
raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
elif site_var5 == 'Fanduel':
raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (6 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean())/50) + raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean(), raw_baselines['Own'])
raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (11 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean())/150) + raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean(), raw_baselines['Own%'])
raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own%']]
raw_baselines.rename(columns={"Own%": "Own"}, inplace = True)
raw_baselines = raw_baselines.sort_values(by='Median', ascending=False)
raw_baselines['lock'] = np.where(raw_baselines['Player'].isin(lock_var5), 1, 0)
st.dataframe(raw_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
st.download_button(
label="Export Projections",
data=convert_df_to_csv(raw_baselines),
file_name='MLB_proj_export.csv',
mime='text/csv',
)
if st.button('Optimize'):
max_proj = 1000
max_own = 1000
total_proj = 0
total_own = 0
optimize_container = st.empty()
lineup_display = []
check_list = []
lineups = []
portfolio = pd.DataFrame()
x = 1
with st.spinner('Wait for it...'):
with optimize_container:
while x <= linenum_var5:
sorted_lineup = []
p_used = []
cvar = 0
firvar = 0
secvar = 0
thirvar = 0
raw_proj_file = raw_baselines
raw_flex_file = raw_proj_file.dropna(how='all')
raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > 0]
flex_file = raw_flex_file
flex_file.rename(columns={"Own": "Proj DK Own%"}, inplace = True)
flex_file['name_var'] = flex_file['Player']
flex_file['lock'] = np.where(flex_file['Player'].isin(lock_var5), 1, 0)
player_ids = flex_file.index
overall_players = flex_file[['Player']]
overall_players['player_var_add'] = flex_file.index
overall_players['player_var'] = 'player_vars_' + overall_players['player_var_add'].astype(str)
player_vars = pulp.LpVariable.dicts("player_vars", flex_file.index, 0, 1, pulp.LpInteger)
total_score = pulp.LpProblem("Fantasy_Points_Problem", pulp.LpMaximize)
player_match = dict(zip(overall_players['player_var'], overall_players['Player']))
player_index_match = dict(zip(overall_players['player_var'], overall_players['player_var_add']))
player_own = dict(zip(flex_file['Player'], flex_file['Proj DK Own%']))
player_team = dict(zip(flex_file['Player'], flex_file['Team']))
player_pos = dict(zip(flex_file['Player'], flex_file['Position']))
player_sal = dict(zip(flex_file['Player'], flex_file['Salary']))
player_proj = dict(zip(flex_file['Player'], flex_file['Median']))
# obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
# total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
# obj_points_max = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
# obj_own_max = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) <= max_sal5
total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal5
if site_var5 == 'Draftkings':
if contest_var5 == 'Cash':
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == flex) & (flex_file['Position'] != 'SP')].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
elif contest_var5 == 'Small Field GPP':
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == stack_var5) & (flex_file['Position'] != 'SP')].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
elif contest_var5 == 'Large Field GPP':
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == stack_var5) & (flex_file['Position'] != 'SP')].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == ministack_var5) & (flex_file['Position'] != 'SP')].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 3
for flex in flex_file['lock'].unique():
sub_idx = flex_file[flex_file['lock'] == 1].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var5)
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] != "Var"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 10
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("SP")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "C"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "1B"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "2B"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "3B"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "SS"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "OF"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("C")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("1B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("2B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("3B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("SS")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("OF")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "3B")| (flex_file['Position'] == "3B/SS")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "2B")| (flex_file['Position'] == "2B/SS")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "2B") | (flex_file['Position'] == "3B")| (flex_file['Position'] == "2B/3B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "1B") | (flex_file['Position'] == "3B")| (flex_file['Position'] == "1B/3B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "1B") | (flex_file['Position'] == "C")| (flex_file['Position'] == "1B/C")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "OF")| (flex_file['Position'] == "SS/OF")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
elif site_var5 == 'Fanduel':
if contest_var5 == 'Cash':
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == flex) & (flex_file['Position'] != 'P')].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
elif contest_var5 == 'Small Field GPP':
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == stack_var5) & (flex_file['Position'] != 'P')].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 4
elif contest_var5 == 'Large Field GPP':
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == stack_var5)].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 4
for flex in flex_file['Team'].unique():
sub_idx = flex_file[(flex_file['Team'] == ministack_var5)].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 4
for flex in flex_file['lock'].unique():
sub_idx = flex_file[flex_file['lock'] == 1].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var5)
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] != "Var"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 9
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("P")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "C") | (flex_file['Position'] == "1B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "C") | (flex_file['Position'] == "1B") | (flex_file['Position'] == "OF")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "2B"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "3B"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "SS"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'] == "OF"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "OF") | (flex_file['Position'] == "C")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "OF") | (flex_file['Position'] == "1B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'].str.contains("C")) | (flex_file['Position'].str.contains("1B"))].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'].str.contains("2B")) | (flex_file['Position'].str.contains("SS"))].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "C") | (flex_file['Position'] == "SS")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
for flex in flex_file['Position'].unique():
sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "2B") | (flex_file['Position'] == "OF") | (flex_file['Position'] == "2B/SS/OF")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("2B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("3B")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("SS")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("OF")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
for flex in flex_file['Position'].unique():
sub_idx = flex_file[flex_file['Position'].str.contains("OF")].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
player_count = []
player_trim = []
lineup_list = []
if contest_var5 == 'Cash':
obj_points = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_own - .001
elif contest_var5 != 'Cash':
obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_proj - .01
total_score.solve()
for v in total_score.variables():
if v.varValue > 0:
lineup_list.append(v.name)
df = pd.DataFrame(lineup_list)
df['Names'] = df[0].map(player_match)
df['Cost'] = df['Names'].map(player_sal)
df['Proj'] = df['Names'].map(player_proj)
df['Own'] = df['Names'].map(player_own)
total_cost = sum(df['Cost'])
total_own = sum(df['Own'])
total_proj = sum(df['Proj'])
lineup_raw = pd.DataFrame(lineup_list)
lineup_raw['Names'] = lineup_raw[0].map(player_match)
lineup_raw['value'] = lineup_raw[0].map(player_index_match)
lineup_final = lineup_raw.sort_values(by=['value'])
del lineup_final[lineup_final.columns[0]]
del lineup_final[lineup_final.columns[1]]
lineup_final = lineup_final.reset_index(drop=True)
if site_var5 == 'Draftkings':
line_hold = lineup_final[['Names']]
line_hold['pos'] = line_hold['Names'].map(player_pos)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'SP':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'C':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
cvar = 1
p_used.extend(sorted_lineup)
if cvar != 1:
for pname in range(0,len(line_hold)):
if 'C' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == '1B':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
firvar = 1
p_used.extend(sorted_lineup)
if firvar != 1:
for pname in range(0,len(line_hold)):
if '1B' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == '2B':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
secvar = 1
p_used.extend(sorted_lineup)
if secvar != 1:
for pname in range(0,len(line_hold)):
if '2B' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == '3B':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
thirvar = 1
p_used.extend(sorted_lineup)
if thirvar != 1:
for pname in range(0,len(line_hold)):
if '3B' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'SS':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if 'SS' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'OF':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if 'OF' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
lineup_final['sorted'] = sorted_lineup
lineup_final = lineup_final.drop(columns=['Names'])
lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
elif site_var5 == 'Fanduel':
line_hold = lineup_final[['Names']]
line_hold['pos'] = line_hold['Names'].map(player_pos)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'P':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'C' or line_hold.iat[pname,1] == '1B':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
cvar = 1
p_used.extend(sorted_lineup)
if cvar != 1:
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] in ['C', '1B']:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == '2B':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
secvar = 1
p_used.extend(sorted_lineup)
if secvar != 1:
for pname in range(0,len(line_hold)):
if '2B' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == '3B':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
thirvar = 1
p_used.extend(sorted_lineup)
if thirvar != 1:
for pname in range(0,len(line_hold)):
if '3B' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'SS':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if 'SS' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,1] == 'OF':
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if 'OF' in line_hold.iat[pname,1]:
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
for pname in range(0,len(line_hold)):
if line_hold.iat[pname,0] not in p_used:
sorted_lineup.append(line_hold.iat[pname,0])
p_used.extend(sorted_lineup)
lineup_final['sorted'] = sorted_lineup
lineup_final = lineup_final.drop(columns=['Names'])
lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
lineup_test = lineup_final
lineup_final = lineup_final.T
lineup_final['Cost'] = total_cost
lineup_final['Proj'] = total_proj
lineup_final['Own'] = total_own
lineup_test['Team'] = lineup_test['Names'].map(player_team)
lineup_test['Position'] = lineup_test['Names'].map(player_pos)
lineup_test['Salary'] = lineup_test['Names'].map(player_sal)
lineup_test['Proj'] = lineup_test['Names'].map(player_proj)
lineup_test['Own'] = lineup_test['Names'].map(player_own)
lineup_test = lineup_test.set_index('Names')
lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0)
lineup_display.append(lineup_test)
with col2:
with st.container():
st.table(lineup_test)
max_proj = total_proj
max_own = total_own
check_list.append(total_proj)
portfolio = pd.concat([portfolio, lineup_final], ignore_index = True)
x += 1
if site_var5 == 'Draftkings':
portfolio.rename(columns={0: "SP1", 1: "SP2", 2: "C", 3: "1B", 4: "2B", 5: "3B", 6: "SS", 7: "OF1", 8: "OF2", 9: "OF3"}, inplace = True)
elif site_var5 == 'Fanduel':
portfolio.rename(columns={0: "SP1", 1: "C/1B", 2: "2B", 3: "3B", 4: "SS", 5: "OF1", 6: "OF2", 7: "OF3", 8: "UTIL"}, inplace = True)
portfolio = portfolio.dropna()
portfolio = portfolio.reset_index()
portfolio['Lineup_num'] = portfolio['index'] + 1
portfolio.rename(columns={'Lineup_num': "Lineup"}, inplace = True)
portfolio = portfolio.set_index('Lineup')
portfolio = portfolio.drop(columns=['index'])
final_outcomes = portfolio
with optimize_container:
optimize_container = st.empty()
st.dataframe(portfolio.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_outcomes),
file_name='MLB_optimals_export.csv',
mime='text/csv',
) |