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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pulp
2
+ import numpy as np
3
+ import pandas as pd
4
+ import streamlit as st
5
+ import gspread
6
+ from itertools import combinations
7
+ import time
8
+
9
+ @st.cache_resource
10
+ def init_conn():
11
+ scope = ['https://www.googleapis.com/auth/spreadsheets',
12
+ "https://www.googleapis.com/auth/drive"]
13
+
14
+ credentials = {
15
+ "type": "service_account",
16
+ "project_id": "sheets-api-connect-378620",
17
+ "private_key_id": "1005124050c80d085e2c5b344345715978dd9cc9",
18
+ "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\ntj8NwVq1ys52eosq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
+ "client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
20
+ "client_id": "106625872877651920064",
21
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
22
+ "token_uri": "https://oauth2.googleapis.com/token",
23
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
24
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
25
+ }
26
+
27
+ gc = gspread.service_account_from_dict(credentials)
28
+ return gc
29
+
30
+ st.set_page_config(layout="wide")
31
+
32
+ gc = init_conn()
33
+
34
+ wrong_acro = ['WSH', 'AZ']
35
+ right_acro = ['WAS', 'ARI']
36
+
37
+ game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}',
38
+ 'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'}
39
+
40
+ team_roo_format = {'Top Score%': '{:.2%}','0 Runs': '{:.2%}', '1 Run': '{:.2%}', '2 Runs': '{:.2%}', '3 Runs': '{:.2%}', '4 Runs': '{:.2%}',
41
+ '5 Runs': '{:.2%}','6 Runs': '{:.2%}', '7 Runs': '{:.2%}', '8 Runs': '{:.2%}', '9 Runs': '{:.2%}', '10 Runs': '{:.2%}'}
42
+
43
+ player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}',
44
+ '4x%': '{:.2%}','GPP%': '{:.2%}'}
45
+
46
+ all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348'
47
+
48
+ @st.cache_resource(ttl=600)
49
+ def load_dk_player_projections():
50
+ sh = gc.open_by_url(all_dk_player_projections)
51
+ worksheet = sh.worksheet('SD_Projections')
52
+ load_display = pd.DataFrame(worksheet.get_all_records())
53
+ load_display.replace('', np.nan, inplace=True)
54
+ raw_display = load_display.dropna(subset=['PPR'])
55
+ raw_display.rename(columns={"name": "Player", "PPR": "Median"}, inplace = True)
56
+ raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
57
+ raw_display = raw_display.loc[raw_display['Median'] > 0]
58
+
59
+ return raw_display
60
+
61
+ @st.cache_resource(ttl=600)
62
+ def load_fd_player_projections():
63
+ sh = gc.open_by_url(all_dk_player_projections)
64
+ worksheet = sh.worksheet('FD_SD_Projections')
65
+ load_display = pd.DataFrame(worksheet.get_all_records())
66
+ load_display.replace('', np.nan, inplace=True)
67
+ raw_display = load_display.dropna(subset=['Half_PPR'])
68
+ raw_display.rename(columns={"name": "Player", "Half_PPR": "Median"}, inplace = True)
69
+ raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
70
+ raw_display = raw_display.loc[raw_display['Median'] > 0]
71
+
72
+ return raw_display
73
+
74
+ dk_roo_raw = load_dk_player_projections()
75
+ fd_roo_raw = load_fd_player_projections()
76
+
77
+ @st.cache_data
78
+ def convert_df_to_csv(df):
79
+ return df.to_csv().encode('utf-8')
80
+
81
+ tab1, tab2, tab3 = st.tabs(['Uploads and Info', 'Range of Outcomes', 'Optimizer'])
82
+
83
+ with tab1:
84
+ st.info("The Projections file can have any columns in any order, but must contain columns explicitly named: 'Player', 'Salary', 'Position', 'Team', 'Opp', 'rush_yards', 'rec', 'Median', and 'Own'. For the purposes of this showdown optimizer, only include FLEX positions, salaries, and medians. The optimizer logic will handle the rest!")
85
+ col1, col2 = st.columns([1, 5])
86
+
87
+ with col1:
88
+ proj_file = st.file_uploader("Upload Projections File", key = 'proj_uploader')
89
+
90
+ if proj_file is not None:
91
+ try:
92
+ proj_dataframe = pd.read_csv(proj_file)
93
+ proj_dataframe = proj_dataframe.loc[proj_dataframe['Median'] > 0]
94
+ except:
95
+ proj_dataframe = pd.read_excel(proj_file)
96
+ proj_dataframe = proj_dataframe.loc[proj_dataframe['Median'] > 0]
97
+ with col2:
98
+ if proj_file is not None:
99
+ st.dataframe(proj_dataframe.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
100
+
101
+ with tab2:
102
+ col1, col2 = st.columns([1, 5])
103
+ with col1:
104
+ if st.button("Load/Reset Data", key='reset2'):
105
+ st.cache_data.clear()
106
+ dk_roo_raw = load_dk_player_projections()
107
+ fd_roo_raw = load_fd_player_projections()
108
+ slate_var2 = st.radio("Which data are you loading?", ('Paydirt', 'User'), key='slate_var2')
109
+ site_var2 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var2')
110
+ if slate_var2 == 'User':
111
+ raw_baselines = proj_dataframe
112
+ elif slate_var2 != 'User':
113
+ if site_var2 == 'Draftkings':
114
+ raw_baselines = dk_roo_raw
115
+ elif site_var2 == 'Fanduel':
116
+ raw_baselines = fd_roo_raw
117
+
118
+ with col2:
119
+ hold_container = st.empty()
120
+ if st.button('Create Range of Outcomes for Slate'):
121
+ with hold_container:
122
+ working_roo = raw_baselines
123
+ working_roo = working_roo.loc[working_roo['Median'] > 0]
124
+ if site_var2 == 'Draftkings':
125
+ working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Median": "Fantasy"}, inplace = True)
126
+ elif site_var2 == 'Draftkings':
127
+ working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Median": "Fantasy"}, inplace = True)
128
+ working_roo.replace('', 0, inplace=True)
129
+ own_dict = dict(zip(working_roo.Player, working_roo.Own))
130
+ team_dict = dict(zip(working_roo.Player, working_roo.Team))
131
+ opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
132
+ total_sims = 1000
133
+
134
+ flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
135
+ flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
136
+ flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
137
+ 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'])
138
+ flex_file['Ceiling'] = flex_file['Ceiling'].fillna(15)
139
+ flex_file['STD'] = np.where(flex_file['Position'] != 'QB', (flex_file['Median']/4) + flex_file['Receptions'], (flex_file['Median']/4))
140
+ flex_file['STD'] = flex_file['Ceiling'].fillna(5)
141
+ flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
142
+ hold_file = flex_file
143
+ overall_file = flex_file
144
+ salary_file = flex_file
145
+
146
+ overall_players = overall_file[['Player']]
147
+
148
+ for x in range(0,total_sims):
149
+ salary_file[x] = salary_file['Salary']
150
+
151
+ salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
152
+ salary_file.astype('int').dtypes
153
+
154
+ salary_file = salary_file.div(1000)
155
+
156
+ for x in range(0,total_sims):
157
+ overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
158
+
159
+ overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
160
+ overall_file.astype('int').dtypes
161
+
162
+ players_only = hold_file[['Player']]
163
+ raw_lineups_file = players_only
164
+
165
+ for x in range(0,total_sims):
166
+ maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
167
+ raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
168
+ players_only[x] = raw_lineups_file[x].rank(ascending=False)
169
+
170
+ players_only=players_only.drop(['Player'], axis=1)
171
+ players_only.astype('int').dtypes
172
+
173
+ salary_2x_check = (overall_file - (salary_file*2))
174
+ salary_3x_check = (overall_file - (salary_file*3))
175
+ salary_4x_check = (overall_file - (salary_file*4))
176
+
177
+ players_only['Average_Rank'] = players_only.mean(axis=1)
178
+ players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
179
+ players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
180
+ players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
181
+ players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
182
+ players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
183
+ players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
184
+ players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
185
+
186
+ players_only['Player'] = hold_file[['Player']]
187
+
188
+ final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
189
+
190
+ final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
191
+ final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
192
+ final_Proj['Own'] = final_Proj['Player'].map(own_dict)
193
+ final_Proj['Team'] = final_Proj['Player'].map(team_dict)
194
+ final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
195
+ 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']]
196
+ final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
197
+ final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
198
+ final_Proj['LevX'] = 0
199
+ final_Proj['LevX'] = final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank']
200
+ final_Proj['CPT_Own'] = final_Proj['Own'] / 4
201
+ final_Proj['CPT_Proj'] = final_Proj['Median'] * 1.5
202
+ final_Proj['CPT_Salary'] = final_Proj['Salary'] * 1.5
203
+
204
+ display_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
205
+ display_Proj = display_Proj.set_index('Player')
206
+ display_Proj = display_Proj.sort_values(by='Median', ascending=False)
207
+
208
+ with hold_container:
209
+ hold_container = st.empty()
210
+ display_Proj = display_Proj
211
+ st.dataframe(display_Proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
212
+
213
+ st.download_button(
214
+ label="Export Tables",
215
+ data=convert_df_to_csv(final_Proj),
216
+ file_name='Custom_NFL_overall_export.csv',
217
+ mime='text/csv',
218
+ )
219
+
220
+ with tab3:
221
+ col1, col2 = st.columns([1, 5])
222
+ with col1:
223
+ if st.button("Load/Reset Data", key='reset1'):
224
+ st.cache_data.clear()
225
+ dk_roo_raw = load_dk_player_projections()
226
+ fd_roo_raw = load_fd_player_projections()
227
+ slate_var1 = st.radio("Which data are you loading?", ('Paydirt', 'User'), key='slate_var1')
228
+ site_var1 = st.selectbox("What site is the showdown on?", ('Draftkings', 'Fanduel'), key='site_var1')
229
+ if site_var1 == 'Draftkings':
230
+ if slate_var1 == 'User':
231
+ raw_baselines = proj_dataframe
232
+ elif slate_var1 != 'User':
233
+ raw_baselines = dk_roo_raw
234
+ elif site_var1 == 'Fanduel':
235
+ if slate_var1 == 'User':
236
+ st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
237
+ raw_baselines = proj_dataframe
238
+ elif slate_var1 != 'User':
239
+ st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
240
+ raw_baselines = fd_roo_raw
241
+ contest_var1 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var1')
242
+ lock_var1 = st.multiselect("Are there any players you want to use in all lineups in the CAPTAIN (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var1')
243
+ lock_var2 = st.multiselect("Are there any players you want to use in all lineups in the FLEX (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var2')
244
+ 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')
245
+ trim_choice1 = st.selectbox("Allow overowned lineups?", options = ['Yes', 'No'])
246
+ 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')
247
+ if trim_choice1 == 'Yes':
248
+ trim_var1 = 0
249
+ elif trim_choice1 == 'No':
250
+ trim_var1 = 1
251
+ if site_var1 == 'Draftkings':
252
+ min_sal1 = st.number_input('Min Salary', min_value = 35000, max_value = 49900, value = 49000, step = 100, key='min_sal1')
253
+ max_sal1 = st.number_input('Max Salary', min_value = 35000, max_value = 50000, value = 50000, step = 100, key='max_sal1')
254
+ elif site_var1 == 'Fanduel':
255
+ min_sal1 = st.number_input('Min Salary', min_value = 45000, max_value = 59900, value = 59000, step = 100, key='min_sal1')
256
+ max_sal1 = st.number_input('Max Salary', min_value = 45000, max_value = 60000, value = 60000, step = 100, key='max_sal1')
257
+ with col2:
258
+ if contest_var1 == 'Small Field GPP':
259
+ if site_var1 == 'Draftkings':
260
+ ownframe = raw_baselines.copy()
261
+ 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'])
262
+ 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%'])
263
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 85, 85, ownframe['Own%'])
264
+ ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
265
+ elif site_var1 == 'Fanduel':
266
+ ownframe = raw_baselines.copy()
267
+ ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
268
+ ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
269
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
270
+ ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
271
+ elif contest_var1 == 'Large Field GPP':
272
+ if site_var1 == 'Draftkings':
273
+ ownframe = raw_baselines.copy()
274
+ ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
275
+ ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
276
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
277
+ ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
278
+ elif site_var1 == 'Fanduel':
279
+ ownframe = raw_baselines.copy()
280
+ ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
281
+ ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
282
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
283
+ ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
284
+ elif contest_var1 == 'Cash':
285
+ if site_var1 == 'Draftkings':
286
+ ownframe = raw_baselines.copy()
287
+ 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'])
288
+ 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%'])
289
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 90, 90, ownframe['Own%'])
290
+ ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
291
+ elif site_var1 == 'Fanduel':
292
+ ownframe = raw_baselines.copy()
293
+ ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
294
+ ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
295
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
296
+ ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
297
+ export_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
298
+ export_baselines['CPT_Proj'] = export_baselines['Median'] * 1.5
299
+ export_baselines['CPT_Salary'] = export_baselines['Salary'] * 1.5
300
+ display_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
301
+ display_baselines['CPT Own'] = display_baselines['Own'] / 4
302
+ display_baselines = display_baselines.sort_values(by='Median', ascending=False)
303
+ display_baselines['cpt_lock'] = np.where(display_baselines['Player'].isin(lock_var1), 1, 0)
304
+ display_baselines['lock'] = np.where(display_baselines['Player'].isin(lock_var2), 1, 0)
305
+
306
+
307
+ index_check = pd.DataFrame()
308
+ flex_proj = pd.DataFrame()
309
+ cpt_proj = pd.DataFrame()
310
+
311
+ if site_var1 == 'Draftkings':
312
+ cpt_proj['Player'] = display_baselines['Player']
313
+ cpt_proj['Salary'] = display_baselines['Salary'] * 1.5
314
+ cpt_proj['Position'] = display_baselines['Position']
315
+ cpt_proj['Team'] = display_baselines['Team']
316
+ cpt_proj['Opp'] = display_baselines['Opp']
317
+ cpt_proj['Median'] = display_baselines['Median'] * 1.5
318
+ cpt_proj['Own'] = display_baselines['CPT Own']
319
+ cpt_proj['lock'] = display_baselines['cpt_lock']
320
+ cpt_proj['roster'] = 'CPT'
321
+ if len(lock_var1) > 0:
322
+ cpt_proj = cpt_proj[cpt_proj['lock'] == 1]
323
+ if len(lock_var2) > 0:
324
+ cpt_proj = cpt_proj[~cpt_proj['Player'].isin(lock_var2)]
325
+
326
+ flex_proj['Player'] = display_baselines['Player']
327
+ flex_proj['Salary'] = display_baselines['Salary']
328
+ flex_proj['Position'] = display_baselines['Position']
329
+ flex_proj['Team'] = display_baselines['Team']
330
+ flex_proj['Opp'] = display_baselines['Opp']
331
+ flex_proj['Median'] = display_baselines['Median']
332
+ flex_proj['Own'] = display_baselines['Own']
333
+ flex_proj['lock'] = display_baselines['lock']
334
+ flex_proj['roster'] = 'FLEX'
335
+ elif site_var1 == 'Fanduel':
336
+ cpt_proj['Player'] = display_baselines['Player']
337
+ cpt_proj['Salary'] = display_baselines['Salary']
338
+ cpt_proj['Position'] = display_baselines['Position']
339
+ cpt_proj['Team'] = display_baselines['Team']
340
+ cpt_proj['Opp'] = display_baselines['Opp']
341
+ cpt_proj['Median'] = display_baselines['Median'] * 1.5
342
+ cpt_proj['Own'] = display_baselines['CPT Own'] *.75
343
+ cpt_proj['lock'] = display_baselines['cpt_lock']
344
+ cpt_proj['roster'] = 'CPT'
345
+
346
+ flex_proj['Player'] = display_baselines['Player']
347
+ flex_proj['Salary'] = display_baselines['Salary']
348
+ flex_proj['Position'] = display_baselines['Position']
349
+ flex_proj['Team'] = display_baselines['Team']
350
+ flex_proj['Opp'] = display_baselines['Opp']
351
+ flex_proj['Median'] = display_baselines['Median']
352
+ flex_proj['Own'] = display_baselines['Own']
353
+ flex_proj['lock'] = display_baselines['lock']
354
+ flex_proj['roster'] = 'FLEX'
355
+
356
+ combo_file = pd.concat([cpt_proj, flex_proj], ignore_index=True)
357
+
358
+ st.dataframe(display_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
359
+ st.download_button(
360
+ label="Export Projections",
361
+ data=convert_df_to_csv(export_baselines),
362
+ file_name='NFL_proj_export.csv',
363
+ mime='text/csv',
364
+ )
365
+ if st.button('Optimize'):
366
+ max_proj = 1000
367
+ max_own = 1000
368
+ total_proj = 0
369
+ total_own = 0
370
+ optimize_container = st.empty()
371
+ lineup_display = []
372
+ check_list = []
373
+ lineups = []
374
+ portfolio = pd.DataFrame()
375
+ x = 1
376
+
377
+ with st.spinner('Wait for it...'):
378
+ with optimize_container:
379
+
380
+ while x <= linenum_var1:
381
+ sorted_lineup = []
382
+ p_used = []
383
+
384
+ raw_proj_file = combo_file
385
+ raw_flex_file = raw_proj_file.dropna(how='all')
386
+ raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > 0]
387
+ flex_file = raw_flex_file
388
+ flex_file.rename(columns={"Own": "Proj DK Own%"}, inplace = True)
389
+ flex_file['name_var'] = flex_file['Player']
390
+ flex_file['lock'] = np.where(flex_file['Player'].isin(lock_var2), 1, 0)
391
+ flex_file = flex_file[~flex_file['Player'].isin(avoid_var1)]
392
+ flex_file['Player'] = np.where(flex_file['roster'] == 'CPT', flex_file['Player'] + ' - CPT', flex_file['Player'] + ' - FLEX')
393
+ player_ids = flex_file.index
394
+
395
+ overall_players = flex_file[['Player']]
396
+ overall_players['player_var_add'] = flex_file.index
397
+ overall_players['player_var'] = 'player_vars_' + overall_players['player_var_add'].astype(str)
398
+
399
+ player_vars = pulp.LpVariable.dicts("player_vars", flex_file.index, 0, 1, pulp.LpInteger)
400
+ total_score = pulp.LpProblem("Fantasy_Points_Problem", pulp.LpMaximize)
401
+ player_match = dict(zip(overall_players['player_var'], overall_players['Player']))
402
+ player_index_match = dict(zip(overall_players['player_var'], overall_players['player_var_add']))
403
+
404
+ player_own = dict(zip(flex_file['Player'], flex_file['Proj DK Own%']))
405
+ player_team = dict(zip(flex_file['Player'], flex_file['Team']))
406
+ player_pos = dict(zip(flex_file['Player'], flex_file['Position']))
407
+ player_sal = dict(zip(flex_file['Player'], flex_file['Salary']))
408
+ player_proj = dict(zip(flex_file['Player'], flex_file['Median']))
409
+
410
+ obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
411
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
412
+
413
+ obj_points_max = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
414
+ obj_own_max = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
415
+
416
+ obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
417
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) <= max_sal1
418
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal1
419
+
420
+ if site_var1 == 'Draftkings':
421
+
422
+ for flex in flex_file['lock'].unique():
423
+ sub_idx = flex_file[flex_file['lock'] == 1].index
424
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var2)
425
+
426
+ for flex in flex_file['roster'].unique():
427
+ sub_idx = flex_file[flex_file['roster'] == "CPT"].index
428
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
429
+
430
+ for flex in flex_file['roster'].unique():
431
+ sub_idx = flex_file[flex_file['roster'] == "FLEX"].index
432
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
433
+
434
+ for playerid in player_ids:
435
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
436
+ (flex_file['name_var'][i] == flex_file['name_var'][playerid])]) <= 1
437
+
438
+ elif site_var1 == 'Fanduel':
439
+
440
+ for flex in flex_file['lock'].unique():
441
+ sub_idx = flex_file[flex_file['lock'] == 1].index
442
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var2)
443
+
444
+ for flex in flex_file['Position'].unique():
445
+ sub_idx = flex_file[flex_file['Position'] != "Var"].index
446
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
447
+
448
+ for flex in flex_file['roster'].unique():
449
+ sub_idx = flex_file[flex_file['roster'] == "CPT"].index
450
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
451
+
452
+ for playerid in player_ids:
453
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
454
+ (flex_file['name_var'][i] == flex_file['name_var'][playerid])]) <= 1
455
+
456
+ player_count = []
457
+ player_trim = []
458
+ lineup_list = []
459
+
460
+ if contest_var1 == 'Cash':
461
+ obj_points = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
462
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
463
+ total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_own - .001
464
+ elif contest_var1 != 'Cash':
465
+ obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
466
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
467
+ total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_proj - .01
468
+ if trim_var1 == 1:
469
+ total_score += pulp.lpSum([player_vars[idx]*obj_own_max[idx] for idx in flex_file.index]) <= max_own - .001
470
+
471
+ total_score.solve()
472
+ for v in total_score.variables():
473
+ if v.varValue > 0:
474
+ lineup_list.append(v.name)
475
+ df = pd.DataFrame(lineup_list)
476
+ df['Names'] = df[0].map(player_match)
477
+ df['Cost'] = df['Names'].map(player_sal)
478
+ df['Proj'] = df['Names'].map(player_proj)
479
+ df['Own'] = df['Names'].map(player_own)
480
+ total_cost = sum(df['Cost'])
481
+ total_own = sum(df['Own'])
482
+ total_proj = sum(df['Proj'])
483
+ lineup_raw = pd.DataFrame(lineup_list)
484
+ lineup_raw['Names'] = lineup_raw[0].map(player_match)
485
+ lineup_raw['value'] = lineup_raw[0].map(player_index_match)
486
+ lineup_final = lineup_raw.sort_values(by=['value'])
487
+ del lineup_final[lineup_final.columns[0]]
488
+ del lineup_final[lineup_final.columns[1]]
489
+ lineup_final['Team'] = lineup_final['Names'].map(player_team)
490
+ lineup_final['Position'] = lineup_final['Names'].map(player_pos)
491
+ lineup_final['Salary'] = lineup_final['Names'].map(player_sal)
492
+ lineup_final['Proj'] = lineup_final['Names'].map(player_proj)
493
+ lineup_final['Own'] = lineup_final['Names'].map(player_own)
494
+ lineup_final.loc['Column_Total'] = lineup_final.sum(numeric_only=True, axis=0)
495
+ lineup_final = lineup_final.reset_index(drop=True)
496
+ # lineup_final = lineup_final.set_index('Names')
497
+
498
+ with col2:
499
+ with st.container():
500
+ st.table(lineup_final)
501
+
502
+ max_proj = total_proj
503
+ max_own = total_own
504
+
505
+ if site_var1 == 'Draftkings':
506
+ if len(lineup_final) == 7:
507
+ port_display = pd.DataFrame(lineup_final['Names'][:-1].values.reshape(1, -1))
508
+
509
+ port_display['Cost'] = total_cost
510
+ port_display['Proj'] = total_proj
511
+ port_display['Own'] = total_own
512
+ st.table(port_display)
513
+
514
+ portfolio = pd.concat([portfolio, port_display], ignore_index = True)
515
+ elif site_var1 == 'Fanduel':
516
+ if len(lineup_final) == 6:
517
+ port_display = pd.DataFrame(lineup_final['Names'][:-1].values.reshape(1, -1))
518
+
519
+ port_display['Cost'] = total_cost
520
+ port_display['Proj'] = total_proj
521
+ port_display['Own'] = total_own
522
+ st.table(port_display)
523
+
524
+ portfolio = pd.concat([portfolio, port_display], ignore_index = True)
525
+
526
+ x += 1
527
+
528
+ if site_var1 == 'Draftkings':
529
+ portfolio.rename(columns={0: "CPT", 1: "FLEX1", 2: "FLEX2", 3: "FLEX3", 4: "FLEX4", 5: "FLEX5"}, inplace = True)
530
+ elif site_var1 == 'Fanduel':
531
+ portfolio.rename(columns={0: "MVP", 1: "FLEX1", 2: "FLEX2", 3: "FLEX3", 4: "FLEX4"}, inplace = True)
532
+ portfolio = portfolio.dropna()
533
+ portfolio = portfolio.reset_index()
534
+ portfolio['Lineup_num'] = portfolio['index'] + 1
535
+ portfolio.rename(columns={'Lineup_num': "Lineup"}, inplace = True)
536
+ portfolio = portfolio.set_index('Lineup')
537
+ portfolio = portfolio.drop(columns=['index'])
538
+ portfolio = portfolio.drop_duplicates()
539
+
540
+ final_outcomes = portfolio
541
+
542
+ with optimize_container:
543
+ optimize_container = st.empty()
544
+ st.dataframe(portfolio.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
545
+
546
+ st.download_button(
547
+ label="Export Tables",
548
+ data=convert_df_to_csv(final_outcomes),
549
+ file_name='MLB_optimals_export.csv',
550
+ mime='text/csv',
551
+ )