Multichem commited on
Commit
d932cbf
·
verified ·
1 Parent(s): 7f18c0a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +792 -0
app.py ADDED
@@ -0,0 +1,792 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pulp
2
+ import numpy as np
3
+ import pandas as pd
4
+ import streamlit as st
5
+ import gspread
6
+ from itertools import combinations
7
+
8
+ st.set_page_config(layout="wide")
9
+
10
+ @st.cache_resource
11
+ def init_conn():
12
+ scope = ['https://www.googleapis.com/auth/spreadsheets',
13
+ "https://www.googleapis.com/auth/drive"]
14
+
15
+ credentials = {
16
+ "type": "service_account",
17
+ "project_id": "sheets-api-connect-378620",
18
+ "private_key_id": "1005124050c80d085e2c5b344345715978dd9cc9",
19
+ "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",
20
+ "client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
21
+ "client_id": "106625872877651920064",
22
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
23
+ "token_uri": "https://oauth2.googleapis.com/token",
24
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
25
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
26
+ }
27
+
28
+ gc = gspread.service_account_from_dict(credentials)
29
+ return gc
30
+
31
+ gc = init_conn()
32
+
33
+ wrong_acro = ['WSH', 'AZ']
34
+ right_acro = ['WAS', 'ARI']
35
+
36
+ game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}',
37
+ 'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'}
38
+
39
+ team_roo_format = {'Top Score%': '{:.2%}','0 Runs': '{:.2%}', '1 Run': '{:.2%}', '2 Runs': '{:.2%}', '3 Runs': '{:.2%}', '4 Runs': '{:.2%}',
40
+ '5 Runs': '{:.2%}','6 Runs': '{:.2%}', '7 Runs': '{:.2%}', '8 Runs': '{:.2%}', '9 Runs': '{:.2%}', '10 Runs': '{:.2%}'}
41
+
42
+ dk_player_projections = 'https://docs.google.com/spreadsheets/d/1MdzPFqIT0MFid2IhegWf39VNR8IXUyo_Fb5dolOSt3o/edit#gid=340831852'
43
+ fd_player_projections = 'https://docs.google.com/spreadsheets/d/1MdzPFqIT0MFid2IhegWf39VNR8IXUyo_Fb5dolOSt3o/edit#gid=340831852'
44
+
45
+ secondary_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1lP4t8N7UhjR94MEwPn6powRyLl_cQBDUMSCs6cbL9ms/edit#gid=340831852'
46
+ secondary_fd_player_projections = 'https://docs.google.com/spreadsheets/d/1lP4t8N7UhjR94MEwPn6powRyLl_cQBDUMSCs6cbL9ms/edit#gid=340831852'
47
+
48
+ all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1f42Ergav8K1VsOLOK9MUn7DM_MLMvv4GR2Fy7EfnZTc/edit#gid=500994479'
49
+ all_fd_player_projections = 'https://docs.google.com/spreadsheets/d/1f42Ergav8K1VsOLOK9MUn7DM_MLMvv4GR2Fy7EfnZTc/edit#gid=500994479'
50
+ final_Proj = 0
51
+
52
+ @st.cache_resource(ttl=600)
53
+ def load_time():
54
+ sh = gc.open_by_url(dk_player_projections)
55
+ worksheet = sh.worksheet('Timestamp')
56
+ raw_stamp = worksheet.acell('a1').value
57
+
58
+ t_stamp = f"Last update was at {raw_stamp}"
59
+
60
+ return t_stamp
61
+
62
+ @st.cache_resource(ttl=600)
63
+ def load_dk_player_projections(URL):
64
+ sh = gc.open_by_url(URL)
65
+ worksheet = sh.worksheet('DK_Projections')
66
+ load_display = pd.DataFrame(worksheet.get_all_records())
67
+ load_display.replace('', np.nan, inplace=True)
68
+ load_display = load_display.drop_duplicates(subset='Player')
69
+ raw_display = load_display.dropna(subset=['Median'])
70
+
71
+ return raw_display
72
+
73
+ @st.cache_resource(ttl=600)
74
+ def load_fd_player_projections(URL):
75
+ sh = gc.open_by_url(URL)
76
+ worksheet = sh.worksheet('FD_Projections')
77
+ load_display = pd.DataFrame(worksheet.get_all_records())
78
+ load_display.replace('', np.nan, inplace=True)
79
+ load_display = load_display.drop_duplicates(subset='Player')
80
+ raw_display = load_display.dropna(subset=['Median'])
81
+
82
+ return raw_display
83
+
84
+ @st.cache_resource(ttl=600)
85
+ def set_slate_teams():
86
+ sh = gc.open_by_url(all_dk_player_projections)
87
+ worksheet = sh.worksheet('Site_Info')
88
+ raw_display = pd.DataFrame(worksheet.get_all_records())
89
+
90
+ for checkVar in range(len(wrong_acro)):
91
+ raw_display['FD Main'] = raw_display['FD Main'].replace(wrong_acro, right_acro)
92
+
93
+ for checkVar in range(len(wrong_acro)):
94
+ raw_display['FD Secondary'] = raw_display['FD Secondary'].replace(wrong_acro, right_acro)
95
+
96
+ for checkVar in range(len(wrong_acro)):
97
+ raw_display['FD Overall'] = raw_display['FD Overall'].replace(wrong_acro, right_acro)
98
+
99
+ return raw_display
100
+
101
+ @st.cache_resource(ttl=600)
102
+ def load_scoring_percentages(URL):
103
+ sh = gc.open_by_url(URL)
104
+ worksheet = sh.worksheet('Scoring_Percentages')
105
+ raw_display = pd.DataFrame(worksheet.get_all_records())
106
+ raw_display['8+ runs'] = raw_display['8+ runs'].str.replace('%', '').astype(float)/100
107
+ raw_display['Win Percentage'] = raw_display['Win Percentage'].str.replace('%', '').astype(float)/100
108
+ raw_display['DK LevX'] = raw_display['DK LevX'].str.replace('%', '').astype(float)/100
109
+ raw_display['FD LevX'] = raw_display['FD LevX'].str.replace('%', '').astype(float)/100
110
+
111
+ return raw_display
112
+
113
+ @st.cache_data
114
+ def convert_df_to_csv(df):
115
+ return df.to_csv().encode('utf-8')
116
+
117
+ t_stamp = load_time()
118
+ site_slates = set_slate_teams()
119
+ col1, col2 = st.columns([1, 5])
120
+
121
+ with col1:
122
+ st.info(t_stamp)
123
+ if st.button("Load/Reset Data", key='reset5'):
124
+ st.cache_data.clear()
125
+ raw_baselines = load_dk_player_projections(all_dk_player_projections)
126
+
127
+ team_baselines = load_scoring_percentages(all_dk_player_projections)
128
+
129
+ slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'All Games'), key='slate_var1')
130
+ site_var5 = st.radio("What site are you working with?", ('Draftkings', 'Fanduel'), key='site_var5')
131
+ if slate_var1 == 'Main Slate':
132
+ if site_var5 == 'Draftkings':
133
+ slate_teams = site_slates['DK Main'].values.tolist()
134
+ raw_baselines = load_dk_player_projections(all_dk_player_projections)
135
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
136
+ team_baselines = load_scoring_percentages(all_dk_player_projections)
137
+ team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
138
+ Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
139
+ SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
140
+ team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
141
+ Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
142
+ raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
143
+ elif site_var5 == 'Fanduel':
144
+ slate_teams = site_slates['FD Main'].values.tolist()
145
+ raw_baselines = load_fd_player_projections(all_fd_player_projections)
146
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
147
+ team_baselines = load_scoring_percentages(all_fd_player_projections)
148
+ team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
149
+ Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
150
+ SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
151
+ team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
152
+ Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
153
+ raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
154
+ elif slate_var1 == 'Secondary Slate':
155
+ if site_var5 == 'Draftkings':
156
+ slate_teams = site_slates['DK Secondary'].values.tolist()
157
+ raw_baselines = load_dk_player_projections(all_dk_player_projections)
158
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
159
+ team_baselines = load_scoring_percentages(all_dk_player_projections)
160
+ team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
161
+ Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
162
+ SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
163
+ team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
164
+ Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
165
+ raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
166
+ elif site_var5 == 'Fanduel':
167
+ slate_teams = site_slates['FD Secondary'].values.tolist()
168
+ raw_baselines = load_fd_player_projections(all_fd_player_projections)
169
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
170
+ team_baselines = load_scoring_percentages(all_fd_player_projections)
171
+ team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
172
+ Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
173
+ SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
174
+ team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
175
+ Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
176
+ raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
177
+ elif slate_var1 == 'All Games':
178
+ if site_var5 == 'Draftkings':
179
+ slate_teams = site_slates['DK Overall'].values.tolist()
180
+ raw_baselines = load_dk_player_projections(all_dk_player_projections)
181
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
182
+ team_baselines = load_scoring_percentages(all_dk_player_projections)
183
+ team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
184
+ Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
185
+ SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
186
+ team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
187
+ Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
188
+ raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
189
+ elif site_var5 == 'Fanduel':
190
+ slate_teams = site_slates['FD Overall'].values.tolist()
191
+ raw_baselines = load_fd_player_projections(all_fd_player_projections)
192
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(slate_teams)]
193
+ team_baselines = load_scoring_percentages(all_fd_player_projections)
194
+ team_baselines = team_baselines[team_baselines['Names'].isin(slate_teams)]
195
+ Max_Rank = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Names'])
196
+ SP_remove = list(team_baselines[team_baselines['Own Rank'] == team_baselines['Own Rank'].max()]['Opp SP'])
197
+ team_baselines = team_baselines[~team_baselines['Names'].isin(Max_Rank)]
198
+ Max_Upside = list(team_baselines[team_baselines['8+ Rank'] == team_baselines['8+ Rank'].min()]['Names'])
199
+ raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
200
+ contest_var5 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var5')
201
+ if contest_var5 == 'Small Field GPP':
202
+ opto_var5 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var5')
203
+ if opto_var5 == "Manual":
204
+ stack_var5 = st.selectbox('Which teams are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var5')
205
+ elif opto_var5 == "Pivot Optimal":
206
+ stack_var5 = Max_Rank[0]
207
+ elif contest_var5 == 'Large Field GPP':
208
+ opto_var5 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var5')
209
+ if opto_var5 == "Manual":
210
+ stack_var5 = st.selectbox('Which team are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var5')
211
+ ministack_var5 = st.selectbox('Which team is your secondary stack?', options = raw_baselines['Team'].unique(), key='ministack_var5')
212
+ elif opto_var5 == "Pivot Optimal":
213
+ stack_var5 = Max_Upside[0]
214
+ ministack_var5 = Max_Rank[0]
215
+ split_var5 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var5')
216
+ if split_var5 == 'Specific Games':
217
+ team_var5 = st.multiselect('Which teams would you like to include in the ROO?', options = raw_baselines['Team'].unique(), key='team_var5')
218
+ elif split_var5 == 'Full Slate Run':
219
+ team_var5 = raw_baselines.Team.values.tolist()
220
+ lock_var5 = st.multiselect("Are there any players you want to use in all lineups (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var5')
221
+ avoid_var5 = st.multiselect("Are there any players you want to remove from the pool (Drop Button)?", options = raw_baselines['Player'].unique(), key='avoid_var5')
222
+ linenum_var5 = st.number_input("How many lineups would you like to produce?", min_value = 1, max_value = 300, value = 20, step = 1, key='linenum_var5')
223
+ if site_var5 == 'Draftkings':
224
+ min_sal5 = st.number_input('Min Salary', min_value = 35000, max_value = 49900, value = 49000, step = 100, key='min_sal5')
225
+ max_sal5 = st.number_input('Max Salary', min_value = 35000, max_value = 50000, value = 50000, step = 100, key='max_sal5')
226
+ elif site_var5 == 'Fanduel':
227
+ min_sal5 = st.number_input('Min Salary', min_value = 25000, max_value = 34900, value = 34000, step = 100, key='min_sal5')
228
+ max_sal5 = st.number_input('Max Salary', min_value = 25000, max_value = 35000, value = 35000, step = 100, key='max_sal5')
229
+
230
+
231
+ with col2:
232
+ raw_baselines = raw_baselines[raw_baselines['Team'].isin(team_var5)]
233
+ raw_baselines = raw_baselines[~raw_baselines['Player'].isin(avoid_var5)]
234
+ if contest_var5 == 'Small Field GPP':
235
+ if site_var5 == 'Draftkings':
236
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean(), raw_baselines['Own'])
237
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (10 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean(), raw_baselines['Own%'])
238
+ raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
239
+ elif site_var5 == 'Fanduel':
240
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean())/50) + raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean(), raw_baselines['Own'])
241
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (10 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean())/150) + raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean(), raw_baselines['Own%'])
242
+ raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
243
+ elif contest_var5 == 'Large Field GPP':
244
+ if site_var5 == 'Draftkings':
245
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (2.5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean(), raw_baselines['Own'])
246
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean(), raw_baselines['Own%'])
247
+ raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
248
+ elif site_var5 == 'Fanduel':
249
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (2.5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean())/50) + raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean(), raw_baselines['Own'])
250
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (5 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean())/150) + raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean(), raw_baselines['Own%'])
251
+ raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
252
+ elif contest_var5 == 'Cash':
253
+ if site_var5 == 'Draftkings':
254
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (6 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] == 'SP', 'Own'].mean(), raw_baselines['Own'])
255
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'SP') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean() >= 0), raw_baselines['Own'] * (11 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean())/100) + raw_baselines.loc[raw_baselines['Position'] != 'SP', 'Own'].mean(), raw_baselines['Own%'])
256
+ raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
257
+ elif site_var5 == 'Fanduel':
258
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] == 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (6 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean())/50) + raw_baselines.loc[raw_baselines['Position'] == 'P', 'Own'].mean(), raw_baselines['Own'])
259
+ raw_baselines['Own%'] = np.where((raw_baselines['Position'] != 'P') & (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean() >= 0), raw_baselines['Own'] * (11 * (raw_baselines['Own'] - raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean())/150) + raw_baselines.loc[raw_baselines['Position'] != 'P', 'Own'].mean(), raw_baselines['Own%'])
260
+ raw_baselines['Own%'] = np.where(raw_baselines['Own%'] > 75, 75, raw_baselines['Own%'])
261
+ raw_baselines = raw_baselines[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own%']]
262
+ raw_baselines.rename(columns={"Own%": "Own"}, inplace = True)
263
+ raw_baselines = raw_baselines.sort_values(by='Median', ascending=False)
264
+ raw_baselines['lock'] = np.where(raw_baselines['Player'].isin(lock_var5), 1, 0)
265
+ st.dataframe(raw_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
266
+ st.download_button(
267
+ label="Export Projections",
268
+ data=convert_df_to_csv(raw_baselines),
269
+ file_name='MLB_proj_export.csv',
270
+ mime='text/csv',
271
+ )
272
+ if st.button('Optimize'):
273
+ max_proj = 1000
274
+ max_own = 1000
275
+ total_proj = 0
276
+ total_own = 0
277
+ optimize_container = st.empty()
278
+ lineup_display = []
279
+ check_list = []
280
+ lineups = []
281
+ portfolio = pd.DataFrame()
282
+ x = 1
283
+
284
+ with st.spinner('Wait for it...'):
285
+ with optimize_container:
286
+
287
+ while x <= linenum_var5:
288
+ sorted_lineup = []
289
+ p_used = []
290
+ cvar = 0
291
+ firvar = 0
292
+ secvar = 0
293
+ thirvar = 0
294
+
295
+ raw_proj_file = raw_baselines
296
+ raw_flex_file = raw_proj_file.dropna(how='all')
297
+ raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > 0]
298
+ flex_file = raw_flex_file
299
+ flex_file.rename(columns={"Own": "Proj DK Own%"}, inplace = True)
300
+ flex_file['name_var'] = flex_file['Player']
301
+ flex_file['lock'] = np.where(flex_file['Player'].isin(lock_var5), 1, 0)
302
+ player_ids = flex_file.index
303
+
304
+ overall_players = flex_file[['Player']]
305
+ overall_players['player_var_add'] = flex_file.index
306
+ overall_players['player_var'] = 'player_vars_' + overall_players['player_var_add'].astype(str)
307
+
308
+ player_vars = pulp.LpVariable.dicts("player_vars", flex_file.index, 0, 1, pulp.LpInteger)
309
+ total_score = pulp.LpProblem("Fantasy_Points_Problem", pulp.LpMaximize)
310
+ player_match = dict(zip(overall_players['player_var'], overall_players['Player']))
311
+ player_index_match = dict(zip(overall_players['player_var'], overall_players['player_var_add']))
312
+
313
+ player_own = dict(zip(flex_file['Player'], flex_file['Proj DK Own%']))
314
+ player_team = dict(zip(flex_file['Player'], flex_file['Team']))
315
+ player_pos = dict(zip(flex_file['Player'], flex_file['Position']))
316
+ player_sal = dict(zip(flex_file['Player'], flex_file['Salary']))
317
+ player_proj = dict(zip(flex_file['Player'], flex_file['Median']))
318
+
319
+ # obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
320
+ # total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
321
+
322
+ # obj_points_max = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
323
+ # obj_own_max = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
324
+
325
+ obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
326
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) <= max_sal5
327
+ total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal5
328
+
329
+ if site_var5 == 'Draftkings':
330
+
331
+ if contest_var5 == 'Cash':
332
+ for flex in flex_file['Team'].unique():
333
+ sub_idx = flex_file[(flex_file['Team'] == flex) & (flex_file['Position'] != 'SP')].index
334
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
335
+ elif contest_var5 == 'Small Field GPP':
336
+ for flex in flex_file['Team'].unique():
337
+ sub_idx = flex_file[(flex_file['Team'] == stack_var5) & (flex_file['Position'] != 'SP')].index
338
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
339
+ elif contest_var5 == 'Large Field GPP':
340
+ for flex in flex_file['Team'].unique():
341
+ sub_idx = flex_file[(flex_file['Team'] == stack_var5) & (flex_file['Position'] != 'SP')].index
342
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
343
+ for flex in flex_file['Team'].unique():
344
+ sub_idx = flex_file[(flex_file['Team'] == ministack_var5) & (flex_file['Position'] != 'SP')].index
345
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 3
346
+
347
+ for flex in flex_file['lock'].unique():
348
+ sub_idx = flex_file[flex_file['lock'] == 1].index
349
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var5)
350
+
351
+ for flex in flex_file['Position'].unique():
352
+ sub_idx = flex_file[flex_file['Position'] != "Var"].index
353
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 10
354
+
355
+ for flex in flex_file['Position'].unique():
356
+ sub_idx = flex_file[flex_file['Position'].str.contains("SP")].index
357
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 2
358
+
359
+ for flex in flex_file['Position'].unique():
360
+ sub_idx = flex_file[flex_file['Position'] == "C"].index
361
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
362
+
363
+ for flex in flex_file['Position'].unique():
364
+ sub_idx = flex_file[flex_file['Position'] == "1B"].index
365
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
366
+
367
+ for flex in flex_file['Position'].unique():
368
+ sub_idx = flex_file[flex_file['Position'] == "2B"].index
369
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
370
+
371
+ for flex in flex_file['Position'].unique():
372
+ sub_idx = flex_file[flex_file['Position'] == "3B"].index
373
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
374
+
375
+ for flex in flex_file['Position'].unique():
376
+ sub_idx = flex_file[flex_file['Position'] == "SS"].index
377
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 1
378
+
379
+ for flex in flex_file['Position'].unique():
380
+ sub_idx = flex_file[flex_file['Position'] == "OF"].index
381
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
382
+
383
+ for flex in flex_file['Position'].unique():
384
+ sub_idx = flex_file[flex_file['Position'].str.contains("C")].index
385
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
386
+
387
+ for flex in flex_file['Position'].unique():
388
+ sub_idx = flex_file[flex_file['Position'].str.contains("1B")].index
389
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
390
+
391
+ for flex in flex_file['Position'].unique():
392
+ sub_idx = flex_file[flex_file['Position'].str.contains("2B")].index
393
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
394
+
395
+ for flex in flex_file['Position'].unique():
396
+ sub_idx = flex_file[flex_file['Position'].str.contains("3B")].index
397
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
398
+
399
+ for flex in flex_file['Position'].unique():
400
+ sub_idx = flex_file[flex_file['Position'].str.contains("SS")].index
401
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
402
+
403
+ for flex in flex_file['Position'].unique():
404
+ sub_idx = flex_file[flex_file['Position'].str.contains("OF")].index
405
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
406
+
407
+ for flex in flex_file['Position'].unique():
408
+ sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "3B")| (flex_file['Position'] == "3B/SS")].index
409
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
410
+
411
+ for flex in flex_file['Position'].unique():
412
+ sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "2B")| (flex_file['Position'] == "2B/SS")].index
413
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
414
+
415
+ for flex in flex_file['Position'].unique():
416
+ sub_idx = flex_file[(flex_file['Position'] == "2B") | (flex_file['Position'] == "3B")| (flex_file['Position'] == "2B/3B")].index
417
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
418
+
419
+ for flex in flex_file['Position'].unique():
420
+ sub_idx = flex_file[(flex_file['Position'] == "1B") | (flex_file['Position'] == "3B")| (flex_file['Position'] == "1B/3B")].index
421
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
422
+
423
+ for flex in flex_file['Position'].unique():
424
+ sub_idx = flex_file[(flex_file['Position'] == "1B") | (flex_file['Position'] == "C")| (flex_file['Position'] == "1B/C")].index
425
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
426
+
427
+ for flex in flex_file['Position'].unique():
428
+ sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "OF")| (flex_file['Position'] == "SS/OF")].index
429
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
430
+
431
+ elif site_var5 == 'Fanduel':
432
+
433
+ if contest_var5 == 'Cash':
434
+ for flex in flex_file['Team'].unique():
435
+ sub_idx = flex_file[(flex_file['Team'] == flex) & (flex_file['Position'] != 'P')].index
436
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
437
+ elif contest_var5 == 'Small Field GPP':
438
+ for flex in flex_file['Team'].unique():
439
+ sub_idx = flex_file[(flex_file['Team'] == stack_var5) & (flex_file['Position'] != 'P')].index
440
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 4
441
+ elif contest_var5 == 'Large Field GPP':
442
+ for flex in flex_file['Team'].unique():
443
+ sub_idx = flex_file[(flex_file['Team'] == stack_var5)].index
444
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 4
445
+ for flex in flex_file['Team'].unique():
446
+ sub_idx = flex_file[(flex_file['Team'] == ministack_var5)].index
447
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 4
448
+
449
+ for flex in flex_file['lock'].unique():
450
+ sub_idx = flex_file[flex_file['lock'] == 1].index
451
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var5)
452
+
453
+ for flex in flex_file['Position'].unique():
454
+ sub_idx = flex_file[flex_file['Position'] != "Var"].index
455
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 9
456
+
457
+ for flex in flex_file['Position'].unique():
458
+ sub_idx = flex_file[flex_file['Position'].str.contains("P")].index
459
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
460
+
461
+ for flex in flex_file['Position'].unique():
462
+ sub_idx = flex_file[(flex_file['Position'] == "C") | (flex_file['Position'] == "1B")].index
463
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
464
+
465
+ for flex in flex_file['Position'].unique():
466
+ sub_idx = flex_file[(flex_file['Position'] == "C") | (flex_file['Position'] == "1B") | (flex_file['Position'] == "OF")].index
467
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
468
+
469
+ for flex in flex_file['Position'].unique():
470
+ sub_idx = flex_file[flex_file['Position'] == "2B"].index
471
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
472
+
473
+ for flex in flex_file['Position'].unique():
474
+ sub_idx = flex_file[flex_file['Position'] == "3B"].index
475
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
476
+
477
+ for flex in flex_file['Position'].unique():
478
+ sub_idx = flex_file[flex_file['Position'] == "SS"].index
479
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 2
480
+
481
+ for flex in flex_file['Position'].unique():
482
+ sub_idx = flex_file[flex_file['Position'] == "OF"].index
483
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
484
+
485
+ for flex in flex_file['Position'].unique():
486
+ sub_idx = flex_file[(flex_file['Position'] == "OF") | (flex_file['Position'] == "C")].index
487
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
488
+
489
+ for flex in flex_file['Position'].unique():
490
+ sub_idx = flex_file[(flex_file['Position'] == "OF") | (flex_file['Position'] == "1B")].index
491
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
492
+
493
+ for flex in flex_file['Position'].unique():
494
+ sub_idx = flex_file[(flex_file['Position'].str.contains("C")) | (flex_file['Position'].str.contains("1B"))].index
495
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
496
+
497
+ for flex in flex_file['Position'].unique():
498
+ sub_idx = flex_file[(flex_file['Position'].str.contains("2B")) | (flex_file['Position'].str.contains("SS"))].index
499
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
500
+
501
+ for flex in flex_file['Position'].unique():
502
+ sub_idx = flex_file[(flex_file['Position'] == "C") | (flex_file['Position'] == "SS")].index
503
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
504
+
505
+ for flex in flex_file['Position'].unique():
506
+ sub_idx = flex_file[(flex_file['Position'] == "SS") | (flex_file['Position'] == "2B") | (flex_file['Position'] == "OF") | (flex_file['Position'] == "2B/SS/OF")].index
507
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 5
508
+
509
+ for flex in flex_file['Position'].unique():
510
+ sub_idx = flex_file[flex_file['Position'].str.contains("2B")].index
511
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
512
+
513
+ for flex in flex_file['Position'].unique():
514
+ sub_idx = flex_file[flex_file['Position'].str.contains("3B")].index
515
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
516
+
517
+ for flex in flex_file['Position'].unique():
518
+ sub_idx = flex_file[flex_file['Position'].str.contains("SS")].index
519
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 1
520
+
521
+ for flex in flex_file['Position'].unique():
522
+ sub_idx = flex_file[flex_file['Position'].str.contains("OF")].index
523
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
524
+
525
+ for flex in flex_file['Position'].unique():
526
+ sub_idx = flex_file[flex_file['Position'].str.contains("OF")].index
527
+ total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
528
+
529
+ player_count = []
530
+ player_trim = []
531
+ lineup_list = []
532
+
533
+ if contest_var5 == 'Cash':
534
+ obj_points = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
535
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
536
+ total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_own - .001
537
+ elif contest_var5 != 'Cash':
538
+ obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
539
+ total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
540
+ total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_proj - .01
541
+
542
+ total_score.solve()
543
+ for v in total_score.variables():
544
+ if v.varValue > 0:
545
+ lineup_list.append(v.name)
546
+ df = pd.DataFrame(lineup_list)
547
+ df['Names'] = df[0].map(player_match)
548
+ df['Cost'] = df['Names'].map(player_sal)
549
+ df['Proj'] = df['Names'].map(player_proj)
550
+ df['Own'] = df['Names'].map(player_own)
551
+ total_cost = sum(df['Cost'])
552
+ total_own = sum(df['Own'])
553
+ total_proj = sum(df['Proj'])
554
+ lineup_raw = pd.DataFrame(lineup_list)
555
+ lineup_raw['Names'] = lineup_raw[0].map(player_match)
556
+ lineup_raw['value'] = lineup_raw[0].map(player_index_match)
557
+ lineup_final = lineup_raw.sort_values(by=['value'])
558
+ del lineup_final[lineup_final.columns[0]]
559
+ del lineup_final[lineup_final.columns[1]]
560
+ lineup_final = lineup_final.reset_index(drop=True)
561
+
562
+ if site_var5 == 'Draftkings':
563
+ line_hold = lineup_final[['Names']]
564
+ line_hold['pos'] = line_hold['Names'].map(player_pos)
565
+
566
+ for pname in range(0,len(line_hold)):
567
+ if line_hold.iat[pname,1] == 'SP':
568
+ if line_hold.iat[pname,0] not in p_used:
569
+ sorted_lineup.append(line_hold.iat[pname,0])
570
+ p_used.extend(sorted_lineup)
571
+
572
+ for pname in range(0,len(line_hold)):
573
+ if line_hold.iat[pname,1] == 'C':
574
+ if line_hold.iat[pname,0] not in p_used:
575
+ sorted_lineup.append(line_hold.iat[pname,0])
576
+ cvar = 1
577
+ p_used.extend(sorted_lineup)
578
+
579
+ if cvar != 1:
580
+ for pname in range(0,len(line_hold)):
581
+ if 'C' in line_hold.iat[pname,1]:
582
+ if line_hold.iat[pname,0] not in p_used:
583
+ sorted_lineup.append(line_hold.iat[pname,0])
584
+ p_used.extend(sorted_lineup)
585
+
586
+ for pname in range(0,len(line_hold)):
587
+ if line_hold.iat[pname,1] == '1B':
588
+ if line_hold.iat[pname,0] not in p_used:
589
+ sorted_lineup.append(line_hold.iat[pname,0])
590
+ firvar = 1
591
+ p_used.extend(sorted_lineup)
592
+
593
+ if firvar != 1:
594
+ for pname in range(0,len(line_hold)):
595
+ if '1B' in line_hold.iat[pname,1]:
596
+ if line_hold.iat[pname,0] not in p_used:
597
+ sorted_lineup.append(line_hold.iat[pname,0])
598
+ p_used.extend(sorted_lineup)
599
+
600
+ for pname in range(0,len(line_hold)):
601
+ if line_hold.iat[pname,1] == '2B':
602
+ if line_hold.iat[pname,0] not in p_used:
603
+ sorted_lineup.append(line_hold.iat[pname,0])
604
+ secvar = 1
605
+ p_used.extend(sorted_lineup)
606
+
607
+ if secvar != 1:
608
+ for pname in range(0,len(line_hold)):
609
+ if '2B' in line_hold.iat[pname,1]:
610
+ if line_hold.iat[pname,0] not in p_used:
611
+ sorted_lineup.append(line_hold.iat[pname,0])
612
+ p_used.extend(sorted_lineup)
613
+
614
+ for pname in range(0,len(line_hold)):
615
+ if line_hold.iat[pname,1] == '3B':
616
+ if line_hold.iat[pname,0] not in p_used:
617
+ sorted_lineup.append(line_hold.iat[pname,0])
618
+ thirvar = 1
619
+ p_used.extend(sorted_lineup)
620
+
621
+ if thirvar != 1:
622
+ for pname in range(0,len(line_hold)):
623
+ if '3B' in line_hold.iat[pname,1]:
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
+
628
+ for pname in range(0,len(line_hold)):
629
+ if line_hold.iat[pname,1] == 'SS':
630
+ if line_hold.iat[pname,0] not in p_used:
631
+ sorted_lineup.append(line_hold.iat[pname,0])
632
+ p_used.extend(sorted_lineup)
633
+
634
+ for pname in range(0,len(line_hold)):
635
+ if 'SS' in line_hold.iat[pname,1]:
636
+ if line_hold.iat[pname,0] not in p_used:
637
+ sorted_lineup.append(line_hold.iat[pname,0])
638
+ p_used.extend(sorted_lineup)
639
+
640
+ for pname in range(0,len(line_hold)):
641
+ if line_hold.iat[pname,1] == 'OF':
642
+ if line_hold.iat[pname,0] not in p_used:
643
+ sorted_lineup.append(line_hold.iat[pname,0])
644
+ p_used.extend(sorted_lineup)
645
+
646
+ for pname in range(0,len(line_hold)):
647
+ if 'OF' in line_hold.iat[pname,1]:
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
+ lineup_final['sorted'] = sorted_lineup
653
+ lineup_final = lineup_final.drop(columns=['Names'])
654
+ lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
655
+
656
+ elif site_var5 == 'Fanduel':
657
+ line_hold = lineup_final[['Names']]
658
+ line_hold['pos'] = line_hold['Names'].map(player_pos)
659
+
660
+ for pname in range(0,len(line_hold)):
661
+ if line_hold.iat[pname,1] == 'P':
662
+ if line_hold.iat[pname,0] not in p_used:
663
+ sorted_lineup.append(line_hold.iat[pname,0])
664
+ p_used.extend(sorted_lineup)
665
+
666
+ for pname in range(0,len(line_hold)):
667
+ if line_hold.iat[pname,1] == 'C' or line_hold.iat[pname,1] == '1B':
668
+ if line_hold.iat[pname,0] not in p_used:
669
+ sorted_lineup.append(line_hold.iat[pname,0])
670
+ cvar = 1
671
+ p_used.extend(sorted_lineup)
672
+
673
+ if cvar != 1:
674
+ for pname in range(0,len(line_hold)):
675
+ if line_hold.iat[pname,1] in ['C', '1B']:
676
+ if line_hold.iat[pname,0] not in p_used:
677
+ sorted_lineup.append(line_hold.iat[pname,0])
678
+ p_used.extend(sorted_lineup)
679
+
680
+ for pname in range(0,len(line_hold)):
681
+ if line_hold.iat[pname,1] == '2B':
682
+ if line_hold.iat[pname,0] not in p_used:
683
+ sorted_lineup.append(line_hold.iat[pname,0])
684
+ secvar = 1
685
+ p_used.extend(sorted_lineup)
686
+
687
+ if secvar != 1:
688
+ for pname in range(0,len(line_hold)):
689
+ if '2B' in line_hold.iat[pname,1]:
690
+ if line_hold.iat[pname,0] not in p_used:
691
+ sorted_lineup.append(line_hold.iat[pname,0])
692
+ p_used.extend(sorted_lineup)
693
+
694
+ for pname in range(0,len(line_hold)):
695
+ if line_hold.iat[pname,1] == '3B':
696
+ if line_hold.iat[pname,0] not in p_used:
697
+ sorted_lineup.append(line_hold.iat[pname,0])
698
+ thirvar = 1
699
+ p_used.extend(sorted_lineup)
700
+
701
+ if thirvar != 1:
702
+ for pname in range(0,len(line_hold)):
703
+ if '3B' in line_hold.iat[pname,1]:
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] == 'SS':
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
+ for pname in range(0,len(line_hold)):
715
+ if 'SS' in line_hold.iat[pname,1]:
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] == 'OF':
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
+ for pname in range(0,len(line_hold)):
727
+ if 'OF' in line_hold.iat[pname,1]:
728
+ if line_hold.iat[pname,0] not in p_used:
729
+ sorted_lineup.append(line_hold.iat[pname,0])
730
+ p_used.extend(sorted_lineup)
731
+
732
+ for pname in range(0,len(line_hold)):
733
+ if line_hold.iat[pname,0] not in p_used:
734
+ sorted_lineup.append(line_hold.iat[pname,0])
735
+ p_used.extend(sorted_lineup)
736
+
737
+ lineup_final['sorted'] = sorted_lineup
738
+ lineup_final = lineup_final.drop(columns=['Names'])
739
+ lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
740
+
741
+ lineup_test = lineup_final
742
+ lineup_final = lineup_final.T
743
+ lineup_final['Cost'] = total_cost
744
+ lineup_final['Proj'] = total_proj
745
+ lineup_final['Own'] = total_own
746
+
747
+ lineup_test['Team'] = lineup_test['Names'].map(player_team)
748
+ lineup_test['Position'] = lineup_test['Names'].map(player_pos)
749
+ lineup_test['Salary'] = lineup_test['Names'].map(player_sal)
750
+ lineup_test['Proj'] = lineup_test['Names'].map(player_proj)
751
+ lineup_test['Own'] = lineup_test['Names'].map(player_own)
752
+ lineup_test = lineup_test.set_index('Names')
753
+ lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0)
754
+
755
+ lineup_display.append(lineup_test)
756
+
757
+ with col2:
758
+ with st.container():
759
+ st.table(lineup_test)
760
+
761
+ max_proj = total_proj
762
+ max_own = total_own
763
+
764
+ check_list.append(total_proj)
765
+
766
+ portfolio = pd.concat([portfolio, lineup_final], ignore_index = True)
767
+
768
+ x += 1
769
+
770
+ if site_var5 == 'Draftkings':
771
+ portfolio.rename(columns={0: "SP1", 1: "SP2", 2: "C", 3: "1B", 4: "2B", 5: "3B", 6: "SS", 7: "OF1", 8: "OF2", 9: "OF3"}, inplace = True)
772
+ elif site_var5 == 'Fanduel':
773
+ portfolio.rename(columns={0: "SP1", 1: "C/1B", 2: "2B", 3: "3B", 4: "SS", 5: "OF1", 6: "OF2", 7: "OF3", 8: "UTIL"}, inplace = True)
774
+ portfolio = portfolio.dropna()
775
+ portfolio = portfolio.reset_index()
776
+ portfolio['Lineup_num'] = portfolio['index'] + 1
777
+ portfolio.rename(columns={'Lineup_num': "Lineup"}, inplace = True)
778
+ portfolio = portfolio.set_index('Lineup')
779
+ portfolio = portfolio.drop(columns=['index'])
780
+
781
+ final_outcomes = portfolio
782
+
783
+ with optimize_container:
784
+ optimize_container = st.empty()
785
+ st.dataframe(portfolio.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
786
+
787
+ st.download_button(
788
+ label="Export Tables",
789
+ data=convert_df_to_csv(final_outcomes),
790
+ file_name='MLB_optimals_export.csv',
791
+ mime='text/csv',
792
+ )