Date Kick Off (local) Home Team Away Team Venue Home Score Away Score Play Off Game?…
- User
Date Kick Off (local) Home Team Away Team Venue Home Score Away Score Play Off Game? Home Goals Home Behinds Away Goals Away Behinds Home Odds Away Odds Bookmakers Surveyed 28-Sep-24 14:30 Sydney Brisbane MCG 60 120 Y 9 6 18 12 1.73 2.02 12 21-Sep-24 17:15 Geelong Brisbane MCG 85 95 Y 12 13 14 11 1.78 1.97 12 20-Sep-24 19:40 Sydney Port Adelaide SCG 95 59 Y 14 11 8 11 1.35 3.02 12 14-Sep-24 19:30 GWS Giants Brisbane ENGIE Stadium 100 105 Y 15 10 15 15 1.67 2.12 12 13-Sep-24 19:10 Port Adelaide Hawthorn Adelaide Oval 75 72 Y 11 9 11 6 2.18 1.64 12 07-Sep-24 19:30 Brisbane Carlton Gabba 99 71 Y 14 15 11 5 1.24 3.80 12 07-Sep-24 15:20 Sydney GWS Giants SCG 88 82 Y 13 10 12 10 1.56 2.32 12 06-Sep-24 19:40 Western Bulldogs Hawthorn MCG 62 99 Y 9 8 14 15 1.62 2.20 12 05-Sep-24 19:10 Port Adelaide Geelong Adelaide Oval 54 138 Y 7 12 20 18 1.35 3.04 12 25-Aug-24 16:10 Fremantle Port Adelaide Optus Stadium 67 87 9 13 13 9 1.72 2.04 12 25-Aug-24 15:20 Carlton St Kilda Marvel Stadium 74 76 11 8 11 10 2.04 1.71 12 25-Aug-24 12:30 Western Bulldogs GWS Giants Mars Stadium 98 61 14 14 9 7 1.39 2.81 12 24-Aug-24 19:40 Sydney Adelaide SCG 121 90 18 13 13 12 1.32 3.17 12 24-Aug-24 19:30 Brisbane Essendon Gabba 87 67 11 21 10 7 1.11 5.82 12 24-Aug-24 15:20 Richmond Gold Coast MCG 66 94 10 6 14 10 2.41 1.52 12 24-Aug-24 13:45 Geelong West Coast GMHBA Stadium 168 75 26 12 11 9 1.02 12.46 12 24-Aug-24 12:30 Hawthorn North Melbourne UTAS Stadium 170 46 26 14 7 4 1.02 10.53 12 23-Aug-24 19:40 Melbourne Collingwood MCG 57 103 8 9 15 13 2.02 1.72 12 18-Aug-24 14:40 West Coast Carlton Optus Stadium 34 99 4 10 14 15 1.70 2.07 12 18-Aug-24 15:20 Hawthorn Richmond MCG 131 68 19 17 10 8 1.06 7.96 12 18-Aug-24 13:10 Western Bulldogs North Melbourne Marvel Stadium 138 42 20 18 6 6 1.07 7.30 12 17-Aug-24 19:00 Port Adelaide Adelaide Adelaide Oval 80 58 11 14 8 10 1.44 2.64 12 Using python, how to make an Elo rating over time for afl teams using the above statistics. Note that this is one sample of the data and the data goes back further in time. Write the code in full.
- Assistant
To create an Elo rating system for AFL teams using your provided data, we'll follow these steps:
-
Data Preparation:
- Load the match data.
- Parse the dates and sort the matches chronologically.
- Extract unique team names.
-
Elo Rating System Implementation:
- Initialize all teams with a base Elo rating (e.g., 1500).
- Define parameters such as the K-factor and home advantage.
- Iterate through each match, calculate expected scores, determine the actual outcome, and update the Elo ratings accordingly.
-
Tracking Elo Ratings Over Time:
- Store the Elo ratings after each match to analyze how they evolve.
Below is a complete Python script using
pandasto implement the Elo rating system based on your data.Prerequisites
Make sure you have the necessary libraries installed. You can install them using
pipif you haven't already:pip install pandasPython Code
import pandas as pd import numpy as np from datetime import datetime # Step 1: Load and Prepare the Data # Replace 'afl_matches.csv' with your actual data file path # For demonstration, we'll create a DataFrame from the sample data provided data = { 'Date': [ '28-Sep-24', '21-Sep-24', '20-Sep-24', '14-Sep-24', '13-Sep-24', '07-Sep-24', '07-Sep-24', '06-Sep-24', '05-Sep-24', '25-Aug-24', '25-Aug-24', '25-Aug-24', '24-Aug-24', '24-Aug-24', '24-Aug-24', '24-Aug-24', '24-Aug-24', '23-Aug-24', '18-Aug-24', '18-Aug-24', '18-Aug-24', '17-Aug-24' ], 'Kick Off (local)': [ '14:30', '17:15', '19:40', '19:30', '19:10', '19:30', '15:20', '19:40', '19:10', '16:10', '15:20', '12:30', '19:40', '19:30', '15:20', '13:45', '12:30', '19:40', '14:40', '15:20', '13:10', '19:00' ], 'Home Team': [ 'Sydney', 'Geelong', 'Sydney', 'GWS Giants', 'Port Adelaide', 'Brisbane', 'Sydney', 'Western Bulldogs', 'Port Adelaide', 'Fremantle', 'Carlton', 'Western Bulldogs', 'Sydney', 'Brisbane', 'Richmond', 'Geelong', 'Hawthorn', 'Melbourne', 'West Coast', 'Hawthorn', 'Western Bulldogs', 'Port Adelaide' ], 'Away Team': [ 'Brisbane', 'Brisbane', 'Port Adelaide', 'Brisbane', 'Hawthorn', 'Carlton', 'GWS Giants', 'Hawthorn', 'Geelong', 'Port Adelaide', 'St Kilda', 'GWS Giants', 'Adelaide', 'Essendon', 'Gold Coast', 'West Coast', 'North Melbourne', 'Collingwood', 'Carlton', 'Richmond', 'North Melbourne', 'Adelaide' ], 'Venue': [ 'MCG', 'MCG', 'SCG', 'ENGIE Stadium', 'Adelaide Oval', 'Gabba', 'SCG', 'MCG', 'Adelaide Oval', 'Optus Stadium', 'Marvel Stadium', 'Mars Stadium', 'SCG', 'Gabba', 'MCG', 'GMHBA Stadium', 'UTAS Stadium', 'MCG', 'Optus Stadium', 'MCG', 'Marvel Stadium', 'Adelaide Oval' ], 'Home Score': [ 60, 85, 95, 100, 75, 99, 88, 62, 54, 67, 74, 98, 121, 87, 66, 168, 170, 57, 34, 131, 138, 80 ], 'Away Score': [ 120, 95, 59, 105, 72, 71, 82, 99, 138, 87, 76, 61, 90, 67, 94, 75, 46, 103, 99, 68, 42, 58 ], 'Play Off Game?': [ 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', '', '', '', '', '', '', '', '', '', '', '', '' ], 'Home Goals': [ 9, 12, 14, 15, 11, 14, 13, 9, 7, 9, 11, 14, 18, 11, 10, 26, 26, 8, 4, 19, 20, 11 ], 'Home Behinds': [ 6, 13, 11, 10, 9, 15, 10, 8, 12, 13, 8, 14, 13, 21, 6, 12, 14, 9, 10, 17, 18, 14 ], 'Away Goals': [ 18, 14, 8, 15, 11, 11, 12, 14, 20, 13, 11, 9, 13, 10, 14, 11, 7, 15, 14, 10, 6, 8 ], 'Away Behinds': [ 12, 11, 11, 15, 6, 5, 10, 15, 18, 9, 10, 7, 12, 7, 10, 9, 4, 13, 15, 8, 6, 10 ], 'Home Odds': [ 1.73, 1.78, 1.35, 1.67, 2.18, 1.24, 1.56, 1.62, 1.35, 1.72, 2.04, 1.39, 1.32, 1.11, 2.41, 1.02, 1.02, 2.02, 1.70, 1.06, 1.07, 1.44 ], 'Away Odds': [ 2.02, 1.97, 3.02, 2.12, 1.64, 3.80, 2.32, 2.20, 3.04, 2.04, 1.71, 2.81, 3.17, 5.82, 1.52, 12.46, 10.53, 1.72, 2.07, 7.96, 7.30, 2.64 ], 'Bookmakers Surveyed': [ 12]*22 } df = pd.DataFrame(data) # Convert 'Date' to datetime df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%y') # Sort by 'Date' and 'Kick Off (local)' time df = df.sort_values(['Date', 'Kick Off (local)']).reset_index(drop=True) # Extract list of unique teams teams = pd.unique(df[['Home Team', 'Away Team']].values.ravel('K')) # Initialize Elo ratings initial_elo = 1500 elo_ratings = {team: initial_elo for team in teams} # Parameters K = 20 # K-factor home_advantage = 100 # Elo points added to home team # To store Elo ratings over time elo_history = {team: [] for team in teams} # Function to calculate expected score def expected_score(rating_a, rating_b): return 1 / (1 + 10 ** ((rating_b - rating_a) / 400)) # Iterate through each match for index, row in df.iterrows(): home_team = row['Home Team'] away_team = row['Away Team'] home_rating = elo_ratings[home_team] + home_advantage away_rating = elo_ratings[away_team] expected_home = expected_score(home_rating, away_rating) expected_away = 1 - expected_home # Determine match outcome if row['Home Score'] > row['Away Score']: score_home = 1 # Home win score_away = 0 elif row['Home Score'] < row['Away Score']: score_home = 0 # Away win score_away = 1 else: score_home = 0.5 # Draw score_away = 0.5 # Update ratings elo_ratings[home_team] += K * (score_home - expected_home) elo_ratings[away_team] += K * (score_away - expected_away) # Record the updated ratings for team in teams: elo_history[team].append(elo_ratings[team]) # Convert Elo history to DataFrame elo_df = pd.DataFrame(elo_history) elo_df['Match'] = df['Date'].dt.strftime('%Y-%m-%d') + ' ' + df['Kick Off (local)'] # Optional: Melt the DataFrame for easier analysis elo_melted = elo_df.melt(id_vars='Match', var_name='Team', value_name='Elo Rating') # Display the Elo ratings after each match print(elo_df) # Optional: Save the Elo ratings to a CSV file # elo_df.to_csv('afl_elo_ratings.csv', index=False) # Optional: Plot the Elo ratings over time using matplotlib import matplotlib.pyplot as plt plt.figure(figsize=(14, 8)) for team in teams: plt.plot(df['Date'], elo_df[team], label=team) plt.xlabel('Date') plt.ylabel('Elo Rating') plt.title('AFL Team Elo Ratings Over Time') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.show()Explanation of the Code
-
Data Loading and Preparation:
- DataFrame Creation: For demonstration purposes, the sample data is manually created into a
DataFrame. In practice, you would load your data from a CSV or another data source usingpd.read_csv(). - Date Parsing: The 'Date' column is converted to
datetimeobjects to ensure proper chronological sorting. - Sorting: The matches are sorted first by date and then by kick-off time to process them in the correct order.
- Team Extraction: All unique team names are extracted to initialize their Elo ratings.
- DataFrame Creation: For demonstration purposes, the sample data is manually created into a
-
Elo Rating Initialization:
- All teams start with an initial Elo rating of 1500.
- Parameters:
- K-factor (
K): Determines the maximum change in Elo rating after each match. A K-factor of 20 is commonly used. - Home Advantage (
home_advantage): An adjustment factor to account for the advantage of playing at home. Here, it's set to 100 Elo points, but you can adjust this based on historical data or preference.
- K-factor (
-
Elo Rating Calculation:
- Expected Score: Calculated using the standard Elo formula. The home team’s rating is adjusted by the home advantage before calculating the expectation.
- Outcome Determination: Based on the
Home ScoreandAway Score, we determine whether the home team won, lost, or if it was a draw. - Rating Update: Both the home and away team’s Elo ratings are updated based on the match outcome and their expected scores.
- History Tracking: After each match, the updated ratings are recorded to track the progression over time.
-
Results:
- Elo Ratings DataFrame (
elo_df): Contains Elo ratings for all teams after each match, along with the match date and time. - Visualization: An optional plot is provided to visualize how each team's Elo rating changes over time.
- Elo Ratings DataFrame (
Customization and Enhancements
- Home Advantage Calibration: You can adjust the
home_advantageparameter or make it dynamic based on historical data to better reflect the actual advantage. - K-factor Variation: Consider varying the K-factor for different types of matches (e.g., finals vs. regular season) if desired.
- Data Source: Replace the sample data with your complete dataset by loading it from a CSV or database.
- Additional Features: Incorporate other match statistics or bookmaker odds to refine the Elo updates.
Final Notes
Elo ratings provide a dynamic way to assess the relative strengths of teams over time. By regularly updating these ratings after each match, you can gain insights into team performance trends, predict future match outcomes, and identify emerging strengths or weaknesses in teams.
-