MLB_Optimizer / app.py
Multichem's picture
Update app.py
e4b01fa verified
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',
)