NFL_Showdown_Optimizer / streamlit_app.py
Multichem's picture
Upload streamlit_app.py
2805ddf
raw
history blame
38.5 kB
import pulp
import numpy as np
import pandas as pd
import streamlit as st
import gspread
from itertools import combinations
import time
@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
st.set_page_config(layout="wide")
gc = init_conn()
wrong_acro = ['WSH', 'AZ']
right_acro = ['WAS', 'ARI']
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%}'}
player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}',
'4x%': '{:.2%}','GPP%': '{:.2%}'}
all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348'
@st.cache_resource(ttl=600)
def load_dk_player_projections():
sh = gc.open_by_url(all_dk_player_projections)
worksheet = sh.worksheet('SD_Projections')
load_display = pd.DataFrame(worksheet.get_all_records())
load_display.replace('', np.nan, inplace=True)
raw_display = load_display.dropna(subset=['PPR'])
raw_display.rename(columns={"name": "Player", "PPR": "Median"}, inplace = True)
raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
raw_display = raw_display.loc[raw_display['Median'] > 0]
return raw_display
@st.cache_resource(ttl=600)
def load_fd_player_projections():
sh = gc.open_by_url(all_dk_player_projections)
worksheet = sh.worksheet('FD_SD_Projections')
load_display = pd.DataFrame(worksheet.get_all_records())
load_display.replace('', np.nan, inplace=True)
raw_display = load_display.dropna(subset=['Half_PPR'])
raw_display.rename(columns={"name": "Player", "Half_PPR": "Median"}, inplace = True)
raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
raw_display = raw_display.loc[raw_display['Median'] > 0]
return raw_display
dk_roo_raw = load_dk_player_projections()
fd_roo_raw = load_fd_player_projections()
@st.cache_data
def convert_df_to_csv(df):
return df.to_csv().encode('utf-8')
tab1, tab2, tab3 = st.tabs(['Uploads and Info', 'Range of Outcomes', 'Optimizer'])
with tab1:
st.info("The Projections file can have any columns in any order, but must contain columns explicitly named: 'Player', 'Salary', 'Position', 'Team', 'Opp', 'rush_yards', 'rec', 'Median', and 'Own'. For the purposes of this showdown optimizer, only include FLEX positions, salaries, and medians. The optimizer logic will handle the rest!")
col1, col2 = st.columns([1, 5])
with col1:
proj_file = st.file_uploader("Upload Projections File", key = 'proj_uploader')
if proj_file is not None:
try:
proj_dataframe = pd.read_csv(proj_file)
proj_dataframe = proj_dataframe.loc[proj_dataframe['Median'] > 0]
except:
proj_dataframe = pd.read_excel(proj_file)
proj_dataframe = proj_dataframe.loc[proj_dataframe['Median'] > 0]
with col2:
if proj_file is not None:
st.dataframe(proj_dataframe.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
with tab2:
col1, col2 = st.columns([1, 5])
with col1:
if st.button("Load/Reset Data", key='reset2'):
st.cache_data.clear()
dk_roo_raw = load_dk_player_projections()
fd_roo_raw = load_fd_player_projections()
slate_var2 = st.radio("Which data are you loading?", ('Paydirt', 'User'), key='slate_var2')
site_var2 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var2')
if slate_var2 == 'User':
raw_baselines = proj_dataframe
elif slate_var2 != 'User':
if site_var2 == 'Draftkings':
raw_baselines = dk_roo_raw
elif site_var2 == 'Fanduel':
raw_baselines = fd_roo_raw
with col2:
hold_container = st.empty()
if st.button('Create Range of Outcomes for Slate'):
with hold_container:
working_roo = raw_baselines
working_roo = working_roo.loc[working_roo['Median'] > 0]
if site_var2 == 'Draftkings':
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Median": "Fantasy"}, inplace = True)
elif site_var2 == 'Draftkings':
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Median": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
own_dict = dict(zip(working_roo.Player, working_roo.Own))
team_dict = dict(zip(working_roo.Player, working_roo.Team))
opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
total_sims = 1000
flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median'] + flex_file['Floor']) + (flex_file['Rush Yards']*.01), flex_file['Median'] + flex_file['Floor'] + flex_file['Receptions'])
flex_file['Ceiling'] = flex_file['Ceiling'].fillna(15)
flex_file['STD'] = np.where(flex_file['Position'] != 'QB', (flex_file['Median']/4) + flex_file['Receptions'], (flex_file['Median']/4))
flex_file['STD'] = flex_file['Ceiling'].fillna(5)
flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
hold_file = flex_file
overall_file = flex_file
salary_file = flex_file
overall_players = overall_file[['Player']]
for x in range(0,total_sims):
salary_file[x] = salary_file['Salary']
salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
salary_file.astype('int').dtypes
salary_file = salary_file.div(1000)
for x in range(0,total_sims):
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
overall_file.astype('int').dtypes
players_only = hold_file[['Player']]
raw_lineups_file = players_only
for x in range(0,total_sims):
maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
players_only[x] = raw_lineups_file[x].rank(ascending=False)
players_only=players_only.drop(['Player'], axis=1)
players_only.astype('int').dtypes
salary_2x_check = (overall_file - (salary_file*2))
salary_3x_check = (overall_file - (salary_file*3))
salary_4x_check = (overall_file - (salary_file*4))
players_only['Average_Rank'] = players_only.mean(axis=1)
players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
players_only['Player'] = hold_file[['Player']]
final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj['Own'] = final_Proj['Player'].map(own_dict)
final_Proj['Team'] = final_Proj['Player'].map(team_dict)
final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
final_Proj['LevX'] = 0
final_Proj['LevX'] = final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank']
final_Proj['CPT_Own'] = final_Proj['Own'] / 4
final_Proj['CPT_Proj'] = final_Proj['Median'] * 1.5
final_Proj['CPT_Salary'] = final_Proj['Salary'] * 1.5
display_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
display_Proj = display_Proj.set_index('Player')
display_Proj = display_Proj.sort_values(by='Median', ascending=False)
with hold_container:
hold_container = st.empty()
display_Proj = display_Proj
st.dataframe(display_Proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='Custom_NFL_overall_export.csv',
mime='text/csv',
)
with tab3:
col1, col2 = st.columns([1, 5])
with col1:
if st.button("Load/Reset Data", key='reset1'):
st.cache_data.clear()
dk_roo_raw = load_dk_player_projections()
fd_roo_raw = load_fd_player_projections()
slate_var1 = st.radio("Which data are you loading?", ('Paydirt', 'User'), key='slate_var1')
site_var1 = st.selectbox("What site is the showdown on?", ('Draftkings', 'Fanduel'), key='site_var1')
if site_var1 == 'Draftkings':
if slate_var1 == 'User':
raw_baselines = proj_dataframe
elif slate_var1 != 'User':
raw_baselines = dk_roo_raw
elif site_var1 == 'Fanduel':
if slate_var1 == 'User':
st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
raw_baselines = proj_dataframe
elif slate_var1 != 'User':
st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
raw_baselines = fd_roo_raw
contest_var1 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var1')
lock_var1 = st.multiselect("Are there any players you want to use in all lineups in the CAPTAIN (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var1')
lock_var2 = st.multiselect("Are there any players you want to use in all lineups in the FLEX (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var2')
avoid_var1 = st.multiselect("Are there any players you want to remove from the pool (Drop Button)?", options = raw_baselines['Player'].unique(), key='avoid_var1')
trim_choice1 = st.selectbox("Allow overowned lineups?", options = ['Yes', 'No'])
linenum_var1 = st.number_input("How many lineups would you like to produce?", min_value = 1, max_value = 300, value = 20, step = 1, key='linenum_var1')
if trim_choice1 == 'Yes':
trim_var1 = 0
elif trim_choice1 == 'No':
trim_var1 = 1
if site_var1 == 'Draftkings':
min_sal1 = st.number_input('Min Salary', min_value = 35000, max_value = 49900, value = 49000, step = 100, key='min_sal1')
max_sal1 = st.number_input('Max Salary', min_value = 35000, max_value = 50000, value = 50000, step = 100, key='max_sal1')
elif site_var1 == 'Fanduel':
min_sal1 = st.number_input('Min Salary', min_value = 45000, max_value = 59900, value = 59000, step = 100, key='min_sal1')
max_sal1 = st.number_input('Max Salary', min_value = 45000, max_value = 60000, value = 60000, step = 100, key='max_sal1')
with col2:
if contest_var1 == 'Small Field GPP':
if site_var1 == 'Draftkings':
ownframe = raw_baselines.copy()
ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
ownframe['Own%'] = np.where(ownframe['Own%'] > 85, 85, ownframe['Own%'])
ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
elif site_var1 == 'Fanduel':
ownframe = raw_baselines.copy()
ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
elif contest_var1 == 'Large Field GPP':
if site_var1 == 'Draftkings':
ownframe = raw_baselines.copy()
ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
elif site_var1 == 'Fanduel':
ownframe = raw_baselines.copy()
ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
elif contest_var1 == 'Cash':
if site_var1 == 'Draftkings':
ownframe = raw_baselines.copy()
ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
ownframe['Own%'] = np.where(ownframe['Own%'] > 90, 90, ownframe['Own%'])
ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
elif site_var1 == 'Fanduel':
ownframe = raw_baselines.copy()
ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
export_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
export_baselines['CPT_Proj'] = export_baselines['Median'] * 1.5
export_baselines['CPT_Salary'] = export_baselines['Salary'] * 1.5
display_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
display_baselines['CPT Own'] = display_baselines['Own'] / 4
display_baselines = display_baselines.sort_values(by='Median', ascending=False)
display_baselines['cpt_lock'] = np.where(display_baselines['Player'].isin(lock_var1), 1, 0)
display_baselines['lock'] = np.where(display_baselines['Player'].isin(lock_var2), 1, 0)
index_check = pd.DataFrame()
flex_proj = pd.DataFrame()
cpt_proj = pd.DataFrame()
if site_var1 == 'Draftkings':
cpt_proj['Player'] = display_baselines['Player']
cpt_proj['Salary'] = display_baselines['Salary'] * 1.5
cpt_proj['Position'] = display_baselines['Position']
cpt_proj['Team'] = display_baselines['Team']
cpt_proj['Opp'] = display_baselines['Opp']
cpt_proj['Median'] = display_baselines['Median'] * 1.5
cpt_proj['Own'] = display_baselines['CPT Own']
cpt_proj['lock'] = display_baselines['cpt_lock']
cpt_proj['roster'] = 'CPT'
if len(lock_var1) > 0:
cpt_proj = cpt_proj[cpt_proj['lock'] == 1]
if len(lock_var2) > 0:
cpt_proj = cpt_proj[~cpt_proj['Player'].isin(lock_var2)]
flex_proj['Player'] = display_baselines['Player']
flex_proj['Salary'] = display_baselines['Salary']
flex_proj['Position'] = display_baselines['Position']
flex_proj['Team'] = display_baselines['Team']
flex_proj['Opp'] = display_baselines['Opp']
flex_proj['Median'] = display_baselines['Median']
flex_proj['Own'] = display_baselines['Own']
flex_proj['lock'] = display_baselines['lock']
flex_proj['roster'] = 'FLEX'
elif site_var1 == 'Fanduel':
cpt_proj['Player'] = display_baselines['Player']
cpt_proj['Salary'] = display_baselines['Salary']
cpt_proj['Position'] = display_baselines['Position']
cpt_proj['Team'] = display_baselines['Team']
cpt_proj['Opp'] = display_baselines['Opp']
cpt_proj['Median'] = display_baselines['Median'] * 1.5
cpt_proj['Own'] = display_baselines['CPT Own'] *.75
cpt_proj['lock'] = display_baselines['cpt_lock']
cpt_proj['roster'] = 'CPT'
flex_proj['Player'] = display_baselines['Player']
flex_proj['Salary'] = display_baselines['Salary']
flex_proj['Position'] = display_baselines['Position']
flex_proj['Team'] = display_baselines['Team']
flex_proj['Opp'] = display_baselines['Opp']
flex_proj['Median'] = display_baselines['Median']
flex_proj['Own'] = display_baselines['Own']
flex_proj['lock'] = display_baselines['lock']
flex_proj['roster'] = 'FLEX'
combo_file = pd.concat([cpt_proj, flex_proj], ignore_index=True)
st.dataframe(display_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(export_baselines),
file_name='NFL_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_var1:
sorted_lineup = []
p_used = []
raw_proj_file = combo_file
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_var2), 1, 0)
flex_file = flex_file[~flex_file['Player'].isin(avoid_var1)]
flex_file['Player'] = np.where(flex_file['roster'] == 'CPT', flex_file['Player'] + ' - CPT', flex_file['Player'] + ' - FLEX')
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_sal1
total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal1
if site_var1 == 'Draftkings':
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_var2)
for flex in flex_file['roster'].unique():
sub_idx = flex_file[flex_file['roster'] == "CPT"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
for flex in flex_file['roster'].unique():
sub_idx = flex_file[flex_file['roster'] == "FLEX"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
for playerid in player_ids:
total_score += pulp.lpSum([player_vars[i] for i in player_ids if
(flex_file['name_var'][i] == flex_file['name_var'][playerid])]) <= 1
elif site_var1 == 'Fanduel':
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_var2)
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]) == 5
for flex in flex_file['roster'].unique():
sub_idx = flex_file[flex_file['roster'] == "CPT"].index
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
for playerid in player_ids:
total_score += pulp.lpSum([player_vars[i] for i in player_ids if
(flex_file['name_var'][i] == flex_file['name_var'][playerid])]) <= 1
player_count = []
player_trim = []
lineup_list = []
if contest_var1 == '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_var1 != '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
if trim_var1 == 1:
total_score += pulp.lpSum([player_vars[idx]*obj_own_max[idx] for idx in flex_file.index]) <= max_own - .001
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['Team'] = lineup_final['Names'].map(player_team)
lineup_final['Position'] = lineup_final['Names'].map(player_pos)
lineup_final['Salary'] = lineup_final['Names'].map(player_sal)
lineup_final['Proj'] = lineup_final['Names'].map(player_proj)
lineup_final['Own'] = lineup_final['Names'].map(player_own)
lineup_final.loc['Column_Total'] = lineup_final.sum(numeric_only=True, axis=0)
lineup_final = lineup_final.reset_index(drop=True)
# lineup_final = lineup_final.set_index('Names')
with col2:
with st.container():
st.table(lineup_final)
max_proj = total_proj
max_own = total_own
if site_var1 == 'Draftkings':
if len(lineup_final) == 7:
port_display = pd.DataFrame(lineup_final['Names'][:-1].values.reshape(1, -1))
port_display['Cost'] = total_cost
port_display['Proj'] = total_proj
port_display['Own'] = total_own
st.table(port_display)
portfolio = pd.concat([portfolio, port_display], ignore_index = True)
elif site_var1 == 'Fanduel':
if len(lineup_final) == 6:
port_display = pd.DataFrame(lineup_final['Names'][:-1].values.reshape(1, -1))
port_display['Cost'] = total_cost
port_display['Proj'] = total_proj
port_display['Own'] = total_own
st.table(port_display)
portfolio = pd.concat([portfolio, port_display], ignore_index = True)
x += 1
if site_var1 == 'Draftkings':
portfolio.rename(columns={0: "CPT", 1: "FLEX1", 2: "FLEX2", 3: "FLEX3", 4: "FLEX4", 5: "FLEX5"}, inplace = True)
elif site_var1 == 'Fanduel':
portfolio.rename(columns={0: "MVP", 1: "FLEX1", 2: "FLEX2", 3: "FLEX3", 4: "FLEX4"}, 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'])
portfolio = portfolio.drop_duplicates()
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',
)