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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pulp
|
2 |
+
import numpy as np
|
3 |
+
import pandas as pd
|
4 |
+
import random
|
5 |
+
import sys
|
6 |
+
import openpyxl
|
7 |
+
import re
|
8 |
+
import time
|
9 |
+
import streamlit as st
|
10 |
+
import matplotlib
|
11 |
+
from matplotlib.colors import LinearSegmentedColormap
|
12 |
+
import json
|
13 |
+
import requests
|
14 |
+
import gspread
|
15 |
+
import plotly.figure_factory as ff
|
16 |
+
|
17 |
+
scope = ['https://www.googleapis.com/auth/spreadsheets',
|
18 |
+
"https://www.googleapis.com/auth/drive"]
|
19 |
+
|
20 |
+
credentials = {
|
21 |
+
"type": "service_account",
|
22 |
+
"project_id": "sheets-api-connect-378620",
|
23 |
+
"private_key_id": "1005124050c80d085e2c5b344345715978dd9cc9",
|
24 |
+
"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+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ZpzajqQA74bPwELJjnzrCnH79TnHG\nJuElxA33rFEjbgbzdyrE768=\n-----END PRIVATE KEY-----\n",
|
25 |
+
"client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
|
26 |
+
"client_id": "106625872877651920064",
|
27 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
28 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
29 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
30 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
|
31 |
+
}
|
32 |
+
|
33 |
+
gc = gspread.service_account_from_dict(credentials)
|
34 |
+
|
35 |
+
st.set_page_config(layout="wide")
|
36 |
+
|
37 |
+
dk_player_url = 'PGA_Basic_ROO'
|
38 |
+
CSV_URL = 'https://sheetdb.io/api/v1/ckjq8yp37qxly?sheet=DK_CSV'
|
39 |
+
|
40 |
+
@st.cache_data
|
41 |
+
def load_dk_player_model(URL):
|
42 |
+
sh = gc.open(URL)
|
43 |
+
worksheet = sh.get_worksheet(0)
|
44 |
+
raw_display = pd.DataFrame(worksheet.get_all_records())
|
45 |
+
raw_display["Salary"] = raw_display["Salary"].replace("$", "", regex=True).astype(float)
|
46 |
+
raw_display['Top_finish'] = raw_display['Top_finish'].str.replace('%', '').astype(float)/100
|
47 |
+
raw_display['Top_5_finish'] = raw_display['Top_5_finish'].str.replace('%', '').astype(float)/100
|
48 |
+
raw_display['Top_10_finish'] = raw_display['Top_10_finish'].str.replace('%', '').astype(float)/100
|
49 |
+
raw_display['100+%'] = raw_display['100+%'].str.replace('%', '').astype(float)/100
|
50 |
+
raw_display['10x%'] = raw_display['10x%'].str.replace('%', '').astype(float)/100
|
51 |
+
raw_display['11x%'] = raw_display['11x%'].str.replace('%', '').astype(float)/100
|
52 |
+
raw_display['12x%'] = raw_display['12x%'].str.replace('%', '').astype(float)/100
|
53 |
+
raw_display['LevX'] = raw_display['LevX'].str.replace('%', '').astype(float)/100
|
54 |
+
|
55 |
+
return raw_display
|
56 |
+
|
57 |
+
@st.cache_data
|
58 |
+
def grab_csv_data(URL):
|
59 |
+
draftkings_data = pd.read_json(URL)
|
60 |
+
draftkings_data.rename(columns={"Name": "Player"}, inplace = True)
|
61 |
+
|
62 |
+
return draftkings_data
|
63 |
+
|
64 |
+
tab1, tab2 = st.tabs(["Player Overall Projections", "Optimizer"])
|
65 |
+
|
66 |
+
def convert_df_to_csv(df):
|
67 |
+
return df.to_csv().encode('utf-8')
|
68 |
+
|
69 |
+
lineup_display = []
|
70 |
+
check_list = []
|
71 |
+
rand_player = 0
|
72 |
+
boost_player = 0
|
73 |
+
salaryCut = 0
|
74 |
+
|
75 |
+
with tab1:
|
76 |
+
if st.button("Reset Data", key='reset1'):
|
77 |
+
# Clear values from *all* all in-memory and on-disk data caches:
|
78 |
+
# i.e. clear values from both square and cube
|
79 |
+
st.cache_data.clear()
|
80 |
+
hold_display = load_dk_player_model(dk_player_url)
|
81 |
+
csv_data = grab_csv_data(CSV_URL)
|
82 |
+
csv_merge = pd.merge(csv_data, hold_display, how='left', left_on=['Player'], right_on = ['Player'])
|
83 |
+
id_dict = dict(zip(csv_merge['Player'], csv_merge['Name + ID']))
|
84 |
+
hold_container = st.empty()
|
85 |
+
display = hold_display.set_index('Player')
|
86 |
+
st.dataframe(display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
|
87 |
+
st.download_button(
|
88 |
+
label="Export Projections",
|
89 |
+
data=convert_df_to_csv(display),
|
90 |
+
file_name='PGA_DFS_export.csv',
|
91 |
+
mime='text/csv',
|
92 |
+
)
|
93 |
+
|
94 |
+
with tab2:
|
95 |
+
col1, col2 = st.columns([1, 4])
|
96 |
+
|
97 |
+
with col1:
|
98 |
+
|
99 |
+
max_sal = st.number_input('Max Salary', min_value = 35000, max_value = 50000, value = 50000, step = 100)
|
100 |
+
min_sal = st.number_input('Min Salary', min_value = 35000, max_value = 49900, value = 49000, step = 100)
|
101 |
+
proj_cut = st.number_input('Lowest median allowed', min_value = 0, max_value = 100, value = 50, step = 1)
|
102 |
+
slack_var = st.number_input('Median randomness', min_value = 0, max_value = 5, value = 0, step = 1)
|
103 |
+
totalRuns_raw = st.number_input('How many Lineups', min_value = 1, max_value = 1000, value = 5, step = 1)
|
104 |
+
|
105 |
+
|
106 |
+
totalRuns = totalRuns_raw
|
107 |
+
cut_group_1 = []
|
108 |
+
cut_group_2 = []
|
109 |
+
force_group_1 = []
|
110 |
+
force_group_2 = []
|
111 |
+
avoid_players = []
|
112 |
+
lock_player = []
|
113 |
+
lineups = []
|
114 |
+
player_pool_raw = []
|
115 |
+
|
116 |
+
player_pool = []
|
117 |
+
player_count = []
|
118 |
+
player_trim_pool = []
|
119 |
+
portfolio = pd.DataFrame()
|
120 |
+
x = 1
|
121 |
+
|
122 |
+
if st.button('Optimize'):
|
123 |
+
max_proj = 1000
|
124 |
+
max_own = 1000
|
125 |
+
total_proj = 0
|
126 |
+
total_own = 0
|
127 |
+
|
128 |
+
with col2:
|
129 |
+
with st.spinner('Wait for it...'):
|
130 |
+
with hold_container.container():
|
131 |
+
|
132 |
+
while x <= totalRuns:
|
133 |
+
|
134 |
+
raw_proj_file = hold_display
|
135 |
+
raw_flex_file = raw_proj_file.dropna(how='all')
|
136 |
+
raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > 0]
|
137 |
+
raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > proj_cut]
|
138 |
+
flex_file = raw_flex_file
|
139 |
+
flex_file = flex_file[['Player', 'Salary', 'Median', 'Own', 'LevX']]
|
140 |
+
flex_file.rename(columns={"Own": "Proj DK Own%"}, inplace = True)
|
141 |
+
flex_file['name_var'] = flex_file['Player']
|
142 |
+
flex_file['lock'] = flex_file['Player'].isin(lock_player)*1
|
143 |
+
flex_file['force_group_1'] = flex_file['Player'].isin(force_group_1)*1
|
144 |
+
flex_file['force_group_2'] = flex_file['Player'].isin(force_group_2)*1
|
145 |
+
flex_file['cut_group_1'] = flex_file['Player'].isin(cut_group_1)*1
|
146 |
+
flex_file['cut_group_2'] = flex_file['Player'].isin(cut_group_2)*1
|
147 |
+
chalk_file = flex_file.sort_values(by='Proj DK Own%', ascending=False)
|
148 |
+
chalk_group_df = chalk_file.sample(n=10)
|
149 |
+
chalk_group = chalk_group_df['Player'].tolist()
|
150 |
+
flex_file['chalk_group'] = flex_file['Player'].isin(chalk_group)*1
|
151 |
+
flex_file['Pos'] = 'G'
|
152 |
+
flex_file = flex_file[['Player', 'name_var', 'Pos', 'Salary', 'Median', 'Proj DK Own%', 'lock', 'force_group_1', 'force_group_2', 'cut_group_1', 'cut_group_2', 'chalk_group', 'LevX']]
|
153 |
+
if x > 1:
|
154 |
+
if slack_var > 0:
|
155 |
+
flex_file['randNumCol'] = np.random.randint(-int(slack_var),int(slack_var), flex_file.shape[0])
|
156 |
+
elif slack_var ==0:
|
157 |
+
flex_file['randNumCol'] = 0
|
158 |
+
elif x == 1:
|
159 |
+
flex_file['randNumCol'] = 0
|
160 |
+
flex_file['Median'] = flex_file['Median'] + flex_file['randNumCol']
|
161 |
+
flex_file_check = flex_file
|
162 |
+
check_list.append(flex_file['Median'][4])
|
163 |
+
player_ids = flex_file.index
|
164 |
+
|
165 |
+
overall_players = flex_file[['Player']]
|
166 |
+
overall_players['player_var_add'] = flex_file.index
|
167 |
+
overall_players['player_var'] = 'player_vars_' + overall_players['player_var_add'].astype(str)
|
168 |
+
|
169 |
+
player_vars = pulp.LpVariable.dicts("player_vars", flex_file.index, 0, 1, pulp.LpInteger)
|
170 |
+
total_score = pulp.LpProblem("Fantasy_Points_Problem", pulp.LpMaximize)
|
171 |
+
player_match = dict(zip(overall_players['player_var'], overall_players['Player']))
|
172 |
+
player_index_match = dict(zip(overall_players['player_var'], overall_players['player_var_add']))
|
173 |
+
player_own = dict(zip(flex_file['Player'], flex_file['Proj DK Own%']))
|
174 |
+
player_sal = dict(zip(flex_file['Player'], flex_file['Salary']))
|
175 |
+
player_lev = dict(zip(flex_file['Player'], flex_file['LevX']))
|
176 |
+
player_proj = dict(zip(flex_file['Player'], flex_file['Median']))
|
177 |
+
|
178 |
+
obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
|
179 |
+
total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
|
180 |
+
|
181 |
+
obj_points_max = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
|
182 |
+
obj_own_max = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
|
183 |
+
|
184 |
+
obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
|
185 |
+
total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) <= max_sal
|
186 |
+
total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal
|
187 |
+
|
188 |
+
for flex in flex_file['Pos'].unique():
|
189 |
+
sub_idx = flex_file[flex_file['Pos'] != "Var"].index
|
190 |
+
total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 6
|
191 |
+
|
192 |
+
player_count = []
|
193 |
+
player_trim = []
|
194 |
+
lineup_list = []
|
195 |
+
|
196 |
+
total_score += pulp.lpSum([player_vars[idx]*obj_points_max[idx] for idx in flex_file.index]) <= max_proj - .01
|
197 |
+
|
198 |
+
total_score.solve()
|
199 |
+
for v in total_score.variables():
|
200 |
+
if v.varValue > 0:
|
201 |
+
lineup_list.append(v.name)
|
202 |
+
df = pd.DataFrame(lineup_list)
|
203 |
+
df['Names'] = df[0].map(player_match)
|
204 |
+
df['Cost'] = df['Names'].map(player_sal)
|
205 |
+
df['Proj'] = df['Names'].map(player_proj)
|
206 |
+
df['Own'] = df['Names'].map(player_own)
|
207 |
+
total_cost = sum(df['Cost'])
|
208 |
+
total_own = sum(df['Own'])
|
209 |
+
total_proj = sum(df['Proj'])
|
210 |
+
lineup_raw = pd.DataFrame(lineup_list)
|
211 |
+
lineup_raw['Names'] = lineup_raw[0].map(player_match)
|
212 |
+
lineup_raw['value'] = lineup_raw[0].map(player_index_match)
|
213 |
+
lineup_final = lineup_raw.sort_values(by=['value'])
|
214 |
+
del lineup_final[lineup_final.columns[0]]
|
215 |
+
del lineup_final[lineup_final.columns[1]]
|
216 |
+
lineup_final = lineup_final.reset_index(drop=True)
|
217 |
+
lineup_test = lineup_final
|
218 |
+
lineup_final = lineup_final.T
|
219 |
+
lineup_final['Cost'] = total_cost
|
220 |
+
lineup_final['Proj'] = total_proj
|
221 |
+
lineup_final['Own'] = total_own
|
222 |
+
|
223 |
+
if total_cost < 50001:
|
224 |
+
lineups.append(lineup_final)
|
225 |
+
|
226 |
+
lineup_test['Salary'] = lineup_test['Names'].map(player_sal)
|
227 |
+
lineup_test['Proj'] = lineup_test['Names'].map(player_proj)
|
228 |
+
lineup_test['Own'] = lineup_test['Names'].map(player_own)
|
229 |
+
lineup_test['LevX'] = lineup_test['Names'].map(player_lev)
|
230 |
+
lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0)
|
231 |
+
|
232 |
+
lineup_display.append(lineup_test)
|
233 |
+
|
234 |
+
with col2:
|
235 |
+
with st.container():
|
236 |
+
st.table(lineup_test)
|
237 |
+
|
238 |
+
max_proj = total_proj
|
239 |
+
max_own = total_own
|
240 |
+
|
241 |
+
check_list.append(total_proj)
|
242 |
+
|
243 |
+
portfolio = portfolio.append(lineup_final, ignore_index = True)
|
244 |
+
|
245 |
+
x += 1
|
246 |
+
|
247 |
+
portfolio.rename(columns={0: "Player_1", 1: "Player_2", 2: "Player_3", 3: "Player_4", 4: "Player_5", 5: "Player_6"}, inplace = True)
|
248 |
+
portfolio = portfolio.dropna()
|
249 |
+
|
250 |
+
final_outcomes = portfolio
|
251 |
+
final_outcomes['p1 id'] = final_outcomes['Player_1'].map(id_dict)
|
252 |
+
final_outcomes['p2 id'] = final_outcomes['Player_2'].map(id_dict)
|
253 |
+
final_outcomes['p3 id'] = final_outcomes['Player_3'].map(id_dict)
|
254 |
+
final_outcomes['p4 id'] = final_outcomes['Player_4'].map(id_dict)
|
255 |
+
final_outcomes['p5 id'] = final_outcomes['Player_5'].map(id_dict)
|
256 |
+
final_outcomes['p6 id'] = final_outcomes['Player_6'].map(id_dict)
|
257 |
+
final_outcomes = final_outcomes[['p1 id', 'p2 id', 'p3 id', 'p4 id', 'p5 id', 'p6 id']]
|
258 |
+
with col1:
|
259 |
+
st.download_button(
|
260 |
+
label="Export Lineups",
|
261 |
+
data=convert_df_to_csv(final_outcomes),
|
262 |
+
file_name='PGA_DFS_export.csv',
|
263 |
+
mime='text/csv',
|
264 |
+
)
|
265 |
+
|
266 |
+
with hold_container:
|
267 |
+
hold_container = st.empty()
|