import numpy as np
from scipy.stats import poisson
import pandas as pd
from itertools import combinations
import math
# Define teams with initial Elo ratings and scoring characteristics
teams = {
'Arsenal': {'elo': 1850, 'avg_goals': 1.8},
'Chelsea': {'elo': 1800, 'avg_goals': 1.6},
'Liverpool': {'elo': 1900, 'avg_goals': 1.7},
'Man City': {'elo': 1950, 'avg_goals': 2.0}
}
# Elo K-factor (determines how much ratings change after each match)
K_FACTOR = 32
def calculate_elo_probabilities(elo1, elo2):
"""Calculate win/draw probabilities based on Elo ratings"""
# Expected score for team 1 (0.5 = draw)
expected1 = 1 / (1 + 10 ** ((elo2 - elo1) / 400))
expected2 = 1 - expected1
# Convert to win/draw/loss probabilities
# Using empirical formula for draw probability based on rating difference
rating_diff = abs(elo1 - elo2)
draw_prob = 0.25 * math.exp(-rating_diff / 250) # Draw probability decreases with rating difference
if elo1 > elo2:
win1_prob = expected1 - draw_prob/2
win2_prob = expected2 - draw_prob/2
else:
win1_prob = expected1 - draw_prob/2
win2_prob = expected2 - draw_prob/2
# Ensure probabilities are valid
win1_prob = max(0, win1_prob)
win2_prob = max(0, win2_prob)
return win1_prob, draw_prob, win2_prob
def determine_match_outcome(win1_prob, draw_prob, win2_prob):
"""Randomly determine match outcome based on probabilities"""
rand = np.random.random()
if rand < win1_prob:
return 'win1'
elif rand < win1_prob + draw_prob:
return 'draw'
else:
return 'win2'
def generate_score_for_outcome(outcome, avg_goals1, avg_goals2):
"""Generate a realistic score using Poisson distribution that matches the outcome"""
if outcome == 'win1':
# Team 1 wins
while True:
goals1 = np.random.poisson(avg_goals1 * 1.2) # Boost for winning team
goals2 = np.random.poisson(avg_goals2 * 0.8) # Reduction for losing team
if goals1 > goals2:
return goals1, goals2
elif outcome == 'win2':
# Team 2 wins
while True:
goals1 = np.random.poisson(avg_goals1 * 0.8)
goals2 = np.random.poisson(avg_goals2 * 1.2)
if goals2 > goals1:
return goals1, goals2
else:
# Draw
while True:
draw_goals = np.random.poisson((avg_goals1 + avg_goals2) / 2 * 0.9)
return draw_goals, draw_goals
def update_elo_ratings(elo1, elo2, outcome):
"""Update Elo ratings based on match outcome"""
# Expected scores
expected1 = 1 / (1 + 10 ** ((elo2 - elo1) / 400))
expected2 = 1 - expected1
# Actual scores
if outcome == 'win1':
actual1, actual2 = 1, 0
elif outcome == 'win2':
actual1, actual2 = 0, 1
else: # draw
actual1, actual2 = 0.5, 0.5
# Update ratings
new_elo1 = elo1 + K_FACTOR * (actual1 - expected1)
new_elo2 = elo2 + K_FACTOR * (actual2 - expected2)
return new_elo1, new_elo2
# Initialize league table
table = {team: {'played': 0, 'won': 0, 'drawn': 0, 'lost': 0,
'goals_for': 0, 'goals_against': 0, 'points': 0,
'initial_elo': teams[team]['elo'], 'final_elo': teams[team]['elo']}
for team in teams}
# Generate all fixtures
fixtures = list(combinations(teams.keys(), 2))
print("=" * 80)
print("LEAGUE SEASON SIMULATION (ELO + POISSON)")
print("=" * 80)
print()
# Display initial Elo ratings
print("Initial Elo Ratings:")
for team, data in sorted(teams.items(), key=lambda x: x[1]['elo'], reverse=True):
print(f"{team}: {data['elo']}")
print()
print("=" * 80)
print()
# Simulate all matches
for i, (team1, team2) in enumerate(fixtures, 1):
# Get current Elo ratings
elo1 = teams[team1]['elo']
elo2 = teams[team2]['elo']
# Calculate win probabilities using Elo
win1_prob, draw_prob, win2_prob = calculate_elo_probabilities(elo1, elo2)
# Determine match outcome
outcome = determine_match_outcome(win1_prob, draw_prob, win2_prob)
# Generate score based on outcome using Poisson
goals1, goals2 = generate_score_for_outcome(
outcome,
teams[team1]['avg_goals'],
teams[team2]['avg_goals']
)
print(f"Match {i}: {team1} vs {team2}")
print(f"Elo ratings: {team1} ({elo1:.0f}) vs {team2} ({elo2:.0f})")
print(f"Win probabilities: {team1} {win1_prob:.1%} | Draw {draw_prob:.1%} | {team2} {win2_prob:.1%}")
print(f"Result: {team1} {goals1} - {goals2} {team2}")
# Update table
table[team1]['played'] += 1
table[team2]['played'] += 1
table[team1]['goals_for'] += goals1
table[team1]['goals_against'] += goals2
table[team2]['goals_for'] += goals2
table[team2]['goals_against'] += goals1
if goals1 > goals2:
print(f"Winner: {team1} (3 points)")
table[team1]['won'] += 1
table[team1]['points'] += 3
table[team2]['lost'] += 1
elif goals1 < goals2:
print(f"Winner: {team2} (3 points)")
table[team2]['won'] += 1
table[team2]['points'] += 3
table[team1]['lost'] += 1
else:
print("Draw (1 point each)")
table[team1]['drawn'] += 1
table[team2]['drawn'] += 1
table[team1]['points'] += 1
table[team2]['points'] += 1
# Update Elo ratings
new_elo1, new_elo2 = update_elo_ratings(elo1, elo2, outcome)
teams[team1]['elo'] = new_elo1
teams[team2]['elo'] = new_elo2
table[team1]['final_elo'] = new_elo1
table[team2]['final_elo'] = new_elo2
print(f"Updated Elo: {team1} ({new_elo1:.0f}) | {team2} ({new_elo2:.0f})")
print("-" * 60)
print()
# Create and sort league table
df_table = pd.DataFrame(table).T
df_table['goal_difference'] = df_table['goals_for'] - df_table['goals_against']
df_table['elo_change'] = df_table['final_elo'] - df_table['initial_elo']
df_table = df_table.sort_values(['points', 'goal_difference', 'goals_for'], ascending=False)
# Display final table
print("=" * 80)
print("FINAL LEAGUE TABLE")
print("=" * 80)
print()
print(f"{'Team':<12} {'P':>3} {'W':>3} {'D':>3} {'L':>3} {'GF':>4} {'GA':>4} {'GD':>4} {'Pts':>4} {'Elo':>5} {'Δ':>5}")
print("-" * 65)
for idx, (team, row) in enumerate(df_table.iterrows(), 1):
print(f"{idx}. {team:<10} {row['played']:>3} {row['won']:>3} {row['drawn']:>3} "
f"{row['lost']:>3} {row['goals_for']:>4} {row['goals_against']:>4} "
f"{row['goal_difference']:>+4} {row['points']:>4} "
f"{row['final_elo']:>5.0f} {row['elo_change']:>+5.0f}")
print()
print("=" * 80)
print()
# Summary statistics
print("SEASON SUMMARY")
print("-" * 30)
total_goals = df_table['goals_for'].sum()
total_matches = len(fixtures)
print(f"Total goals scored: {total_goals}")
print(f"Average goals per match: {total_goals/total_matches:.2f}")
print(f"Total matches played: {total_matches}")