James McCool
Remove redundant logging statements in lineup initialization functions for DK and FD.
82ae966
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 pymongo
from itertools import combinations
@st.cache_resource
def init_conn():
uri = st.secrets['mongo_uri']
client = pymongo.MongoClient(uri, retryWrites=True, serverSelectionTimeoutMS=500000)
db = client["NFL_Database"]
return db
db = init_conn()
game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}',
'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'}
player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}',
'4x%': '{:.2%}','GPP%': '{:.2%}'}
dk_columns = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']
fd_columns = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']
@st.cache_resource(ttl=60)
def player_stat_table():
collection = db["Player_Baselines"]
cursor = collection.find()
raw_display = pd.DataFrame(list(cursor))
raw_display = raw_display[['name', 'Team', 'Opp', 'Position', 'Salary', 'team_plays', 'team_pass', 'team_rush', 'team_tds', 'team_pass_tds', 'team_rush_tds', 'dropbacks', 'pass_yards', 'pass_tds',
'rush_att', 'rush_yards', 'rush_tds', 'targets', 'rec', 'rec_yards', 'rec_tds', 'PPR', 'Half_PPR', 'Own']]
player_stats = raw_display[raw_display['Position'] != 'K']
collection = db["DK_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']]
load_display = raw_display[raw_display['Position'] != 'K']
dk_roo_raw = load_display.dropna(subset=['Median'])
collection = db["FD_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']]
load_display = raw_display[raw_display['Position'] != 'K']
fd_roo_raw = load_display.dropna(subset=['Median'])
collection = db["DK_DFS_Stacks"]
cursor = collection.find()
raw_display = pd.DataFrame(list(cursor))
raw_display = raw_display[['Team', 'QB', 'WR1_TE', 'WR2_TE', 'Total', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '60+%', '2x%', '3x%', '4x%', 'Own', 'LevX', 'slate', 'version']]
dk_stacks_raw = raw_display.copy()
collection = db["FD_DFS_Stacks"]
cursor = collection.find()
raw_display = pd.DataFrame(list(cursor))
raw_display = raw_display[['Team', 'QB', 'WR1_TE', 'WR2_TE', 'Total', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '60+%', '2x%', '3x%', '4x%', 'Own', 'LevX', 'slate', 'version']]
fd_stacks_raw = raw_display.copy()
return player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw
@st.cache_resource(ttl = 60)
def init_DK_lineups():
collection = db['DK_NFL_name_map']
cursor = collection.find()
raw_data = pd.DataFrame(list(cursor))
names_dict = dict(zip(raw_data['key'], raw_data['value']))
collection = db["DK_NFL_seed_frame"]
cursor = collection.find().limit(10000)
raw_display = pd.DataFrame(list(cursor))
raw_display = raw_display[['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
dict_columns = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST']
for col in dict_columns:
raw_display[col] = raw_display[col].map(names_dict)
DK_seed = raw_display.to_numpy()
return DK_seed
@st.cache_resource(ttl = 60)
def init_FD_lineups():
collection = db['FD_NFL_name_map']
cursor = collection.find()
raw_data = pd.DataFrame(list(cursor))
names_dict = dict(zip(raw_data['key'], raw_data['value']))
collection = db["FD_NFL_seed_frame"]
cursor = collection.find().limit(10000)
raw_display = pd.DataFrame(list(cursor))
raw_display = raw_display[['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
dict_columns = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST']
for col in dict_columns:
raw_display[col] = raw_display[col].map(names_dict)
FD_seed = raw_display.to_numpy()
return FD_seed
@st.cache_data
def convert_df(array):
array = pd.DataFrame(array, columns=column_names)
return array.to_csv().encode('utf-8')
@st.cache_data
def convert_df_to_csv(df):
return df.to_csv().encode('utf-8')
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
try:
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
except:
dk_lineups = pd.DataFrame(columns=dk_columns)
fd_lineups = pd.DataFrame(columns=fd_columns)
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs(["Team Stacks Range of Outcomes", "Overall Range of Outcomes", "QB Range of Outcomes", "RB Range of Outcomes", "WR Range of Outcomes", "TE Range of Outcomes", "Optimals"])
# ... existing code ...
@st.cache_data
def optimize_lineup(player_data, sidebar_site):
"""
Creates optimal lineup based on median projections while respecting position and salary constraints
"""
# Create optimization problem
prob = pulp.LpProblem("NFL_Lineup_Optimization", pulp.LpMaximize)
# Create player dictionary with binary variables
players = {}
for idx, row in player_data.iterrows():
players[row['Player']] = pulp.LpVariable(f"player_{idx}", 0, 1, pulp.LpBinary)
# Objective: Maximize total median points
prob += pulp.lpSum([players[row['Player']] * row['Median'] for idx, row in player_data.iterrows()])
# Constraint: Salary cap
if sidebar_site == 'Draftkings':
prob += pulp.lpSum([players[row['Player']] * row['Salary'] for idx, row in player_data.iterrows()]) <= 50000
elif sidebar_site == 'Fanduel':
prob += pulp.lpSum([players[row['Player']] * row['Salary'] for idx, row in player_data.iterrows()]) <= 60000
# Constraint: 9 players
prob += pulp.lpSum([players[row['Player']] for idx, row in player_data.iterrows()]) == 9
# Position constraints
qbs = player_data[player_data['Position'] == 'QB']['Player'].tolist()
rbs = player_data[player_data['Position'] == 'RB']['Player'].tolist()
wrs = player_data[player_data['Position'] == 'WR']['Player'].tolist()
tes = player_data[player_data['Position'] == 'TE']['Player'].tolist()
dsts = player_data[player_data['Position'] == 'DST']['Player'].tolist()
# QB: exactly 1
prob += pulp.lpSum([players[p] for p in qbs]) == 1
# RB: 2-3
prob += pulp.lpSum([players[p] for p in rbs]) >= 2
prob += pulp.lpSum([players[p] for p in rbs]) <= 3
# WR: 3-4
prob += pulp.lpSum([players[p] for p in wrs]) >= 3
prob += pulp.lpSum([players[p] for p in wrs]) <= 4
# TE: 1-2
prob += pulp.lpSum([players[p] for p in tes]) >= 1
prob += pulp.lpSum([players[p] for p in tes]) <= 2
# DST: exactly 1
prob += pulp.lpSum([players[p] for p in dsts]) == 1
# Solve the problem
prob.solve()
# Get selected players
selected_players = []
total_salary = 0
total_median = 0
for idx, row in player_data.iterrows():
if players[row['Player']].value() == 1:
selected_players.append({
'Player': row['Player'],
'Position': row['Position'],
'Salary': row['Salary'],
'Median': row['Median']
})
total_salary += row['Salary']
total_median += row['Median']
return selected_players, total_salary, total_median
with st.sidebar:
st.header("Quick Builder")
sidebar_site = st.selectbox("What site are you running?", ('Draftkings', 'Fanduel'), key='sidebar_site')
sidebar_slate = st.selectbox("What slate are you running?", ('Main Slate', 'Secondary Slate', 'Late Slate', 'Thurs-Mon Slate'), key='sidebar_slate')
if sidebar_site == 'Draftkings':
roo_sample = dk_roo_raw[dk_roo_raw['slate'] == str(sidebar_slate)]
roo_sample = roo_sample[roo_sample['version'] == 'overall']
#roo_sample = roo_sample.sort_values(by='Own', ascending=False)
elif sidebar_site == 'Fanduel':
roo_sample = fd_roo_raw[fd_roo_raw['slate'] == str(sidebar_slate)]
roo_sample = roo_sample[roo_sample['version'] == 'overall']
#roo_sample = roo_sample.sort_values(by='Own', ascending=False)
st.write("---")
if st.button("Generate Optimal Lineup"):
if sidebar_site == 'Draftkings':
roo_data = dk_roo_raw[dk_roo_raw['slate'] == str(sidebar_slate)]
roo_data = roo_data[roo_data['version'] == 'overall']
else:
roo_data = fd_roo_raw[fd_roo_raw['slate'] == str(sidebar_slate)]
roo_data = roo_data[roo_data['version'] == 'overall']
optimal_players, total_salary, total_median = optimize_lineup(roo_data, sidebar_site)
st.write("Optimal Lineup:")
# Sort players into position groups
qb = [p for p in optimal_players if p['Position'] == 'QB'][0]
rbs = [p for p in optimal_players if p['Position'] == 'RB']
wrs = [p for p in optimal_players if p['Position'] == 'WR']
tes = [p for p in optimal_players if p['Position'] == 'TE']
dst = [p for p in optimal_players if p['Position'] == 'DST'][0]
# Display QB
st.write(f"QB: {qb['Player']} (${qb['Salary']:,})")
# Display RB1 and RB2
st.write(f"RB: {rbs[0]['Player']} (${rbs[0]['Salary']:,})")
st.write(f"RB: {rbs[1]['Player']} (${rbs[1]['Salary']:,})")
# Display WR1, WR2, WR3
st.write(f"WR: {wrs[0]['Player']} (${wrs[0]['Salary']:,})")
st.write(f"WR: {wrs[1]['Player']} (${wrs[1]['Salary']:,})")
st.write(f"WR: {wrs[2]['Player']} (${wrs[2]['Salary']:,})")
# Display TE1
st.write(f"TE: {tes[0]['Player']} (${tes[0]['Salary']:,})")
# Display FLEX (either RB3, WR4, or TE2)
if len(rbs) > 2:
st.write(f"FLEX (RB): {rbs[2]['Player']} (${rbs[2]['Salary']:,})")
elif len(wrs) > 3:
st.write(f"FLEX (WR): {wrs[3]['Player']} (${wrs[3]['Salary']:,})")
elif len(tes) > 1:
st.write(f"FLEX (TE): {tes[1]['Player']} (${tes[1]['Salary']:,})")
# Display DST
st.write(f"DST: {dst['Player']} (${dst['Salary']:,})")
st.write(f"Total Salary: ${total_salary:,}")
st.write(f"Projected Points: {total_median:.2f}")
# Create empty lists to store selected players
selected_qbs = []
selected_rb1 = []
selected_rb2 = []
selected_wr1 = []
selected_wr2 = []
selected_wr3 = []
selected_te = []
selected_flex = []
selected_dst = []
# Get unique players by position from dk_roo_raw
qbs = roo_sample[roo_sample['Position'] == 'QB']['Player'].unique()
rbs = roo_sample[roo_sample['Position'] == 'RB']['Player'].unique()
wrs = roo_sample[roo_sample['Position'] == 'WR']['Player'].unique()
tes = roo_sample[roo_sample['Position'] == 'TE']['Player'].unique()
flex = roo_sample['Player'].unique()
dst = roo_sample[roo_sample['Position'] == 'DST']['Player'].unique()
# Create multiselect dropdowns for each position
selected_qbs = st.multiselect('Select QB:', list(qbs), default=None, key='qb1')
if selected_qbs:
qb_team = roo_sample[roo_sample['Player'] == selected_qbs[0]]['Team'].values[0]
qb_sample = roo_sample[roo_sample['Team'] == qb_team]
bb_sample = roo_sample[roo_sample['Opp'] == qb_team]
wr_suggest = qb_sample[qb_sample['Position'] == 'WR']['Player'].values[0]
wr2_suggest = bb_sample[bb_sample['Position'] == 'WR']['Player'].values[0]
te_suggest = qb_sample[qb_sample['Position'] == 'TE']['Player'].values[0]
selected_rb1 = st.multiselect('Select RBs:', list(rbs), default=None, key='rb1')
selected_rb2 = st.multiselect('Select RB2:', list(rbs), default=None, label_visibility='collapsed', key='rb2')
if selected_qbs:
selected_wr1 = st.multiselect('Select WRs:', list(wrs), default=None, placeholder=f'Suggestion: {wr_suggest}', key='wr1')
else:
selected_wr1 = st.multiselect('Select WRs:', list(wrs), default=None, key='wr1')
if selected_qbs:
selected_wr2 = st.multiselect('Select WR2:', list(wrs), default=None, placeholder=f'Suggestion: {wr2_suggest}', label_visibility='collapsed', key='wr2')
else:
selected_wr2 = st.multiselect('Select WR2:', list(wrs), default=None, label_visibility='collapsed', key='wr2')
selected_wr3 = st.multiselect('Select WR3:', list(wrs), default=None, label_visibility='collapsed', key='wr3')
if selected_qbs:
selected_te = st.multiselect('Select TE:', list(tes), default=None, placeholder=f'Suggestion: {te_suggest}', key='te')
else:
selected_te = st.multiselect('Select TE:', list(tes), default=None, key='te')
selected_flex = st.multiselect('Select Flex:', list(flex), default=None, key='flex')
selected_dst = st.multiselect('Select DST:', list(dst), default=None, key='dst')
# Combine all selected players
all_selected = selected_qbs + selected_rb1 + selected_rb2 + selected_wr1 + selected_wr2 + selected_wr3 + selected_te + selected_flex + selected_dst
if all_selected:
# Get stats for selected players
selected_stats = roo_sample[roo_sample['Player'].isin(all_selected)]
# Calculate sums
salary_sum = selected_stats['Salary'].sum()
median_sum = selected_stats['Median'].sum()
own_sum = selected_stats['Own'].sum()
levx_sum = selected_stats['LevX'].sum()
# Display sums
st.write('---')
if sidebar_site == 'Draftkings':
if salary_sum > 50000:
st.warning(f'Total Salary: ${salary_sum:.2f} exceeds limit of $50,000')
else:
st.write(f'Total Salary: ${salary_sum:.2f}')
elif sidebar_site == 'Fanduel':
if salary_sum > 60000:
st.warning(f'Total Salary: ${salary_sum:.2f} exceeds limit of $60,000')
else:
st.write(f'Total Salary: ${salary_sum:.2f}')
st.write(f'Total Median: {median_sum:.2f}')
st.write(f'Total Ownership: {own_sum:.2f}%')
st.write(f'Total LevX: {levx_sum:.2f}')
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()
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
for key in st.session_state.keys():
del st.session_state[key]
slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'Late Slate', 'Thurs-Mon Slate'), key='slate_var1')
site_var1 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var1')
view_var1 = st.radio("What view would you like to display?", ('Advanced', 'Simple'), key='view_var1')
custom_var1 = st.radio("Are you creating a custom table?", ('No', 'Yes'), key='custom_var1')
if custom_var1 == 'No':
if site_var1 == 'Draftkings':
raw_baselines = dk_stacks_raw[dk_stacks_raw['slate'] == str(slate_var1)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
raw_baselines = raw_baselines.iloc[:,:-2]
elif site_var1 == 'Fanduel':
raw_baselines = fd_stacks_raw[fd_stacks_raw['slate'] == str(slate_var1)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
raw_baselines = raw_baselines.iloc[:,:-2]
split_var1 = st.radio("Would you like to view the whole slate or just specific 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 ROO?', options = raw_baselines['Team'].unique(), key='team_var1')
elif split_var1 == 'Full Slate Run':
team_var1 = raw_baselines.Team.values.tolist()
if custom_var1 == 'Yes':
contest_var1 = st.selectbox("What contest type are you running for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var1')
if site_var1 == 'Draftkings':
raw_baselines = dk_stacks_raw[dk_stacks_raw['slate'] == str(slate_var1)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
elif site_var1 == 'Fanduel':
raw_baselines = fd_stacks_raw[fd_stacks_raw['slate'] == str(slate_var1)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
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 ROO?', options = raw_baselines['Team'].unique(), key='team_var1')
elif split_var1 == 'Full Slate Run':
team_var1 = raw_baselines.Team.values.tolist()
with col2:
if custom_var1 == 'No':
final_stacks = raw_baselines[raw_baselines['Team'].isin(team_var1)]
if view_var1 == 'Simple':
final_stacks = final_stacks[['Team', 'QB', 'WR1_TE', 'WR2_TE', 'Salary', 'Median', '60+%', '4x%']]
elif view_var1 == 'Advanced':
final_stacks = final_stacks[['Team', 'QB', 'WR1_TE', 'WR2_TE', 'Total', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish',
'Top_10_finish', '60+%', '2x%', '3x%', '4x%', 'Own', 'LevX']]
st.dataframe(final_stacks.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_stacks),
file_name='NFL_stacks_export.csv',
mime='text/csv',
)
elif custom_var1 == 'Yes':
hold_container = st.empty()
if st.button('Create Range of Outcomes for Slate'):
with hold_container:
if site_var1 == 'Draftkings':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
if site_var1 == 'Fanduel':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Half_PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Team'].isin(team_var1)]
total_sims = 1000
salary_dict = dict(zip(working_roo.name, working_roo.Salary))
own_dict = dict(zip(working_roo.name, working_roo.Own))
fantasy_dict = dict(zip(working_roo.name, working_roo.Fantasy))
QB_group = working_roo.loc[working_roo['Position'] == 'QB']
stacks_df = pd.DataFrame(columns=['Team','QB', 'WR1', 'WR2_TE'])
for stack in range(0,len(QB_group)):
team_var = QB_group.iat[stack,1]
WR_group_1 = working_roo.loc[working_roo['Position'] == 'WR']
WR_group_2 = WR_group_1.loc[working_roo['Team'] == team_var]
TE_group_1 = working_roo.loc[working_roo['Position'] == 'TE']
TE_group_2 = TE_group_1.loc[working_roo['Team'] == team_var]
cur_list = []
qb_piece = QB_group.iat[stack,0]
wr_piece = WR_group_2.iat[0,0]
te_piece = TE_group_2.iat[0,0]
cur_list.append(team_var)
cur_list.append(qb_piece)
cur_list.append(wr_piece)
cur_list.append(te_piece)
stacks_df.loc[len(stacks_df)] = cur_list
cur_list = []
qb_piece = QB_group.iat[stack,0]
wr_piece = WR_group_2.iat[1,0]
te_piece = TE_group_2.iat[0,0]
cur_list.append(team_var)
cur_list.append(qb_piece)
cur_list.append(wr_piece)
cur_list.append(te_piece)
stacks_df.loc[len(stacks_df)] = cur_list
cur_list = []
qb_piece = QB_group.iat[stack,0]
wr_piece = WR_group_2.iat[0,0]
te_piece = WR_group_2.iat[1,0]
cur_list.append(team_var)
cur_list.append(qb_piece)
cur_list.append(wr_piece)
cur_list.append(te_piece)
stacks_df.loc[len(stacks_df)] = cur_list
stacks_df['Salary'] = sum([stacks_df['QB'].map(salary_dict),
stacks_df['WR1'].map(salary_dict),
stacks_df['WR2_TE'].map(salary_dict)])
stacks_df['Fantasy'] = sum([stacks_df['QB'].map(fantasy_dict),
stacks_df['WR1'].map(fantasy_dict),
stacks_df['WR2_TE'].map(fantasy_dict)])
stacks_df['Own'] = sum([stacks_df['QB'].map(own_dict),
stacks_df['WR1'].map(own_dict),
stacks_df['WR2_TE'].map(own_dict)])
stacks_df['team_combo'] = stacks_df['Team'] + " " + stacks_df['QB'] + " " + stacks_df['WR1'] + " " + stacks_df['WR2_TE']
own_dict = dict(zip(stacks_df.team_combo, stacks_df.Own))
qb_dict = dict(zip(stacks_df.team_combo, stacks_df.QB))
wr1_dict = dict(zip(stacks_df.team_combo, stacks_df.WR1))
wr2_dict = dict(zip(stacks_df.team_combo, stacks_df.WR2_TE))
team_dict = dict(zip(stacks_df.team_combo, stacks_df.Team))
flex_file = stacks_df[['team_combo', 'Salary', 'Fantasy']]
flex_file.rename(columns={"Fantasy": "Median"}, inplace = True)
flex_file['Floor'] = flex_file['Median']*.25
flex_file['Ceiling'] = flex_file['Median'] + flex_file['Floor']
flex_file['STD'] = flex_file['Median']/4
flex_file = flex_file[['team_combo', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
hold_file = flex_file
overall_file = flex_file
salary_file = flex_file
overall_players = overall_file[['team_combo']]
for x in range(0,total_sims):
salary_file[x] = salary_file['Salary']
salary_file=salary_file.drop(['team_combo', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
salary_file.astype('int').dtypes
salary_file = salary_file.div(1000)
for x in range(0,total_sims):
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
overall_file=overall_file.drop(['team_combo', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
overall_file.astype('int').dtypes
players_only = hold_file[['team_combo']]
raw_lineups_file = players_only
for x in range(0,total_sims):
maps_dict = {'proj_map':dict(zip(hold_file.team_combo,hold_file[x]))}
raw_lineups_file[x] = sum([raw_lineups_file['team_combo'].map(maps_dict['proj_map'])])
players_only[x] = raw_lineups_file[x].rank(ascending=False)
players_only=players_only.drop(['team_combo'], axis=1)
players_only.astype('int').dtypes
salary_2x_check = (overall_file - (salary_file*2))
salary_3x_check = (overall_file - (salary_file*3))
salary_4x_check = (overall_file - (salary_file*4))
players_only['Average_Rank'] = players_only.mean(axis=1)
players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
players_only['60+%'] = overall_file[overall_file >= 60].count(axis=1)/float(total_sims)
players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
players_only['team_combo'] = hold_file[['team_combo']]
final_outcomes = players_only[['team_combo', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '60+%', '2x%', '3x%', '4x%']]
final_stacks = pd.merge(hold_file, final_outcomes, on="team_combo")
final_stacks = final_stacks[['team_combo', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '60+%', '2x%', '3x%', '4x%']]
final_stacks['Own'] = final_stacks['team_combo'].map(own_dict)
final_stacks = final_stacks[['team_combo', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '60+%', '2x%', '3x%', '4x%', 'Own']]
final_stacks['Projection Rank'] = final_stacks.Median.rank(pct = True)
final_stacks['Own Rank'] = final_stacks.Own.rank(pct = True)
final_stacks['LevX'] = final_stacks['Projection Rank'] - final_stacks['Own Rank']
final_stacks['Team'] = final_stacks['team_combo'].map(team_dict)
final_stacks['QB'] = final_stacks['team_combo'].map(qb_dict)
final_stacks['WR1_TE'] = final_stacks['team_combo'].map(wr1_dict)
final_stacks['WR2_TE'] = final_stacks['team_combo'].map(wr2_dict)
final_stacks = final_stacks[['Team', 'QB', 'WR1_TE', 'WR2_TE', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish',
'Top_10_finish', '60+%', '2x%', '3x%', '4x%', 'Own', 'LevX']]
final_stacks = final_stacks.sort_values(by='Median', ascending=False)
with hold_container:
hold_container = st.empty()
final_stacks = final_stacks
if view_var1 == 'Simple':
final_stacks = final_stacks[['Team', 'QB', 'WR1_TE', 'WR2_TE', 'Salary', 'Median', '60+%', '4x%']]
elif view_var1 == 'Advanced':
final_stacks = final_stacks[['Team', 'QB', 'WR1_TE', 'WR2_TE', 'Total', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish',
'Top_10_finish', '60+%', '2x%', '3x%', '4x%', 'Own', 'LevX']]
st.dataframe(final_stacks.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_stacks),
file_name='Custom_NFL_stacks_export.csv',
mime='text/csv',
)
with tab2:
col1, col2 = st.columns([1, 5])
with col1:
st.info(t_stamp)
if st.button("Load/Reset Data", key='reset2'):
st.cache_data.clear()
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
for key in st.session_state.keys():
del st.session_state[key]
slate_var2 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'Late Slate', 'Thurs-Mon Slate'), key='slate_var2')
site_var2 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var2')
view_var2 = st.radio("What view would you like to display?", ('Advanced', 'Simple'), key='view_var2')
custom_var2 = st.radio("Are you creating a custom table?", ('No', 'Yes'), key='custom_var2')
if custom_var2 == 'No':
if site_var2 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var2)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
raw_baselines = raw_baselines.iloc[:,:-2]
elif site_var2 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var2)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
raw_baselines = raw_baselines.iloc[:,:-2]
split_var2 = st.radio("Would you like to view the whole slate or just specific games?", ('Full Slate Run', 'Specific Games'), key='split_var2')
if split_var2 == 'Specific Games':
team_var2 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var2')
elif split_var2 == 'Full Slate Run':
team_var2 = raw_baselines.Team.values.tolist()
pos_split2 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split2')
if pos_split2 == 'Specific Positions':
pos_var2 = st.multiselect('What Positions would you like to view?', options = ['QB', 'RB', 'WR', 'TE'])
elif pos_split2 == 'All Positions':
pos_var2 = 'All'
sal_var2 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var2')
if custom_var2 == 'Yes':
contest_var2 = st.selectbox("What contest type are you running for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var2')
if site_var2 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var2)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
elif site_var2 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var2)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
split_var2 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var2')
if split_var2 == 'Specific Games':
team_var2 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var2')
elif split_var2 == 'Full Slate Run':
team_var2 = raw_baselines.Team.values.tolist()
pos_split2 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split2')
if pos_split2 == 'Specific Positions':
pos_var2 = st.multiselect('What Positions would you like to view?', options = ['QB', 'RB', 'WR', 'TE'])
elif pos_split2 == 'All Positions':
pos_var2 = 'All'
sal_var2 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var2')
with col2:
if custom_var2 == 'No':
final_Proj = raw_baselines[raw_baselines['Team'].isin(team_var2)]
final_Proj = final_Proj[final_Proj['Salary'] >= sal_var2[0]]
final_Proj = final_Proj[final_Proj['Salary'] <= sal_var2[1]]
if pos_var2 != 'All':
final_Proj = raw_baselines[raw_baselines['Position'].str.contains('|'.join(pos_var2))]
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
if view_var2 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var2 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='NFL_overall_export.csv',
mime='text/csv',
)
elif custom_var2 == 'Yes':
hold_container = st.empty()
if st.button('Create Range of Outcomes for Slate'):
with hold_container:
if site_var2 == 'Draftkings':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
if site_var2 == 'Fanduel':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Half_PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Team'].isin(team_var2)]
working_roo = working_roo[working_roo['Salary'] >= sal_var2[0]]
working_roo = working_roo[working_roo['Salary'] <= sal_var2[1]]
own_dict = dict(zip(working_roo.Player, working_roo.Own))
team_dict = dict(zip(working_roo.Player, working_roo.Team))
opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
total_sims = 1000
flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median'] + flex_file['Floor']) + (flex_file['Rush Yards']*.01), flex_file['Median'] + flex_file['Floor'] + flex_file['Receptions'])
flex_file['STD'] = (flex_file['Median']/4) + flex_file['Receptions']
flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
hold_file = flex_file
overall_file = flex_file
salary_file = flex_file
overall_players = overall_file[['Player']]
for x in range(0,total_sims):
salary_file[x] = salary_file['Salary']
salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
salary_file.astype('int').dtypes
salary_file = salary_file.div(1000)
for x in range(0,total_sims):
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
overall_file.astype('int').dtypes
players_only = hold_file[['Player']]
raw_lineups_file = players_only
for x in range(0,total_sims):
maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
players_only[x] = raw_lineups_file[x].rank(ascending=False)
players_only=players_only.drop(['Player'], axis=1)
players_only.astype('int').dtypes
salary_2x_check = (overall_file - (salary_file*2))
salary_3x_check = (overall_file - (salary_file*3))
salary_4x_check = (overall_file - (salary_file*4))
players_only['Average_Rank'] = players_only.mean(axis=1)
players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
players_only['Player'] = hold_file[['Player']]
final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj['Own'] = final_Proj['Player'].map(own_dict)
final_Proj['Team'] = final_Proj['Player'].map(team_dict)
final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
final_Proj['LevX'] = 0
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'QB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'TE', final_Proj[['Projection Rank', '2x%']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'RB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['20+%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'WR', final_Proj[['Projection Rank', 'Top_10_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['CPT_Own'] = final_Proj['Own'] / 4
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
with hold_container:
hold_container = st.empty()
final_Proj = final_Proj
if view_var2 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var2 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='Custom_NFL_overall_export.csv',
mime='text/csv',
)
with tab3:
col1, col2 = st.columns([1, 5])
with col1:
st.info(t_stamp)
if st.button("Load/Reset Data", key='reset3'):
st.cache_data.clear()
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
for key in st.session_state.keys():
del st.session_state[key]
slate_var3 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'Late Slate', 'Thurs-Mon Slate'), key='slate_var3')
site_var3 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var3')
view_var3 = st.radio("What view would you like to display?", ('Advanced', 'Simple'), key='view_var3')
custom_var3 = st.radio("Are you creating a custom table?", ('No', 'Yes'), key='custom_var3')
if custom_var3 == 'No':
if site_var3 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var3)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_qbs']
raw_baselines = raw_baselines.iloc[:,:-3]
elif site_var3 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var3)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_qbs']
raw_baselines = raw_baselines.iloc[:,:-3]
split_var3 = st.radio("Would you like to view the whole slate or just specific games?", ('Full Slate Run', 'Specific Games'), key='split_var3')
if split_var3 == 'Specific Games':
team_var3 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var3')
elif split_var3 == 'Full Slate Run':
team_var3 = raw_baselines.Team.values.tolist()
pos_split3 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split3')
if pos_split3 == 'Specific Positions':
pos_var3 = st.multiselect('What Positions would you like to view?', options = ['QB'], key='pos_var3')
elif pos_split3 == 'All Positions':
pos_var3 = 'All'
sal_var3 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var3')
if custom_var3 == 'Yes':
contest_var3 = st.selectbox("What contest type are you running for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var3')
if site_var3 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var3)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_qbs']
raw_baselines = raw_baselines.iloc[:,:-3]
elif site_var3 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var3)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_qbs']
raw_baselines = raw_baselines.iloc[:,:-3]
split_var3 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var3')
if split_var3 == 'Specific Games':
team_var3 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var3')
elif split_var3 == 'Full Slate Run':
team_var3 = raw_baselines.Team.values.tolist()
pos_split3 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split3')
if pos_split3 == 'Specific Positions':
pos_var3 = st.multiselect('What Positions would you like to view?', options = ['QB'])
elif pos_split3 == 'All Positions':
pos_var3 = 'All'
sal_var3 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var3')
with col2:
if custom_var3 == 'No':
final_Proj = raw_baselines[raw_baselines['Team'].isin(team_var3)]
final_Proj = final_Proj[final_Proj['Salary'] >= sal_var3[0]]
final_Proj = final_Proj[final_Proj['Salary'] <= sal_var3[1]]
if pos_var3 != 'All':
final_Proj = raw_baselines[raw_baselines['Position'].str.contains('|'.join(pos_var3))]
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
if view_var3 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var3 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='NFL_qb_export.csv',
mime='text/csv',
)
elif custom_var3 == 'Yes':
hold_container = st.empty()
if st.button('Create Range of Outcomes for Slate'):
with hold_container:
if site_var3 == 'Draftkings':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'QB']
if site_var3 == 'Fanduel':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Half_PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'QB']
working_roo = working_roo[working_roo['Team'].isin(team_var3)]
working_roo = working_roo[working_roo['Salary'] >= sal_var2[0]]
working_roo = working_roo[working_roo['Salary'] <= sal_var2[1]]
own_dict = dict(zip(working_roo.Player, working_roo.Own))
team_dict = dict(zip(working_roo.Player, working_roo.Team))
opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
total_sims = 1000
flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median'] + flex_file['Floor']) + (flex_file['Rush Yards']*.01), flex_file['Median'] + flex_file['Floor'] + flex_file['Receptions'])
flex_file['STD'] = (flex_file['Median']/4) + flex_file['Receptions']
flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
hold_file = flex_file
overall_file = flex_file
salary_file = flex_file
overall_players = overall_file[['Player']]
for x in range(0,total_sims):
salary_file[x] = salary_file['Salary']
salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
salary_file.astype('int').dtypes
salary_file = salary_file.div(1000)
for x in range(0,total_sims):
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
overall_file.astype('int').dtypes
players_only = hold_file[['Player']]
raw_lineups_file = players_only
for x in range(0,total_sims):
maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
players_only[x] = raw_lineups_file[x].rank(ascending=False)
players_only=players_only.drop(['Player'], axis=1)
players_only.astype('int').dtypes
salary_2x_check = (overall_file - (salary_file*2))
salary_3x_check = (overall_file - (salary_file*3))
salary_4x_check = (overall_file - (salary_file*4))
players_only['Average_Rank'] = players_only.mean(axis=1)
players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
players_only['Player'] = hold_file[['Player']]
final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj['Own'] = final_Proj['Player'].map(own_dict)
final_Proj['Team'] = final_Proj['Player'].map(team_dict)
final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
final_Proj['LevX'] = 0
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'QB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'TE', final_Proj[['Projection Rank', '2x%']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'RB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['20+%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'WR', final_Proj[['Projection Rank', 'Top_10_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['CPT_Own'] = final_Proj['Own'] / 4
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
with hold_container:
hold_container = st.empty()
final_Proj = final_Proj
if view_var3 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var3 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='Custom_NFL_qb_export.csv',
mime='text/csv',
)
with tab4:
col1, col2 = st.columns([1, 5])
with col1:
st.info(t_stamp)
if st.button("Load/Reset Data", key='reset4'):
st.cache_data.clear()
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
for key in st.session_state.keys():
del st.session_state[key]
slate_var4 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'Late Slate', 'Thurs-Mon Slate'), key='slate_var4')
site_var4 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var4')
view_var4 = st.radio("What view would you like to display?", ('Advanced', 'Simple'), key='view_var4')
custom_var4 = st.radio("Are you creating a custom table?", ('No', 'Yes'), key='custom_var4')
if custom_var4 == 'No':
if site_var4 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var4)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_rbs']
raw_baselines = raw_baselines.iloc[:,:-3]
elif site_var4 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var4)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_rbs']
raw_baselines = raw_baselines.iloc[:,:-3]
split_var4 = st.radio("Would you like to view the whole slate or just specific games?", ('Full Slate Run', 'Specific Games'), key='split_var4')
if split_var4 == 'Specific Games':
team_var4 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var4')
elif split_var4 == 'Full Slate Run':
team_var4 = raw_baselines.Team.values.tolist()
pos_split4 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split4')
if pos_split4 == 'Specific Positions':
pos_var4 = st.multiselect('What Positions would you like to view?', options = ['RB'], key='pos_var4')
elif pos_split4 == 'All Positions':
pos_var4 = 'All'
sal_var4 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var4')
if custom_var4 == 'Yes':
contest_var4 = st.selectbox("What contest type are you running for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var4')
if site_var4 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var4)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_rbs']
elif site_var4 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var4)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_rbs']
split_var4 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var4')
if split_var4 == 'Specific Games':
team_var4 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var4')
elif split_var4 == 'Full Slate Run':
team_var4 = raw_baselines.Team.values.tolist()
pos_split4 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split4')
if pos_split4 == 'Specific Positions':
pos_var4 = st.multiselect('What Positions would you like to view?', options = ['RB'])
elif pos_split4 == 'All Positions':
pos_var4 = 'All'
sal_var4 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var4')
with col2:
if custom_var4 == 'No':
final_Proj = raw_baselines[raw_baselines['Team'].isin(team_var4)]
final_Proj = final_Proj[final_Proj['Salary'] >= sal_var4[0]]
final_Proj = final_Proj[final_Proj['Salary'] <= sal_var4[1]]
if pos_var4 != 'All':
final_Proj = raw_baselines[raw_baselines['Position'].str.contains('|'.join(pos_var4))]
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
if view_var4 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var4 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='NFL_rb_export.csv',
mime='text/csv',
)
elif custom_var4 == 'Yes':
hold_container = st.empty()
if st.button('Create Range of Outcomes for Slate'):
with hold_container:
if site_var4 == 'Draftkings':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'RB']
if site_var4 == 'Fanduel':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Half_PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'RB']
working_roo = working_roo[working_roo['Team'].isin(team_var4)]
working_roo = working_roo[working_roo['Salary'] >= sal_var4[0]]
working_roo = working_roo[working_roo['Salary'] <= sal_var4[1]]
own_dict = dict(zip(working_roo.Player, working_roo.Own))
team_dict = dict(zip(working_roo.Player, working_roo.Team))
opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
total_sims = 1000
flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median'] + flex_file['Floor']) + (flex_file['Rush Yards']*.01), flex_file['Median'] + flex_file['Floor'] + flex_file['Receptions'])
flex_file['STD'] = (flex_file['Median']/4) + flex_file['Receptions']
flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
hold_file = flex_file
overall_file = flex_file
salary_file = flex_file
overall_players = overall_file[['Player']]
for x in range(0,total_sims):
salary_file[x] = salary_file['Salary']
salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
salary_file.astype('int').dtypes
salary_file = salary_file.div(1000)
for x in range(0,total_sims):
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
overall_file.astype('int').dtypes
players_only = hold_file[['Player']]
raw_lineups_file = players_only
for x in range(0,total_sims):
maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
players_only[x] = raw_lineups_file[x].rank(ascending=False)
players_only=players_only.drop(['Player'], axis=1)
players_only.astype('int').dtypes
salary_2x_check = (overall_file - (salary_file*2))
salary_3x_check = (overall_file - (salary_file*3))
salary_4x_check = (overall_file - (salary_file*4))
players_only['Average_Rank'] = players_only.mean(axis=1)
players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
players_only['Player'] = hold_file[['Player']]
final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj['Own'] = final_Proj['Player'].map(own_dict)
final_Proj['Team'] = final_Proj['Player'].map(team_dict)
final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
final_Proj['LevX'] = 0
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'QB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'TE', final_Proj[['Projection Rank', '2x%']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'RB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['20+%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'WR', final_Proj[['Projection Rank', 'Top_10_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['CPT_Own'] = final_Proj['Own'] / 4
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
with hold_container:
hold_container = st.empty()
final_Proj = final_Proj
if view_var4 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var4 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='Custom_NFL_rb_export.csv',
mime='text/csv',
)
with tab5:
col1, col2 = st.columns([1, 5])
with col1:
st.info(t_stamp)
if st.button("Load/Reset Data", key='reset5'):
st.cache_data.clear()
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
for key in st.session_state.keys():
del st.session_state[key]
slate_var5 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'Late Slate', 'Thurs-Mon Slate'), key='slate_var5')
site_var5 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var5')
view_var5 = st.radio("What view would you like to display?", ('Advanced', 'Simple'), key='view_var5')
custom_var5 = st.radio("Are you creating a custom table?", ('No', 'Yes'), key='custom_var5')
if custom_var5 == 'No':
if site_var5 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var5)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_wrs']
raw_baselines = raw_baselines.iloc[:,:-3]
elif site_var5 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var5)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_wrs']
raw_baselines = raw_baselines.iloc[:,:-3]
split_var5 = st.radio("Would you like to view the whole slate or just specific games?", ('Full Slate Run', 'Specific Games'), key='split_var5')
if split_var5 == 'Specific Games':
team_var5 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var5')
elif split_var5 == 'Full Slate Run':
team_var5 = raw_baselines.Team.values.tolist()
pos_split5 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split5')
if pos_split5 == 'Specific Positions':
pos_var5 = st.multiselect('What Positions would you like to view?', options = ['WR'], key='pos_var5')
elif pos_split5 == 'All Positions':
pos_var5 = 'All'
sal_var5 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var5')
if custom_var5 == 'Yes':
contest_var5 = st.selectbox("What contest type are you running for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var5')
if site_var5 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var5)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_wrs']
elif site_var5 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var5)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_wrs']
split_var5 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var5')
if split_var5 == 'Specific Games':
team_var5 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var5')
elif split_var5 == 'Full Slate Run':
team_var5 = raw_baselines.Team.values.tolist()
pos_split5 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split5')
if pos_split5 == 'Specific Positions':
pos_var5 = st.multiselect('What Positions would you like to view?', options = ['WR'])
elif pos_split5 == 'All Positions':
pos_var5 = 'All'
sal_var5 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var5')
with col2:
if custom_var5 == 'No':
final_Proj = raw_baselines[raw_baselines['Team'].isin(team_var5)]
final_Proj = final_Proj[final_Proj['Salary'] >= sal_var5[0]]
final_Proj = final_Proj[final_Proj['Salary'] <= sal_var5[1]]
if pos_var5 != 'All':
final_Proj = raw_baselines[raw_baselines['Position'].str.contains('|'.join(pos_var5))]
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
if view_var5 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var5 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='NFL_wr_export.csv',
mime='text/csv',
)
elif custom_var5 == 'Yes':
hold_container = st.empty()
if st.button('Create Range of Outcomes for Slate'):
with hold_container:
if site_var5 == 'Draftkings':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'WR']
if site_var5 == 'Fanduel':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Half_PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'WR']
working_roo = working_roo[working_roo['Team'].isin(team_var5)]
working_roo = working_roo[working_roo['Salary'] >= sal_var5[0]]
working_roo = working_roo[working_roo['Salary'] <= sal_var5[1]]
own_dict = dict(zip(working_roo.Player, working_roo.Own))
team_dict = dict(zip(working_roo.Player, working_roo.Team))
opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
total_sims = 1000
flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median'] + flex_file['Floor']) + (flex_file['Rush Yards']*.01), flex_file['Median'] + flex_file['Floor'] + flex_file['Receptions'])
flex_file['STD'] = (flex_file['Median']/4) + flex_file['Receptions']
flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
hold_file = flex_file
overall_file = flex_file
salary_file = flex_file
overall_players = overall_file[['Player']]
for x in range(0,total_sims):
salary_file[x] = salary_file['Salary']
salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
salary_file.astype('int').dtypes
salary_file = salary_file.div(1000)
for x in range(0,total_sims):
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
overall_file.astype('int').dtypes
players_only = hold_file[['Player']]
raw_lineups_file = players_only
for x in range(0,total_sims):
maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
players_only[x] = raw_lineups_file[x].rank(ascending=False)
players_only=players_only.drop(['Player'], axis=1)
players_only.astype('int').dtypes
salary_2x_check = (overall_file - (salary_file*2))
salary_3x_check = (overall_file - (salary_file*3))
salary_4x_check = (overall_file - (salary_file*4))
players_only['Average_Rank'] = players_only.mean(axis=1)
players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
players_only['Player'] = hold_file[['Player']]
final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj['Own'] = final_Proj['Player'].map(own_dict)
final_Proj['Team'] = final_Proj['Player'].map(team_dict)
final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
final_Proj['LevX'] = 0
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'QB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'TE', final_Proj[['Projection Rank', '2x%']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'RB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['20+%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'WR', final_Proj[['Projection Rank', 'Top_10_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['CPT_Own'] = final_Proj['Own'] / 4
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
with hold_container:
hold_container = st.empty()
final_Proj = final_Proj
if view_var5 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var5 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='Custom_NFL_wr_export.csv',
mime='text/csv',
)
with tab6:
col1, col2 = st.columns([1, 5])
with col1:
st.info(t_stamp)
if st.button("Load/Reset Data", key='reset6'):
st.cache_data.clear()
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
for key in st.session_state.keys():
del st.session_state[key]
slate_var6 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'Late Slate', 'Thurs-Mon Slate'), key='slate_var6')
site_var6 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var6')
view_var6 = st.radio("What view would you like to display?", ('Advanced', 'Simple'), key='view_var6')
custom_var6 = st.radio("Are you creating a custom table?", ('No', 'Yes'), key='custom_var6')
if custom_var6 == 'No':
if site_var6 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var6)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_tes']
raw_baselines = raw_baselines.iloc[:,:-3]
elif site_var6 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var6)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_tes']
raw_baselines = raw_baselines.iloc[:,:-3]
split_var6 = st.radio("Would you like to view the whole slate or just specific games?", ('Full Slate Run', 'Specific Games'), key='split_var6')
if split_var6 == 'Specific Games':
team_var6 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var6')
elif split_var6 == 'Full Slate Run':
team_var6 = raw_baselines.Team.values.tolist()
pos_split6 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split6')
if pos_split6 == 'Specific Positions':
pos_var6 = st.multiselect('What Positions would you like to view?', options = ['TE'], key='pos_var6')
elif pos_split5 == 'All Positions':
pos_var6 = 'All'
sal_var6 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var6')
if custom_var6 == 'Yes':
contest_var6 = st.selectbox("What contest type are you running for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var6')
if site_var6 == 'Draftkings':
raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var6)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'dk_tes']
elif site_var6 == 'Fanduel':
raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var6)]
raw_baselines = raw_baselines[raw_baselines['version'] == 'fd_tes']
split_var6 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var6')
if split_var6 == 'Specific Games':
team_var6 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var6')
elif split_var6 == 'Full Slate Run':
team_var6 = raw_baselines.Team.values.tolist()
pos_split6 = st.radio("Are you viewing all positions, specific groups, or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split6')
if pos_split6 == 'Specific Positions':
pos_var6 = st.multiselect('What Positions would you like to view?', options = ['TE'])
elif pos_split6 == 'All Positions':
pos_var6 = 'All'
sal_var6 = st.slider("Is there a certain price range you want to view?", 2000, 15000, (2000, 15000), key='sal_var6')
with col2:
if custom_var6 == 'No':
final_Proj = raw_baselines[raw_baselines['Team'].isin(team_var6)]
final_Proj = final_Proj[final_Proj['Salary'] >= sal_var6[0]]
final_Proj = final_Proj[final_Proj['Salary'] <= sal_var6[1]]
if pos_var6 != 'All':
final_Proj = raw_baselines[raw_baselines['Position'].str.contains('|'.join(pos_var6))]
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
if view_var6 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var6 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='NFL_te_export.csv',
mime='text/csv',
)
elif custom_var6 == 'Yes':
hold_container = st.empty()
if st.button('Create Range of Outcomes for Slate'):
with hold_container:
if site_var6 == 'Draftkings':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'TE']
if site_var6 == 'Fanduel':
working_roo = player_stats
working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Half_PPR": "Fantasy"}, inplace = True)
working_roo.replace('', 0, inplace=True)
working_roo = working_roo[working_roo['Position'] == 'TE']
working_roo = working_roo[working_roo['Team'].isin(team_var6)]
working_roo = working_roo[working_roo['Salary'] >= sal_var6[0]]
working_roo = working_roo[working_roo['Salary'] <= sal_var6[1]]
own_dict = dict(zip(working_roo.Player, working_roo.Own))
team_dict = dict(zip(working_roo.Player, working_roo.Team))
opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
total_sims = 1000
flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median'] + flex_file['Floor']) + (flex_file['Rush Yards']*.01), flex_file['Median'] + flex_file['Floor'] + flex_file['Receptions'])
flex_file['STD'] = (flex_file['Median']/4) + flex_file['Receptions']
flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
hold_file = flex_file
overall_file = flex_file
salary_file = flex_file
overall_players = overall_file[['Player']]
for x in range(0,total_sims):
salary_file[x] = salary_file['Salary']
salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
salary_file.astype('int').dtypes
salary_file = salary_file.div(1000)
for x in range(0,total_sims):
overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
overall_file.astype('int').dtypes
players_only = hold_file[['Player']]
raw_lineups_file = players_only
for x in range(0,total_sims):
maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
players_only[x] = raw_lineups_file[x].rank(ascending=False)
players_only=players_only.drop(['Player'], axis=1)
players_only.astype('int').dtypes
salary_2x_check = (overall_file - (salary_file*2))
salary_3x_check = (overall_file - (salary_file*3))
salary_4x_check = (overall_file - (salary_file*4))
players_only['Average_Rank'] = players_only.mean(axis=1)
players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
players_only['Player'] = hold_file[['Player']]
final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
final_Proj['Own'] = final_Proj['Player'].map(own_dict)
final_Proj['Team'] = final_Proj['Player'].map(team_dict)
final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
final_Proj['LevX'] = 0
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'QB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'TE', final_Proj[['Projection Rank', '2x%']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'RB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['20+%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['LevX'] = np.where(final_Proj['Position'] == 'WR', final_Proj[['Projection Rank', 'Top_10_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
final_Proj['CPT_Own'] = final_Proj['Own'] / 4
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
final_Proj = final_Proj.set_index('Player')
final_Proj = final_Proj.sort_values(by='Median', ascending=False)
with hold_container:
hold_container = st.empty()
final_Proj = final_Proj
if view_var6 == 'Simple':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Salary', 'Median', 'Top_5_finish', '4x%']]
disp_proj = final_Proj.set_index('Player')
elif view_var6 == 'Advanced':
final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
disp_proj = final_Proj.set_index('Player')
st.dataframe(disp_proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(final_Proj),
file_name='Custom_NFL_te_export.csv',
mime='text/csv',
)
with tab7:
col1, col2 = st.columns([1, 7])
with col1:
if st.button("Load/Reset Data", key='reset7'):
st.cache_data.clear()
player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = player_stat_table()
dk_lineups = init_DK_lineups()
fd_lineups = init_FD_lineups()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
for key in st.session_state.keys():
del st.session_state[key]
slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Just the Main Slate'))
site_var1 = st.radio("What site are you working with?", ('Draftkings', 'Fanduel'))
lineup_num_var = st.number_input("How many lineups do you want to display?", min_value=1, max_value=1000, value=150, step=1)
if site_var1 == 'Draftkings':
ROO_slice = dk_roo_raw[dk_roo_raw['site'] == 'Draftkings']
id_dict = dict(zip(ROO_slice.Player, ROO_slice.player_id))
column_names = dk_columns
player_var1 = st.radio("Do you want a frame with specific Players?", ('Full Slate', 'Specific Players'), key='player_var1')
if player_var1 == 'Specific Players':
player_var2 = st.multiselect('Which players do you want?', options = dk_roo_raw['Player'].unique())
elif player_var1 == 'Full Slate':
player_var2 = dk_roo_raw.Player.values.tolist()
elif site_var1 == 'Fanduel':
ROO_slice = fd_roo_raw[fd_roo_raw['site'] == 'Fanduel']
id_dict = dict(zip(ROO_slice.Player, ROO_slice.player_id))
column_names = fd_columns
player_var1 = st.radio("Do you want a frame with specific Players?", ('Full Slate', 'Specific Players'), key='player_var1')
if player_var1 == 'Specific Players':
player_var2 = st.multiselect('Which players do you want?', options = fd_roo_raw['Player'].unique())
elif player_var1 == 'Full Slate':
player_var2 = fd_roo_raw.Player.values.tolist()
if st.button("Prepare data export", key='data_export'):
data_export = st.session_state.working_seed.copy()
if site_var1 == 'Draftkings':
for col_idx in range(9):
data_export[:, col_idx] = np.array([id_dict.get(player, player) for player in data_export[:, col_idx]])
elif site_var1 == 'Fanduel':
for col_idx in range(9):
data_export[:, col_idx] = np.array([id_dict.get(player, player) for player in data_export[:, col_idx]])
st.download_button(
label="Export optimals set",
data=convert_df(data_export),
file_name='NFL_optimals_export.csv',
mime='text/csv',
)
with col2:
if site_var1 == 'Draftkings':
if 'working_seed' in st.session_state:
st.session_state.working_seed = st.session_state.working_seed
if player_var1 == 'Specific Players':
st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
elif player_var1 == 'Full Slate':
st.session_state.working_seed = dk_lineups.copy()
st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
elif 'working_seed' not in st.session_state:
st.session_state.working_seed = dk_lineups.copy()
st.session_state.working_seed = st.session_state.working_seed
if player_var1 == 'Specific Players':
st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
elif player_var1 == 'Full Slate':
st.session_state.working_seed = dk_lineups.copy()
st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
elif site_var1 == 'Fanduel':
if 'working_seed' in st.session_state:
st.session_state.working_seed = st.session_state.working_seed
if player_var1 == 'Specific Players':
st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
elif player_var1 == 'Full Slate':
st.session_state.working_seed = fd_lineups.copy()
st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
elif 'working_seed' not in st.session_state:
st.session_state.working_seed = fd_lineups.copy()
st.session_state.working_seed = st.session_state.working_seed
if player_var1 == 'Specific Players':
st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
elif player_var1 == 'Full Slate':
st.session_state.working_seed = fd_lineups.copy()
st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
export_file = st.session_state.data_export_display.copy()
if site_var1 == 'Draftkings':
for col_idx in range(9):
export_file.iloc[:, col_idx] = export_file.iloc[:, col_idx].map(id_dict)
elif site_var1 == 'Fanduel':
for col_idx in range(9):
export_file.iloc[:, col_idx] = export_file.iloc[:, col_idx].map(id_dict)
with st.container():
if st.button("Reset Optimals", key='reset9'):
for key in st.session_state.keys():
del st.session_state[key]
if site_var1 == 'Draftkings':
st.session_state.working_seed = dk_lineups.copy()
elif site_var1 == 'Fanduel':
st.session_state.working_seed = fd_lineups.copy()
if 'data_export_display' in st.session_state:
st.dataframe(st.session_state.data_export_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), height=500, use_container_width = True)
st.download_button(
label="Export display optimals",
data=convert_df(export_file),
file_name='NFL_display_optimals.csv',
mime='text/csv',
)
with st.container():
if 'working_seed' in st.session_state:
# Create a new dataframe with summary statistics
if site_var1 == 'Draftkings':
summary_df = pd.DataFrame({
'Metric': ['Min', 'Average', 'Max', 'STDdev'],
'Salary': [
np.min(st.session_state.working_seed[:,9]),
np.mean(st.session_state.working_seed[:,9]),
np.max(st.session_state.working_seed[:,9]),
np.std(st.session_state.working_seed[:,9])
],
'Proj': [
np.min(st.session_state.working_seed[:,10]),
np.mean(st.session_state.working_seed[:,10]),
np.max(st.session_state.working_seed[:,10]),
np.std(st.session_state.working_seed[:,10])
],
'Own': [
np.min(st.session_state.working_seed[:,15]),
np.mean(st.session_state.working_seed[:,15]),
np.max(st.session_state.working_seed[:,15]),
np.std(st.session_state.working_seed[:,15])
]
})
elif site_var1 == 'Fanduel':
summary_df = pd.DataFrame({
'Metric': ['Min', 'Average', 'Max', 'STDdev'],
'Salary': [
np.min(st.session_state.working_seed[:,9]),
np.mean(st.session_state.working_seed[:,9]),
np.max(st.session_state.working_seed[:,9]),
np.std(st.session_state.working_seed[:,9])
],
'Proj': [
np.min(st.session_state.working_seed[:,10]),
np.mean(st.session_state.working_seed[:,10]),
np.max(st.session_state.working_seed[:,10]),
np.std(st.session_state.working_seed[:,10])
],
'Own': [
np.min(st.session_state.working_seed[:,15]),
np.mean(st.session_state.working_seed[:,15]),
np.max(st.session_state.working_seed[:,15]),
np.std(st.session_state.working_seed[:,15])
]
})
# Set the index of the summary dataframe as the "Metric" column
summary_df = summary_df.set_index('Metric')
# Display the summary dataframe
st.subheader("Optimal Statistics")
st.dataframe(summary_df.style.format({
'Salary': '{:.2f}',
'Proj': '{:.2f}',
'Own': '{:.2f}'
}).background_gradient(cmap='RdYlGn', axis=0, subset=['Salary', 'Proj', 'Own']), use_container_width=True)
with st.container():
tab1, tab2 = st.tabs(["Display Frequency", "Seed Frame Frequency"])
with tab1:
if 'data_export_display' in st.session_state:
if site_var1 == 'Draftkings':
player_columns = st.session_state.data_export_display.iloc[:, :9]
elif site_var1 == 'Fanduel':
player_columns = st.session_state.data_export_display.iloc[:, :9]
# Flatten the DataFrame and count unique values
value_counts = player_columns.values.flatten().tolist()
value_counts = pd.Series(value_counts).value_counts()
percentages = (value_counts / lineup_num_var * 100).round(2)
# Create a DataFrame with the results
summary_df = pd.DataFrame({
'Player': value_counts.index,
'Frequency': value_counts.values,
'Percentage': percentages.values
})
# Sort by frequency in descending order
summary_df = summary_df.sort_values('Frequency', ascending=False)
# Display the table
st.write("Player Frequency Table:")
st.dataframe(summary_df.style.format({'Percentage': '{:.2f}%'}), height=500, use_container_width=True)
st.download_button(
label="Export player frequency",
data=convert_df_to_csv(summary_df),
file_name='NFL_player_frequency.csv',
mime='text/csv',
)
with tab2:
if 'working_seed' in st.session_state:
if site_var1 == 'Draftkings':
player_columns = st.session_state.working_seed[:, :9]
elif site_var1 == 'Fanduel':
player_columns = st.session_state.working_seed[:, :9]
# Flatten the DataFrame and count unique values
value_counts = player_columns.flatten().tolist()
value_counts = pd.Series(value_counts).value_counts()
percentages = (value_counts / len(st.session_state.working_seed) * 100).round(2)
# Create a DataFrame with the results
summary_df = pd.DataFrame({
'Player': value_counts.index,
'Frequency': value_counts.values,
'Percentage': percentages.values
})
# Sort by frequency in descending order
summary_df = summary_df.sort_values('Frequency', ascending=False)
# Display the table
st.write("Seed Frame Frequency Table:")
st.dataframe(summary_df.style.format({'Percentage': '{:.2f}%'}), height=500, use_container_width=True)
st.download_button(
label="Export seed frame frequency",
data=convert_df_to_csv(summary_df),
file_name='NFL_seed_frame_frequency.csv',
mime='text/csv',
)