-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrade_all_seasons.py
297 lines (231 loc) · 9.93 KB
/
grade_all_seasons.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
import tools, info, grade
player_stats_path = "data/seasons/{}/players/stats.json"
player_grades_path = "data/seasons/{}/players/grades.json"
teams_path = "data/seasons/{}/teams/{}.json"
team_grades_path = "data/seasons/{}/teams/grades.json"
info_path = "data/seasons/{}/info.json"
standings_path = "data/seasons/{}/league/standings.json"
league_path = "data/seasons/{}/league/league.json"
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%"]
def get_team_categories(data):
categories=[
"FG%", "PTS", "FT%", "AST"
]
old_categories = []
for i in range(len(categories)):
category = categories[i]
cats = list(data[list(data.items())[0][0]]['stats']['Team'].keys())
# if category in cats:
# old_categories.append(category)
# for category in old_categories:
# categories.remove(category)
return categories
def get_categories(data):
old_categories = []
for i in range(len(categories)):
category = categories[i]
if category not in list(data[list(data)[0]]):
old_categories.append(category)
for category in old_categories:
categories.remove(category)
return categories
def clean_team_stats_quick(data):
stats = {}
for team in data:
j = {
"Tm": team,
"RRK": data[team]["standings"]["Rk"],
"Name": data[team]["standings"]["Team"],
"img": data[team]["img"],
'standing': data[team]["info"]["standing"],
"last_update": data[team]["last_update"]
}
stats[team] = j
return stats
def clean_player_stats(data):
categories = get_categories(data)
stats = {}
for player in data:
stats[player]= {}
for category in categories:
stats[player][category] = data[player][category]
stats[player]["G"] = data[player]["G"]
stats[player]["id"] = data[player]["id"]
stats[player]["img"] = data[player]["img"]
stats[player]["name"] = data[player]["Player"]
stats[player]["last_update"] = data[player]["last_update"]
stats[player]["age"] = data[player]["Age"]
stats[player]["pos"] = data[player]["Pos"]
stats[player]["link"] = data[player]["link"]
if isinstance(data[player]["Tm"], list):
team = data[player]["Tm"][-1]
else:
team = data[player]["Tm"]
stats[player]["team"] = team
return stats, categories
def clean_team_stats(data):
categories = get_team_categories(data)
stats = {}
for team in data:
stat_ranks = {}
for cat in data[team]["stats"]["Lg Rank"]:
if cat in categories:
stat_ranks[cat] = data[team]["stats"]["Lg Rank"][cat]
for cat in data[team]["stats"]["Opp Lg Rank"]:
if cat in categories:
stat_ranks[f'O_{cat}'] = data[team]["stats"]["Opp Lg Rank"][cat]
j = {
"Tm": team,
"RRK": data[team]["standings"]["Rk"],
"Name": data[team]["standings"]["Team"],
"img": data[team]["img"],
"Players": data[team]["roster"],
"stat_ranks": stat_ranks,
'standing': data[team]["info"]["standing"],
"last_update": data[team]["last_update"],
"record": data[team]["info"]["record"]
}
stats[team] = j
return stats, categories
def grade_players(data, categoires, year):
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
for category in ranks[player]:
score += ranks[player][category]
# divide total score by all categories used
player_grade = score / len(categories)
# 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 = grade.get_all_min_categories(player, ranks)
new_ranks[player]["top_category"] = [f"{category}: {min_value}" for category in min_categories]
max_categories, max_value = grade.get_all_max_categories(player, ranks)
new_ranks[player]["worst_category"] = [f"{category}: {max_value}" for category in max_categories]
sorted_players = {k: v for k, v in sorted(new_ranks.items(), key=lambda item: item[1]['grade'], reverse=True)}
team_stats = clean_team_stats_quick(tools.load(league_path.format(year)))
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
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(stats, player_grades, categories, year):
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 categories:
# 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
return sorted_teams
if __name__ == "__main__":
for season in info.seasons:
stats, categories = clean_player_stats(tools.load(player_stats_path.format(season)))
player_ranks = grade_players(stats, categories, season)
team_stats, team_categories = clean_team_stats(tools.load(league_path.format(season, season)))
ranks = grade_team(team_stats, player_ranks, team_categories, season)
tools.dump(team_grades_path.format(season), ranks)
for player in player_ranks:
player_ranks[player]["team_standing_string"] = ranks[player_ranks[player]["team"]]["standing"]
tools.dump(player_grades_path.format(season), player_ranks)