Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions ml/src/subspot_ml/data/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Data loading and team-name canonicalization for Subspot's match data."""
77 changes: 77 additions & 0 deletions ml/src/subspot_ml/data/football_data.py
Original file line number Diff line number Diff line change
@@ -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])
80 changes: 80 additions & 0 deletions ml/src/subspot_ml/data/teams.py
Original file line number Diff line number Diff line change
@@ -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}
Loading