-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathExponential_Moving_Average.py
319 lines (195 loc) · 6.76 KB
/
Exponential_Moving_Average.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
matches_df = pd.read_csv('final_df.csv',parse_dates = [5,6],infer_datetime_format=True)
# In[ ]:
#we need a formula to calculate the alpha (decay factor for the exponential moving average)
#we want it to be based on the amount of games played by a player
# let's see the distribution of total games played by players
# In[2]:
#get player id's
players = []
for item in matches_df['player_id'].unique():
players.append(item)
for item in matches_df['opponent_id'].unique():
if item not in players:
players.append(item)
players
# In[3]:
len(players)
# In[148]:
players_games = dict()
for player in players:
temp = matches_df.loc[(matches_df['player_id']==player)|(matches_df['opponent_id']==player)]
players_games[player] = len(temp)
# In[102]:
#average numbers of games played
sum(players_games.values())/len(players_games)
# In[109]:
import seaborn as sns
sns.displot(data = players_games.values(),kind='kde',aspect=2.5)
# In[111]:
#we can see that very few players have a total number of games played above 200
#our alpha will be defined as alpha = 2/(N+1)
# In[154]:
matches_df
# In[91]:
#FUNCTION
#Function to get exp moving average
# N ---> elements to put into moving average(variable , last games in a 6-week period)
# alpha --> decay factor = 2/(N+1)
#function that computes and sets ema for specific column of data
import numpy as np
def exp_moving_average(data,player,column1,column2,dest_col1,dest_col2):
#get relevant data
temp = data.loc[(data['player_id']==player) | (data['opponent_id']==player)].copy()
temp.reset_index(inplace=True)
aa = dict()
index = temp.index
orig_index = temp['index']
#print(index)
#print(orig_index)
for i in range(0,len(temp)):
if temp.iloc[i]['player_id'] == player:
if np.isnan(temp.iloc[i][column1])==True:
continue
aa[str(orig_index[i]) + 'a'] = temp.iloc[i][column1]
if temp.iloc[i]['opponent_id'] == player:
if np.isnan(temp.iloc[i][column2])==True:
continue
aa[str(orig_index[i]) + 'b'] = temp.iloc[i][column2]
#print(counter1)
#print(counter2)
ema = dict()
wcount = 0
wsum = 0
alpha = 2/(len(aa) + 1)
factor = 1 - alpha
bb = list(aa.values())
cc = list(aa.keys())
for j in range(1,len(aa)):
wsum = bb[j-1] + factor*wsum
#print(wsum)
wcount = 1 + factor*wcount
#print(wcount)
ema[cc[j]] = wsum/wcount
#print(ema)
for key,value in ema.items():
if key[len(key)-1] == 'a':
data.at[int(key[:len(key)-1]),dest_col1] = value
if key[len(key)-1] == 'b':
data.at[int(key[:len(key)-1]),dest_col2] = value
del temp
return
# In[87]:
tryout = exp_moving_average(matches_df,'roger-federer','service_pca_1','service_pca_2','service_pca_1_ema','service_pca_2_ema')
# In[20]:
list(tryout.opponent_id)
# In[205]:
federer = matches_df.loc[(matches_df['player_id']=='roger-federer') | (matches_df['opponent_id']=='roger-federer')]
# In[206]:
federer.to_csv('federer.csv')
# In[43]:
list(federer.service_pca_2)
# In[91]:
list(matches_df.columns)
# In[207]:
#compute emas and assign them to our df
matches_df['service_pca_1_ema'] = None
matches_df['service_pca_2_ema'] = None
matches_df['return_pca_1_ema'] = None
matches_df['return_pca_2_ema'] = None
i=0
j=0
for plyr in players:
exp_moving_average(matches_df,plyr,'service_pca_1','service_pca_2','service_pca_1_ema','service_pca_2_ema')
i=i+1
print('serve pca iterations : ',i)
for plyr in players:
exp_moving_average(matches_df,plyr,'return_pca_1','return_pca_2','return_pca_1_ema','return_pca_2_ema')
j=j+1
print('return pca iterations : ',j)
# In[93]:
matches_df
# In[211]:
#FUNCTION
#fill na values of moving averages with the last known moving average for every player
def get_last_ema(player,col1,col2,data,row):
#find first ema of given cols
temp = data.iloc[:row]
temp = temp.loc[(temp['player_id']==player)|(temp['opponent_id']==player)].copy()
#print(temp)
row1=0
row2=0
for i in range(len(temp)-1,0,-1):
if temp.iloc[i]['player_id'] == player:
if pd.isnull(temp.iloc[i][col1]):
continue
row1 = i
break
if temp.iloc[i]['opponent_id'] == player:
if pd.isnull(temp.iloc[i][col2]):
continue
row2 = i
break
#print(row1,row2)
if row1 != 0 :
last_ema = temp.iloc[row1][col1]
rowf = row1
if row2 != 0 :
last_ema = temp.iloc[row2][col2]
rowf = row2
del temp
if (row1 == 0) & (row2 == 0):
return 0,0
return last_ema,rowf
def get_nans(player,data,col1,col2):
temp = data.loc[(data['player_id']==player)|(data['opponent_id']==player)].copy()
temp.reset_index(inplace=True)
nanrows1 = []
nanrows2 = []
for i in range(0,len(temp)):
if temp.iloc[i]['player_id'] == player:
if pd.isnull(temp.iloc[i][col1]):
nanrows1.append(temp.iloc[i]['index'])
if temp.iloc[i]['opponent_id'] == player:
if pd.isnull(temp.iloc[i][col2]):
nanrows2.append(temp.iloc[i]['index'])
#fill nans
for item in nanrows1:
last_ema,rowf = get_last_ema(player,col1,col2,data,item)
if (last_ema!=0) & (rowf!=0):
data.at[item,col1] = last_ema
for item in nanrows2:
last_ema,rowf = get_last_ema(player,col1,col2,data,item)
if (last_ema!=0) & (rowf!=0):
data.at[item,col2] = last_ema
return
# In[201]:
get_nans('roger-federer',matches_df,'service_pca_1_ema','service_pca_2_ema')
# In[204]:
federer.loc[(federer['service_pca_1_ema'].isnull()) & (federer['player_id']=='roger-federer')]
# In[212]:
#fill nas for all players
i=0
for player in players:
get_nans(player,matches_df,'service_pca_1_ema','service_pca_2_ema')
get_nans(player,matches_df,'return_pca_1_ema','return_pca_2_ema')
i=i+1
print('iteration number :',i,' of ',len(players))
# In[213]:
matches_df
# In[214]:
matches_df.to_csv('final_df1.csv')
# In[220]:
#check the results on a excel file, we pick a random player (in this case carlos moya) and check
carlosmoya = matches_df.loc[(matches_df['player_id']=='carlos-moya')|(matches_df['opponent_id']=='carlos-moya')]
# In[221]:
carlosmoya.to_csv('carlos-moya.csv')
# In[ ]:
#moving averages calculations and na fill checks out
# In[227]:
matches_df.dropna(subset=['service_pca_1_ema','service_pca_2_ema','return_pca_1_ema','return_pca_2_ema'])
# In[ ]:
#we have a total of 132504 matches at our disposal for training and testing, which should be enough