-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFD_NBA_2.py
265 lines (196 loc) · 7.16 KB
/
FD_NBA_2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!NBA FanDuel 2.0
'''
This is the second incarnation of the python engine for predicting successful FanDuel match-ups
'''
import pandas as pd
import os
import matplotlib.pyplot as plt
from tabulate import tabulate
from pprint import pprint
import time
from pulp import *
import webbrowser
import logging
logging.basicConfig(level=logging.DEBUG,
format=' %(asctime)s - %(levelname)s- %(message)s')
logging.debug('Start of Program')
# road = 'C:\\Users\\ngoodroe\\Desktop'
# road = r'/Users/goodroe/Dropbox/Python/Pandas'
# Prompt for 3pt competetion?
##threepoint = input('\nDo you want to run the program for the 3pt competition? (y/n)\n').lower()
# 3 different csv's: FanDuel, NBAPlayers, and NBATeamDef
teamName = {
'Hawks' : 'ATL',
'Celtics' : 'BOS',
'Nets' : 'BKN',
'Hornets' : 'CHA',
'Bulls' : 'CHI',
'Cavaliers' : 'CLE',
'Mavericks' : 'DAL',
'Nuggets' : 'DEN',
'Pistons' : 'DET',
'Warriors' : 'GS',
'Rockets' : 'HOU',
'Pacers' : 'IND',
'Clippers' : 'LAC',
'Lakers' : 'LAL',
'Grizzlies' : 'MEM',
'Heat' : 'MIA',
'Bucks' : 'MIL',
'Timberwolves' : 'MIN',
'Pelicans' : 'NO',
'Knicks' : 'NY',
'Thunder' : 'OKC',
'Magic' : 'ORL',
'76ers' : 'PHI',
'Suns' : 'PHO',
'Blazers' : 'POR',
'Kings' : 'SAC',
'Spurs' : 'SA',
'Raptors' : 'TOT',
'Jazz' : 'UTA',
'Wizards' : 'WAS',
'GSW': 'GS','BRK':'BKN','NYK':'NY','NOP':'NO'}
'''
Sport Ref teams = ['ATL', 'BOS', 'BRK', 'CHI', 'CHO',
'CLE', 'DAL', 'DEN', 'DET', 'GSW', 'HOU', 'IND',
'LAC', 'LAL', 'MEM', 'MIA', 'MIL', 'MIN', 'NOP',
'NYK', 'OKC', 'ORL', 'PHI', 'PHO', 'POR', 'SAC',
'SAS', 'TOR', 'TOT', 'UTA', 'WAS']
FanDuel teams = ['ATL', 'BOS', 'BKN', 'CHI', 'CHO',
'CLE', 'DAL', 'DEN', 'DET', 'GS', 'HOU', 'IND',
'LAC', 'LAL', 'MEM', 'MIA', 'MIL', 'MIN', 'NO',
'NY', 'OKC', 'ORL', 'PHI', 'PHO', 'POR', 'SAC',
'SAS', 'TOR', 'TOT', 'UTA', 'WAS']
Differences:
GSW -> GS
BRK -> BKN
NYK -> NY
NOP -> NO
### Settle discrepancies between FD and
SR team abbreviations
Defer to FD
Split the string of team name and get the last one.
Map it to these
'''
d = pd.read_csv('NBA_D.csv')
#d['newName'] = teamName[d['Team']]
fd = pd.read_csv('FanDuel-NBA-2019-03-19-33647-players-list.csv')
for each in range(len(fd.index)):
fd.loc[each,'Name'] = ''.join(fd.loc[each].Nickname.split('.'))
fd = fd.set_index('Name')
#fd.index.names = ['Name']
p = pd.read_csv('NBAp.csv')
loc = p.Player.str.find('\\')
p['temp'] = p.Player.str.split('\\')
p['Name2'] = p['temp'].str[0]
p = p.drop(columns = ['temp'])
for each in range(len(p.index)):
p.loc[each, 'Name'] = ''.join(p.loc[each].Name2.split('.'))
p = p.set_index('Name')
p = p.drop(columns = ['Rk'])
for each_fd in range(len(fd.index)):
for each_p in range(len(p.index)):
if fd.index[each_fd] == p.index[each_p]:
continue
elif fd.index[each_fd] in p.index[each_p]:
logging.debug('Changed '+fd.index[each_fd]+' to '+p.index[each_p])
fd = fd.rename(index = {fd.index[each_fd]:p.index[each_p]})
continue
elif p.index[each_p] in fd.index[each_fd]:
logging.debug('Changed '+p.index[each_p]+' to '+fd.index[each_fd])
p = p.rename(index = {p.index[each_p]:fd.index[each_fd]})
#Fix names like J.J. into JJ
# ''.join(name.split('.'))
df = pd.concat([fd,p],axis=1
#, sort = True
)
df = df[df['Injury Indicator'] != 'O']
teams = list(fd.Team)
teams = list(set(teams))
df = df.query('Team in @teams')
d['temp'] = d.Team.str.split(' ')
d['Name'] = d['temp'].str[-1]
d['temp'] = d['Name'].str.split('*')
d['Name'] = d['temp'].str[0]
for x in range(len(d.index)):
d.loc[x,'Abrv'] = teamName[d.iloc[x].Name] #Change columns to their abreviations
d = d.set_index('Abrv')
for x in df.index:
df.loc[x,'OppPts'] = d.loc[df.loc[x].Opponent].PTS
df = df[df.MP > 1]
df['Score'] = (df['FPPG'] * df['MP'] * df['OppPts'])**(1/3)
df['nScore'] = (df['Score']-df['Score'].min())/(df['Score'].max()-df['Score'].min())
df['Score'] = 3* (20 ** df.nScore)
df = df.sort_values('Position', axis=0)
df = df[df['Injury Indicator'] != 'O']
### MANUAL TAKEOUT
#df = df[df.index != 'Anthony Davis']
df = df[df.index != 'Derrick Rose']
player_df = df
# Get list of teams from both FD and TeamD and match them up
# Combine both player csv into one.
# Eliminate any nonplaying players (hurt or wrong team)
# Columns needed: MP, 3PA, and FPPG
# New column with opponent's 3pt% and pts allowed
''' Calculate each player's score using
geometric mean with the following qualities:
*3pt = Opp 3p%, Minutes Played, and 3PA
*Full Roster = MP, Opponent Points Allowed, and FPPG
'''
# if threepoint == y:
# #CODE
# else:
# #CODE
# breakup the dataframe by position.
# Normalize Data
players = []
for total in range(len(player_df)):
players.append([player_df.iloc[total]['Position'],
player_df.index[total],
player_df.iloc[total].Score,
player_df.iloc[total].Salary,
player_df.iloc[total].FPPG])
# Linear Programming to find largest score for a team
playernum = [str(i) for i in range(len(player_df.index))]
pgplayers = {str(i): 1 if (player_df.iloc[i]['Position'] == 'PG') else 0 for i in range(len(player_df.index))}
sgplayers = {str(i): 1 if (player_df.iloc[i]['Position'] == 'SG') else 0 for i in range(len(player_df.index))}
sfplayers = {str(i): 1 if (player_df.iloc[i]['Position'] == 'SF') else 0 for i in range(len(player_df.index))}
pfplayers = {str(i): 1 if (player_df.iloc[i]['Position'] == 'PF') else 0 for i in range(len(player_df.index))}
cplayers = {str(i): 1 if (player_df.iloc[i]['Position'] == 'C' ) else 0 for i in range(len(player_df.index))}
cost = {str(i): player_df.iloc[i]['Salary'] for i in range(len(player_df.index))}
pts = {str(i): player_df.iloc[i]['Score'] for i in range(len(player_df.index))}
model = LpProblem('Fantasy Basketball', LpMaximize)
player_var = LpVariable.dicts('Players',playernum,0,1,LpBinary)
model += lpSum([pts[i]*player_var[i] for i in playernum]),'TotalScore'
model += lpSum([cost[i]*player_var[i] for i in playernum]) <= 60000#56500
model += lpSum([pgplayers[i]*player_var[i] for i in playernum]) <= 2
model += lpSum([sgplayers[i]*player_var[i] for i in playernum]) <= 2
model += lpSum([sfplayers[i]*player_var[i] for i in playernum]) <= 2
model += lpSum([pfplayers[i]*player_var[i] for i in playernum]) <= 2
model += lpSum( [cplayers[i]*player_var[i] for i in playernum]) <= 1
model += lpSum([player_var[i] for i in playernum]) == 9
status = model.solve()
LpStatus[model.status]
best = []
lineup = []
totalcost = 0
totalfant = 0
totalpoints = 0
for var in player_var:
var_value = player_var[var].varValue
if var_value == 1:
best.append(var)
for each in best:
lineup.append(players[int(each)])
for each in lineup:
totalpoints += each[2]
totalcost += each[3]
totalfant += each[4]
lineup.append(['Total','',totalpoints,totalcost,totalfant])
titles = ['Pos','Name','Score','Price','FPPG']
print(tabulate(lineup,headers = titles))
# Print out the answers
#x = input('What is the last position you need?\n').upper()
#print('\n')
#print(df[(df.Pos == x)&(df.Salary ==3500)].Score.nlargest(6))