Spaces:
Sleeping
Sleeping
Created probability engine file
Browse files- src/probability_engine.py +72 -0
src/probability_engine.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import random
|
| 3 |
+
import itertools
|
| 4 |
+
|
| 5 |
+
from data_loader import teams, team_map
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def elo_probability(teamA, teamB):
|
| 9 |
+
|
| 10 |
+
teamA = team_map.get(teamA.upper(), teamA.upper())
|
| 11 |
+
teamB = team_map.get(teamB.upper(), teamB.upper())
|
| 12 |
+
|
| 13 |
+
teamA_row = teams[teams['team'] == teamA]
|
| 14 |
+
teamB_row = teams[teams['team'] == teamB]
|
| 15 |
+
|
| 16 |
+
if teamA_row.empty:
|
| 17 |
+
return f"Error: Team {teamA} not found"
|
| 18 |
+
|
| 19 |
+
if teamB_row.empty:
|
| 20 |
+
return f"Error: Team {teamB} not found"
|
| 21 |
+
|
| 22 |
+
eloA = teamA_row['elo_rating'].values[0]
|
| 23 |
+
eloB = teamB_row['elo_rating'].values[0]
|
| 24 |
+
|
| 25 |
+
probA = 1 / (1 + 10 ** ((eloB - eloA) / 550))
|
| 26 |
+
|
| 27 |
+
return {
|
| 28 |
+
"teamA": teamA,
|
| 29 |
+
"teamB": teamB,
|
| 30 |
+
"probA": probA,
|
| 31 |
+
"probB": 1 - probA
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def simulate_match(teamA, teamB):
|
| 36 |
+
|
| 37 |
+
probs = elo_probability(teamA, teamB)
|
| 38 |
+
|
| 39 |
+
r = random.random()
|
| 40 |
+
|
| 41 |
+
if r < probs["probA"]:
|
| 42 |
+
return teamA
|
| 43 |
+
else:
|
| 44 |
+
return teamB
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def monte_carlo_group(group_name, simulations=3000):
|
| 48 |
+
|
| 49 |
+
group_teams = teams[teams["group"] == group_name]["team"].tolist()
|
| 50 |
+
|
| 51 |
+
qualify_counts = {team:0 for team in group_teams}
|
| 52 |
+
|
| 53 |
+
for _ in range(simulations):
|
| 54 |
+
|
| 55 |
+
results = {team:0 for team in group_teams}
|
| 56 |
+
|
| 57 |
+
for a,b in itertools.combinations(group_teams,2):
|
| 58 |
+
|
| 59 |
+
winner = simulate_match(a,b)
|
| 60 |
+
results[winner] += 2
|
| 61 |
+
|
| 62 |
+
standings = sorted(results.items(), key=lambda x:x[1], reverse=True)
|
| 63 |
+
|
| 64 |
+
qualify_counts[standings[0][0]] += 1
|
| 65 |
+
qualify_counts[standings[1][0]] += 1
|
| 66 |
+
|
| 67 |
+
output = {}
|
| 68 |
+
|
| 69 |
+
for team in qualify_counts:
|
| 70 |
+
output[team] = qualify_counts[team]/simulations
|
| 71 |
+
|
| 72 |
+
return output
|