"""Dixon-Coles goal model for international football, with time decay and neutral-venue handling. Wraps penaltyblog.""" from __future__ import annotations import json from dataclasses import dataclass import numpy as np import pandas as pd import penaltyblog as pb import config from db import connect def load_training_frame(train_from: str = config.TRAIN_FROM) -> pd.DataFrame: """Played matches since `train_from`, restricted to teams we can model.""" with connect() as conn: df = pd.read_sql_query( "SELECT date,home_team,away_team,home_score,away_score,neutral " "FROM matches WHERE home_score IS NOT NULL AND date >= ? " "ORDER BY date", conn, params=(train_from,), ) df["date"] = pd.to_datetime(df["date"]) return df @dataclass class WorldCupModel: xi: float = config.XI_DEFAULT model: pb.models.DixonColesGoalModel | None = None teams: set[str] | None = None def fit(self, df: pd.DataFrame, base_date: pd.Timestamp | None = None) -> "WorldCupModel": base = base_date if base_date is not None else df["date"].max() weights = pb.models.dixon_coles_weights(df["date"], xi=self.xi, base_date=base) self.model = pb.models.DixonColesGoalModel( df["home_score"].astype(int).to_numpy(), df["away_score"].astype(int).to_numpy(), df["home_team"].to_numpy(), df["away_team"].to_numpy(), weights=weights, neutral_venue=df["neutral"].astype(int).to_numpy(), ) self.model.fit() self.teams = set(df["home_team"]) | set(df["away_team"]) return self def predict_grid(self, home: str, away: str, neutral: bool = True): return self.model.predict(home, away, max_goals=config.MAX_GOALS, neutral_venue=neutral) def match_summary(self, home: str, away: str, neutral: bool = True) -> dict: """Full prediction payload for one fixture.""" g = self.predict_grid(home, away, neutral) grid = np.asarray(g.grid) ph, pd_, pa = (float(x) for x in g.home_draw_away) # most-likely scorelines flat = [(i, j, float(grid[i, j])) for i in range(grid.shape[0]) for j in range(grid.shape[1])] flat.sort(key=lambda t: t[2], reverse=True) top = [[i, j, round(p, 4)] for i, j, p in flat[:6]] exp_home = float(sum(i * grid[i, :].sum() for i in range(grid.shape[0]))) exp_away = float(sum(j * grid[:, j].sum() for j in range(grid.shape[1]))) over25 = float(sum(grid[i, j] for i in range(grid.shape[0]) for j in range(grid.shape[1]) if i + j > 2.5)) btts = float(sum(grid[i, j] for i in range(1, grid.shape[0]) for j in range(1, grid.shape[1]))) return { "home_team": home, "away_team": away, "neutral": neutral, "p_home": round(ph, 4), "p_draw": round(pd_, 4), "p_away": round(pa, 4), "exp_home": round(exp_home, 3), "exp_away": round(exp_away, 3), "top_scores": top, "grid": np.round(grid[:7, :7], 5).tolist(), "over25": round(over25, 4), "btts": round(btts, 4), } def can_predict(self, *names: str) -> bool: return self.teams is not None and all(n in self.teams for n in names) def save(self, path=None): path = path or (config.ARTIFACTS / "dixon_coles.pkl") self.model.save(str(path)) (config.ARTIFACTS / "model_meta.json").write_text( json.dumps({"xi": self.xi, "teams": sorted(self.teams)}, ensure_ascii=False), encoding="utf-8", ) @classmethod def load(cls, xi: float = config.XI_DEFAULT) -> "WorldCupModel": m = pb.models.DixonColesGoalModel.load(str(config.ARTIFACTS / "dixon_coles.pkl")) meta = json.loads((config.ARTIFACTS / "model_meta.json").read_text(encoding="utf-8")) obj = cls(xi=meta.get("xi", xi), model=m, teams=set(meta["teams"])) return obj if __name__ == "__main__": df = load_training_frame() print(f"training rows: {len(df)} ({df.date.min().date()} -> {df.date.max().date()})") m = WorldCupModel().fit(df) m.save() print("Spain vs Brazil (neutral):") s = m.match_summary("Spain", "Brazil") print(f" 1X2 = {s['p_home']} / {s['p_draw']} / {s['p_away']} xG {s['exp_home']}-{s['exp_away']}") print(f" top scores: {s['top_scores'][:3]}")