Spaces:
Runtime error
Runtime error
import streamlit as st | |
st.set_page_config(layout="wide") | |
for name in dir(): | |
if not name.startswith('_'): | |
del globals()[name] | |
import pulp | |
import numpy as np | |
import pandas as pd | |
import streamlit as st | |
import gspread | |
import time | |
from itertools import combinations | |
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 | |
gcservice_account = init_conn() | |
expose_format = {'Proj Own': '{:.2%}','Exposure': '{:.2%}'} | |
all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1NmKa-b-2D3w7rRxwMPSchh31GKfJ1XcDI2GU8rXWnHI/edit#gid=943304327' | |
def grab_baseline_stuff(): | |
sh = gcservice_account.open_by_url(all_dk_player_projections) | |
worksheet = sh.worksheet('Player_Data_Master') | |
raw_display = pd.DataFrame(worksheet.get_all_records()) | |
raw_display.replace(' - ', 0, inplace=True) | |
raw_display.replace('', np.nan, inplace=True) | |
raw_display = raw_display.dropna(subset=' Clean Name ') | |
dk_raw_proj = raw_display[[' Clean Name ', 'Team', 'Opp', 'Line', 'PP Unit', ' Position ', ' DK Salary ', 'Final DK Projection', 'DK uploadID', 'DK_Own']] | |
dk_raw_proj = dk_raw_proj.set_axis(['Player', 'Team', 'Opp', 'Line', 'PP Unit', 'Position', 'Salary', 'Median', 'player_id', 'Own'], axis=1) | |
dk_raw_proj = dk_raw_proj.dropna(subset='Salary') | |
fd_raw_proj = raw_display[[' Clean Name ', 'Team', 'Opp', 'Line', 'PP Unit', ' FD Position ', 'FD Salary', 'Final FD Projection', 'FD uploadID', 'FD_Own']] | |
fd_raw_proj = fd_raw_proj.set_axis(['Player', 'Team', 'Opp', 'Line', 'PP Unit', 'Position', 'Salary', 'Median', 'player_id', 'Own'], axis=1) | |
fd_raw_proj = fd_raw_proj.dropna(subset='Salary') | |
dk_raw_proj['Salary'] = dk_raw_proj['Salary'].str.replace(',', '') | |
dk_raw_proj['Salary'] = dk_raw_proj['Salary'].str.replace('$', '').astype(float) | |
fd_raw_proj['Salary'] = fd_raw_proj['Salary'].str.replace(',', '') | |
fd_raw_proj['Salary'] = fd_raw_proj['Salary'].str.replace('$', '').astype(float) | |
dk_raw_proj['Median'] = dk_raw_proj['Median'].astype(float) | |
fd_raw_proj['Median'] = fd_raw_proj['Median'].astype(float) | |
dk_raw_proj['Own'] = dk_raw_proj['Median'].astype(float) | |
fd_raw_proj['Own'] = fd_raw_proj['Median'].astype(float) | |
dk_raw_proj['player_id'] = dk_raw_proj['player_id'].astype(str) | |
fd_raw_proj['player_id'] = fd_raw_proj['player_id'].astype(str) | |
dk_raw_proj['Name_ID'] = dk_raw_proj['Player'] + ' (' + dk_raw_proj['player_id'].str[:-2] + ')' | |
fd_raw_proj['Name_ID'] = fd_raw_proj['player_id'].str[:-2] + ':' + fd_raw_proj['Player'] | |
dk_ids = dict(zip(dk_raw_proj['Player'], dk_raw_proj['Name_ID'])) | |
fd_ids = dict(zip(fd_raw_proj['Player'], fd_raw_proj['Name_ID'])) | |
worksheet = sh.worksheet('Timestamp') | |
timestamp = worksheet.acell('A1').value | |
return dk_raw_proj, fd_raw_proj, dk_ids, fd_ids, timestamp | |
def convert_df_to_csv(df): | |
return df.to_csv().encode('utf-8') | |
dk_raw_proj, fd_raw_proj, dkid_dict, fdid_dict, timestamp = grab_baseline_stuff() | |
t_stamp = f"Last Update: " + str(timestamp) + f" CST" | |
opp_dict = dict(zip(dk_raw_proj.Team, dk_raw_proj.Opp)) | |
tab1, tab2 = st.tabs(['Uploads and Info', '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', 'Median', 'Line', 'PP Unit', 'Own', and 'player_id'. The player_id is the draftkings or fanduel ID associated with the player for upload.") | |
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) | |
except: | |
proj_dataframe = pd.read_excel(proj_file) | |
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: | |
st.info(t_stamp) | |
if st.button("Load/Reset Data", key='reset1'): | |
st.cache_data.clear() | |
dk_raw_proj, fd_raw_proj, dk_ids, fd_ids, timestamp = grab_baseline_stuff() | |
t_stamp = f"Last Update: " + str(timestamp) + f" CST" | |
slate_var1 = st.radio("Which data are you loading?", ('Paydirt', 'User'), key='slate_var1') | |
site_var1 = st.radio("What site are you working with?", ('Draftkings', 'Fanduel'), key='site_var1') | |
if site_var1 == 'Draftkings': | |
if slate_var1 == 'User': | |
raw_baselines = proj_dataframe | |
elif slate_var1 != 'User': | |
raw_baselines = dk_raw_proj | |
elif site_var1 == 'Fanduel': | |
if slate_var1 == 'User': | |
raw_baselines = proj_dataframe | |
elif slate_var1 != 'User': | |
raw_baselines = fd_raw_proj | |
contest_var1 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP', 'Round Robin'), key='contest_var1') | |
if contest_var1 != 'Cash': | |
stack_var1 = st.selectbox('Which team are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var1') | |
stack_size_var1 = st.selectbox('What size of stack?', options = [3, 4], key='stack_size_var1') | |
line_choice_var1 = st.selectbox('Which line for main?', options = [1, 2, 3, 4], key='line_choice_var1') | |
ministack_var1 = st.selectbox('Who should be the secondary stack?', options = raw_baselines['Team'].unique(), key='ministack_var1') | |
ministack_size_var1 = st.selectbox('What size of secondary stack?', options = [2, 3, 4], key='ministack_size_var1') | |
miniline_choice_var1 = st.selectbox('Which line for secondary?', options = [1, 2, 3, 4], key='miniline_choice_var1') | |
opp_var1 = opp_dict[stack_var1] | |
split_var1 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var1') | |
if split_var1 == 'Specific Games': | |
team_var1 = st.multiselect('Which teams would you like to include in the optimization?', options = raw_baselines['Team'].unique(), key='team_var1') | |
elif split_var1 == 'Full Slate Run': | |
team_var1 = raw_baselines.Team.values.tolist() | |
lock_var1 = st.multiselect("Are there any players you want to use in all lineups (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var1') | |
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') | |
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 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 = 54900, value = 54000, step = 100, key='min_sal1') | |
max_sal1 = st.number_input('Max Salary', min_value = 45000, max_value = 55000, value = 55000, step = 100, key='max_sal1') | |
with col2: | |
raw_baselines = raw_baselines[raw_baselines['Team'].isin(team_var1)] | |
raw_baselines = raw_baselines[~raw_baselines['Player'].isin(avoid_var1)] | |
ownframe = raw_baselines.copy() | |
if contest_var1 == 'Cash': | |
ownframe['Own%'] = np.where((ownframe['Position'] == 'G') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean() >= 0), ownframe['Own'] * (10 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean(), ownframe['Own']) | |
ownframe['Own%'] = np.where((ownframe['Position'] != 'G') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean(), ownframe['Own%']) | |
ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%']) | |
ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum()) | |
if contest_var1 == 'Small Field GPP': | |
ownframe['Own%'] = np.where((ownframe['Position'] == 'G') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean(), ownframe['Own']) | |
ownframe['Own%'] = np.where((ownframe['Position'] != 'G') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean() >= 0), ownframe['Own'] * (3 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean(), ownframe['Own%']) | |
ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%']) | |
ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum()) | |
if contest_var1 == 'Large Field GPP': | |
ownframe['Own%'] = np.where((ownframe['Position'] == 'G') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean() >= 0), ownframe['Own'] * (3 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'G', 'Own'].mean(), ownframe['Own']) | |
ownframe['Own%'] = np.where((ownframe['Position'] != 'G') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean() >= 0), ownframe['Own'] * (1.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'G', 'Own'].mean(), ownframe['Own%']) | |
ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%']) | |
ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum()) | |
raw_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Line', 'PP Unit', 'Median', 'Own']] | |
raw_baselines = raw_baselines.sort_values(by='Median', ascending=False) | |
raw_baselines['lock'] = np.where(raw_baselines['Player'].isin(lock_var1), 1, 0) | |
st.session_state.export_baselines = raw_baselines | |
st.session_state.display_baselines = raw_baselines | |
if st.button('Optimize'): | |
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 = [] | |
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_var1), 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'])) | |
player_line = dict(zip(flex_file['Player'], flex_file['Line'])) | |
player_ppunit = dict(zip(flex_file['Player'], flex_file['PP Unit'])) | |
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': | |
if contest_var1 == 'Cash': | |
for flex in flex_file['Team'].unique(): | |
sub_idx = flex_file[(flex_file['Team'] == flex) & (flex_file['Position'] != 'G')].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4 | |
elif contest_var1 != 'Cash': | |
for flex in flex_file['Team'].unique(): | |
sub_idx = flex_file[(flex_file['Team'] == stack_var1) & (flex_file['Position'] != 'G') & (flex_file['Line'] == line_choice_var1)].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == stack_size_var1 | |
for flex in flex_file['Team'].unique(): | |
sub_idx = flex_file[(flex_file['Team'] == ministack_var1) & (flex_file['Position'] != 'G') & (flex_file['Line'] == miniline_choice_var1)].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == ministack_size_var1 | |
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_var1) | |
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("G")].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"].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("W")].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'] == "D"].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'] == "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'].str.contains("W")].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'] == "D"].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2 | |
elif site_var1 == 'Fanduel': | |
if contest_var1 == 'Cash': | |
for flex in flex_file['Team'].unique(): | |
sub_idx = flex_file[(flex_file['Team'] == flex) & (flex_file['Position'] != 'G')].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4 | |
elif contest_var1 != 'Cash': | |
for flex in flex_file['Team'].unique(): | |
sub_idx = flex_file[(flex_file['Team'] == stack_var1) & (flex_file['Position'] != 'G') & (flex_file['Line'] == line_choice_var1)].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == stack_size_var1 | |
for flex in flex_file['Team'].unique(): | |
sub_idx = flex_file[(flex_file['Team'] == ministack_var1) & (flex_file['Position'] != 'G') & (flex_file['Line'] == miniline_choice_var1)].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == ministack_size_var1 | |
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_var1) | |
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("G")].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"].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'].str.contains("W")].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'] == "D"].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'] == "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'].str.contains("W")].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'] == "D"].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2 | |
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 | |
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) | |
df['Line'] = df['Names'].map(player_line) | |
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_var1 == 'Draftkings': | |
line_hold = lineup_final[['Names']] | |
line_hold['pos'] = line_hold['Names'].map(player_pos) | |
cvar = 0 | |
for pname in range(0,len(line_hold)): | |
if cvar == 2: | |
pname = len(line_hold) | |
elif cvar < 2: | |
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 = cvar + 1 | |
p_used.extend(sorted_lineup) | |
wvar = 0 | |
for pname in range(0,len(line_hold)): | |
if wvar == 3: | |
pname = len(line_hold) | |
elif wvar < 3: | |
if line_hold.iat[pname,1] in ['RW', 'LW']: | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
wvar = wvar + 1 | |
p_used.extend(sorted_lineup) | |
dvar = 0 | |
for pname in range(0,len(line_hold)): | |
if dvar == 2: | |
pname = len(line_hold) | |
elif dvar < 2: | |
if line_hold.iat[pname,1] == "D": | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
dvar = dvar + 1 | |
p_used.extend(sorted_lineup) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] == 'G': | |
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] != 'G': | |
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_var1 == 'Fanduel': | |
line_hold = lineup_final[['Names']] | |
line_hold['pos'] = line_hold['Names'].map(player_pos) | |
cvar = 0 | |
for pname in range(0,len(line_hold)): | |
if cvar == 2: | |
pname = len(line_hold) | |
elif cvar < 2: | |
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 = cvar + 1 | |
p_used.extend(sorted_lineup) | |
wvar = 0 | |
for pname in range(0,len(line_hold)): | |
if wvar == 2: | |
pname = len(line_hold) | |
elif wvar < 2: | |
if line_hold.iat[pname,1] == 'W': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
wvar = wvar + 1 | |
p_used.extend(sorted_lineup) | |
dvar = 0 | |
for pname in range(0,len(line_hold)): | |
if dvar == 2: | |
pname = len(line_hold) | |
elif dvar < 2: | |
if line_hold.iat[pname,1] == "D": | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
dvar = dvar + 1 | |
p_used.extend(sorted_lineup) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] != 'G': | |
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] == 'G': | |
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['Line'] = lineup_test['Names'].map(player_line) | |
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_var1 == 'Draftkings': | |
portfolio.rename(columns={0: "C1", 1: "C2", 2: "W1", 3: "W2", 4: "W3", 5: "D1", 6: "D2", 7: "G", 8: "UTIL"}, inplace = True) | |
elif site_var1 == 'Fanduel': | |
portfolio.rename(columns={0: "C1", 1: "C2", 2: "W1", 3: "W2", 4: "D1", 5: "D2", 6: "UTIL1", 7: "UTIL2", 8: "G"}, 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() | |
st.session_state.final_outcomes = portfolio | |
if site_var1 == 'Draftkings': | |
final_outcomes = portfolio[['C1', 'C2', 'W1', 'W2', 'W3', 'D1', 'D2', 'G', 'UTIL', 'Cost', 'Proj', 'Own']] | |
final_outcomes_export = pd.DataFrame() | |
final_outcomes_export['C1'] = final_outcomes['C1'] | |
final_outcomes_export['C2'] = final_outcomes['C2'] | |
final_outcomes_export['W1'] = final_outcomes['W1'] | |
final_outcomes_export['W2'] = final_outcomes['W2'] | |
final_outcomes_export['W3'] = final_outcomes['W3'] | |
final_outcomes_export['D1'] = final_outcomes['D1'] | |
final_outcomes_export['D2'] = final_outcomes['D2'] | |
final_outcomes_export['G'] = final_outcomes['G'] | |
final_outcomes_export['UTIL'] = final_outcomes['UTIL'] | |
final_outcomes_export['Salary'] = final_outcomes['Cost'] | |
final_outcomes_export['Own'] = final_outcomes['Own'] | |
final_outcomes_export['Proj'] = final_outcomes['Proj'] | |
final_outcomes_export['C1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['C2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['W1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['W2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['W3'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['D1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['D2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['G'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['UTIL'].replace(dkid_dict, inplace=True) | |
st.session_state.final_outcomes_export = final_outcomes_export.copy() | |
elif site_var1 == 'Fanduel': | |
final_outcomes = portfolio[['C1', 'C2', 'W1', 'W2', 'D1', 'D2', 'UTIL1', 'UTIL2', 'G', 'Cost', 'Proj', 'Own']] | |
final_outcomes_export = pd.DataFrame() | |
final_outcomes_export['C1'] = final_outcomes['C1'] | |
final_outcomes_export['C2'] = final_outcomes['C2'] | |
final_outcomes_export['W1'] = final_outcomes['W1'] | |
final_outcomes_export['W2'] = final_outcomes['W2'] | |
final_outcomes_export['D1'] = final_outcomes['D1'] | |
final_outcomes_export['D2'] = final_outcomes['D2'] | |
final_outcomes_export['UTIL1'] = final_outcomes['UTIL1'] | |
final_outcomes_export['UTIL2'] = final_outcomes['UTIL2'] | |
final_outcomes_export['G'] = final_outcomes['G'] | |
final_outcomes_export['Salary'] = final_outcomes['Cost'] | |
final_outcomes_export['Own'] = final_outcomes['Own'] | |
final_outcomes_export['Proj'] = final_outcomes['Proj'] | |
final_outcomes_export['C1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['C2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['W1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['W2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['D1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['D2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['UTIL1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['UTIL2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['G'].replace(dkid_dict, inplace=True) | |
st.session_state.FD_final_outcomes_export = final_outcomes_export.copy() | |
st.session_state.player_freq = pd.DataFrame(np.column_stack(np.unique(st.session_state.portfolio.iloc[:,0:8].values, return_counts=True)), | |
columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True) | |
st.session_state.player_freq['Freq'] = st.session_state.player_freq['Freq'].astype(int) | |
st.session_state.player_freq['Position'] = st.session_state.player_freq['Player'].map(player_pos) | |
st.session_state.player_freq['Salary'] = st.session_state.player_freq['Player'].map(player_sal) | |
st.session_state.player_freq['Proj Own'] = st.session_state.player_freq['Player'].map(player_own) / 100 | |
st.session_state.player_freq['Exposure'] = st.session_state.player_freq['Freq']/(linenum_var1) | |
st.session_state.player_freq['Team'] = st.session_state.player_freq['Player'].map(player_team) | |
st.session_state.player_freq = st.session_state.player_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure']] | |
st.session_state.player_freq = st.session_state.player_freq.set_index('Player') | |
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='NHL_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='NHL_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_NHL_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) |