Multichem commited on
Commit
d3b9a22
·
1 Parent(s): f7bc741

Upload app (5).py

Browse files
Files changed (1) hide show
  1. app (5).py +1241 -0
app (5).py ADDED
@@ -0,0 +1,1241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ st.set_page_config(layout="wide")
3
+
4
+ for name in dir():
5
+ if not name.startswith('_'):
6
+ del globals()[name]
7
+
8
+ import pulp
9
+ import numpy as np
10
+ import pandas as pd
11
+ import streamlit as st
12
+ import gspread
13
+ import time
14
+ from itertools import combinations
15
+
16
+ @st.cache_resource
17
+ def init_conn():
18
+ scope = ['https://www.googleapis.com/auth/spreadsheets',
19
+ "https://www.googleapis.com/auth/drive"]
20
+
21
+ credentials = {
22
+ "type": "service_account",
23
+ "project_id": "sheets-api-connect-378620",
24
+ "private_key_id": "1005124050c80d085e2c5b344345715978dd9cc9",
25
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtKa01beXwc88R\nnPZVQTNPVQuBnbwoOfc66gW3547ja/UEyIGAF112dt/VqHprRafkKGmlg55jqJNt\na4zceLKV+wTm7vBu7lDISTJfGzCf2TrxQYNqwMKE2LOjI69dBM8u4Dcb4k0wcp9v\ntW1ZzLVVuwTvmrg7JBHjiSaB+x5wxm/r3FOiJDXdlAgFlytzqgcyeZMJVKKBQHyJ\njEGg/1720A0numuOCt71w/2G0bDmijuj1e6tH32MwRWcvRNZ19K9ssyDz2S9p68s\nYDhIxX69OWxwScTIHLY6J2t8txf/XMivL/636fPlDADvBEVTdlT606n8CcKUVQeq\npUVdG+lfAgMBAAECggEAP38SUA7B69eTfRpo658ycOs3Amr0JW4H/bb1rNeAul0K\nZhwd/HnU4E07y81xQmey5kN5ZeNrD5EvqkZvSyMJHV0EEahZStwhjCfnDB/cxyix\nZ+kFhv4y9eK+kFpUAhBy5nX6T0O+2T6WvzAwbmbVsZ+X8kJyPuF9m8ldcPlD0sce\ntj8NwVq1ys52eosqs7zi2vjt+eMcaY393l4ls+vNq8Yf27cfyFw45W45CH/97/Nu\n5AmuzlCOAfFF+z4OC5g4rei4E/Qgpxa7/uom+BVfv9G0DIGW/tU6Sne0+37uoGKt\nW6DzhgtebUtoYkG7ZJ05BTXGp2lwgVcNRoPwnKJDxQKBgQDT5wYPUBDW+FHbvZSp\nd1m1UQuXyerqOTA9smFaM8sr/UraeH85DJPEIEk8qsntMBVMhvD3Pw8uIUeFNMYj\naLmZFObsL+WctepXrVo5NB6RtLB/jZYxiKMatMLUJIYtcKIp+2z/YtKiWcLnwotB\nWdCjVnPTxpkurmF2fWP/eewZ+wKBgQDRMtJg7etjvKyjYNQ5fARnCc+XsI3gkBe1\nX9oeXfhyfZFeBXWnZzN1ITgFHplDznmBdxAyYGiQdbbkdKQSghviUQ0igBvoDMYy\n1rWcy+a17Mj98uyNEfmb3X2cC6WpvOZaGHwg9+GY67BThwI3FqHIbyk6Ko09WlTX\nQpRQjMzU7QKBgAfi1iflu+q0LR+3a3vvFCiaToskmZiD7latd9AKk2ocsBd3Woy9\n+hXXecJHPOKV4oUJlJgvAZqe5HGBqEoTEK0wyPNLSQlO/9ypd+0fEnArwFHO7CMF\nycQprAKHJXM1eOOFFuZeQCaInqdPZy1UcV5Szla4UmUZWkk1m24blHzXAoGBAMcA\nyH4qdbxX9AYrC1dvsSRvgcnzytMvX05LU0uF6tzGtG0zVlub4ahvpEHCfNuy44UT\nxRWW/oFFaWjjyFxO5sWggpUqNuHEnRopg3QXx22SRRTGbN45li/+QAocTkgsiRh1\nqEcYZsO4mPCsQqAy6E2p6RcK+Xa+omxvSnVhq0x1AoGAKr8GdkCl4CF6rieLMAQ7\nLNBuuoYGaHoh8l5E2uOQpzwxVy/nMBcAv+2+KqHEzHryUv1owOi6pMLv7A9mTFoS\n18B0QRLuz5fSOsVnmldfC9fpUc6H8cH1SINZpzajqQA74bPwELJjnzrCnH79TnHG\nJuElxA33rFEjbgbzdyrE768=\n-----END PRIVATE KEY-----\n",
26
+ "client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
27
+ "client_id": "106625872877651920064",
28
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
29
+ "token_uri": "https://oauth2.googleapis.com/token",
30
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
31
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
32
+ }
33
+
34
+ gc = gspread.service_account_from_dict(credentials)
35
+ return gc
36
+
37
+ gcservice_account = init_conn()
38
+
39
+ wrong_acro = ['WSH', 'AZ']
40
+ right_acro = ['WAS', 'ARI']
41
+
42
+ game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}',
43
+ 'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'}
44
+
45
+ team_roo_format = {'Top Score%': '{:.2%}','0 Runs': '{:.2%}', '1 Run': '{:.2%}', '2 Runs': '{:.2%}', '3 Runs': '{:.2%}', '4 Runs': '{:.2%}',
46
+ '5 Runs': '{:.2%}','6 Runs': '{:.2%}', '7 Runs': '{:.2%}', '8 Runs': '{:.2%}', '9 Runs': '{:.2%}', '10 Runs': '{:.2%}'}
47
+
48
+ expose_format = {'Proj Own': '{:.2%}','Exposure': '{:.2%}'}
49
+
50
+ all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348'
51
+
52
+ @st.cache_resource(ttl = 600)
53
+ def set_slate_teams():
54
+ sh = gcservice_account.open_by_url(all_dk_player_projections)
55
+ worksheet = sh.worksheet('Site_Info')
56
+ raw_display = pd.DataFrame(worksheet.get_all_records())
57
+
58
+ return raw_display
59
+
60
+ @st.cache_resource(ttl = 600)
61
+ def player_stat_table():
62
+ sh = gcservice_account.open_by_url(all_dk_player_projections)
63
+ worksheet = sh.worksheet('Player_Projections')
64
+ raw_display = pd.DataFrame(worksheet.get_all_records())
65
+
66
+ return raw_display
67
+
68
+ @st.cache_resource(ttl = 600)
69
+ def load_dk_player_projections():
70
+ sh = gcservice_account.open_by_url(all_dk_player_projections)
71
+ worksheet = sh.worksheet('DK_ROO')
72
+ load_display = pd.DataFrame(worksheet.get_all_records())
73
+ load_display.replace('', np.nan, inplace=True)
74
+ raw_display = load_display.dropna(subset=['Median'])
75
+
76
+ return raw_display
77
+
78
+ @st.cache_resource(ttl = 600)
79
+ def load_fd_player_projections():
80
+ sh = gcservice_account.open_by_url(all_dk_player_projections)
81
+ worksheet = sh.worksheet('FD_ROO')
82
+ load_display = pd.DataFrame(worksheet.get_all_records())
83
+ load_display.replace('', np.nan, inplace=True)
84
+ raw_display = load_display.dropna(subset=['Median'])
85
+
86
+ return raw_display
87
+
88
+ @st.cache_resource(ttl = 600)
89
+ def load_dk_stacks():
90
+ sh = gcservice_account.open_by_url(all_dk_player_projections)
91
+ worksheet = sh.worksheet('DK_Stacks')
92
+ load_display = pd.DataFrame(worksheet.get_all_records())
93
+ raw_display = load_display
94
+ raw_display = raw_display.sort_values(by='Own', ascending=False)
95
+
96
+ return raw_display
97
+
98
+ @st.cache_resource(ttl = 600)
99
+ def load_fd_stacks():
100
+ sh = gcservice_account.open_by_url(all_dk_player_projections)
101
+ worksheet = sh.worksheet('FD_Stacks')
102
+ load_display = pd.DataFrame(worksheet.get_all_records())
103
+ raw_display = load_display
104
+ raw_display = raw_display.sort_values(by='Own', ascending=False)
105
+
106
+ return raw_display
107
+
108
+ @st.cache_resource(ttl = 3600)
109
+ def set_export_ids():
110
+ sh = gcservice_account.open_by_url(all_dk_player_projections)
111
+ worksheet = sh.worksheet('DK_ROO')
112
+ load_display = pd.DataFrame(worksheet.get_all_records())
113
+ load_display.replace('', np.nan, inplace=True)
114
+ raw_display = load_display.dropna(subset=['Median'])
115
+ dk_ids = dict(zip(raw_display['Player'], raw_display['player_id']))
116
+
117
+ worksheet = sh.worksheet('FD_ROO')
118
+ load_display = pd.DataFrame(worksheet.get_all_records())
119
+ load_display.replace('', np.nan, inplace=True)
120
+ raw_display = load_display.dropna(subset=['Median'])
121
+ fd_ids = dict(zip(raw_display['Player'], raw_display['player_id']))
122
+
123
+ return dk_ids, fd_ids
124
+
125
+ @st.cache_data
126
+ def convert_df_to_csv(df):
127
+ return df.to_csv().encode('utf-8')
128
+
129
+ player_stats = player_stat_table()
130
+ dk_stacks_raw = load_fd_stacks()
131
+ fd_stacks_raw = load_fd_stacks()
132
+ dk_roo_raw = load_dk_player_projections()
133
+ fd_roo_raw = load_fd_player_projections()
134
+ t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
135
+ site_slates = set_slate_teams()
136
+ col1, col2 = st.columns([1, 5])
137
+ dk_Max_Rank = dk_stacks_raw['Team'][0]
138
+ fd_Max_Rank = dk_stacks_raw['Team'][0]
139
+ dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False)
140
+ fd_stacks_raw = fd_stacks_raw.sort_values(by='Median', ascending=False)
141
+ dk_Max_Upside = dk_stacks_raw['Team'][0]
142
+ fd_Max_Upside = dk_stacks_raw['Team'][0]
143
+ opp_dict = dict(zip(dk_roo_raw.Team, dk_roo_raw.Opp))
144
+ dkid_dict, fdid_dict = set_export_ids()
145
+
146
+ tab1, tab2 = st.tabs(['Uploads and Info', 'Optimizer'])
147
+
148
+ with tab1:
149
+ st.info("The Projections file can have any columns in any order, but must contain columns explicitly named: 'Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', and 'Own'.")
150
+ col1, col2 = st.columns([1, 5])
151
+
152
+ with col1:
153
+ proj_file = st.file_uploader("Upload Projections File", key = 'proj_uploader')
154
+
155
+ if proj_file is not None:
156
+ try:
157
+ proj_dataframe = pd.read_csv(proj_file)
158
+ except:
159
+ proj_dataframe = pd.read_excel(proj_file)
160
+ with col2:
161
+ if proj_file is not None:
162
+ st.dataframe(proj_dataframe.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
163
+
164
+ with tab2:
165
+ col1, col2 = st.columns([1, 5])
166
+ with col1:
167
+ st.info(t_stamp)
168
+ if st.button("Load/Reset Data", key='reset1'):
169
+ st.cache_data.clear()
170
+ player_stats = player_stat_table()
171
+ dk_stacks_raw = load_fd_stacks()
172
+ fd_stacks_raw = load_fd_stacks()
173
+ dk_roo_raw = load_dk_player_projections()
174
+ fd_roo_raw = load_fd_player_projections()
175
+ t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
176
+ site_slates = set_slate_teams()
177
+
178
+ slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'All Games', 'User'), key='slate_var1')
179
+ site_var1 = st.radio("What site are you working with?", ('Draftkings', 'Fanduel'), key='site_var1')
180
+ if site_var1 == 'Draftkings':
181
+ if slate_var1 == 'User':
182
+ raw_baselines = proj_dataframe
183
+ Max_Rank = dk_Max_Rank
184
+ Max_Upside = dk_Max_Upside
185
+ elif slate_var1 != 'User':
186
+ raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var1)]
187
+ raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
188
+ Max_Rank = dk_Max_Rank
189
+ Max_Upside = dk_Max_Upside
190
+ elif site_var1 == 'Fanduel':
191
+ if slate_var1 == 'User':
192
+ raw_baselines = proj_dataframe
193
+ Max_Rank = fd_Max_Rank
194
+ Max_Upside = fd_Max_Upside
195
+ elif slate_var1 != 'User':
196
+ raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var1)]
197
+ raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
198
+ Max_Rank = fd_Max_Rank
199
+ Max_Upside = fd_Max_Upside
200
+ contest_var1 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP', 'Round Robin'), key='contest_var1')
201
+ if contest_var1 == 'Small Field GPP':
202
+ st.info('The Pivot optimal uses backend functions to create a stack and lock in certain pieces, if you want control over QB pairing use the Manual model instead.')
203
+ opto_var1 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var1')
204
+ if opto_var1 == "Manual":
205
+ stack_var1 = st.selectbox('Which teams are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var1')
206
+ opp_var1 = opp_dict[stack_var1]
207
+ qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1')
208
+ ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1')
209
+ elif opto_var1 == "Pivot Optimal":
210
+ stack_var1 = Max_Rank
211
+ opp_var1 = opp_dict[stack_var1]
212
+ qbstack_var1 = 2
213
+ ministack_var1 = 0
214
+ elif contest_var1 == 'Large Field GPP':
215
+ st.info('The Pivot optimal uses backend functions to create a stack and lock in certain pieces, if you want control over QB pairing use the Manual model instead.')
216
+ opto_var1 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var1')
217
+ if opto_var1 == "Manual":
218
+ stack_var1 = st.selectbox('Which team are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var1')
219
+ opp_var1 = opp_dict[stack_var1]
220
+ qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1')
221
+ ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1')
222
+ elif opto_var1 == "Pivot Optimal":
223
+ stack_var1 = Max_Upside
224
+ opp_var1 = opp_dict[stack_var1]
225
+ qbstack_var1 = 2
226
+ ministack_var1 = 1
227
+ elif contest_var1 == 'Round Robin':
228
+ st.info('A Round Robin optimization will run a single optimal for all the teams on the slate based on your stacking inputs')
229
+ qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1')
230
+ ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1')
231
+ split_var1 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var1')
232
+ if split_var1 == 'Specific Games':
233
+ team_var1 = st.multiselect('Which teams would you like to include in the optimization?', options = raw_baselines['Team'].unique(), key='team_var1')
234
+ elif split_var1 == 'Full Slate Run':
235
+ team_var1 = raw_baselines.Team.values.tolist()
236
+ lock_var1 = st.multiselect("Are there any players you want to use in all lineups (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var1')
237
+ 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')
238
+ if contest_var1 == 'Round Robin':
239
+ linenum_var1 = len(raw_baselines['Team'].unique())
240
+ elif contest_var1 != 'Round Robin':
241
+ 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')
242
+ if site_var1 == 'Draftkings':
243
+ min_sal1 = st.number_input('Min Salary', min_value = 35000, max_value = 49900, value = 49000, step = 100, key='min_sal1')
244
+ max_sal1 = st.number_input('Max Salary', min_value = 35000, max_value = 50000, value = 50000, step = 100, key='max_sal1')
245
+ elif site_var1 == 'Fanduel':
246
+ min_sal1 = st.number_input('Min Salary', min_value = 45000, max_value = 59900, value = 59000, step = 100, key='min_sal1')
247
+ max_sal1 = st.number_input('Max Salary', min_value = 45000, max_value = 60000, value = 60000, step = 100, key='max_sal1')
248
+ with col2:
249
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(team_var1)]
250
+ raw_baselines = raw_baselines[~raw_baselines['Player'].isin(avoid_var1)]
251
+ ownframe = raw_baselines.copy()
252
+ if contest_var1 == 'Cash':
253
+ ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (10 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
254
+ 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%'])
255
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
256
+ ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum())
257
+ if contest_var1 == 'Small Field GPP':
258
+ 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'])
259
+ ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (3 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
260
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
261
+ ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum())
262
+ if contest_var1 == 'Large Field GPP':
263
+ ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (3 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
264
+ ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (1.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
265
+ ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
266
+ ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum())
267
+ raw_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
268
+ raw_baselines = raw_baselines.sort_values(by='Median', ascending=False)
269
+ raw_baselines['lock'] = np.where(raw_baselines['Player'].isin(lock_var1), 1, 0)
270
+ st.dataframe(raw_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
271
+ st.download_button(
272
+ label="Export Projections",
273
+ data=convert_df_to_csv(raw_baselines),
274
+ file_name='NFL_proj_export.csv',
275
+ mime='text/csv',
276
+ )
277
+ if st.button('Optimize'):
278
+ max_proj = 1000
279
+ max_own = 1000
280
+ total_proj = 0
281
+ total_own = 0
282
+ optimize_container = st.empty()
283
+ download_container = st.empty()
284
+ freq_container = st.empty()
285
+ lineup_display = []
286
+ check_list = []
287
+ lineups = []
288
+ portfolio = pd.DataFrame()
289
+ x = 1
290
+
291
+ with st.spinner('Wait for it...'):
292
+ with optimize_container:
293
+ if contest_var1 == 'Round Robin':
294
+
295
+ while x <= len(raw_baselines['Team'].unique()):
296
+ stack_var1 = raw_baselines['Team'].unique()[x-1]
297
+ opp_var1 = opp_dict[stack_var1]
298
+ st.write(stack_var1)
299
+ sorted_lineup = []
300
+ p_used = []
301
+ cvar = 0
302
+ firvar = 0
303
+ secvar = 0
304
+ thirvar = 0
305
+
306
+ raw_proj_file = raw_baselines
307
+ raw_flex_file = raw_proj_file.dropna(how='all')
308
+ raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > 0]
309
+ flex_file = raw_flex_file
310
+ flex_file.rename(columns={"Own": "Proj DK Own%"}, inplace = True)
311
+ flex_file['name_var'] = flex_file['Player']
312
+ flex_file['lock'] = np.where(flex_file['Player'].isin(lock_var1), 1, 0)
313
+ player_ids = flex_file.index
314
+
315
+ overall_players = flex_file[['Player']]
316
+ overall_players['player_var_add'] = flex_file.index
317
+ overall_players['player_var'] = 'player_vars_' + overall_players['player_var_add'].astype(str)
318
+
319
+ player_vars = pulp.LpVariable.dicts("player_vars", flex_file.index, 0, 1, pulp.LpInteger)
320
+ total_score = pulp.LpProblem("Fantasy_Points_Problem", pulp.LpMaximize)
321
+ player_match = dict(zip(overall_players['player_var'], overall_players['Player']))
322
+ player_index_match = dict(zip(overall_players['player_var'], overall_players['player_var_add']))
323
+
324
+ player_own = dict(zip(flex_file['Player'], flex_file['Proj DK Own%']))
325
+ player_team = dict(zip(flex_file['Player'], flex_file['Team']))
326
+ player_pos = dict(zip(flex_file['Player'], flex_file['Position']))
327
+ player_sal = dict(zip(flex_file['Player'], flex_file['Salary']))
328
+ player_proj = dict(zip(flex_file['Player'], flex_file['Median']))
329
+
330
+ obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
331
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) <= max_sal1
332
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal1
333
+
334
+ if site_var1 == 'Draftkings':
335
+
336
+ if contest_var1 == 'Cash':
337
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
338
+ qbfile = qbfile[qbfile['Position'] == 'QB']
339
+ qbfile = qbfile.reset_index()
340
+ qb_var = qbfile['Player'][0]
341
+ elif contest_var1 == 'Small Field GPP':
342
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
343
+ qbfile = qbfile[qbfile['Position'] == 'QB']
344
+ qbfile = qbfile.reset_index()
345
+ qb_var = qbfile['Player'][0]
346
+ st.table(qbfile)
347
+ #st.write(stack_var1 + ' ' + qb_var)
348
+ for qbid in player_ids:
349
+ if flex_file['Position'][qbid] == 'QB':
350
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
351
+ (flex_file['Team'][i] == stack_var1 and
352
+ flex_file['Position'][i] in ('WR', 'TE'))] +
353
+ [-qbstack_var1*player_vars[qbid]]) >= 0
354
+ if flex_file['Position'][qbid] == 'QB':
355
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
356
+ (flex_file['Team'][i] == stack_var1 and
357
+ flex_file['Position'][i] in ('RB'))] +
358
+ [0*player_vars[qbid]]) == 0
359
+ if flex_file['Position'][qbid] == 'QB':
360
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
361
+ (flex_file['Team'][i] == opp_var1 and
362
+ flex_file['Position'][i] in ('WR', 'TE'))] +
363
+ [-ministack_var1*player_vars[qbid]]) >= 0
364
+ for flex in flex_file['Player'].unique():
365
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
366
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
367
+ elif contest_var1 == 'Round Robin':
368
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
369
+ qbfile = qbfile[qbfile['Position'] == 'QB']
370
+ qbfile = qbfile.reset_index()
371
+ qb_var = qbfile['Player'][0]
372
+ st.table(qbfile)
373
+ #st.write(stack_var1 + ' ' + qb_var)
374
+ for qbid in player_ids:
375
+ if flex_file['Position'][qbid] == 'QB':
376
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
377
+ (flex_file['Team'][i] == stack_var1 and
378
+ flex_file['Position'][i] in ('WR', 'TE'))] +
379
+ [-qbstack_var1*player_vars[qbid]]) >= 0
380
+ if flex_file['Position'][qbid] == 'QB':
381
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
382
+ (flex_file['Team'][i] == stack_var1 and
383
+ flex_file['Position'][i] in ('RB'))] +
384
+ [0*player_vars[qbid]]) == 0
385
+ if flex_file['Position'][qbid] == 'QB':
386
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
387
+ (flex_file['Team'][i] == opp_var1 and
388
+ flex_file['Position'][i] in ('WR', 'TE'))] +
389
+ [-ministack_var1*player_vars[qbid]]) >= 0
390
+ for flex in flex_file['Player'].unique():
391
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
392
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
393
+ elif contest_var1 == 'Large Field GPP':
394
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
395
+ qbfile = qbfile[qbfile['Position'] == 'QB']
396
+ qbfile = qbfile.reset_index()
397
+ qb_var = qbfile['Player'][0]
398
+ st.table(qbfile)
399
+ #st.write(stack_var1 + ' ' + qb_var)
400
+ for qbid in player_ids:
401
+ if flex_file['Position'][qbid] == 'QB':
402
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
403
+ (flex_file['Team'][i] == stack_var1 and
404
+ flex_file['Position'][i] in ('WR', 'TE'))] +
405
+ [-qbstack_var1*player_vars[qbid]]) >= 0
406
+ if flex_file['Position'][qbid] == 'QB':
407
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
408
+ (flex_file['Team'][i] == stack_var1 and
409
+ flex_file['Position'][i] in ('RB'))] +
410
+ [0*player_vars[qbid]]) == 0
411
+ if flex_file['Position'][qbid] == 'QB':
412
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
413
+ (flex_file['Team'][i] == opp_var1 and
414
+ flex_file['Position'][i] in ('WR', 'TE'))] +
415
+ [-ministack_var1*player_vars[qbid]]) >= 0
416
+ for flex in flex_file['Player'].unique():
417
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
418
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
419
+
420
+ for flex in flex_file['lock'].unique():
421
+ sub_idx = flex_file[flex_file['lock'] == 1].index
422
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var1)
423
+
424
+ for flex in flex_file['Position'].unique():
425
+ sub_idx = flex_file[flex_file['Position'] != "Var"].index
426
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 9
427
+
428
+ for flex in flex_file['Position'].unique():
429
+ sub_idx = flex_file[flex_file['Position'] == "QB"].index
430
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
431
+
432
+ for flex in flex_file['Position'].unique():
433
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
434
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
435
+
436
+ for flex in flex_file['Position'].unique():
437
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
438
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
439
+
440
+ for flex in flex_file['Position'].unique():
441
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
442
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
443
+
444
+ for flex in flex_file['Position'].unique():
445
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
446
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
447
+
448
+ for flex in flex_file['Position'].unique():
449
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
450
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
451
+
452
+ for flex in flex_file['Position'].unique():
453
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
454
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
455
+
456
+ for flex in flex_file['Position'].unique():
457
+ sub_idx = flex_file[flex_file['Position'] == "DST"].index
458
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
459
+
460
+ elif site_var1 == 'Fanduel':
461
+
462
+ if contest_var1 == 'Cash':
463
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
464
+ qbfile = qbfile[qbfile['Position'] == 'QB']
465
+ qbfile = qbfile.reset_index()
466
+ qb_var = qbfile['Player'][0]
467
+ elif contest_var1 == 'Small Field GPP':
468
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
469
+ qbfile = qbfile[qbfile['Position'] == 'QB']
470
+ qbfile = qbfile.reset_index()
471
+ qb_var = qbfile['Player'][0]
472
+ st.table(qbfile)
473
+ #st.write(stack_var1 + ' ' + qb_var)
474
+ for qbid in player_ids:
475
+ if flex_file['Position'][qbid] == 'QB':
476
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
477
+ (flex_file['Team'][i] == stack_var1 and
478
+ flex_file['Position'][i] in ('WR', 'TE'))] +
479
+ [-qbstack_var1*player_vars[qbid]]) >= 0
480
+ if flex_file['Position'][qbid] == 'QB':
481
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
482
+ (flex_file['Team'][i] == stack_var1 and
483
+ flex_file['Position'][i] in ('RB'))] +
484
+ [0*player_vars[qbid]]) == 0
485
+ if flex_file['Position'][qbid] == 'QB':
486
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
487
+ (flex_file['Team'][i] == opp_var1 and
488
+ flex_file['Position'][i] in ('WR', 'TE'))] +
489
+ [-ministack_var1*player_vars[qbid]]) >= 0
490
+ for flex in flex_file['Player'].unique():
491
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
492
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
493
+ elif contest_var1 == 'Round Robin':
494
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
495
+ qbfile = qbfile[qbfile['Position'] == 'QB']
496
+ qbfile = qbfile.reset_index()
497
+ qb_var = qbfile['Player'][0]
498
+ st.table(qbfile)
499
+ #st.write(stack_var1 + ' ' + qb_var)
500
+ for qbid in player_ids:
501
+ if flex_file['Position'][qbid] == 'QB':
502
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
503
+ (flex_file['Team'][i] == stack_var1 and
504
+ flex_file['Position'][i] in ('WR', 'TE'))] +
505
+ [-qbstack_var1*player_vars[qbid]]) >= 0
506
+ if flex_file['Position'][qbid] == 'QB':
507
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
508
+ (flex_file['Team'][i] == stack_var1 and
509
+ flex_file['Position'][i] in ('RB'))] +
510
+ [0*player_vars[qbid]]) == 0
511
+ if flex_file['Position'][qbid] == 'QB':
512
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
513
+ (flex_file['Team'][i] == opp_var1 and
514
+ flex_file['Position'][i] in ('WR', 'TE'))] +
515
+ [-ministack_var1*player_vars[qbid]]) >= 0
516
+ for flex in flex_file['Player'].unique():
517
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
518
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
519
+ elif contest_var1 == 'Large Field GPP':
520
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
521
+ qbfile = qbfile[qbfile['Position'] == 'QB']
522
+ qbfile = qbfile.reset_index()
523
+ qb_var = qbfile['Player'][0]
524
+ st.table(qbfile)
525
+ #st.write(stack_var1 + ' ' + qb_var)
526
+ for qbid in player_ids:
527
+ if flex_file['Position'][qbid] == 'QB':
528
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
529
+ (flex_file['Team'][i] == stack_var1 and
530
+ flex_file['Position'][i] in ('WR', 'TE'))] +
531
+ [-qbstack_var1*player_vars[qbid]]) >= 0
532
+ if flex_file['Position'][qbid] == 'QB':
533
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
534
+ (flex_file['Team'][i] == stack_var1 and
535
+ flex_file['Position'][i] in ('RB'))] +
536
+ [0*player_vars[qbid]]) == 0
537
+ if flex_file['Position'][qbid] == 'QB':
538
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
539
+ (flex_file['Team'][i] == opp_var1 and
540
+ flex_file['Position'][i] in ('WR', 'TE'))] +
541
+ [-ministack_var1*player_vars[qbid]]) >= 0
542
+ for flex in flex_file['Player'].unique():
543
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
544
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
545
+
546
+ for flex in flex_file['lock'].unique():
547
+ sub_idx = flex_file[flex_file['lock'] == 1].index
548
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var1)
549
+
550
+ for flex in flex_file['Position'].unique():
551
+ sub_idx = flex_file[flex_file['Position'] != "Var"].index
552
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 9
553
+
554
+ for flex in flex_file['Position'].unique():
555
+ sub_idx = flex_file[flex_file['Position'] == "QB"].index
556
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
557
+
558
+ for flex in flex_file['Position'].unique():
559
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
560
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
561
+
562
+ for flex in flex_file['Position'].unique():
563
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
564
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
565
+
566
+ for flex in flex_file['Position'].unique():
567
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
568
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
569
+
570
+ for flex in flex_file['Position'].unique():
571
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
572
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
573
+
574
+ for flex in flex_file['Position'].unique():
575
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
576
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
577
+
578
+ for flex in flex_file['Position'].unique():
579
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
580
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
581
+
582
+ for flex in flex_file['Position'].unique():
583
+ sub_idx = flex_file[flex_file['Position'] == "D"].index
584
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
585
+
586
+ player_count = []
587
+ player_trim = []
588
+ lineup_list = []
589
+
590
+ if contest_var1 == 'Cash':
591
+ obj_points = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
592
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
593
+ elif contest_var1 != 'Cash':
594
+ obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
595
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
596
+
597
+
598
+ total_score.solve()
599
+ for v in total_score.variables():
600
+ if v.varValue > 0:
601
+ lineup_list.append(v.name)
602
+ df = pd.DataFrame(lineup_list)
603
+ df['Names'] = df[0].map(player_match)
604
+ df['Cost'] = df['Names'].map(player_sal)
605
+ df['Proj'] = df['Names'].map(player_proj)
606
+ df['Own'] = df['Names'].map(player_own)
607
+ total_cost = sum(df['Cost'])
608
+ total_own = sum(df['Own'])
609
+ total_proj = sum(df['Proj'])
610
+ lineup_raw = pd.DataFrame(lineup_list)
611
+ lineup_raw['Names'] = lineup_raw[0].map(player_match)
612
+ lineup_raw['value'] = lineup_raw[0].map(player_index_match)
613
+ lineup_final = lineup_raw.sort_values(by=['value'])
614
+ del lineup_final[lineup_final.columns[0]]
615
+ del lineup_final[lineup_final.columns[1]]
616
+ lineup_final = lineup_final.reset_index(drop=True)
617
+
618
+ if site_var1 == 'Draftkings':
619
+ line_hold = lineup_final[['Names']]
620
+ line_hold['pos'] = line_hold['Names'].map(player_pos)
621
+
622
+ for pname in range(0,len(line_hold)):
623
+ if line_hold.iat[pname,1] == 'QB':
624
+ if line_hold.iat[pname,0] not in p_used:
625
+ sorted_lineup.append(line_hold.iat[pname,0])
626
+ p_used.extend(sorted_lineup)
627
+ rbvar = 0
628
+ for pname in range(0,len(line_hold)):
629
+ if rbvar == 2:
630
+ pname = len(line_hold)
631
+ elif rbvar < 2:
632
+ if line_hold.iat[pname,1] == 'RB':
633
+ if line_hold.iat[pname,0] not in p_used:
634
+ sorted_lineup.append(line_hold.iat[pname,0])
635
+ rbvar = rbvar + 1
636
+ p_used.extend(sorted_lineup)
637
+ wrvar = 0
638
+ for pname in range(0,len(line_hold)):
639
+ if wrvar == 3:
640
+ pname = len(line_hold)
641
+ elif wrvar < 3:
642
+ if line_hold.iat[pname,1] == 'WR':
643
+ if line_hold.iat[pname,0] not in p_used:
644
+ sorted_lineup.append(line_hold.iat[pname,0])
645
+ wrvar = wrvar + 1
646
+ p_used.extend(sorted_lineup)
647
+ tevar = 0
648
+ for pname in range(0,len(line_hold)):
649
+ if tevar == 1:
650
+ pname = len(line_hold)
651
+ elif tevar < 1:
652
+ if line_hold.iat[pname,1] == 'TE':
653
+ if line_hold.iat[pname,0] not in p_used:
654
+ sorted_lineup.append(line_hold.iat[pname,0])
655
+ tevar = tevar + 1
656
+ p_used.extend(sorted_lineup)
657
+
658
+ for pname in range(0,len(line_hold)):
659
+ if line_hold.iat[pname,1] != 'DST':
660
+ if line_hold.iat[pname,0] not in p_used:
661
+ sorted_lineup.append(line_hold.iat[pname,0])
662
+ p_used.extend(sorted_lineup)
663
+
664
+ for pname in range(0,len(line_hold)):
665
+ if line_hold.iat[pname,1] == 'DST':
666
+ if line_hold.iat[pname,0] not in p_used:
667
+ sorted_lineup.append(line_hold.iat[pname,0])
668
+ p_used.extend(sorted_lineup)
669
+
670
+ lineup_final['sorted'] = sorted_lineup
671
+ lineup_final = lineup_final.drop(columns=['Names'])
672
+ lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
673
+
674
+ elif site_var1 == 'Fanduel':
675
+ line_hold = lineup_final[['Names']]
676
+ line_hold['pos'] = line_hold['Names'].map(player_pos)
677
+
678
+ for pname in range(0,len(line_hold)):
679
+ if line_hold.iat[pname,1] == 'QB':
680
+ if line_hold.iat[pname,0] not in p_used:
681
+ sorted_lineup.append(line_hold.iat[pname,0])
682
+ p_used.extend(sorted_lineup)
683
+ rbvar = 0
684
+ for pname in range(0,len(line_hold)):
685
+ if rbvar == 2:
686
+ pname = len(line_hold)
687
+ elif rbvar < 2:
688
+ if line_hold.iat[pname,1] == 'RB':
689
+ if line_hold.iat[pname,0] not in p_used:
690
+ sorted_lineup.append(line_hold.iat[pname,0])
691
+ rbvar = rbvar + 1
692
+ p_used.extend(sorted_lineup)
693
+ wrvar = 0
694
+ for pname in range(0,len(line_hold)):
695
+ if wrvar == 3:
696
+ pname = len(line_hold)
697
+ elif wrvar < 3:
698
+ if line_hold.iat[pname,1] == 'WR':
699
+ if line_hold.iat[pname,0] not in p_used:
700
+ sorted_lineup.append(line_hold.iat[pname,0])
701
+ wrvar = wrvar + 1
702
+ p_used.extend(sorted_lineup)
703
+ tevar = 0
704
+ for pname in range(0,len(line_hold)):
705
+ if tevar == 1:
706
+ pname = len(line_hold)
707
+ elif tevar < 1:
708
+ if line_hold.iat[pname,1] == 'TE':
709
+ if line_hold.iat[pname,0] not in p_used:
710
+ sorted_lineup.append(line_hold.iat[pname,0])
711
+ tevar = tevar + 1
712
+ p_used.extend(sorted_lineup)
713
+
714
+ for pname in range(0,len(line_hold)):
715
+ if line_hold.iat[pname,1] != 'DST':
716
+ if line_hold.iat[pname,0] not in p_used:
717
+ sorted_lineup.append(line_hold.iat[pname,0])
718
+ p_used.extend(sorted_lineup)
719
+
720
+ for pname in range(0,len(line_hold)):
721
+ if line_hold.iat[pname,1] == 'DST':
722
+ if line_hold.iat[pname,0] not in p_used:
723
+ sorted_lineup.append(line_hold.iat[pname,0])
724
+ p_used.extend(sorted_lineup)
725
+
726
+ lineup_final['sorted'] = sorted_lineup
727
+ lineup_final = lineup_final.drop(columns=['Names'])
728
+ lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
729
+
730
+ lineup_test = lineup_final
731
+ lineup_final = lineup_final.T
732
+ lineup_final['Cost'] = total_cost
733
+ lineup_final['Proj'] = total_proj
734
+ lineup_final['Own'] = total_own
735
+
736
+ lineup_test['Team'] = lineup_test['Names'].map(player_team)
737
+ lineup_test['Position'] = lineup_test['Names'].map(player_pos)
738
+ lineup_test['Salary'] = lineup_test['Names'].map(player_sal)
739
+ lineup_test['Proj'] = lineup_test['Names'].map(player_proj)
740
+ lineup_test['Own'] = lineup_test['Names'].map(player_own)
741
+ lineup_test = lineup_test.set_index('Names')
742
+ lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0)
743
+
744
+ lineup_display.append(lineup_test)
745
+
746
+ with col2:
747
+ with st.container():
748
+ st.table(lineup_test)
749
+
750
+ max_proj = total_proj
751
+ max_own = total_own
752
+
753
+ check_list.append(total_proj)
754
+
755
+ portfolio = pd.concat([portfolio, lineup_final], ignore_index = True)
756
+
757
+ x += 1
758
+
759
+ elif contest_var1 != 'Round Robin':
760
+ while x <= linenum_var1:
761
+ sorted_lineup = []
762
+ p_used = []
763
+ cvar = 0
764
+ firvar = 0
765
+ secvar = 0
766
+ thirvar = 0
767
+
768
+ raw_proj_file = raw_baselines
769
+ raw_flex_file = raw_proj_file.dropna(how='all')
770
+ raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > 0]
771
+ flex_file = raw_flex_file
772
+ flex_file.rename(columns={"Own": "Proj DK Own%"}, inplace = True)
773
+ flex_file['name_var'] = flex_file['Player']
774
+ flex_file['lock'] = np.where(flex_file['Player'].isin(lock_var1), 1, 0)
775
+ player_ids = flex_file.index
776
+
777
+ overall_players = flex_file[['Player']]
778
+ overall_players['player_var_add'] = flex_file.index
779
+ overall_players['player_var'] = 'player_vars_' + overall_players['player_var_add'].astype(str)
780
+
781
+ player_vars = pulp.LpVariable.dicts("player_vars", flex_file.index, 0, 1, pulp.LpInteger)
782
+ total_score = pulp.LpProblem("Fantasy_Points_Problem", pulp.LpMaximize)
783
+ player_match = dict(zip(overall_players['player_var'], overall_players['Player']))
784
+ player_index_match = dict(zip(overall_players['player_var'], overall_players['player_var_add']))
785
+
786
+ player_own = dict(zip(flex_file['Player'], flex_file['Proj DK Own%']))
787
+ player_team = dict(zip(flex_file['Player'], flex_file['Team']))
788
+ player_pos = dict(zip(flex_file['Player'], flex_file['Position']))
789
+ player_sal = dict(zip(flex_file['Player'], flex_file['Salary']))
790
+ player_proj = dict(zip(flex_file['Player'], flex_file['Median']))
791
+
792
+ obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
793
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) <= max_sal1
794
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal1
795
+
796
+ if site_var1 == 'Draftkings':
797
+
798
+ if contest_var1 == 'Cash':
799
+ qbfile = flex_file
800
+ qbfile = qbfile[qbfile['Position'] == 'QB']
801
+ qbfile = qbfile.reset_index()
802
+ elif contest_var1 == 'Small Field GPP':
803
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
804
+ qbfile = qbfile[qbfile['Position'] == 'QB']
805
+ qbfile = qbfile.reset_index()
806
+ qb_var = qbfile['Player'][0]
807
+ st.table(qbfile)
808
+ #st.write(stack_var1 + ' ' + qb_var)
809
+ for qbid in player_ids:
810
+ if flex_file['Position'][qbid] == 'QB':
811
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
812
+ (flex_file['Team'][i] == stack_var1 and
813
+ flex_file['Position'][i] in ('WR', 'TE'))] +
814
+ [-qbstack_var1*player_vars[qbid]]) >= 0
815
+ if flex_file['Position'][qbid] == 'QB':
816
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
817
+ (flex_file['Team'][i] == stack_var1 and
818
+ flex_file['Position'][i] in ('RB'))] +
819
+ [0*player_vars[qbid]]) == 0
820
+ if flex_file['Position'][qbid] == 'QB':
821
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
822
+ (flex_file['Team'][i] == opp_var1 and
823
+ flex_file['Position'][i] in ('WR', 'TE'))] +
824
+ [-ministack_var1*player_vars[qbid]]) >= 0
825
+ for flex in flex_file['Player'].unique():
826
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
827
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
828
+ elif contest_var1 == 'Large Field GPP':
829
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
830
+ qbfile = qbfile[qbfile['Position'] == 'QB']
831
+ qbfile = qbfile.reset_index()
832
+ qb_var = qbfile['Player'][0]
833
+ st.table(qbfile)
834
+ #st.write(stack_var1 + ' ' + qb_var)
835
+ for qbid in player_ids:
836
+ if flex_file['Position'][qbid] == 'QB':
837
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
838
+ (flex_file['Team'][i] == stack_var1 and
839
+ flex_file['Position'][i] in ('WR', 'TE'))] +
840
+ [-qbstack_var1*player_vars[qbid]]) >= 0
841
+ if flex_file['Position'][qbid] == 'QB':
842
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
843
+ (flex_file['Team'][i] == stack_var1 and
844
+ flex_file['Position'][i] in ('RB'))] +
845
+ [0*player_vars[qbid]]) == 0
846
+ if flex_file['Position'][qbid] == 'QB':
847
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
848
+ (flex_file['Team'][i] == opp_var1 and
849
+ flex_file['Position'][i] in ('WR', 'TE'))] +
850
+ [-ministack_var1*player_vars[qbid]]) >= 0
851
+ for flex in flex_file['Player'].unique():
852
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
853
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
854
+
855
+ for flex in flex_file['lock'].unique():
856
+ sub_idx = flex_file[flex_file['lock'] == 1].index
857
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var1)
858
+
859
+ for flex in flex_file['Position'].unique():
860
+ sub_idx = flex_file[flex_file['Position'] != "Var"].index
861
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 9
862
+
863
+ for flex in flex_file['Position'].unique():
864
+ sub_idx = flex_file[flex_file['Position'] == "QB"].index
865
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
866
+
867
+ for flex in flex_file['Position'].unique():
868
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
869
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
870
+
871
+ for flex in flex_file['Position'].unique():
872
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
873
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
874
+
875
+ for flex in flex_file['Position'].unique():
876
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
877
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
878
+
879
+ for flex in flex_file['Position'].unique():
880
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
881
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
882
+
883
+ for flex in flex_file['Position'].unique():
884
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
885
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
886
+
887
+ for flex in flex_file['Position'].unique():
888
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
889
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
890
+
891
+ for flex in flex_file['Position'].unique():
892
+ sub_idx = flex_file[flex_file['Position'] == "DST"].index
893
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
894
+
895
+ elif site_var1 == 'Fanduel':
896
+
897
+ if contest_var1 == 'Cash':
898
+ qbfile = flex_file
899
+ qbfile = qbfile[qbfile['Position'] == 'QB']
900
+ qbfile = qbfile.reset_index()
901
+ elif contest_var1 == 'Small Field GPP':
902
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
903
+ qbfile = qbfile[qbfile['Position'] == 'QB']
904
+ qbfile = qbfile.reset_index()
905
+ qb_var = qbfile['Player'][0]
906
+ st.table(qbfile)
907
+ #st.write(stack_var1 + ' ' + qb_var)
908
+ for qbid in player_ids:
909
+ if flex_file['Position'][qbid] == 'QB':
910
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
911
+ (flex_file['Team'][i] == stack_var1 and
912
+ flex_file['Position'][i] in ('WR', 'TE'))] +
913
+ [-qbstack_var1*player_vars[qbid]]) >= 0
914
+ if flex_file['Position'][qbid] == 'QB':
915
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
916
+ (flex_file['Team'][i] == stack_var1 and
917
+ flex_file['Position'][i] in ('RB'))] +
918
+ [0*player_vars[qbid]]) == 0
919
+ if flex_file['Position'][qbid] == 'QB':
920
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
921
+ (flex_file['Team'][i] == opp_var1 and
922
+ flex_file['Position'][i] in ('WR', 'TE'))] +
923
+ [-ministack_var1*player_vars[qbid]]) >= 0
924
+ for flex in flex_file['Player'].unique():
925
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
926
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
927
+ elif contest_var1 == 'Large Field GPP':
928
+ qbfile = flex_file[flex_file['Team'] == stack_var1]
929
+ qbfile = qbfile[qbfile['Position'] == 'QB']
930
+ qbfile = qbfile.reset_index()
931
+ qb_var = qbfile['Player'][0]
932
+ st.table(qbfile)
933
+ #st.write(stack_var1 + ' ' + qb_var)
934
+ for qbid in player_ids:
935
+ if flex_file['Position'][qbid] == 'QB':
936
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
937
+ (flex_file['Team'][i] == stack_var1 and
938
+ flex_file['Position'][i] in ('WR', 'TE'))] +
939
+ [-qbstack_var1*player_vars[qbid]]) >= 0
940
+ if flex_file['Position'][qbid] == 'QB':
941
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
942
+ (flex_file['Team'][i] == stack_var1 and
943
+ flex_file['Position'][i] in ('RB'))] +
944
+ [0*player_vars[qbid]]) == 0
945
+ if flex_file['Position'][qbid] == 'QB':
946
+ total_score += pulp.lpSum([player_vars[i] for i in player_ids if
947
+ (flex_file['Team'][i] == opp_var1 and
948
+ flex_file['Position'][i] in ('WR', 'TE'))] +
949
+ [-ministack_var1*player_vars[qbid]]) >= 0
950
+ for flex in flex_file['Player'].unique():
951
+ sub_idx = flex_file[flex_file['Player'] == qb_var].index
952
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
953
+
954
+ for flex in flex_file['lock'].unique():
955
+ sub_idx = flex_file[flex_file['lock'] == 1].index
956
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var1)
957
+
958
+ for flex in flex_file['Position'].unique():
959
+ sub_idx = flex_file[flex_file['Position'] != "Var"].index
960
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 9
961
+
962
+ for flex in flex_file['Position'].unique():
963
+ sub_idx = flex_file[flex_file['Position'] == "QB"].index
964
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
965
+
966
+ for flex in flex_file['Position'].unique():
967
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
968
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
969
+
970
+ for flex in flex_file['Position'].unique():
971
+ sub_idx = flex_file[flex_file['Position'] == "RB"].index
972
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
973
+
974
+ for flex in flex_file['Position'].unique():
975
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
976
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
977
+
978
+ for flex in flex_file['Position'].unique():
979
+ sub_idx = flex_file[flex_file['Position'] == "WR"].index
980
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
981
+
982
+ for flex in flex_file['Position'].unique():
983
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
984
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
985
+
986
+ for flex in flex_file['Position'].unique():
987
+ sub_idx = flex_file[flex_file['Position'] == "TE"].index
988
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
989
+
990
+ for flex in flex_file['Position'].unique():
991
+ sub_idx = flex_file[flex_file['Position'] == "D"].index
992
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
993
+
994
+ player_count = []
995
+ player_trim = []
996
+ lineup_list = []
997
+
998
+ if contest_var1 == 'Cash':
999
+ obj_points = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
1000
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
1001
+ total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_own - .001
1002
+ elif contest_var1 != 'Cash':
1003
+ obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
1004
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
1005
+ total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_proj - .01
1006
+
1007
+
1008
+ total_score.solve()
1009
+ for v in total_score.variables():
1010
+ if v.varValue > 0:
1011
+ lineup_list.append(v.name)
1012
+ df = pd.DataFrame(lineup_list)
1013
+ df['Names'] = df[0].map(player_match)
1014
+ df['Cost'] = df['Names'].map(player_sal)
1015
+ df['Proj'] = df['Names'].map(player_proj)
1016
+ df['Own'] = df['Names'].map(player_own)
1017
+ total_cost = sum(df['Cost'])
1018
+ total_own = sum(df['Own'])
1019
+ total_proj = sum(df['Proj'])
1020
+ lineup_raw = pd.DataFrame(lineup_list)
1021
+ lineup_raw['Names'] = lineup_raw[0].map(player_match)
1022
+ lineup_raw['value'] = lineup_raw[0].map(player_index_match)
1023
+ lineup_final = lineup_raw.sort_values(by=['value'])
1024
+ del lineup_final[lineup_final.columns[0]]
1025
+ del lineup_final[lineup_final.columns[1]]
1026
+ lineup_final = lineup_final.reset_index(drop=True)
1027
+
1028
+ if site_var1 == 'Draftkings':
1029
+ line_hold = lineup_final[['Names']]
1030
+ line_hold['pos'] = line_hold['Names'].map(player_pos)
1031
+
1032
+ for pname in range(0,len(line_hold)):
1033
+ if line_hold.iat[pname,1] == 'QB':
1034
+ if line_hold.iat[pname,0] not in p_used:
1035
+ sorted_lineup.append(line_hold.iat[pname,0])
1036
+ p_used.extend(sorted_lineup)
1037
+ rbvar = 0
1038
+ for pname in range(0,len(line_hold)):
1039
+ if rbvar == 2:
1040
+ pname = len(line_hold)
1041
+ elif rbvar < 2:
1042
+ if line_hold.iat[pname,1] == 'RB':
1043
+ if line_hold.iat[pname,0] not in p_used:
1044
+ sorted_lineup.append(line_hold.iat[pname,0])
1045
+ rbvar = rbvar + 1
1046
+ p_used.extend(sorted_lineup)
1047
+ wrvar = 0
1048
+ for pname in range(0,len(line_hold)):
1049
+ if wrvar == 3:
1050
+ pname = len(line_hold)
1051
+ elif wrvar < 3:
1052
+ if line_hold.iat[pname,1] == 'WR':
1053
+ if line_hold.iat[pname,0] not in p_used:
1054
+ sorted_lineup.append(line_hold.iat[pname,0])
1055
+ wrvar = wrvar + 1
1056
+ p_used.extend(sorted_lineup)
1057
+ tevar = 0
1058
+ for pname in range(0,len(line_hold)):
1059
+ if tevar == 1:
1060
+ pname = len(line_hold)
1061
+ elif tevar < 1:
1062
+ if line_hold.iat[pname,1] == 'TE':
1063
+ if line_hold.iat[pname,0] not in p_used:
1064
+ sorted_lineup.append(line_hold.iat[pname,0])
1065
+ tevar = tevar + 1
1066
+ p_used.extend(sorted_lineup)
1067
+
1068
+ for pname in range(0,len(line_hold)):
1069
+ if line_hold.iat[pname,1] != 'DST':
1070
+ if line_hold.iat[pname,0] not in p_used:
1071
+ sorted_lineup.append(line_hold.iat[pname,0])
1072
+ p_used.extend(sorted_lineup)
1073
+
1074
+ for pname in range(0,len(line_hold)):
1075
+ if line_hold.iat[pname,1] == 'DST':
1076
+ if line_hold.iat[pname,0] not in p_used:
1077
+ sorted_lineup.append(line_hold.iat[pname,0])
1078
+ p_used.extend(sorted_lineup)
1079
+
1080
+ lineup_final['sorted'] = sorted_lineup
1081
+ lineup_final = lineup_final.drop(columns=['Names'])
1082
+ lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
1083
+
1084
+ elif site_var1 == 'Fanduel':
1085
+ line_hold = lineup_final[['Names']]
1086
+ line_hold['pos'] = line_hold['Names'].map(player_pos)
1087
+
1088
+ for pname in range(0,len(line_hold)):
1089
+ if line_hold.iat[pname,1] == 'QB':
1090
+ if line_hold.iat[pname,0] not in p_used:
1091
+ sorted_lineup.append(line_hold.iat[pname,0])
1092
+ p_used.extend(sorted_lineup)
1093
+ rbvar = 0
1094
+ for pname in range(0,len(line_hold)):
1095
+ if rbvar == 2:
1096
+ pname = len(line_hold)
1097
+ elif rbvar < 2:
1098
+ if line_hold.iat[pname,1] == 'RB':
1099
+ if line_hold.iat[pname,0] not in p_used:
1100
+ sorted_lineup.append(line_hold.iat[pname,0])
1101
+ rbvar = rbvar + 1
1102
+ p_used.extend(sorted_lineup)
1103
+ wrvar = 0
1104
+ for pname in range(0,len(line_hold)):
1105
+ if wrvar == 3:
1106
+ pname = len(line_hold)
1107
+ elif wrvar < 3:
1108
+ if line_hold.iat[pname,1] == 'WR':
1109
+ if line_hold.iat[pname,0] not in p_used:
1110
+ sorted_lineup.append(line_hold.iat[pname,0])
1111
+ wrvar = wrvar + 1
1112
+ p_used.extend(sorted_lineup)
1113
+ tevar = 0
1114
+ for pname in range(0,len(line_hold)):
1115
+ if tevar == 1:
1116
+ pname = len(line_hold)
1117
+ elif tevar < 1:
1118
+ if line_hold.iat[pname,1] == 'TE':
1119
+ if line_hold.iat[pname,0] not in p_used:
1120
+ sorted_lineup.append(line_hold.iat[pname,0])
1121
+ tevar = tevar + 1
1122
+ p_used.extend(sorted_lineup)
1123
+
1124
+ for pname in range(0,len(line_hold)):
1125
+ if line_hold.iat[pname,1] != 'DST':
1126
+ if line_hold.iat[pname,0] not in p_used:
1127
+ sorted_lineup.append(line_hold.iat[pname,0])
1128
+ p_used.extend(sorted_lineup)
1129
+
1130
+ for pname in range(0,len(line_hold)):
1131
+ if line_hold.iat[pname,1] == 'DST':
1132
+ if line_hold.iat[pname,0] not in p_used:
1133
+ sorted_lineup.append(line_hold.iat[pname,0])
1134
+ p_used.extend(sorted_lineup)
1135
+
1136
+ lineup_final['sorted'] = sorted_lineup
1137
+ lineup_final = lineup_final.drop(columns=['Names'])
1138
+ lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
1139
+
1140
+ lineup_test = lineup_final
1141
+ lineup_final = lineup_final.T
1142
+ lineup_final['Cost'] = total_cost
1143
+ lineup_final['Proj'] = total_proj
1144
+ lineup_final['Own'] = total_own
1145
+
1146
+ lineup_test['Team'] = lineup_test['Names'].map(player_team)
1147
+ lineup_test['Position'] = lineup_test['Names'].map(player_pos)
1148
+ lineup_test['Salary'] = lineup_test['Names'].map(player_sal)
1149
+ lineup_test['Proj'] = lineup_test['Names'].map(player_proj)
1150
+ lineup_test['Own'] = lineup_test['Names'].map(player_own)
1151
+ lineup_test = lineup_test.set_index('Names')
1152
+ lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0)
1153
+
1154
+ lineup_display.append(lineup_test)
1155
+
1156
+ with col2:
1157
+ with st.container():
1158
+ st.table(lineup_test)
1159
+
1160
+ max_proj = total_proj
1161
+ max_own = total_own
1162
+
1163
+ check_list.append(total_proj)
1164
+
1165
+ portfolio = pd.concat([portfolio, lineup_final], ignore_index = True)
1166
+
1167
+ x += 1
1168
+
1169
+ if site_var1 == 'Draftkings':
1170
+ portfolio.rename(columns={0: "QB", 1: "RB1", 2: "RB2", 3: "WR1", 4: "WR2", 5: "WR3", 6: "TE", 7: "UTIL", 8: "DST"}, inplace = True)
1171
+ elif site_var1 == 'Fanduel':
1172
+ portfolio.rename(columns={0: "QB", 1: "RB1", 2: "RB2", 3: "WR1", 4: "WR2", 5: "WR3", 6: "TE", 7: "UTIL", 8: "DST"}, inplace = True)
1173
+ portfolio = portfolio.dropna()
1174
+ portfolio = portfolio.reset_index()
1175
+ portfolio['Lineup_num'] = portfolio['index'] + 1
1176
+ portfolio.rename(columns={'Lineup_num': "Lineup"}, inplace = True)
1177
+ portfolio = portfolio.set_index('Lineup')
1178
+ portfolio = portfolio.drop(columns=['index'])
1179
+
1180
+ final_outcomes = portfolio[['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'UTIL', 'DST', 'Cost', 'Proj', 'Own']]
1181
+ final_outcomes = final_outcomes.set_axis(['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'UTIL', 'DST', 'Cost', 'Proj', 'Own'], axis=1)
1182
+ final_outcomes_export = pd.DataFrame()
1183
+ final_outcomes_export['QB'] = final_outcomes['QB']
1184
+ final_outcomes_export['RB1'] = final_outcomes['RB1']
1185
+ final_outcomes_export['RB2'] = final_outcomes['RB2']
1186
+ final_outcomes_export['WR1'] = final_outcomes['WR1']
1187
+ final_outcomes_export['WR2'] = final_outcomes['WR2']
1188
+ final_outcomes_export['WR3'] = final_outcomes['WR3']
1189
+ final_outcomes_export['TE'] = final_outcomes['TE']
1190
+ final_outcomes_export['UTIL'] = final_outcomes['UTIL']
1191
+ final_outcomes_export['DST'] = final_outcomes['DST']
1192
+ final_outcomes_export['Salary'] = final_outcomes['Cost']
1193
+ final_outcomes_export['Own'] = final_outcomes['Own']
1194
+ final_outcomes_export['Proj'] = final_outcomes['Proj']
1195
+ if site_var1 == 'Draftkings':
1196
+ final_outcomes_export['QB'].replace(dkid_dict, inplace=True)
1197
+ final_outcomes_export['RB1'].replace(dkid_dict, inplace=True)
1198
+ final_outcomes_export['RB2'].replace(dkid_dict, inplace=True)
1199
+ final_outcomes_export['WR1'].replace(dkid_dict, inplace=True)
1200
+ final_outcomes_export['WR2'].replace(dkid_dict, inplace=True)
1201
+ final_outcomes_export['WR3'].replace(dkid_dict, inplace=True)
1202
+ final_outcomes_export['TE'].replace(dkid_dict, inplace=True)
1203
+ final_outcomes_export['UTIL'].replace(dkid_dict, inplace=True)
1204
+ final_outcomes_export['DST'].replace(dkid_dict, inplace=True)
1205
+ elif site_var1 == 'Fanduel':
1206
+ final_outcomes_export['QB'].replace(fdid_dict, inplace=True)
1207
+ final_outcomes_export['RB1'].replace(fdid_dict, inplace=True)
1208
+ final_outcomes_export['RB2'].replace(fdid_dict, inplace=True)
1209
+ final_outcomes_export['WR1'].replace(fdid_dict, inplace=True)
1210
+ final_outcomes_export['WR2'].replace(fdid_dict, inplace=True)
1211
+ final_outcomes_export['WR3'].replace(fdid_dict, inplace=True)
1212
+ final_outcomes_export['TE'].replace(fdid_dict, inplace=True)
1213
+ final_outcomes_export['UTIL'].replace(fdid_dict, inplace=True)
1214
+ final_outcomes_export['DST'].replace(fdid_dict, inplace=True)
1215
+
1216
+ player_freq = pd.DataFrame(np.column_stack(np.unique(portfolio.iloc[:,0:8].values, return_counts=True)),
1217
+ columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
1218
+ player_freq['Freq'] = player_freq['Freq'].astype(int)
1219
+ player_freq['Position'] = player_freq['Player'].map(player_pos)
1220
+ player_freq['Salary'] = player_freq['Player'].map(player_sal)
1221
+ player_freq['Proj Own'] = player_freq['Player'].map(player_own) / 100
1222
+ player_freq['Exposure'] = player_freq['Freq']/(linenum_var1)
1223
+ player_freq['Team'] = player_freq['Player'].map(player_team)
1224
+
1225
+ player_freq = player_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure']]
1226
+ player_freq = player_freq.set_index('Player')
1227
+
1228
+ with optimize_container:
1229
+ optimize_container = st.empty()
1230
+ st.dataframe(final_outcomes.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
1231
+ with download_container:
1232
+ download_container = st.empty()
1233
+ st.download_button(
1234
+ label="Export Optimals",
1235
+ data=convert_df_to_csv(final_outcomes_export),
1236
+ file_name='NFL_optimals_export.csv',
1237
+ mime='text/csv',
1238
+ )
1239
+ with freq_container:
1240
+ freq_container = st.empty()
1241
+ st.dataframe(player_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(expose_format, precision=2), use_container_width = True)