-
Notifications
You must be signed in to change notification settings - Fork 2
/
nba.py
executable file
·488 lines (360 loc) · 18.5 KB
/
nba.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#!/usr/bin/env python
from __future__ import division, print_function
import argparse
import csv
import datetime as dt
import json
import os
import re
import sys
import dateutil.parser as dtparser
import pandas as pd
import pymongo
from tqdm import tqdm
from termcolor import colored
from analysis.features import construct_global_features, construct_all_features
from analysis.prediction import predict_game_outcome, predict_game_day, predict_all_games
from game.Game import Game
from game.Player import Player
from game.Season import Season
from utils.network import get_odds_from_donbest, get_all_data
from utils.settings import pbp, players, seasons
from utils.misc import compute_ts_length
team_to_espn_ids = {'Hawks': 1,
'Celtics': 2,
'Hornets': 3,
'Bulls': 4,
'Cavaliers': 5,
'Mavericks': 6,
'Nuggets': 7,
'Pistons': 8,
'Warriors': 9,
'Rockets': 10,
'Pacers': 11,
'Clippers': 12,
'Lakers': 13,
'Heat': 14,
'Bucks': 15,
'Timberwolves': 16,
'Nets': 17,
'Knicks': 18,
'Magic': 19,
'76ers': 20,
'Suns': 21,
'Trail Blazers': 22,
'Kings': 23,
'Spurs': 24,
'Thunder': 25,
'Jazz': 26,
'Wizards': 27,
'Raptors': 50,
'Grizzlies': 51,
'Bobcats': 74}
def compute_all_season_lineups(year):
print('Loading the {}-{} NBA season'.format(year, year + 1))
season = Season(year)
print('Loaded season')
print('Computing lineups for all teams in all games...')
for game in tqdm(season):
print('Computing lineups for {}'.format(game))
home_team = game.home_team
away_team = game.away_team
home_lineups = game.lineup_combinations(home_team)
away_lineups = game.lineup_combinations(away_team)
try:
for lineup in home_lineups:
home_timestream = game.time_by_lineup(lineup)
for lineup in away_lineups:
away_timestream = game.time_by_lineup(lineup)
home_minutes = compute_ts_length(home_timestream)
away_minutes = compute_ts_length(away_timestream)
print('Home team: {} minutes, Away team: {} minutes'.format(home_minutes, away_minutes))
except Exception as ex:
print('Oh no, something terrible happened while computing lineups for {}'.format(game))
print(ex)
def import_pbp(pbp_file):
print('importing {}'.format(pbp_file))
json_data = json.load(open(pbp_file, 'r'))
game_id = json_data['league']['season']['eventType'][0]['events'][0]['eventId']
print(game_id)
pbp.update({'league.season.eventType.0.events.0.eventId': game_id}, json_data, upsert=True)
def import_pbp_files(files):
for pbp_file in files:
import_pbp(pbp_file)
def initialize_seasons():
seasons.update({'season': 2013},
{'season': 2013,
'start': dt.datetime(year=2013, month=10, day=29),
'end': dt.datetime(year=2014, month=4, day=17),
'allStarGame': dt.datetime(year=2014, month=2, day=16)}, upsert=True)
seasons.update({'season': 2014},
{'season': 2014,
'start': dt.datetime(year=2014, month=10, day=28),
'end': dt.datetime(year=2015, month=4, day=16),
'allStarGame': dt.datetime(year=2015, month=2, day=15)}, upsert=True)
seasons.update({'season': 2015},
{'season': 2015,
'start': dt.datetime(year=2015, month=10, day=27),
'end': dt.datetime(year=2016, month=4, day=14),
'allStarGame': dt.datetime(year=2016, month=2, day=14)}, upsert=True)
seasons.update({'season': 2016},
{'season': 2016,
'start': dt.datetime(year=2016, month=10, day=25),
'end': dt.datetime(year=2017, month=4, day=15),
'allStarGame': dt.datetime(year=2017, month=2, day=19)}, upsert=True)
def update_game_times():
games = pbp.find({})
for game in games:
game_obj = Game(game['id'])
game['game_date'] = game_obj.date
# print('updating game {} on {}'.format(game_obj.id, game_obj.date))
pbp.update({'id': game_obj.id}, game)
def calc_all_player_times(year, recompute=False):
class TimeComputationError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
all_players = players.find({}, no_cursor_timeout=True).sort('id', pymongo.ASCENDING)
print('Loading the {}-{} NBA season'.format(year, year + 1))
season = Season(year)
print('Loaded season')
print('Computing time on court for all players in all games...')
for player_data in all_players:
player = Player(player_data['id'])
games_played = season.get_player_games_in_range(player)
for game in games_played:
print('Calculating time on court for {} ({}) in {} ({})'.format(player, player.id, game, game.id))
boxscore_minutes = game.player_boxscore(player)['total_seconds_played'] / 60.0
if boxscore_minutes > 0:
time_on_court = player.time_on_court(game, recompute=recompute)
computed_minutes = compute_ts_length(time_on_court, unit='minutes')
else:
# there's never anything to calculate anyway
computed_minutes = 0
if not abs(computed_minutes - boxscore_minutes) <= 0.5:
print('In computing playing time for {} ({}) in {} ({}):'.format(player, player.id, game, game.id),
file=sys.stderr)
print('Discrepancy between computed time: {0:2.2f}, and boxscore time: {1:2.2f}'.format(computed_minutes, boxscore_minutes),
file=sys.stderr)
#raise TimeComputationError('Discrepancy between computed time: {}, and boxscore time: {}'.format(computed_minutes, boxscore_minutes)
else:
print('{} played {} minutes in {}'.format(player, round(computed_minutes, 3), game))
del player
del games_played
def fix_broken_times_json(err_file):
data = json.load(open(err_file, 'r'))
fixes = data['fixes']
for fix in fixes:
game_id = fix['game_id']
game = Game(game_id)
player_id = fix['player_id']
player = Player(player_id)
time_data = [(dt.timedelta(seconds=t['start']), dt.timedelta(seconds=t['end'])) for t in fix['times']]
print('Updating playing time for {} ({}) in {} ({})'.format(player, player.id, game, game.id))
player.save_timestream(game, time_data)
#print(compute_ts_length(time_data, unit='minutes'))
boxscore_minutes = game.player_boxscore(player)['total_seconds_played'] / 60.0
computed_minutes = compute_ts_length(player.time_on_court(game, recompute=False), unit='minutes')
if not abs(computed_minutes - boxscore_minutes) <= 0.5:
err = colored('Discrepancy between computed time: {0: 2.2f} and boxscore time: {1:2.2f}'.format(computed_minutes, boxscore_minutes), 'red')
print(err)
else:
print('{} played {} minutes in {}'.format(player, round(computed_minutes, 3), game))
def fix_broken_times(err_file):
with open(err_file, 'r') as f:
for line in f:
matches = re.findall('\([\d]+\)', line)
if matches and matches != []:
ids = map(lambda x: int(x.replace('(', '').replace(')', '')), matches)
player_id, game_id = ids[0], ids[1]
player = Player(player_id)
game = Game(game_id)
print('Calculating time on court for {} ({}) in {} ({})'.format(player, player.id, game, game.id))
time_on_court = player.time_on_court(game, recompute=True)
computed_minutes = compute_ts_length(time_on_court, unit='minutes')
boxscore_minutes = game.player_boxscore(player)['totalSecondsPlayed'] / 60.0
if not abs(computed_minutes - boxscore_minutes) <= 1.0:
print('In computing playing time for {} ({}) in {} ({}):'.format(player, player.id, game, game.id), file=sys.stderr)
print('Discrepancy between computed time: {0:2.2f}, and boxscore time: {1:2.2f}'.format(computed_minutes, boxscore_minutes), file=sys.stderr)
else:
print('{} played {} minutes in {}'.format(player, round(computed_minutes, 3), game))
def compute_global_features(season, start_date=None, end_date=None, output_file=None):
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--operation', dest='operation')
parser.add_argument('-fn', '--firstname', dest='player_firstname')
parser.add_argument('-ln', '--lastname', dest='player_lastname')
parser.add_argument('-pt', '--plot_type', dest='plot_type', default='hexbin')
parser.add_argument('-gid', '--game_id', dest='game_id', type=int)
parser.add_argument('-if', '--input_file', dest='input_file', nargs='*')
parser.add_argument('-of', '--output_file', dest='output_file')
parser.add_argument('--game-date', dest='game_date')
parser.add_argument('--start-date', dest='start_date', type=lambda x: dt.datetime.strptime(x, '%Y-%m-%d').date())
parser.add_argument('--end-date', dest='end_date', type=lambda x: dt.datetime.strptime(x, '%Y-%m-%d').date())
parser.add_argument('--ignore-dates', dest='ignore_dates', type=lambda x: dt.datetime.strptime(x, '%Y-%m-%d').date(), nargs='*')
parser.add_argument('--season', dest='season', type=int)
parser.add_argument('--method', dest='method', default='LogReg', nargs='*')
parser.add_argument('--window', dest='window', type=int, default=20)
args = parser.parse_args()
if args.operation == 'init_seasons':
initialize_seasons()
if args.operation == 'update_game_times':
update_game_times()
if args.operation == 'compute_timelines' and args.season:
compute_all_season_lineups(args.season)
if args.operation == 'import_pbp' and args.input_file:
import_pbp_files(args.input_file)
if args.operation == 'compute_player_times' and args.season:
calc_all_player_times(args.season)
if args.operation == 'fix_broken_times' and args.input_file:
fix_broken_times_json(args.input_file[0])
if args.operation == 'construct_global_features' and args.season:
season = Season(args.season)
if args.start_date:
start_date = dtparser.parse(args.start_date)
else:
start_date = season.start_date
if args.end_date:
end_date = dtparser.parse(args.end_date)
else:
end_date = season.end_date
str_format = '%Y-%m-%d'
if args.output_file:
output_file = args.output_file
else:
path = 'features-from-{}-to-{}'.format(start_date.strftime(str_format), end_date.strftime(str_format))
output_file = os.path.join('season_data', str(season.season), path)
print('Constructing global features for {}'.format(season))
construct_global_features(season, start_date=start_date, end_date=end_date, output_file=output_file)
if args.operation == 'construct_all_features' and args.season:
season = Season(args.season)
if args.window:
window = args.window
else:
window = 20
construct_all_features(season, window_size=window)
if args.operation == 'predict_game' and args.season and args.game_id:
season = Season(args.season)
game = Game(args.game_id)
if args.start_date:
start_date = dtparser.parse(args.start_date)
else:
start_date = season.start_date
if args.end_date:
end_date = dtparser.parse(args.end_date)
else:
end_date = season.end_date
str_format = '%Y-%m-%d'
if args.input_file:
input_file = args.input_file
else:
path = 'features-from-{}-to-{}'.format(start_date.strftime(str_format), end_date.strftime(str_format))
input_file = os.path.join('season_data', str(season.season), path)
if os.path.exists(input_file):
predict_game_outcome(input_file, game, season)
else:
print('Only precomputed features currently supported!')
if args.operation == 'predict_game' and args.season and args.game_date:
season = Season(args.season)
game_date = dtparser.parse(args.game_date)
if args.start_date:
start_date = dtparser.parse(args.start_date)
else:
start_date = season.start_date
if args.end_date:
end_date = dtparser.parse(args.end_date)
else:
end_date = season.end_date
if args.method:
method = args.method
else:
method = 'LogReg'
predict_game_day(game_date, season, start_date, end_date, method=method)
if args.operation == 'predict_season' and args.season:
season = Season(args.season)
odds_file = 'odds/{}/odds-from-{}-to-{}.csv'.format(args.season,
season.start_date.strftime('%Y-%m-%d'),
season.end_date.strftime('%Y-%m-%d'))
odds_data = pd.read_csv(odds_file)
for method in args.method:
print('Generating predictions using {}'.format(method))
results = predict_all_games(season, args.window, method=method)
game_ids = [res['game'].id for res in results]
data = pd.DataFrame(columns=['game_date',
'home_team',
'away_team',
'spread',
'prediction',
'prob_home_cover',
'prob_away_cover',
'prob_tie',
'actual_margin'],
index=game_ids)
data.index.name = 'game_id'
# import pdb; pdb.set_trace();
for i, result in enumerate(results):
game = result['game']
scores = result['classes']
score_distribution = result['probabilities']
prediction = result['prediction']
odds_for_game = odds_data[odds_data.game_id == game.id]
spread = odds_for_game.spread.values[0]
prob_home_cover = 0
prob_away_cover = 0
prob_tie = 0
probs_file = os.path.join('predictions', str(season.season), 'probabilities', str(game.id))
writer = csv.writer(open(probs_file, 'w'))
for score, prob in zip(scores, score_distribution):
if score < spread:
prob_away_cover += prob
elif score > spread:
prob_home_cover += prob
elif score == spread:
prob_tie += prob
writer.writerow([score, prob])
data.iloc[i]['game_date'] = game.date.strftime('%Y-%m-%d')
data.iloc[i]['home_team'] = game.home_team.id
data.iloc[i]['away_team'] = game.away_team.id
data.iloc[i]['spread'] = spread
data.iloc[i]['prediction'] = prediction
data.iloc[i]['prob_home_cover'] = prob_home_cover
data.iloc[i]['prob_away_cover'] = prob_away_cover
data.iloc[i]['prob_tie'] = prob_tie
data.iloc[i]['actual_margin'] = game.home_points - game.away_points
data.to_csv('predictions/{0}/predictions_{1}.csv'.format(season.season, method))
if args.operation == 'get-odds' and args.start_date and args.end_date and args.season:
#print(args.start_date, args.end_date)
game_odds = get_odds_from_donbest(args.start_date, args.end_date)
game_odds.to_csv('odds/{}/odds-from-{}-to-{}.csv'.format(args.season,
args.start_date.strftime('%Y-%m-%d'),
args.end_date.strftime('%Y-%m-%d')))
if args.operation == 'scrape_data' and args.start_date and args.end_date and args.ignore_dates and args.season:
get_all_data(args.start_date, args.end_date, args.season, args.ignore_dates)
if args.operation == 'plot_player_shots':
plot_player_shots(args.player_firstname, args.player_lastname, args.plot_type)
if args.operation == 'times_played':
player_id = look_up_player_id(args.player_firstname, args.player_lastname)
player_times_on_court(player_id)
if args.operation == 'check_consistency':
player_id = look_up_player_id(args.player_firstname, args.player_lastname)
check_sub_times_consistency(player_id)
if args.operation == 'quarter_starters' and args.game_id is not None:
q_starters = quarter_starters(args.game_id)
team1, team1_id, team2, team2_id = game_teams(args.game_id)
print('{} vs {}'.format(team1, team2))
for q in q_starters.keys():
player_ids = q_starters[q]
print('Quarter {} starters:'.format(q))
for player_id in player_ids:
fn, ln = look_up_player_name(player_id)
print(fn, ln)
if args.operation == 'construct_odds_csv' and args.input_file is not None and args.output_file is not None:
construct_odds_csv(args.input_file, args.output_file)
if args.operation == 'plot_all_game_charts' and args.game_id is not None:
plot_all_game_charts(args.game_id)
if args.operation == 'cluster_players_defense' and args.output_file is not None:
cluster_players_defense(args.output_file)
if args.operation == 'cluster_teams_defense' and args.output_file is not None:
cluster_teams_defense(args.output_file)