Multichem commited on
Commit
49e77f1
·
1 Parent(s): 698adde

Upload streamlit_app (1).py

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