import logging import pandas as pd import numpy as np from typing import Dict, Tuple logger = logging.getLogger("nexus.features.classical") class RatingEngine: """Calculates historical ratings (Elo, Pi) for teams.""" def __init__(self, k_factor: int = 20, pi_lambda: float = 0.035, pi_gamma: float = 0.7): self.k_factor = k_factor self.pi_lambda = pi_lambda self.pi_gamma = pi_gamma def calculate_elo(self, df: pd.DataFrame) -> pd.DataFrame: """Calculate Elo ratings sequentially, enhanced with Expected Goals (xG).""" logger.info(f"Calculating xG-Enhanced Elo for {len(df)} matches...") # Sort by kickoff date if 'kickoff' in df.columns: df = df.sort_values('kickoff') ratings = {} # team_id -> current_rating home_ratings = [] away_ratings = [] for idx, row in df.iterrows(): h_id = row['home_team_id'] a_id = row['away_team_id'] # Initial ratings r_h = ratings.get(h_id, 1500.0) r_a = ratings.get(a_id, 1500.0) home_ratings.append(r_h) away_ratings.append(r_a) # Update if match is finished and columns exist if 'home_goals' in row and 'away_goals' in row and pd.notna(row['home_goals']) and pd.notna(row['away_goals']): # Expected win prob e_h = 1 / (1 + 10 ** ((r_a - r_h) / 400)) # Did they overperform or underperform their xG? # If xG is missing, fall back to pure goals h_xg = row.get('home_xg', row['home_goals']) a_xg = row.get('away_xg', row['away_goals']) if pd.isna(h_xg): h_xg = row['home_goals'] if pd.isna(a_xg): a_xg = row['away_goals'] # Hybrid win metric: heavily weights absolute truth (xG) over variance (goals) # s_h becomes a continuous variable bounded [0, 1] based on dominance # Classic s_h is just 1, 0.5, or 0. if row['home_goals'] > row['away_goals']: win_component = 1.0 elif row['home_goals'] < row['away_goals']: win_component = 0.0 else: win_component = 0.5 # xG dominance component (squashed via sigmoid-like mapping) xg_diff = h_xg - a_xg xg_component = 1 / (1 + np.exp(-xg_diff)) # Blended actual outcome and underlying performance s_h = (win_component * 0.4) + (xg_component * 0.6) # Update with Margin Multiplier based on xG diff margin_multiplier = np.sqrt(abs(xg_diff) + 1) delta = self.k_factor * margin_multiplier * (s_h - e_h) ratings[h_id] = r_h + delta ratings[a_id] = r_a - delta df['home_elo'] = home_ratings df['away_elo'] = away_ratings df['elo_diff'] = df['home_elo'] - df['away_elo'] return df def calculate_pi(self, df: pd.DataFrame) -> pd.DataFrame: """Calculate Pi ratings (Constantinou et al).""" logger.info(f"Calculating Pi ratings for {len(df)} matches...") # Sort by kickoff date if 'kickoff' in df.columns: df = df.sort_values('kickoff') # Pi ratings are based on home/away goals ratings = {} # team_id -> [home_rating, away_rating] h_ratings = [] a_ratings = [] for idx, row in df.iterrows(): h_id = row['home_team_id'] a_id = row['away_team_id'] curr_h = ratings.get(h_id, [0.0, 0.0]) curr_a = ratings.get(a_id, [0.0, 0.0]) h_ratings.append(curr_h[0]) # Use team's home/away combined logic or just one a_ratings.append(curr_a[1]) # Update if finished and columns exist if 'home_goals' in row and 'away_goals' in row and pd.notna(row['home_goals']) and pd.notna(row['away_goals']): # Goal diff gd = row['home_goals'] - row['away_goals'] # Update logic (simplified) # This is a stub for real Pi-ratings math ratings[h_id] = [curr_h[0] + gd * self.pi_lambda, curr_h[1]] ratings[a_id] = [curr_a[0], curr_a[1] - gd * self.pi_lambda] df['home_pi'] = h_ratings df['away_pi'] = a_ratings df['pi_diff'] = df['home_pi'] - df['away_pi'] return df