Spaces:
Running
Running
James McCool
Enhance opponent variable assignment in app.py to include additional logic for non-JAC stacks, improving accuracy in team identification for Fanduel. This change builds on previous refactoring efforts to ensure clarity and maintainability of the code.
8c6ff6e
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 | |
def init_conn(): | |
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] | |
credentials = { | |
"type": "service_account", | |
"project_id": "sheets-api-connect-378620", | |
"private_key_id": st.secrets['sheets_api_pk'], | |
"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" | |
} | |
NFL_Data = st.secrets["NFL_data"] | |
gc_con = gspread.service_account_from_dict(credentials, scope) | |
return gc_con, NFL_Data | |
gc, all_dk_player_projections = 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%}'} | |
expose_format = {'Proj Own': '{:.2%}','Exposure': '{:.2%}'} | |
def init_baselines(): | |
sh = gc.open_by_url(all_dk_player_projections) | |
worksheet = sh.worksheet('Site_Info') | |
raw_display = pd.DataFrame(worksheet.get_all_records()) | |
site_slates = raw_display | |
worksheet = sh.worksheet('Player_Projections') | |
raw_display = pd.DataFrame(worksheet.get_all_records()) | |
raw_display = raw_display[raw_display['Position'] != 'K'] | |
player_stats = raw_display | |
worksheet = sh.worksheet('DK_ROO') | |
load_display = pd.DataFrame(worksheet.get_all_records()) | |
load_display.replace('', np.nan, inplace=True) | |
raw_display = load_display.dropna(subset=['Median']) | |
raw_display = raw_display[raw_display['Position'] != 'K'] | |
dk_ids = dict(zip(raw_display['Player'], raw_display['player_id'])) | |
dk_roo_raw = raw_display | |
worksheet = sh.worksheet('FD_ROO') | |
load_display = pd.DataFrame(worksheet.get_all_records()) | |
load_display.replace('', np.nan, inplace=True) | |
raw_display = load_display.dropna(subset=['Median']) | |
raw_display = raw_display[raw_display['Position'] != 'K'] | |
fd_ids = dict(zip(raw_display['Player'], raw_display['player_id'])) | |
fd_roo_raw = raw_display | |
worksheet = sh.worksheet('DK_Stacks') | |
load_display = pd.DataFrame(worksheet.get_all_records()) | |
raw_display = load_display | |
raw_display = raw_display.sort_values(by='Own', ascending=False) | |
dk_stacks_raw = raw_display | |
worksheet = sh.worksheet('FD_Stacks') | |
load_display = pd.DataFrame(worksheet.get_all_records()) | |
raw_display = load_display | |
raw_display = raw_display.sort_values(by='Own', ascending=False) | |
fd_stacks_raw = raw_display | |
return site_slates, player_stats, dk_roo_raw, fd_roo_raw, dk_stacks_raw, fd_stacks_raw, dk_ids, fd_ids | |
def convert_df_to_csv(df): | |
return df.to_csv().encode('utf-8') | |
site_slates, player_stats, dk_roo_raw, fd_roo_raw, dk_stacks_raw, fd_stacks_raw, dkid_dict, fdid_dict = init_baselines() | |
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST" | |
col1, col2 = st.columns([1, 5]) | |
opp_dict = dict(zip(dk_roo_raw.Team, dk_roo_raw.Opp)) | |
tab1, tab2 = st.tabs(['Optimizer', 'Uploads and Info']) | |
with tab2: | |
st.info("The Projections file can have any columns in any order, but must contain columns explicitly named: 'Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', and 'Own'.") | |
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 tab1: | |
col1, col2 = st.columns([1, 5]) | |
with col1: | |
st.info(t_stamp) | |
if st.button("Load/Reset Data", key='reset1'): | |
st.cache_data.clear() | |
site_slates, player_stats, dk_roo_raw, fd_roo_raw, dk_stacks_raw, fd_stacks_raw, dk_ids, fd_ids = init_baselines() | |
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST" | |
col1, col2 = st.columns([1, 5]) | |
opp_dict = dict(zip(dk_roo_raw.Team, dk_roo_raw.Opp)) | |
slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'All Games', '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_roo_raw[dk_roo_raw['slate'] == str(slate_var1)] | |
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall'] | |
elif site_var1 == 'Fanduel': | |
if slate_var1 == 'User': | |
raw_baselines = proj_dataframe | |
elif slate_var1 != 'User': | |
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var1)] | |
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall'] | |
contest_var1 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP', 'Round Robin'), key='contest_var1') | |
trim_choice1 = st.selectbox("Allow overowned lineups?", options = ['Yes', 'No']) | |
if trim_choice1 == 'Yes': | |
trim_var1 = 0 | |
elif trim_choice1 == 'No': | |
trim_var1 = 1 | |
if contest_var1 == 'Small Field GPP': | |
st.info('The Pivot optimal uses backend functions to create a stack and lock in certain pieces, if you want control over QB pairing use the Manual model instead.') | |
opto_var1 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var1') | |
if opto_var1 == "Manual": | |
stack_var1 = st.selectbox('Which teams are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var1') | |
opp_var1 = opp_dict[stack_var1] | |
qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1') | |
ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1') | |
elif contest_var1 == 'Large Field GPP': | |
st.info('The Pivot optimal uses backend functions to create a stack and lock in certain pieces, if you want control over QB pairing use the Manual model instead.') | |
opto_var1 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var1') | |
if opto_var1 == "Manual": | |
stack_var1 = st.selectbox('Which team are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var1') | |
opp_var1 = opp_dict[stack_var1] | |
qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1') | |
ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1') | |
elif contest_var1 == 'Round Robin': | |
st.info('A Round Robin optimization will run a single optimal for all the teams on the slate based on your stacking inputs') | |
qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1') | |
ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_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') | |
if contest_var1 == 'Round Robin': | |
linenum_var1 = len(raw_baselines['Team'].unique()) | |
elif contest_var1 != 'Round Robin': | |
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 = 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: | |
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'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (10 * (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%'] > 75, 75, ownframe['Own%']) | |
ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum()) | |
if contest_var1 == 'Small Field GPP': | |
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'] * (3 * (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%'] * (900 / ownframe['Own%'].sum()) | |
if contest_var1 == 'Large Field GPP': | |
ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (3 * (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'] * (1.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%'] * (900 / ownframe['Own%'].sum()) | |
raw_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', '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.dataframe(raw_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) | |
st.download_button( | |
label="Export Projections", | |
data=convert_df_to_csv(raw_baselines), | |
file_name='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() | |
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: | |
if contest_var1 == 'Round Robin': | |
while x <= len(raw_baselines['Team'].unique()): | |
stack_var1 = raw_baselines['Team'].unique()[x-1] | |
if site_var1 == 'Draftkings': | |
opp_var1 = opp_dict[stack_var1] | |
elif site_var1 == 'Fanduel': | |
if stack_var1 == 'JAC': | |
opp_var1 = opp_dict['JAX'] | |
elif stack_var1 != 'JAC': | |
opp_var1 = opp_dict[stack_var1] | |
st.write(stack_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'])) | |
obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index} | |
obj_own_max = {idx: (flex_file['Proj DK Own%'][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': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
elif contest_var1 == 'Small Field GPP': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif contest_var1 == 'Round Robin': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif contest_var1 == 'Large Field GPP': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
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'] == "QB"].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'] == "RB"].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'] == "RB"].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'] == "WR"].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'] == "WR"].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'] == "TE"].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'] == "DST"].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif site_var1 == 'Fanduel': | |
if contest_var1 == 'Cash': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
elif contest_var1 == 'Small Field GPP': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif contest_var1 == 'Round Robin': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif contest_var1 == 'Large Field GPP': | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
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'] == "QB"].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'] == "RB"].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'] == "RB"].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'] == "WR"].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'] == "WR"].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'] == "TE"].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'] == "DST"].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 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]) | |
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.solve() | |
for v in total_score.variables(): | |
if v.varValue > 0: | |
lineup_list.append(v.name) | |
df = pd.DataFrame(lineup_list) | |
df['Names'] = df[0].map(player_match) | |
df['Cost'] = df['Names'].map(player_sal) | |
df['Proj'] = df['Names'].map(player_proj) | |
df['Own'] = df['Names'].map(player_own) | |
total_cost = sum(df['Cost']) | |
total_own = sum(df['Own']) | |
total_proj = sum(df['Proj']) | |
lineup_raw = pd.DataFrame(lineup_list) | |
lineup_raw['Names'] = lineup_raw[0].map(player_match) | |
lineup_raw['value'] = lineup_raw[0].map(player_index_match) | |
lineup_final = lineup_raw.sort_values(by=['value']) | |
del lineup_final[lineup_final.columns[0]] | |
del lineup_final[lineup_final.columns[1]] | |
lineup_final = lineup_final.reset_index(drop=True) | |
if site_var1 == 'Draftkings': | |
line_hold = lineup_final[['Names']] | |
line_hold['pos'] = line_hold['Names'].map(player_pos) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] == 'QB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
p_used.extend(sorted_lineup) | |
rbvar = 0 | |
for pname in range(0,len(line_hold)): | |
if rbvar == 2: | |
pname = len(line_hold) | |
elif rbvar < 2: | |
if line_hold.iat[pname,1] == 'RB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
rbvar = rbvar + 1 | |
p_used.extend(sorted_lineup) | |
wrvar = 0 | |
for pname in range(0,len(line_hold)): | |
if wrvar == 3: | |
pname = len(line_hold) | |
elif wrvar < 3: | |
if line_hold.iat[pname,1] == 'WR': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
wrvar = wrvar + 1 | |
p_used.extend(sorted_lineup) | |
tevar = 0 | |
for pname in range(0,len(line_hold)): | |
if tevar == 1: | |
pname = len(line_hold) | |
elif tevar < 1: | |
if line_hold.iat[pname,1] == 'TE': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
tevar = tevar + 1 | |
p_used.extend(sorted_lineup) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] != 'DST': | |
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] == 'DST': | |
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) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] == 'QB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
p_used.extend(sorted_lineup) | |
rbvar = 0 | |
for pname in range(0,len(line_hold)): | |
if rbvar == 2: | |
pname = len(line_hold) | |
elif rbvar < 2: | |
if line_hold.iat[pname,1] == 'RB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
rbvar = rbvar + 1 | |
p_used.extend(sorted_lineup) | |
wrvar = 0 | |
for pname in range(0,len(line_hold)): | |
if wrvar == 3: | |
pname = len(line_hold) | |
elif wrvar < 3: | |
if line_hold.iat[pname,1] == 'WR': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
wrvar = wrvar + 1 | |
p_used.extend(sorted_lineup) | |
tevar = 0 | |
for pname in range(0,len(line_hold)): | |
if tevar == 1: | |
pname = len(line_hold) | |
elif tevar < 1: | |
if line_hold.iat[pname,1] == 'TE': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
tevar = tevar + 1 | |
p_used.extend(sorted_lineup) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] != 'DST': | |
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] == 'DST': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
p_used.extend(sorted_lineup) | |
lineup_final['sorted'] = sorted_lineup | |
lineup_final = lineup_final.drop(columns=['Names']) | |
lineup_final.rename(columns={"sorted": "Names"}, inplace = True) | |
lineup_test = lineup_final | |
lineup_final = lineup_final.T | |
lineup_final['Cost'] = total_cost | |
lineup_final['Proj'] = total_proj | |
lineup_final['Own'] = total_own | |
lineup_test['Team'] = lineup_test['Names'].map(player_team) | |
lineup_test['Position'] = lineup_test['Names'].map(player_pos) | |
lineup_test['Salary'] = lineup_test['Names'].map(player_sal) | |
lineup_test['Proj'] = lineup_test['Names'].map(player_proj) | |
lineup_test['Own'] = lineup_test['Names'].map(player_own) | |
lineup_test = lineup_test.set_index('Names') | |
lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0) | |
lineup_display.append(lineup_test) | |
with col2: | |
with st.container(): | |
st.table(lineup_test) | |
max_proj = total_proj | |
max_own = total_own | |
check_list.append(total_proj) | |
portfolio = pd.concat([portfolio, lineup_final], ignore_index = True) | |
x += 1 | |
elif contest_var1 != 'Round Robin': | |
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'])) | |
obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index} | |
obj_own_max = {idx: (flex_file['Proj DK Own%'][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': | |
qbfile = flex_file | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
elif contest_var1 == 'Small Field GPP': | |
if opto_var1 == "Pivot Optimal": | |
qbstack_var1 = 2 | |
ministack_var1 = 0 | |
dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False) | |
dk_stacks_raw.reset_index(drop=True) | |
fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False) | |
fd_stacks_raw.reset_index(drop=True) | |
dk_Max_Rank = dk_stacks_raw['Team'].values[0] | |
fd_Max_Rank = fd_stacks_raw['Team'].values[0] | |
stack_var1 = dk_Max_Rank | |
opp_var1 = opp_dict[stack_var1] | |
st.table(dk_stacks_raw) | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif contest_var1 == 'Large Field GPP': | |
if opto_var1 == "Pivot Optimal": | |
qbstack_var1 = 2 | |
ministack_var1 = 0 | |
dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False) | |
dk_stacks_raw.reset_index(drop=True) | |
fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False) | |
fd_stacks_raw.reset_index(drop=True) | |
dk_Max_Rank = dk_stacks_raw['Team'].values[0] | |
fd_Max_Rank = fd_stacks_raw['Team'].values[0] | |
stack_var1 = dk_Max_Rank | |
opp_var1 = opp_dict[stack_var1] | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
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'] == "QB"].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'] == "RB"].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'] == "RB"].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'] == "WR"].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'] == "WR"].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'] == "TE"].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'] == "DST"].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif site_var1 == 'Fanduel': | |
if contest_var1 == 'Cash': | |
qbfile = flex_file | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
elif contest_var1 == 'Small Field GPP': | |
if opto_var1 == "Pivot Optimal": | |
qbstack_var1 = 2 | |
ministack_var1 = 0 | |
dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False) | |
dk_stacks_raw.reset_index(drop=True) | |
fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False) | |
fd_stacks_raw.reset_index(drop=True) | |
dk_Max_Rank = dk_stacks_raw['Team'].values[0] | |
fd_Max_Rank = fd_stacks_raw['Team'].values[0] | |
stack_var1 = dk_Max_Rank | |
opp_var1 = opp_dict[stack_var1] | |
st.table(fd_stacks_raw) | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
elif contest_var1 == 'Large Field GPP': | |
if opto_var1 == "Pivot Optimal": | |
qbstack_var1 = 2 | |
ministack_var1 = 0 | |
dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False) | |
dk_stacks_raw.reset_index(drop=True) | |
fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)] | |
dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False) | |
fd_stacks_raw.reset_index(drop=True) | |
dk_Max_Rank = dk_stacks_raw['Team'].values[0] | |
fd_Max_Rank = fd_stacks_raw['Team'].values[0] | |
stack_var1 = fd_Max_Rank | |
opp_var1 = opp_dict[stack_var1] | |
qbfile = flex_file[flex_file['Team'] == stack_var1] | |
qbfile = qbfile[qbfile['Position'] == 'QB'] | |
qbfile = qbfile.reset_index() | |
qb_var = qbfile['Player'][0] | |
st.table(qbfile) | |
#st.write(stack_var1 + ' ' + qb_var) | |
for qbid in player_ids: | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-qbstack_var1*player_vars[qbid]]) >= 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == stack_var1 and | |
flex_file['Position'][i] in ('RB'))] + | |
[0*player_vars[qbid]]) == 0 | |
if flex_file['Position'][qbid] == 'QB': | |
total_score += pulp.lpSum([player_vars[i] for i in player_ids if | |
(flex_file['Team'][i] == opp_var1 and | |
flex_file['Position'][i] in ('WR', 'TE'))] + | |
[-ministack_var1*player_vars[qbid]]) >= 0 | |
for flex in flex_file['Player'].unique(): | |
sub_idx = flex_file[flex_file['Player'] == qb_var].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1 | |
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'] == "QB"].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'] == "RB"].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'] == "RB"].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'] == "WR"].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'] == "WR"].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'] == "TE"].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'] == "DST"].index | |
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 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 = lineup_final.reset_index(drop=True) | |
if site_var1 == 'Draftkings': | |
line_hold = lineup_final[['Names']] | |
line_hold['pos'] = line_hold['Names'].map(player_pos) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] == 'QB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
p_used.extend(sorted_lineup) | |
rbvar = 0 | |
for pname in range(0,len(line_hold)): | |
if rbvar == 2: | |
pname = len(line_hold) | |
elif rbvar < 2: | |
if line_hold.iat[pname,1] == 'RB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
rbvar = rbvar + 1 | |
p_used.extend(sorted_lineup) | |
wrvar = 0 | |
for pname in range(0,len(line_hold)): | |
if wrvar == 3: | |
pname = len(line_hold) | |
elif wrvar < 3: | |
if line_hold.iat[pname,1] == 'WR': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
wrvar = wrvar + 1 | |
p_used.extend(sorted_lineup) | |
tevar = 0 | |
for pname in range(0,len(line_hold)): | |
if tevar == 1: | |
pname = len(line_hold) | |
elif tevar < 1: | |
if line_hold.iat[pname,1] == 'TE': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
tevar = tevar + 1 | |
p_used.extend(sorted_lineup) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] != 'DST': | |
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] == 'DST': | |
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) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] == 'QB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
p_used.extend(sorted_lineup) | |
rbvar = 0 | |
for pname in range(0,len(line_hold)): | |
if rbvar == 2: | |
pname = len(line_hold) | |
elif rbvar < 2: | |
if line_hold.iat[pname,1] == 'RB': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
rbvar = rbvar + 1 | |
p_used.extend(sorted_lineup) | |
wrvar = 0 | |
for pname in range(0,len(line_hold)): | |
if wrvar == 3: | |
pname = len(line_hold) | |
elif wrvar < 3: | |
if line_hold.iat[pname,1] == 'WR': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
wrvar = wrvar + 1 | |
p_used.extend(sorted_lineup) | |
tevar = 0 | |
for pname in range(0,len(line_hold)): | |
if tevar == 1: | |
pname = len(line_hold) | |
elif tevar < 1: | |
if line_hold.iat[pname,1] == 'TE': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
tevar = tevar + 1 | |
p_used.extend(sorted_lineup) | |
for pname in range(0,len(line_hold)): | |
if line_hold.iat[pname,1] != 'DST': | |
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] == 'DST': | |
if line_hold.iat[pname,0] not in p_used: | |
sorted_lineup.append(line_hold.iat[pname,0]) | |
p_used.extend(sorted_lineup) | |
lineup_final['sorted'] = sorted_lineup | |
lineup_final = lineup_final.drop(columns=['Names']) | |
lineup_final.rename(columns={"sorted": "Names"}, inplace = True) | |
lineup_test = lineup_final | |
lineup_final = lineup_final.T | |
lineup_final['Cost'] = total_cost | |
lineup_final['Proj'] = total_proj | |
lineup_final['Own'] = total_own | |
lineup_test['Team'] = lineup_test['Names'].map(player_team) | |
lineup_test['Position'] = lineup_test['Names'].map(player_pos) | |
lineup_test['Salary'] = lineup_test['Names'].map(player_sal) | |
lineup_test['Proj'] = lineup_test['Names'].map(player_proj) | |
lineup_test['Own'] = lineup_test['Names'].map(player_own) | |
lineup_test = lineup_test.set_index('Names') | |
lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0) | |
lineup_display.append(lineup_test) | |
with col2: | |
with st.container(): | |
st.table(lineup_test) | |
max_proj = total_proj | |
max_own = total_own | |
check_list.append(total_proj) | |
portfolio = pd.concat([portfolio, lineup_final], ignore_index = True) | |
x += 1 | |
if site_var1 == 'Draftkings': | |
portfolio.rename(columns={0: "QB", 1: "RB1", 2: "RB2", 3: "WR1", 4: "WR2", 5: "WR3", 6: "TE", 7: "UTIL", 8: "DST"}, inplace = True) | |
elif site_var1 == 'Fanduel': | |
portfolio.rename(columns={0: "QB", 1: "RB1", 2: "RB2", 3: "WR1", 4: "WR2", 5: "WR3", 6: "TE", 7: "UTIL", 8: "DST"}, inplace = True) | |
portfolio = portfolio.dropna() | |
portfolio = portfolio.reset_index() | |
portfolio['Lineup_num'] = portfolio['index'] + 1 | |
portfolio.rename(columns={'Lineup_num': "Lineup"}, inplace = True) | |
portfolio = portfolio.set_index('Lineup') | |
portfolio = portfolio.drop(columns=['index']) | |
final_outcomes = portfolio[['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'UTIL', 'DST', 'Cost', 'Proj', 'Own']] | |
final_outcomes = final_outcomes.set_axis(['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'UTIL', 'DST', 'Cost', 'Proj', 'Own'], axis=1) | |
final_outcomes_export = pd.DataFrame() | |
final_outcomes_export['QB'] = final_outcomes['QB'] | |
final_outcomes_export['RB1'] = final_outcomes['RB1'] | |
final_outcomes_export['RB2'] = final_outcomes['RB2'] | |
final_outcomes_export['WR1'] = final_outcomes['WR1'] | |
final_outcomes_export['WR2'] = final_outcomes['WR2'] | |
final_outcomes_export['WR3'] = final_outcomes['WR3'] | |
final_outcomes_export['TE'] = final_outcomes['TE'] | |
final_outcomes_export['UTIL'] = final_outcomes['UTIL'] | |
final_outcomes_export['DST'] = final_outcomes['DST'] | |
final_outcomes_export['Salary'] = final_outcomes['Cost'] | |
final_outcomes_export['Own'] = final_outcomes['Own'] | |
final_outcomes_export['Proj'] = final_outcomes['Proj'] | |
if site_var1 == 'Draftkings': | |
final_outcomes_export['QB'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['RB1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['RB2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['WR1'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['WR2'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['WR3'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['TE'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['UTIL'].replace(dkid_dict, inplace=True) | |
final_outcomes_export['DST'].replace(dkid_dict, inplace=True) | |
elif site_var1 == 'Fanduel': | |
final_outcomes_export['QB'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['RB1'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['RB2'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['WR1'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['WR2'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['WR3'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['TE'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['UTIL'].replace(fdid_dict, inplace=True) | |
final_outcomes_export['DST'].replace(fdid_dict, inplace=True) | |
player_freq = pd.DataFrame(np.column_stack(np.unique(portfolio.iloc[:,0:8].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) | |
player_freq = player_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure']] | |
player_freq = player_freq.set_index('Player') | |
with optimize_container: | |
optimize_container = st.empty() | |
st.dataframe(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() | |
st.download_button( | |
label="Export Optimals", | |
data=convert_df_to_csv(final_outcomes_export), | |
file_name='NFL_optimals_export.csv', | |
mime='text/csv', | |
) | |
with freq_container: | |
freq_container = st.empty() | |
st.dataframe(player_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(expose_format, precision=2), use_container_width = True) | |