-
Notifications
You must be signed in to change notification settings - Fork 0
/
NhlElo.py
221 lines (168 loc) · 6.11 KB
/
NhlElo.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
import pandas as pd
import numpy as np
from tkinter import *
from tkintertable import TableCanvas
import matplotlib.pyplot as plt
k_factor = 10
def update_elo(w_elo, l_elo):
exp_win = expected_result(w_elo, l_elo)
change = k_factor * (1-exp_win)
w_elo = w_elo + change
l_elo = l_elo - change
return w_elo, l_elo
def expected_result(elo_a, elo_b):
expect = 1.0/(1+10**((elo_b - elo_a)/400))
return expect
df_lists = pd.DataFrame()
start_year = 2018
end_year = 2020
# scrapes data from hockeyreference.com
for year in range(start_year, end_year + 1):
k = 1
# 2005 was the lockout so there is no data to be scraped
if year == 2005:
print("2005 was the lockout")
else:
url = r'https://www.hockey-reference.com/leagues/NHL_' + str(year) + r'_games.html'
df_temp_reg = pd.DataFrame(pd.read_html(url)[0])
df_temp_reg['season'] = year
# use commented out code if playoff data is desired
try:
df_temp_post = pd.DataFrame(pd.read_html(url)[1])
df_temp_post['season'] = year
except IndexError as e:
k = 0
print('no playoffs available yet')
print(str(year) + " scraped")
df_lists = df_lists.append(df_temp_reg)
if k == 1:
df_lists.append(df_temp_post)
df_lists.rename(columns={'G': 'VisitingGoals',
'G.1': 'HomeGoals',
'Unnamed: 5': 'OTSO',
'season': 'Season'},
inplace=True)
df_lists.drop(['Att.', 'LOG', 'Notes'], axis=1, inplace=True)
df_lists.loc[:, 'Date'] = pd.to_datetime(df_lists['Date'])
replace_dict = {'Home': {'Atlanta Thrashers': 'Winnipeg Jets',
'Mighty Ducks of Anaheim': 'Anaheim Ducks',
'Phoenix Coyotes': 'Arizona Coyotes'},
'Visitor': {'Atlanta Thrashers': 'Winnipeg Jets',
'Mighty Ducks of Anaheim': 'Anaheim Ducks',
'Phoenix Coyotes': 'Arizona Coyotes'}}
df_lists.replace(replace_dict, inplace=True)
ind = df_lists['OTSO'].isna()
df_lists.loc[ind, 'OTSO'] = 'REG'
# how come this doesnt work??? teams = df_lists['Home'].unique().sort()
teams = df_lists['Home'].unique()
teams.sort()
games = df_lists.reset_index()
games.drop('index', axis=1, inplace=True)
class TeamElos(dict):
def __init__(self, teams):
super().__init__(self)
for team in teams:
self[team] = 1500
self.history = HistoryList(teams)
def plot_history(self, *args):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim([1350,1700])
plt.xticks(rotation=45)
for team in args:
cax = plt.plot(
self.history[team]['Date'],
self.history[team]['Elo Rating'],
label = team)
plt.title(f'{args} Elo History')
plt.legend()
plt.show()
def update(self, game_tuple):
if game_tuple.VisitingGoals > game_tuple.HomeGoals:
winning_team = game_tuple.Visitor
losing_team = game_tuple.Home
else:
winning_team = game_tuple.Home
losing_team = game_tuple.Visitor
self[winning_team], self[losing_team] = update_elo(
self[winning_team],
self[losing_team])
self.history.update(
winning_team = winning_team,
losing_team = losing_team,
win_elo = self[winning_team],
lose_elo = self[losing_team],
date = game_tuple.Date
)
class HistoryList(dict):
def __init__(self, teams):
super().__init__(self)
for team in teams:
self[team] = pd.DataFrame(columns = ['Date', 'Elo Rating'])
def update(self, winning_team, losing_team, win_elo, lose_elo, date):
self[winning_team] = self[winning_team].append(
{'Date': date,'Elo Rating': win_elo},
ignore_index = True)
self[losing_team]= self[losing_team].append(
{'Date': date,'Elo Rating': lose_elo},
ignore_index = True)
elos = TeamElos(teams)
for row in games.itertuples():
if row.Date.date() < pd.Timestamp.today().date():
elos.update(row)
elos.plot_history('Toronto Maple Leafs', 'Montreal Canadiens')
elos = pd.DataFrame(
elos,
index=['Elo Rating']).T.sort_values(by='Elo Rating', ascending=False)
ind = games['Date'] > pd.Timestamp('today')
games_future = games.loc[ind, :].reset_index()
games_future.drop('index', axis=1, inplace=True)
games_prediction = games_future.loc[0:10, ['Date', 'Visitor', 'Home']]
games_prediction = pd.DataFrame.merge(
games_prediction,
elos,
left_on='Visitor',
right_index=True)
games_prediction.rename(
columns={'Elo Rating': 'Visitor Elo Rating'},
inplace=True)
games_prediction = pd.DataFrame.merge(
games_prediction,
elos,
left_on='Home',
right_index=True)
games_prediction.rename(
columns={'Elo Rating': 'Home Elo Rating'},
inplace=True)
games_prediction['Home Win%'] = expected_result(
games_prediction['Home Elo Rating'],
games_prediction['Visitor Elo Rating'])
games_prediction['Visitor Win%'] = 1-games_prediction['Home Win%']
games_prediction.drop(
['Visitor Elo Rating', 'Home Elo Rating'],
axis=1,
inplace=True)
games_prediction = games_prediction[['Date', 'Visitor', 'Visitor Win%', 'Home', 'Home Win%']]
elos.to_csv('elos.csv', index=True)
games_prediction.to_csv('prediction.csv', index=False)
root = Tk()
root.title('NHL Elo Predictions')
root.geometry('800x600')
one = Label(root, text='NHL Elo Rankings', bg='blue', fg='white')
one.pack()
tframe = Frame(root)
tframe.pack()
table = TableCanvas(tframe, rowheaderwidth=0,
cellwidth=100, editable=False, width=325)
table.importCSV('elos.csv')
table.sortTable(columnName='Elo Rating', reverse=1)
colIndex = 1
table.show()
two = Label(root, text='Games Today', bg='blue', fg='white')
two.pack()
tframe2 = Frame(root)
tframe2.pack()
table2 = TableCanvas(tframe2, rowheaderwidth=0, editable=False, width=725)
table2.importCSV('prediction.csv')
table2.show()
root.mainloop()