From 5d6188a3b8f41cded713de0d14eb6c46590b256e Mon Sep 17 00:00:00 2001 From: Kymani Jarrett Date: Thu, 19 Nov 2026 04:31:32 -0500 Subject: [PATCH] fix(ml): commit the subspot_ml.data package hidden by gitignore --- .gitignore | 6 +- ml/src/subspot_ml/data/__init__.py | 1 + ml/src/subspot_ml/data/football_data.py | 77 ++++++++++++++++++++++++ ml/src/subspot_ml/data/teams.py | 80 +++++++++++++++++++++++++ 4 files changed, 162 insertions(+), 2 deletions(-) create mode 100644 ml/src/subspot_ml/data/__init__.py create mode 100644 ml/src/subspot_ml/data/football_data.py create mode 100644 ml/src/subspot_ml/data/teams.py diff --git a/.gitignore b/.gitignore index e55bf07..ebb8965 100644 --- a/.gitignore +++ b/.gitignore @@ -14,8 +14,10 @@ __pycache__/ .coverage htmlcov/ -# Data and model artifacts (regenerated by the pipeline, never committed) -data/ +# Data and model artifacts (regenerated by the pipeline, never committed). +# Anchored so the subspot_ml.data source package is still tracked. +/data/ +/ml/data/ *.parquet *.pt *.mlmodel diff --git a/ml/src/subspot_ml/data/__init__.py b/ml/src/subspot_ml/data/__init__.py new file mode 100644 index 0000000..a3e240c --- /dev/null +++ b/ml/src/subspot_ml/data/__init__.py @@ -0,0 +1 @@ +"""Data loading and team-name canonicalization for Subspot's match data.""" diff --git a/ml/src/subspot_ml/data/football_data.py b/ml/src/subspot_ml/data/football_data.py new file mode 100644 index 0000000..00204b8 --- /dev/null +++ b/ml/src/subspot_ml/data/football_data.py @@ -0,0 +1,77 @@ +"""Load Premier League results and closing odds from football-data.co.uk.""" + +from __future__ import annotations + +import re +from pathlib import Path + +import numpy as np +import pandas as pd + +from subspot_ml.data.teams import canonical_team + +BASE_URL = "https://www.football-data.co.uk/mmz4281" + +# Pinnacle closing odds: the sharpest public benchmark for a forecast. +_CLOSING_COLUMNS = {"PSCH": "close_home", "PSCD": "close_draw", "PSCA": "close_away"} + +COLUMNS = [ + "date", + "home", + "away", + "home_goals", + "away_goals", + "result", + "close_home", + "close_draw", + "close_away", +] + + +def season_url(season: str) -> str: + """URL of one Premier League season's CSV, e.g. ``season_url("2425")``.""" + if not re.fullmatch(r"\d{4}", season) or (int(season[:2]) + 1) % 100 != int(season[2:]): + raise ValueError(f"season must look like '2425' (2024-25), got {season!r}") + return f"{BASE_URL}/{season}/E0.csv" + + +def _parse_dates(raw: pd.Series) -> pd.Series: + four_digit = pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce") + two_digit = pd.to_datetime(raw, format="%d/%m/%y", errors="coerce") + return four_digit.fillna(two_digit) + + +def load_matches(path: str | Path) -> pd.DataFrame: + """Read one season CSV into canonical columns, sorted by date. + + Unplayed fixtures are dropped and every team name is canonicalized, so an + unknown spelling raises ``UnknownTeamError`` instead of losing the match. + """ + raw = pd.read_csv(path, encoding="latin-1") + played = raw.dropna(subset=["FTHG", "FTAG"]).copy() + + home_goals = played["FTHG"].astype(int) + away_goals = played["FTAG"].astype(int) + result = np.select([home_goals > away_goals, home_goals < away_goals], ["H", "A"], default="D") + + df = pd.DataFrame( + { + "date": _parse_dates(played["Date"]), + "home": played["HomeTeam"].map(canonical_team), + "away": played["AwayTeam"].map(canonical_team), + "home_goals": home_goals, + "away_goals": away_goals, + "result": result, + } + ) + for source, target in _CLOSING_COLUMNS.items(): + df[target] = played[source].astype(float) if source in played else np.nan + + return df.sort_values("date", kind="stable").reset_index(drop=True)[COLUMNS] + + +def implied_probabilities(home: float, draw: float, away: float) -> tuple[float, float, float]: + """Turn decimal odds into probabilities, removing the bookmaker margin.""" + inverse = np.array([1 / home, 1 / draw, 1 / away]) + probs = inverse / inverse.sum() + return float(probs[0]), float(probs[1]), float(probs[2]) diff --git a/ml/src/subspot_ml/data/teams.py b/ml/src/subspot_ml/data/teams.py new file mode 100644 index 0000000..bd64c45 --- /dev/null +++ b/ml/src/subspot_ml/data/teams.py @@ -0,0 +1,80 @@ +"""Map every source's spelling of a club to one canonical team id. + +football-data.co.uk, Understat and the odds feeds all spell clubs differently +("Man United", "Manchester United"). Joining sources on raw names silently +drops matches, so every name goes through ``canonical_team`` and unknown names +fail loudly instead of being guessed. +""" + +from __future__ import annotations + +from collections.abc import Iterable + +_ALIASES: dict[str, str] = { + "arsenal": "arsenal", + "aston villa": "aston_villa", + "bournemouth": "bournemouth", + "afc bournemouth": "bournemouth", + "brentford": "brentford", + "brighton": "brighton", + "brighton and hove albion": "brighton", + "burnley": "burnley", + "chelsea": "chelsea", + "crystal palace": "crystal_palace", + "everton": "everton", + "fulham": "fulham", + "ipswich": "ipswich", + "ipswich town": "ipswich", + "leeds": "leeds", + "leeds united": "leeds", + "leicester": "leicester", + "leicester city": "leicester", + "liverpool": "liverpool", + "luton": "luton", + "luton town": "luton", + "man city": "man_city", + "manchester city": "man_city", + "man united": "man_united", + "manchester united": "man_united", + "newcastle": "newcastle", + "newcastle united": "newcastle", + "nott'm forest": "nottm_forest", + "nottingham forest": "nottm_forest", + "sheffield united": "sheffield_united", + "sheffield utd": "sheffield_united", + "southampton": "southampton", + "sunderland": "sunderland", + "tottenham": "tottenham", + "tottenham hotspur": "tottenham", + "spurs": "tottenham", + "west ham": "west_ham", + "west ham united": "west_ham", + "wolves": "wolves", + "wolverhampton wanderers": "wolves", +} + + +class UnknownTeamError(KeyError): + """Raised when a source uses a team name with no entry in ``_ALIASES``.""" + + def __str__(self) -> str: + return str(self.args[0]) if self.args else "" + + +def _normalize(name: str) -> str: + return " ".join(name.split()).lower() + + +def canonical_team(name: str) -> str: + """Return the canonical id for ``name``, ignoring case and extra whitespace.""" + try: + return _ALIASES[_normalize(name)] + except KeyError: + raise UnknownTeamError( + f"Unknown team name {name!r}. Add it to _ALIASES in subspot_ml/data/teams.py." + ) from None + + +def unmapped(names: Iterable[str]) -> set[str]: + """Return the names that ``canonical_team`` cannot resolve.""" + return {name for name in names if _normalize(name) not in _ALIASES}