|
import pulp |
|
import numpy as np |
|
import pandas as pd |
|
import streamlit as st |
|
import pymongo |
|
from itertools import combinations |
|
import time |
|
|
|
@st.cache_resource |
|
def init_conn(): |
|
uri = st.secrets['mongo_uri'] |
|
client = pymongo.MongoClient(uri, retryWrites=True, serverSelectionTimeoutMS=500000) |
|
nba_db = client["NBA_DFS"] |
|
nfl_db = client["NFL_Database"] |
|
|
|
return nba_db, nfl_db |
|
|
|
st.set_page_config(layout="wide") |
|
|
|
nba_db, nfl_db = 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%}'} |
|
|
|
nfl_player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}', |
|
'4x%': '{:.2%}','GPP%': '{:.2%}'} |
|
|
|
nba_player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '4x%': '{:.2%}', '5x%': '{:.2%}', |
|
'6x%': '{:.2%}','GPP%': '{:.2%}'} |
|
|
|
expose_format = {'Proj Own': '{:.2%}','Exposure': '{:.2%}'} |
|
|
|
all_dk_player_projections = st.secrets["NFL_data"] |
|
|
|
st.markdown(""" |
|
<style> |
|
/* Tab styling */ |
|
.stTabs [data-baseweb="tab-list"] { |
|
gap: 8px; |
|
padding: 4px; |
|
} |
|
|
|
.stTabs [data-baseweb="tab"] { |
|
height: 50px; |
|
white-space: pre-wrap; |
|
background-color: #FFD700; |
|
color: white; |
|
border-radius: 10px; |
|
gap: 1px; |
|
padding: 10px 20px; |
|
font-weight: bold; |
|
transition: all 0.3s ease; |
|
} |
|
|
|
.stTabs [aria-selected="true"] { |
|
background-color: #DAA520; |
|
color: white; |
|
} |
|
|
|
.stTabs [data-baseweb="tab"]:hover { |
|
background-color: #DAA520; |
|
cursor: pointer; |
|
} |
|
</style>""", unsafe_allow_html=True) |
|
|
|
@st.cache_resource(ttl=60) |
|
def init_baselines(): |
|
collection = nba_db["Player_SD_Range_Of_Outcomes"] |
|
cursor = collection.find() |
|
|
|
raw_display = pd.DataFrame(list(cursor)) |
|
raw_display = raw_display[['Player', 'Minutes Proj', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '4x%', '5x%', '6x%', 'GPP%', |
|
'Own', 'Small_Own', 'Large_Own', 'Cash_Own', 'CPT_Own', 'LevX', 'ValX', 'site', 'version', 'slate', 'timestamp', 'player_id']] |
|
raw_display = raw_display.loc[raw_display['Median'] > 0] |
|
raw_display = raw_display.sort_values(by='Median', ascending=False) |
|
nba_dk_sd_raw = raw_display[raw_display['site'] == 'Draftkings'] |
|
nba_fd_sd_raw = raw_display[raw_display['site'] == 'Fanduel'] |
|
|
|
try: |
|
collection = nfl_db["DK_SD_NFL_ROO"] |
|
cursor = collection.find() |
|
|
|
raw_display = pd.DataFrame(list(cursor)) |
|
raw_display = raw_display[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', |
|
'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX', 'version', 'slate', 'timestamp', 'player_id', 'site']] |
|
raw_display = raw_display.loc[raw_display['Median'] > 0] |
|
raw_display = raw_display.apply(pd.to_numeric, errors='ignore') |
|
nfl_dk_sd_raw = raw_display.sort_values(by='Median', ascending=False) |
|
except: |
|
nfl_dk_sd_raw = pd.DataFrame() |
|
|
|
try: |
|
collection = nfl_db["FD_SD_NFL_ROO"] |
|
cursor = collection.find() |
|
|
|
raw_display = pd.DataFrame(list(cursor)) |
|
raw_display = raw_display[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', |
|
'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX', 'version', 'slate', 'timestamp', 'player_id', 'site']] |
|
raw_display = raw_display.loc[raw_display['Median'] > 0] |
|
raw_display = raw_display.apply(pd.to_numeric, errors='ignore') |
|
nfl_fd_sd_raw = raw_display.sort_values(by='Median', ascending=False) |
|
except: |
|
nfl_fd_sd_raw = pd.DataFrame() |
|
|
|
|
|
try: |
|
nba_timestamp = nba_dk_sd_raw['timestamp'].values[0] |
|
except: |
|
nba_timestamp = nba_fd_sd_raw['timestamp'].values[0] |
|
try: |
|
try: |
|
nfl_dk_timestamp = nfl_dk_sd_raw['timestamp'].values[0] |
|
except: |
|
nfl_dk_timestamp = nfl_fd_sd_raw['timestamp'].values[0] |
|
except: |
|
try: |
|
nfl_dk_timestamp = time.time() |
|
except: |
|
nfl_dk_timestamp = time.time() |
|
|
|
try: |
|
nba_dk_id_dict = dict(zip(nba_dk_sd_raw['Player'], nba_dk_sd_raw['player_id'])) |
|
nfl_dk_id_dict = dict(zip(nfl_dk_sd_raw['Player'], nfl_dk_sd_raw['player_id'])) |
|
nba_fd_id_dict = dict(zip(nba_fd_sd_raw['Player'], nba_fd_sd_raw['player_id'])) |
|
nfl_fd_id_dict = dict(zip(nfl_fd_sd_raw['Player'], nfl_fd_sd_raw['player_id'])) |
|
except: |
|
nba_dk_id_dict = dict(zip(nba_dk_sd_raw['Player'], nba_dk_sd_raw['player_id'])) |
|
nfl_dk_id_dict = dict() |
|
nba_fd_id_dict = dict(zip(nba_fd_sd_raw['Player'], nba_fd_sd_raw['player_id'])) |
|
nfl_fd_id_dict = dict() |
|
|
|
return nba_dk_sd_raw, nba_fd_sd_raw, nfl_dk_sd_raw, nfl_fd_sd_raw, nba_timestamp, nfl_dk_timestamp, nba_dk_id_dict, nfl_dk_id_dict, nba_fd_id_dict, nfl_fd_id_dict |
|
|
|
nba_dk_sd_raw, nba_fd_sd_raw, nfl_dk_sd_raw, nfl_fd_sd_raw, nba_timestamp, nfl_dk_timestamp, nba_dk_id_dict, nfl_dk_id_dict, nba_fd_id_dict, nfl_fd_id_dict = init_baselines() |
|
|
|
@st.cache_data |
|
def convert_df_to_csv(df): |
|
return df.to_csv().encode('utf-8') |
|
|
|
tab1, tab2 = st.tabs(['Range of Outcomes', 'Optimizer']) |
|
|
|
with tab1: |
|
with st.expander('Info and Filters'): |
|
if st.button("Load/Reset Data", key='reset2'): |
|
st.cache_data.clear() |
|
nba_dk_sd_raw, nba_fd_sd_raw, nfl_dk_sd_raw, nfl_fd_sd_raw, nba_timestamp, nfl_dk_timestamp, nba_dk_id_dict, nfl_dk_id_dict, nba_fd_id_dict, nfl_fd_id_dict = init_baselines() |
|
info_container = st.container() |
|
with info_container: |
|
st.info("Simple view is better for mobile and shows just the most valuable stats, Advanced view is better for desktop and shows all stats and thresholds") |
|
options_container = st.container() |
|
with options_container: |
|
col1, col2, col3, col4 = st.columns(4) |
|
|
|
with col1: |
|
view_var2 = st.radio("View Type", ("Simple", "Advanced"), key='view_var2') |
|
|
|
with col2: |
|
sport_var2 = st.radio("Sport", ('NBA', 'NFL'), key='sport_var2') |
|
if sport_var2 == 'NBA': |
|
dk_roo_raw = nba_dk_sd_raw |
|
fd_roo_raw = nba_fd_sd_raw |
|
elif sport_var2 == 'NFL': |
|
dk_roo_raw = nfl_dk_sd_raw |
|
fd_roo_raw = nfl_fd_sd_raw |
|
|
|
with col3: |
|
slate_var2 = st.radio("Slate", ('Paydirt (Main)', 'Paydirt (Secondary)', 'Paydirt (Auxiliary)'), key='slate_var2') |
|
|
|
with col4: |
|
site_var2 = st.radio("Site", ('Draftkings', 'Fanduel'), key='site_var2') |
|
|
|
if site_var2 == 'Draftkings': |
|
if slate_var2 == 'Paydirt (Main)': |
|
raw_baselines = dk_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #1'] |
|
elif slate_var2 == 'Paydirt (Secondary)': |
|
raw_baselines = dk_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #2'] |
|
elif slate_var2 == 'Paydirt (Auxiliary)': |
|
raw_baselines = dk_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #3'] |
|
|
|
elif site_var2 == 'Fanduel': |
|
if slate_var2 == 'Paydirt (Main)': |
|
raw_baselines = fd_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #1'] |
|
elif slate_var2 == 'Paydirt (Secondary)': |
|
raw_baselines = fd_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #2'] |
|
elif slate_var2 == 'Paydirt (Auxiliary)': |
|
raw_baselines = fd_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #3'] |
|
|
|
hold_container = st.empty() |
|
|
|
if sport_var2 == 'NBA': |
|
if view_var2 == 'Simple': |
|
display_Proj = raw_baselines[['Player', 'Position', 'Salary', 'Median', 'GPP%', 'Own']] |
|
display_Proj = display_Proj.drop_duplicates(subset=['Player']) |
|
display_Proj = display_Proj.set_index('Player') |
|
elif view_var2 == 'Advanced': |
|
display_Proj = raw_baselines[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '4x%', '5x%', '6x%', 'GPP%', 'Own', 'Small_Own', 'Large_Own', 'Cash_Own', 'CPT_Own', 'LevX', 'ValX', 'site', 'version', 'slate', 'timestamp', 'player_id']] |
|
display_Proj = display_Proj.drop_duplicates(subset=['Player']) |
|
display_Proj = display_Proj.set_index('Player') |
|
elif sport_var2 == 'NFL': |
|
if view_var2 == 'Simple': |
|
display_Proj = raw_baselines[['Player', 'Position', 'Salary', 'Median', '20+%', 'Own']] |
|
display_Proj = display_Proj.drop_duplicates(subset=['Player']) |
|
display_Proj = display_Proj.set_index('Player') |
|
elif view_var2 == 'Advanced': |
|
display_Proj = raw_baselines[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX', 'version', 'slate', 'timestamp', 'player_id', 'site']] |
|
display_Proj = display_Proj.drop_duplicates(subset=['Player']) |
|
display_Proj = display_Proj.set_index('Player') |
|
display_Proj = display_Proj.sort_values(by='Median', ascending=False) |
|
|
|
with hold_container: |
|
hold_container = st.empty() |
|
|
|
|
|
if sport_var2 == 'NBA': |
|
st.dataframe(display_Proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(nba_player_roo_format, precision=2), height=1000, use_container_width = True) |
|
elif sport_var2 == 'NFL': |
|
st.dataframe(display_Proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(nfl_player_roo_format, precision=2), height=1000, use_container_width = True) |
|
|
|
st.download_button( |
|
label="Export Tables", |
|
data=convert_df_to_csv(raw_baselines), |
|
file_name='NFL_SD_export.csv', |
|
mime='text/csv', |
|
) |
|
|
|
with tab2: |
|
with st.expander('Info and Filters'): |
|
if st.button("Load/Reset Data", key='reset1'): |
|
st.cache_data.clear() |
|
nba_dk_sd_raw, nba_fd_sd_raw, nfl_dk_sd_raw, nfl_fd_sd_raw, nba_timestamp, nfl_dk_timestamp, nba_dk_id_dict, nfl_dk_id_dict, nba_fd_id_dict, nfl_fd_id_dict = init_baselines() |
|
for key in st.session_state.keys(): |
|
del st.session_state[key] |
|
sport_var1 = st.radio("What sport are you optimizing?", ('NBA', 'NFL'), key='sport_var1') |
|
if sport_var1 == 'NBA': |
|
dk_roo_raw = nba_dk_sd_raw |
|
fd_roo_raw = nba_fd_sd_raw |
|
elif sport_var1 == 'NFL': |
|
dk_roo_raw = nfl_dk_sd_raw |
|
fd_roo_raw = nfl_fd_sd_raw |
|
slate_var1 = st.radio("Which data are you loading?", ('Paydirt (Main)', 'Paydirt (Secondary)', 'Paydirt (Auxiliary)'), 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 == 'Paydirt (Main)': |
|
raw_baselines = dk_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #1'] |
|
elif slate_var1 == 'Paydirt (Secondary)': |
|
raw_baselines = dk_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #2'] |
|
elif slate_var1 == 'Paydirt (Auxiliary)': |
|
raw_baselines = dk_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #3'] |
|
elif site_var1 == 'Fanduel': |
|
if slate_var1 == 'Paydirt (Main)': |
|
st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen") |
|
raw_baselines = fd_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #1'] |
|
elif slate_var1 == 'Paydirt (Secondary)': |
|
st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen") |
|
raw_baselines = fd_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #2'] |
|
elif slate_var1 == 'Paydirt (Auxiliary)': |
|
st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen") |
|
raw_baselines = fd_roo_raw |
|
raw_baselines = raw_baselines[raw_baselines['slate'] == 'Showdown #3'] |
|
|
|
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') |
|
|
|
if contest_var1 == 'Small Field GPP': |
|
ownframe = raw_baselines.copy() |
|
if sport_var1 == 'NBA': |
|
ownframe['Own'] = ownframe['Small_Own'] |
|
elif sport_var1 == 'NFL': |
|
ownframe['Own'] = ownframe['Small_Field_Own'] |
|
elif contest_var1 == 'Large Field GPP': |
|
ownframe = raw_baselines.copy() |
|
if sport_var1 == 'NBA': |
|
ownframe['Own'] = ownframe['Large_Own'] |
|
elif sport_var1 == 'NFL': |
|
ownframe['Own'] = ownframe['Large_Field_Own'] |
|
elif contest_var1 == 'Cash': |
|
ownframe = raw_baselines.copy() |
|
if sport_var1 == 'NBA': |
|
ownframe['Own'] = ownframe['Cash_Own'] |
|
elif sport_var1 == 'NFL': |
|
ownframe['Own'] = ownframe['Cash_Field_Own'] |
|
export_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'CPT_Own', 'player_id']] |
|
export_baselines['CPT_Proj'] = export_baselines['Median'] * 1.5 |
|
if sport_var1 == 'NBA': |
|
export_baselines['CPT_Salary'] = export_baselines['Salary'] * 1.5 |
|
elif sport_var1 == 'NFL': |
|
export_baselines['CPT_Salary'] = export_baselines['Salary'] |
|
export_baselines['salary'] = export_baselines['Salary'] / 1.5 |
|
export_baselines['ID'] = export_baselines['player_id'] |
|
display_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'CPT_Own']] |
|
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) |
|
display_baselines = display_baselines.drop_duplicates(subset=['Player']) |
|
|
|
st.session_state.display_baselines = display_baselines.copy() |
|
st.session_state.export_baselines = export_baselines.copy() |
|
|
|
index_check = pd.DataFrame() |
|
flex_proj = pd.DataFrame() |
|
cpt_proj = pd.DataFrame() |
|
|
|
if site_var1 == 'Draftkings': |
|
cpt_proj['Player'] = display_baselines['Player'] |
|
if sport_var1 == 'NBA': |
|
cpt_proj['Salary'] = display_baselines['Salary'] * 1.5 |
|
elif sport_var1 == 'NFL': |
|
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'] |
|
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'] |
|
if sport_var1 == 'NBA': |
|
flex_proj['Salary'] = display_baselines['Salary'] |
|
elif sport_var1 == 'NFL': |
|
flex_proj['Salary'] = display_baselines['Salary'] / 1.5 |
|
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) |
|
|
|
display_container = st.empty() |
|
display_dl_container = st.empty() |
|
optimize_container = st.empty() |
|
download_container = st.empty() |
|
freq_container = st.empty() |
|
if st.button('Optimize'): |
|
for key in st.session_state.keys(): |
|
del st.session_state[key] |
|
max_proj = 1000 |
|
max_own = 1000 |
|
total_proj = 0 |
|
total_own = 0 |
|
display_container = st.empty() |
|
display_dl_container = st.empty() |
|
optimize_container = st.empty() |
|
download_container = st.empty() |
|
freq_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) |
|
|
|
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']) |
|
st.session_state.portfolio = portfolio.drop_duplicates() |
|
|
|
final_outcomes = portfolio |
|
st.session_state.final_outcomes = portfolio |
|
|
|
player_freq = pd.DataFrame(np.column_stack(np.unique(st.session_state.portfolio.iloc[:,0:6].values, return_counts=True)), |
|
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True) |
|
player_freq['Freq'] = player_freq['Freq'].astype(int) |
|
player_freq['Position'] = player_freq['Player'].map(player_pos) |
|
player_freq['Salary'] = player_freq['Player'].map(player_sal) |
|
player_freq['Proj Own'] = player_freq['Player'].map(player_own) / 100 |
|
player_freq['Exposure'] = player_freq['Freq']/(linenum_var1) |
|
player_freq['Team'] = player_freq['Player'].map(player_team) |
|
|
|
final_outcomes_export = pd.DataFrame() |
|
split_portfolio = pd.DataFrame() |
|
|
|
if site_var1 == 'Draftkings': |
|
|
|
split_portfolio[['CPT', 'CPT_ID']] = final_outcomes.CPT.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX1', 'FLEX1_ID']] = final_outcomes.FLEX1.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX2', 'FLEX2_ID']] = final_outcomes.FLEX2.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX3', 'FLEX3_ID']] = final_outcomes.FLEX3.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX4', 'FLEX4_ID']] = final_outcomes.FLEX4.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX5', 'FLEX5_ID']] = final_outcomes.FLEX5.str.split("-", n=1, expand = True) |
|
|
|
split_portfolio['CPT'] = split_portfolio['CPT'].str.strip() |
|
split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str.strip() |
|
split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str.strip() |
|
split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str.strip() |
|
split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str.strip() |
|
split_portfolio['FLEX5'] = split_portfolio['FLEX5'].str.strip() |
|
|
|
final_outcomes_export['CPT'] = split_portfolio['CPT'] |
|
final_outcomes_export['FLEX1'] = split_portfolio['FLEX1'] |
|
final_outcomes_export['FLEX2'] = split_portfolio['FLEX2'] |
|
final_outcomes_export['FLEX3'] = split_portfolio['FLEX3'] |
|
final_outcomes_export['FLEX4'] = split_portfolio['FLEX4'] |
|
final_outcomes_export['FLEX5'] = split_portfolio['FLEX5'] |
|
|
|
if sport_var1 == 'NFL': |
|
final_outcomes_export['CPT'].replace(nfl_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX1'].replace(nfl_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX2'].replace(nfl_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX3'].replace(nfl_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX4'].replace(nfl_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX5'].replace(nfl_dk_id_dict, inplace=True) |
|
elif sport_var1 == 'NBA': |
|
final_outcomes_export['CPT'].replace(nba_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX1'].replace(nba_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX2'].replace(nba_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX3'].replace(nba_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX4'].replace(nba_dk_id_dict, inplace=True) |
|
final_outcomes_export['FLEX5'].replace(nba_dk_id_dict, inplace=True) |
|
final_outcomes_export['Salary'] = final_outcomes['Cost'] |
|
final_outcomes_export['Own'] = final_outcomes['Own'] |
|
final_outcomes_export['Proj'] = final_outcomes['Proj'] |
|
|
|
st.session_state.final_outcomes_export = final_outcomes_export.copy() |
|
|
|
elif site_var1 == 'Fanduel': |
|
|
|
split_portfolio[['MVP', 'CPT_ID']] = final_outcomes.MVP.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX1', 'FLEX1_ID']] = final_outcomes.FLEX1.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX2', 'FLEX2_ID']] = final_outcomes.FLEX2.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX3', 'FLEX3_ID']] = final_outcomes.FLEX3.str.split("-", n=1, expand = True) |
|
split_portfolio[['FLEX4', 'FLEX4_ID']] = final_outcomes.FLEX4.str.split("-", n=1, expand = True) |
|
|
|
split_portfolio['MVP'] = split_portfolio['MVP'].str.strip() |
|
split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str.strip() |
|
split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str.strip() |
|
split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str.strip() |
|
split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str.strip() |
|
|
|
final_outcomes_export['MVP'] = split_portfolio['MVP'] |
|
final_outcomes_export['FLEX1'] = split_portfolio['FLEX1'] |
|
final_outcomes_export['FLEX2'] = split_portfolio['FLEX2'] |
|
final_outcomes_export['FLEX3'] = split_portfolio['FLEX3'] |
|
final_outcomes_export['FLEX4'] = split_portfolio['FLEX4'] |
|
|
|
if sport_var1 == 'NFL': |
|
final_outcomes_export['MVP'].replace(nfl_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX1'].replace(nfl_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX2'].replace(nfl_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX3'].replace(nfl_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX4'].replace(nfl_fd_id_dict, inplace=True) |
|
elif sport_var1 == 'NBA': |
|
final_outcomes_export['MVP'].replace(nba_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX1'].replace(nba_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX2'].replace(nba_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX3'].replace(nba_fd_id_dict, inplace=True) |
|
final_outcomes_export['FLEX4'].replace(nba_fd_id_dict, inplace=True) |
|
final_outcomes_export['Salary'] = final_outcomes['Cost'] |
|
final_outcomes_export['Own'] = final_outcomes['Own'] |
|
final_outcomes_export['Proj'] = final_outcomes['Proj'] |
|
|
|
st.session_state.FD_final_outcomes_export = final_outcomes_export.copy() |
|
|
|
st.session_state.player_freq = player_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure']] |
|
with display_container: |
|
display_container = st.empty() |
|
if 'display_baselines' in st.session_state: |
|
st.dataframe(st.session_state.display_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) |
|
|
|
with display_dl_container: |
|
display_dl_container = st.empty() |
|
if 'export_baselines' in st.session_state: |
|
st.download_button( |
|
label="Export Projections", |
|
data=convert_df_to_csv(st.session_state.export_baselines), |
|
file_name='showdown_proj_export.csv', |
|
mime='text/csv', |
|
) |
|
|
|
with optimize_container: |
|
optimize_container = st.empty() |
|
if 'final_outcomes' in st.session_state: |
|
st.dataframe(st.session_state.final_outcomes.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) |
|
|
|
with download_container: |
|
download_container = st.empty() |
|
if site_var1 == 'Draftkings': |
|
if 'final_outcomes_export' in st.session_state: |
|
st.download_button( |
|
label="Export Optimals", |
|
data=convert_df_to_csv(st.session_state.final_outcomes_export), |
|
file_name='NFL_optimals_export.csv', |
|
mime='text/csv', |
|
) |
|
elif site_var1 == 'Fanduel': |
|
if 'FD_final_outcomes_export' in st.session_state: |
|
st.download_button( |
|
label="Export Optimals", |
|
data=convert_df_to_csv(st.session_state.FD_final_outcomes_export), |
|
file_name='FD_NFL_optimals_export.csv', |
|
mime='text/csv', |
|
) |
|
|
|
with freq_container: |
|
freq_container = st.empty() |
|
if 'player_freq' in st.session_state: |
|
st.dataframe(st.session_state.player_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(expose_format, precision=2), use_container_width = True) |
|
|