Skip to content

Instantly share code, notes, and snippets.

@russelllim22
Created December 2, 2022 10:51
Show Gist options
  • Save russelllim22/fa6d194d9f128fd8225786cf1ac4bc59 to your computer and use it in GitHub Desktop.
Save russelllim22/fa6d194d9f128fd8225786cf1ac4bc59 to your computer and use it in GitHub Desktop.
import random
import pandas as pd
results_df = pd.read_csv('results_tally_blank.csv')
results_df.set_index("Country", inplace=True)
group_A = [{
"team": "Netherlands",
"rating": 1716
}, {
"team": "Senegal",
"rating": 1604
}]
group_B = [{
"team": "England",
"rating": 1756
}, {
"team": "United States",
"rating": 1653
}]
# ... and so on up to Group H
def play_match(team1, team2, round):
r_diff = team2["rating"] - team1["rating"]
pr_team1_win = 1 / (1 + 10**(r_diff / 400))
if random.random() < pr_team1_win:
new_rating = team1["rating"] + 60 * (1 - pr_team1_win)
winner = {"team": team1["team"], "rating": new_rating}
loser = team2
else:
new_rating = team2["rating"] + 60 * pr_team1_win
winner = {"team": team2["team"], "rating": new_rating}
loser = team1
results_df.loc[winner["team"]][round] += 1
results_df.loc[loser["team"]][round] += 1
return winner
# https://www.worldcup2022football.co.uk/wc-2022-schedule.pdf
def simulate_knockout():
quarter_finals_teams = [
#Match 49
play_match(group_A[0], group_B[1], "Round of 16"),
#Match 50
play_match(group_C[0], group_D[1], "Round of 16"),
#Match 51
play_match(group_A[1], group_B[0], "Round of 16"),
#Match 52
play_match(group_C[1], group_D[0], "Round of 16"),
#Match 53
play_match(group_E[0], group_F[1], "Round of 16"),
#Match 54
play_match(group_G[0], group_H[1], "Round of 16"),
#Match 55
play_match(group_E[1], group_F[0], "Round of 16"),
#Match 56
play_match(group_G[1], group_H[0], "Round of 16")
]
QF = quarter_finals_teams
semi_finals_teams = [
#Match 57
play_match(QF[0], QF[1], "Quarter Finals"),
#Match 58
play_match(QF[4], QF[5], "Quarter Finals"),
#Match 59
play_match(QF[2], QF[3], "Quarter Finals"),
#Match 60
play_match(QF[6], QF[7], "Quarter Finals"),
]
SF = semi_finals_teams
final_teams = [
#Match 61
play_match(SF[0], SF[1], "Semi Finals"),
#Match 62
play_match(SF[2], SF[3], "Semi Finals"),
]
winner = play_match(final_teams[0], final_teams[1], "Final")
results_df.loc[winner["team"]]["Win"] += 1
return "one tournament done!"
import time
start_time = time.time()
num_sims = 50000
for i in range(0, num_sims):
simulate_knockout()
print(results_df.to_string())
print("\n--- " + str(num_sims) + " simulations took " +
str(round(time.time() - start_time, 2)) + " seconds ---")
results_df.to_csv("results_output.csv", encoding='utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment