File size: 13,367 Bytes
49a060f
 
 
 
 
 
38b12ed
49a060f
 
 
 
 
 
38b12ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
 
 
 
 
 
 
 
 
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
 
 
 
 
 
 
 
 
 
 
 
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
 
 
 
 
 
 
49a060f
 
 
 
 
 
 
 
 
9e6c24e
 
 
 
 
 
 
 
49a060f
 
9e6c24e
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
49a060f
 
 
 
9e6c24e
 
 
 
 
 
 
 
49a060f
9e6c24e
 
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
 
49a060f
 
 
 
9e6c24e
 
 
 
 
 
49a060f
 
 
9e6c24e
 
 
 
 
 
49a060f
9e6c24e
 
 
 
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
 
 
 
 
49a060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6c24e
 
 
 
 
49a060f
 
 
 
 
 
 
9e6c24e
 
 
 
 
 
 
 
49a060f
 
 
 
 
 
9e6c24e
 
 
 
 
 
49a060f
 
9e6c24e
 
 
 
 
 
49a060f
 
 
 
 
 
 
9e6c24e
 
 
 
 
49a060f
 
 
 
 
 
9e6c24e
 
 
 
 
 
 
 
49a060f
 
 
 
 
 
9e6c24e
 
 
 
 
 
49a060f
 
9e6c24e
 
 
 
 
 
49a060f
 
 
 
 
 
 
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
import os.path
from operator import itemgetter
from typing import Text, Tuple

import numpy as np
import pandas as pd
import requests

from configs.config import cfg
from configs.constants import DATA_ROOT
from ml.model import MLModel
from ml.utils import load_pickle

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)


class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO


class Predictor:
    """
    A match predictor using ML
    """

    def __init__(self, base_df: pd.DataFrame, model: MLModel):
        self.model = model
        self.base_df = base_df

    def find_stats(self, team):
        """

        :param team: Name of the team, eg: Qatar, etc.
        :return:
        """

        last_game = self.base_df[
            (self.base_df["home_team"] == team) | (self.base_df["away_team"] == team)
        ].tail(1)

        if last_game["home_team"].values[0] == team:
            team_rank = last_game["rank_home"].values[0]
            team_goals = last_game["home_goals_mean"].values[0]
            team_goals_l5 = last_game["home_goals_mean_l5"].values[0]
            team_goals_suf = last_game["home_goals_suf_mean"].values[0]
            team_goals_suf_l5 = last_game["home_goals_suf_mean_l5"].values[0]
            team_rank_suf = last_game["home_rank_mean"].values[0]
            team_rank_suf_l5 = last_game["home_rank_mean_l5"].values[0]
            team_gp_rank = last_game["home_game_points_rank_mean"].values[0]
            team_gp_rank_l5 = last_game["home_game_points_rank_mean_l5"].values[0]
        else:
            team_rank = last_game["rank_away"].values[0]
            team_goals = last_game["away_goals_mean"].values[0]
            team_goals_l5 = last_game["away_goals_mean_l5"].values[0]
            team_goals_suf = last_game["away_goals_suf_mean"].values[0]
            team_goals_suf_l5 = last_game["away_goals_suf_mean_l5"].values[0]
            team_rank_suf = last_game["away_rank_mean"].values[0]
            team_rank_suf_l5 = last_game["away_rank_mean_l5"].values[0]
            team_gp_rank = last_game["away_game_points_rank_mean"].values[0]
            team_gp_rank_l5 = last_game["away_game_points_rank_mean_l5"].values[0]

        return [
            team_rank,
            team_goals,
            team_goals_l5,
            team_goals_suf,
            team_goals_suf_l5,
            team_rank_suf,
            team_rank_suf_l5,
            team_gp_rank,
            team_gp_rank_l5,
        ]

    @staticmethod
    def find_features(team_1, team_2):
        """

        :param team_1:
        :param team_2:
        :return:
        """
        rank_dif = team_1[0] - team_2[0]
        goals_dif = team_1[1] - team_2[1]
        goals_dif_l5 = team_1[2] - team_2[2]
        goals_suf_dif = team_1[3] - team_2[3]
        goals_suf_dif_l5 = team_1[4] - team_2[4]
        goals_per_ranking_dif = (team_1[1] / team_1[5]) - (team_2[1] / team_2[5])
        dif_rank_agst = team_1[5] - team_2[5]
        dif_rank_agst_l5 = team_1[6] - team_2[6]
        dif_gp_rank = team_1[7] - team_2[7]
        dif_gp_rank_l5 = team_1[8] - team_2[8]

        return [
            rank_dif,
            goals_dif,
            goals_dif_l5,
            goals_suf_dif,
            goals_suf_dif_l5,
            goals_per_ranking_dif,
            dif_rank_agst,
            dif_rank_agst_l5,
            dif_gp_rank,
            dif_gp_rank_l5,
            1,
            0,
        ]

    def __predict(self, team_1: Text, team_2: Text):

        team_1_stat = self.find_stats(team_1)
        team_2_stat = self.find_stats(team_2)

        features_g1 = self.find_features(team_1_stat, team_2_stat)
        features_g2 = self.find_features(team_2_stat, team_1_stat)

        probs_g1 = self.model.predict_proba([features_g1])
        probs_g2 = self.model.predict_proba([features_g2])
        team_1_prob_g1 = probs_g1[0][0]
        team_1_prob_g2 = probs_g2[0][1]
        team_2_prob_g1 = probs_g1[0][1]
        team_2_prob_g2 = probs_g2[0][0]

        team_1_prob = (probs_g1[0][0] + probs_g2[0][1]) / 2
        team_2_prob = (probs_g2[0][0] + probs_g1[0][1]) / 2

        return (
            team_1_prob_g1,
            team_1_prob_g2,
            team_1_prob,
            team_2_prob,
            team_2_prob_g1,
            team_2_prob_g2,
        )

    def predict(self, team_1: Text, team_2: Text) -> Tuple[bool, Text, float]:
        """

        :param team_1:
        :param team_2:
        :return:
        """
        draw = False
        (
            team_1_prob_g1,
            team_1_prob_g2,
            team_1_prob,
            team_2_prob,
            team_2_prob_g1,
            team_2_prob_g2,
        ) = self.__predict(team_1, team_2)
        winner, winner_proba = "", 0.0
        if ((team_1_prob_g1 > team_2_prob_g1) & (team_2_prob_g2 > team_1_prob_g2)) | (
            (team_1_prob_g1 < team_2_prob_g1) & (team_2_prob_g2 < team_1_prob_g2)
        ):
            draw = True

        elif team_1_prob > team_2_prob:
            winner = team_1
            winner_proba = team_1_prob

        elif team_2_prob > team_1_prob:
            winner = team_2
            winner_proba = team_2_prob
        return draw, winner, winner_proba

    def predict_all_matches(self) -> Text:
        """
        Predict all the matches in the tournament
        :return:
        """
        result = ""
        data = load_pickle(os.path.join(DATA_ROOT, cfg.data.table_matches))
        table = data["table"]
        matches = data["matches"]
        advanced_group, last_group = [], ""

        for teams in matches:
            draw = False
            (
                team_1_prob_g1,
                team_1_prob_g2,
                team_1_prob,
                team_2_prob,
                team_2_prob_g1,
                team_2_prob_g2,
            ) = self.__predict(teams[1], teams[2])
            winner, winner_proba = "", 0.0
            if (
                (team_1_prob_g1 > team_2_prob_g1) & (team_2_prob_g2 > team_1_prob_g2)
            ) | ((team_1_prob_g1 < team_2_prob_g1) & (team_2_prob_g2 < team_1_prob_g2)):
                draw = True
                for i in table[teams[0]]:
                    if i[0] == teams[1] or i[0] == teams[2]:
                        i[1] += 1

            elif team_1_prob > team_2_prob:
                winner = teams[1]
                winner_proba = team_1_prob
                for i in table[teams[0]]:
                    if i[0] == teams[1]:
                        i[1] += 3

            elif team_2_prob > team_1_prob:
                winner = teams[2]
                winner_proba = team_2_prob
                for i in table[teams[0]]:
                    if i[0] == teams[2]:
                        i[1] += 3

            for i in table[teams[0]]:  # adding tiebreaker (probs per game)
                if i[0] == teams[1]:
                    i[2].append(team_1_prob)
                if i[0] == teams[2]:
                    i[2].append(team_2_prob)

            if last_group != teams[0]:
                if last_group != "":
                    result += "\n"
                    result += "Group %s advanced: \n" % last_group
                    for i in table[last_group]:  # adding tiebreaker
                        i[2] = np.mean(i[2])

                    final_points = table[last_group]
                    final_table = sorted(
                        final_points, key=itemgetter(1, 2), reverse=True
                    )
                    advanced_group.append([final_table[0][0], final_table[1][0]])
                    for i in final_table:
                        result += "%s -------- %d\n" % (i[0], i[1])
                result += "\n"
                result += (
                    "-" * 10
                    + " Starting Analysis for Group %s " % (teams[0])
                    + "-" * 10
                    + "\n"
                )

            if draw is False:
                result += "Group %s - %s vs. %s: Winner %s with %.2f probability\n" % (
                    teams[0],
                    teams[1],
                    teams[2],
                    winner,
                    winner_proba,
                )
            else:
                result += "Group %s - %s vs. %s: Draw\n" % (
                    teams[0],
                    teams[1],
                    teams[2],
                )
            last_group = teams[0]
        result += "\n"
        result += "Group %s advanced: \n" % last_group

        for i in table[last_group]:  # adding tiebreaker
            i[2] = np.mean(i[2])

        final_points = table[last_group]
        final_table = sorted(final_points, key=itemgetter(1, 2), reverse=True)
        advanced_group.append([final_table[0][0], final_table[1][0]])
        for i in final_table:
            result += "%s -------- %d\n" % (i[0], i[1])

        advanced = advanced_group
        playoffs = {
            "Round of 16": [],
            "Quarter-Final": [],
            "Semi-Final": [],
            "Final": [],
        }

        for p in playoffs.keys():
            playoffs[p] = []

        actual_round = ""
        next_rounds = []

        for p in playoffs.keys():
            if p == "Round of 16":
                control = []
                for a in range(0, len(advanced * 2), 1):
                    if a < len(advanced):
                        if a % 2 == 0:
                            control.append((advanced * 2)[a][0])
                        else:
                            control.append((advanced * 2)[a][1])
                    else:
                        if a % 2 == 0:
                            control.append((advanced * 2)[a][1])
                        else:
                            control.append((advanced * 2)[a][0])
                playoffs[p] = [
                    [control[c], control[c + 1]]
                    for c in range(0, len(control) - 1, 1)
                    if c % 2 == 0
                ]

                for i in range(0, len(playoffs[p]), 1):
                    game = playoffs[p][i]

                    home = game[0]
                    away = game[1]

                    (
                        team_1_prob_g1,
                        team_1_prob_g2,
                        team_1_prob,
                        team_2_prob,
                        team_2_prob_g1,
                        team_2_prob_g2,
                    ) = self.__predict(home, away)
                    if actual_round != p:
                        result += "-" * 10 + "\n"
                        result += "Starting simulation of %s\n" % p
                        result += "-" * 10 + "\n"

                    if team_1_prob < team_2_prob:
                        result += "%s vs. %s: %s advances with prob %.2f\n" % (
                            home,
                            away,
                            away,
                            team_2_prob,
                        )
                        next_rounds.append(away)
                    else:
                        result += "%s vs. %s: %s advances with prob %.2f\n" % (
                            home,
                            away,
                            home,
                            team_1_prob,
                        )
                        next_rounds.append(home)

                    game.append([team_1_prob, team_2_prob])
                    playoffs[p][i] = game
                    actual_round = p

            else:
                playoffs[p] = [
                    [next_rounds[c], next_rounds[c + 1]]
                    for c in range(0, len(next_rounds) - 1, 1)
                    if c % 2 == 0
                ]
                next_rounds = []
                for i in range(0, len(playoffs[p])):
                    game = playoffs[p][i]
                    home = game[0]
                    away = game[1]

                    (
                        team_1_prob_g1,
                        team_1_prob_g2,
                        team_1_prob,
                        team_2_prob,
                        team_2_prob_g1,
                        team_2_prob_g2,
                    ) = self.__predict(home, away)
                    if actual_round != p:
                        result += "-" * 10 + "\n"
                        result += "Starting simulation of %s\n" % p
                        result += "-" * 10 + "\n"

                    if team_1_prob < team_2_prob:
                        result += "%s vs. %s: %s advances with prob %.2f \n" % (
                            home,
                            away,
                            away,
                            team_2_prob,
                        )
                        next_rounds.append(away)
                    else:
                        result += "%s vs. %s: %s advances with prob %.2f \n" % (
                            home,
                            away,
                            home,
                            team_1_prob,
                        )
                        next_rounds.append(home)
                    game.append([team_1_prob, team_2_prob])
                    playoffs[p][i] = game
                    actual_round = p

        print(result)
        return result