-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrade.py
465 lines (369 loc) · 15.8 KB
/
grade.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
import json
import tools
import os
import getters
from datetime import datetime, timedelta
import heapq
ignore_categories = {
"PG": ["BLK", "TRB", "2P%"],
"SG": ["BLK", "TRB", "2P%"],
"SF": [],
"PF": [],
"C": []
}
def get_top_three_categories(ranks, player):
# Get the top three categories based on their scores
top_three = heapq.nlargest(3, ranks[player].items(), key=lambda x: x[1])
# Extract and return only the category names
return [category for category, score in top_three]
def should_ignore(player, ranks, category):
how_bad = ranks[player][category] / len(ranks.keys())
if how_bad >= .5 and how_bad <= .8:
return True
return False
def get_ignore_categories(player, pos, ranks):
ignore = []
for category in ignore_categories[pos]:
if should_ignore(player, ranks, category):
ignore.append(category)
return ignore
def get_all_min_categories(player, ranks):
min_value = min(ranks[player].values())
min_categories = [k for k, v in ranks[player].items() if v == min_value]
return min_categories, min_value
def get_all_max_categories(player, ranks):
max_value = max(ranks[player].values())
max_categories = [k for k, v in ranks[player].items() if v == max_value]
return max_categories, max_value
def grade_players(year, date_string,
categories=[
"PTS", "AST", "TRB", "FG%", "FT%", "3P%", "STL", "BLK",
"MP", "PER", "TS%", "WS", "BPM", "2P%", "OWS", "DWS",
"WS/48", "USG%", "OBPM", "DBPM", "VORP", "eFG%"
],
all_time_categories=["eFG%", "2P%","FG%", "AST", "PTS", "TS%", "FT%"],
extra_categories=[],
):
categories = list(categories + extra_categories)
stats = getters.get_player_stats(date_string, categories)
ranks = {}
for player in stats:
ranks[player] = {}
topster_averages = []
def rank(category):
category_rankings = []
for player in stats:
if stats[player][category] != "":
category_rankings.append([player, float(stats[player][category])])
else:
category_rankings.append([player, 0])
category_rankings = sorted(category_rankings, key=lambda x: x[1])
category_rankings.reverse()
if category in all_time_categories:
avg = 0
topsters = category_rankings[0:10]
for player in topsters:
avg += player[1]
topster_averages.append([category, round(avg / 10, 2)])
for i in range(len(category_rankings)):
name = category_rankings[i][0]
value = category_rankings[i][1]
ranks[name][category] = i + 1
for category in categories:
rank(category)
league_grade = 0
for t in topster_averages:
if t[0] in ["PTS", "AST"]:
league_grade += t[1] / 2
else:
league_grade += t[1] * 10
league_grade = round((league_grade / len(all_time_categories)) * 11, 2)
new_ranks = {}
for player in ranks:
score = 0
# get the three highest values in ranks[player][category]
ignored = get_ignore_categories(player, stats[player]["pos"], ranks)
count = 0
for category in ranks[player]:
if category not in ignored:
score += ranks[player][category]
count += 1
# divide total score by all categories used
player_grade = score / count
# divide by all players then multiply by 100
player_grade = (player_grade / len(list(stats))) * 100
# divide score by league grade times 2
player_grade = player_grade / (league_grade * 2)
# subtract from 100
player_grade = 100 - (player_grade * 100)
player_grade += (5 * (league_grade/100))
player_grade -= (2.5 - (league_grade/100))
new_ranks[player] = {}
new_ranks[player]["grade"] = round(player_grade, 2)
new_ranks[player]["name"] = stats[player]["name"]
new_ranks[player]["league_grade"] = league_grade
new_ranks[player]["year"] = year
new_ranks[player]["games_played"] = int(stats[player]["G"])
new_ranks[player]["team"] = stats[player]["team"]
new_ranks[player]["img"] = stats[player]["img"]
new_ranks[player]["id"] = stats[player]["id"]
new_ranks[player]["age"] = stats[player]["age"]
new_ranks[player]["pos"] = stats[player]["pos"]
new_ranks[player]["link"] = stats[player]["link"]
new_ranks[player]["last_update"] = stats[player]["last_update"]
min_categories, min_value = get_all_min_categories(player, ranks)
new_ranks[player]["top_category"] = [f"{category}: {min_value}" for category in min_categories]
max_categories, max_value = get_all_max_categories(player, ranks)
new_ranks[player]["worst_category"] = [f"{category}: {max_value}" for category in max_categories]
new_ranks[player]["ignored_categories"] = ignored
new_ranks[player]["full_grade"] = {}
for category in ranks[player]:
new_ranks[player]["full_grade"][category] = ranks[player][category]
sorted_players = {k: v for k, v in sorted(new_ranks.items(), key=lambda item: item[1]['grade'], reverse=True)}
team_stats = getters.get_team_stats_quick(date_string)
for player in sorted_players:
team = sorted_players[player]["team"]
sorted_players[player]["team_standing_string"] = team_stats[team]["standing"]
sorted_players[player]["team_league_ranking"] = team_stats[team]["RRK"]
sorted_players[player]["team_name"] = team_stats[team]["Name"]
sorted_players[player]["team_img"] = team_stats[team]["img"]
placement = 1
for player in sorted_players:
sorted_players[player]["rank"] = placement
placement += 1
date_obj = datetime.strptime(date_string, "%m_%d_%Y")
yesterday = date_obj - timedelta(days=1)
yesterday_str = yesterday.strftime("%m_%d_%Y")
try:
yesterday_grades = getters.get_grades(yesterday_str)
except:
yesterday_grades = {}
for player in sorted_players:
try:
sorted_players[player]["change"] = yesterday_grades[player]["rank"] - sorted_players[player]["rank"]
except:
sorted_players[player]["change"] = 0
return sorted_players
def get_ordinal(i):
SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
if 10 <= i % 100 <= 20:
return 'th'
else:
return SUFFIXES.get(i % 10, 'th')
def grade_team(year, date_string,
categories=[
"PTS", "AST", "TRB", "FG%", "FT%", "3P%", "STL", "BLK",
"MP", "PER", "TS%", "WS", "BPM", "2P%"
],
extra_categories=[],
):
categories = list(categories + extra_categories)
for i in range(len(categories)):
categories.append(f'O_{categories[i]}')
stats = getters.get_team_stats(date_string, categories)
player_grades = getters.get_grades(date_string)
f = {}
east_teams = 1
west_teams = 1
for team in stats:
if "east" in stats[team]["standing"].lower():
stats[team]["conference"] = "East"
stats[team]["conference_rank"] = east_teams
east_teams += 1
else:
stats[team]["conference"] = "West"
stats[team]["conference_rank"] = west_teams
west_teams += 1
stats[team]["standing"] = f'{stats[team]["conference_rank"]}{get_ordinal(stats[team]["conference_rank"])} in {stats[team]["conference"]}'
grades = []
for player in stats[team]["Players"]:
try:
grades.append(player_grades[player]["grade"])
except KeyError:
pass
grades = sorted(grades, reverse=True)
grades = grades[0:8]
grade_avg = round((sum(grades) / len(grades)), 2)
score = 0
for cat in stats[team]["stat_ranks"]:
score += int(stats[team]["stat_ranks"][cat])
score += int(stats[team]["RRK"])*2.5
grade = 100 - round(score/len(categories), 2)
grade = round((grade*2 + grade_avg)/3, 2)
f[team] = {}
f[team] = stats[team]
del f[team]["stat_ranks"]
del f[team]["Players"]
f[team]["avg_grade"] = grade_avg
f[team]['score'] = grade
f[team]['last_update'] = stats[team]["last_update"]
f[team]['link'] = "https://www.basketball-reference.com/teams/{}/{}.html".format(year, team)
sorted_teams = {k: v for k, v in sorted(f.items(), key=lambda item: item[1]['score'], reverse=True)}
placement = 1
for player in sorted_teams:
sorted_teams[player]["rank"] = placement
placement += 1
date_obj = datetime.strptime(date_string, "%m_%d_%Y")
yesterday = date_obj - timedelta(days=1)
yesterday_str = yesterday.strftime("%m_%d_%Y")
try:
yesterday_grades = getters.get_grades_team(yesterday_str)
except:
yesterday_grades = {}
sorted_players = sorted_teams
for player in sorted_players:
try:
sorted_players[player]["change"] = yesterday_grades[player]["rank"] - sorted_players[player]["rank"]
except:
sorted_players[player]["change"] = 0
return sorted_players
def archive(year):
r = {
"players": {},
"teams": {},
"league_progression": [],
"final_results": {}
}
player_path = f"data/archive/{year}/stat/players/grades"
team_path = f"data/archive/{year}/team/grades"
final_results_path = f"data/seasons/{year}/info.json"
player_results_path = f"data/seasons/{year}/players/grades.json"
team_results_path = f"data/seasons/{year}/teams/grades.json"
for filename in os.listdir(player_path):
player_grades = tools.load(os.path.join(player_path, filename))
team_grades = tools.load(os.path.join(team_path, filename))
r["league_progression"].append(
{
"grade": player_grades[list(player_grades.keys())[0]]["league_grade"],
"date": filename.split(".")[0]
}
)
for player in player_grades:
if player not in list(r["players"].keys()):
r["players"][player] = []
r["players"][player].append(
{
"grade": player_grades[player]["grade"],
"rank": player_grades[player]["rank"],
"games_played": player_grades[player]["games_played"],
"team": player_grades[player]["team"],
"date": filename.split(".")[0],
}
)
for team in team_grades:
if team not in list(r["teams"].keys()):
r["teams"][team] = []
r["teams"][team].append( {
"score": team_grades[team]["score"],
"rank": team_grades[team]["rank"],
"avg_grade": team_grades[team]["avg_grade"],
"standing": team_grades[team]["standing"],
"date": filename.split(".")[0],
})
final_player_grades = tools.load(player_results_path)
final_team_grades = tools.load(team_results_path)
final_results = tools.load(final_results_path)
r["final_results"] = final_results
for data in r["league_progression"]:
data["date"] = datetime.strptime(data["date"], "%m_%d_%Y")
r["league_progression"].sort(key=lambda x: x['date'])
for data in r["league_progression"]:
data["date"] = data["date"].strftime("%m_%d_%Y")
r["league_progression"].append(
{
"grade": final_player_grades[list(final_player_grades.keys())[0]]["league_grade"],
"date": "Final"
}
)
for player in final_player_grades:
# sort
for data in r["players"][player]:
data["date"] = datetime.strptime(data["date"], "%m_%d_%Y")
r["players"][player].sort(key=lambda x: x['date'])
for data in r["players"][player]:
data["date"] = data["date"].strftime("%m_%d_%Y")
if player in list(r["players"].keys()):
r["players"][player].append(
{
"grade": final_player_grades[player]["grade"],
"rank": final_player_grades[player]["rank"],
"games_played": final_player_grades[player]["games_played"],
"team": final_player_grades[player]["team"],
"img": final_player_grades[player]["img"],
"id": final_player_grades[player]["id"],
"link": final_player_grades[player]["link"],
"team_img": final_player_grades[player]["team_img"],
"team": final_player_grades[player]["team"],
"name": final_player_grades[player]["name"],
}
)
for team in final_team_grades:
# sort
for data in r["teams"][team]:
data["date"] = datetime.strptime(data["date"], "%m_%d_%Y")
r["teams"][team].sort(key=lambda x: x['date'])
for data in r["teams"][team]:
data["date"] = data["date"].strftime("%m_%d_%Y")
r["teams"][team].append (
{
"score": final_team_grades[team]["score"],
"rank": final_team_grades[team]["rank"],
"avg_grade": final_team_grades[team]["avg_grade"],
"standing": final_team_grades[team]["standing"],
"img": final_team_grades[team]["img"],
"link": final_team_grades[team]["link"],
"name": final_team_grades[team]["Name"],
"conference": final_team_grades[team]["conference"],
"conference_rank": final_team_grades[team]["conference_rank"],
"record": final_team_grades[team]["record"]
}
)
return r
def soft_archive(year, most_recent_date=""):
r = {
"players": {},
"teams": {},
"league_progression": [],
"final_results": {}
}
player_path = f"data/archive/{year}/stat/players/grades"
team_path = f"data/archive/{year}/team/grades"
for filename in os.listdir(player_path):
player_grades = tools.load(os.path.join(player_path, filename))
team_grades = tools.load(os.path.join(team_path, filename))
r["league_progression"].append(
{
"grade": player_grades[list(player_grades.keys())[0]]["league_grade"],
"date": filename.split(".")[0]
}
)
for player in player_grades:
if player not in list(r["players"].keys()):
r["players"][player] = []
r["players"][player].append(
{
"grade": player_grades[player]["grade"],
"rank": player_grades[player]["rank"],
"games_played": player_grades[player]["games_played"],
"team": player_grades[player]["team"],
"date": filename.split(".")[0],
}
)
for team in team_grades:
if team not in list(r["teams"].keys()):
r["teams"][team] = []
r["teams"][team].append( {
"score": team_grades[team]["score"],
"rank": team_grades[team]["rank"],
"avg_grade": team_grades[team]["avg_grade"],
"standing": team_grades[team]["standing"],
"date": filename.split(".")[0],
})
for data in r["league_progression"]:
data["date"] = datetime.strptime(data["date"], "%m_%d_%Y")
r["league_progression"].sort(key=lambda x: x['date'])
for data in r["league_progression"]:
data["date"] = data["date"].strftime("%m_%d_%Y")
return r
if __name__ == "__main__":
tools.dump("data/archive/2024/results.json", archive("2024"))