fpl-solver / build_match_data.py
AnayShukla's picture
Claude Opus 5
Rebuild match_data.csv and newdata.csv in the cron, by stat title
9232595
Raw History Blame Contribute Delete
14.5 kB
"""Rebuild match_data.csv and newdata.csv from the Fotmob match JSONs in data/.
Both files are pure functions of what scrape_luigi has already put on disk, but
they lived in notebooks (match.ipynb, newdata.ipynb) and were run by hand -
which is to say they stopped being run. ewmapois reads both, so a stale CSV
means the team model is fitted on matches that finished months ago while the
JSONs for the current ones sit unread in data/.
Two scopes, matching what each consumer needs:
match_data.csv Premier League only, the full team-stat row - xG, xA, shots,
the defensive contributions behind CBIT/CBITR, cards, saves.
newdata.csv Premier League plus Championship, the short row: date,
competition, teams, goals, xG. The wider net is the point -
promoted sides need last season's second-tier form.
Everything here is looked up by title, never by position, because Fotmob's
layout has moved twice and the notebooks never caught up:
- A "Physical performance" block appeared partway through 2024-25, pushing
every later block along by one. The notebooks probed index 3 for it, which
handled that case.
- "Top stats" then gained "Touches in opposition box" and "Yellow cards",
which shifted the rows *inside* the block. Nothing probed for that, so on
current-season matches the notebook read Big chances missed as accurate
passes and yellow cards as corners.
- From 2025-26 the Defence block renamed "Tackles won" (rendered "8 (67%)")
to "Tackles" (a plain integer). The notebook split that on "(", which
raises on an int, so tackles - and with them tackles_attempted, and so
CBIT and CBITR - silently came out as zero for every match in the last two
seasons. Those are the columns ewmapois actually fits on.
Reading by title is immune to all three. A stat that genuinely is not there
still leaves a zero behind rather than losing the whole match.
"""
import json
from glob import glob
from pathlib import Path
import pandas as pd
MATCH_DATA_OUTPUT = "match_data.csv"
NEWDATA_OUTPUT = "newdata.csv"
# match_data.csv is the Premier League team model's input; newdata.csv also
# feeds Championship form in, for sides that have just come up.
MATCH_DATA_LEAGUES = ["data/Premier_League"]
NEWDATA_LEAGUES = ["data/Premier_League", "data/Championship"]
# A rebuild that loses a chunk of the history is a data loss, not an update,
# so a run that comes back with far fewer matches than the file it would
# replace is refused instead of written.
MIN_RETAINED_FRACTION = 0.9
def safe_float_convert(value, default=0.0):
"""Fotmob renders numbers as strings, sometimes as '12 (4)' or '-'."""
if value is None or value == "":
return default
try:
if isinstance(value, str):
value = value.strip()
if value == "" or value == "-":
return default
if "(" in value:
value = value.split("(")[0]
return float(value)
except (ValueError, TypeError):
return default
def _all_stats(data):
return data["stats"]["Periods"]["All"]["stats"]
def _raw(data, block_title, *row_titles):
"""The raw [home, away] cell for a row, found by title. None if absent.
Several row titles may be given: Fotmob has renamed rows between seasons
("Tackles won" -> "Tackles"), and the first one present wins.
"""
try:
blocks = _all_stats(data)
except (KeyError, IndexError, TypeError):
return None
for block in blocks:
if block.get("title") != block_title:
continue
rows = {r.get("title"): r.get("stats") for r in block.get("stats", [])}
for title in row_titles:
cell = rows.get(title)
if cell and len(cell) >= 2:
return cell
return None
def _pair(data, block_title, *row_titles):
"""The (home, away) numbers for a row, or (None, None) if it is not there."""
cell = _raw(data, block_title, *row_titles)
if cell is None:
return None, None
return safe_float_convert(cell[0]), safe_float_convert(cell[1])
def _basic(data, stats):
"""Date, teams and the full-time score - shared by both output shapes."""
try:
stats["match_date"] = data["matchFacts"]["infoBox"]["Match Date"]["utcTime"].split("T")[0]
except KeyError:
pass
try:
stats["home_team"] = data["lineup"]["homeTeam"]["name"]
stats["away_team"] = data["lineup"]["awayTeam"]["name"]
except KeyError:
# No lineup published (very old or abandoned matches): fall back to the
# odds poll, which carries the names in a different spelling scheme.
try:
stats["home_team"] = data["matchFacts"]["poll"]["oddspoll"]["HomeTeam"]
stats["away_team"] = data["matchFacts"]["poll"]["oddspoll"]["AwayTeam"]
except KeyError:
pass
# fetch_fixtures and the team model both key on the long form.
for side in ("home_team", "away_team"):
if stats.get(side) == "Brighton & Hove Albion":
stats[side] = "Brighton and Hove Albion"
try:
for event in reversed(data["matchFacts"]["events"]["events"]):
if event.get("type") == "Half" and event.get("halfStrShort") == "FT":
stats["home_goals"] = event.get("homeScore", 0)
stats["away_goals"] = event.get("awayScore", 0)
break
except (KeyError, IndexError):
pass
stats["xg_home"], stats["xg_away"] = _pair(data, "Top stats", "Expected goals (xG)")
return stats
def extract_summary(raw_json):
"""newdata.csv row: competition, date, teams, goals, xG."""
try:
data = json.loads(raw_json)
except (ValueError, TypeError):
return None
stats = {"match_date": None, "comp": None, "home_team": None, "away_team": None,
"home_goals": 0, "away_goals": 0, "xg_home": 0, "xg_away": 0}
try:
stats["comp"] = data["matchFacts"]["infoBox"]["Tournament"]["leagueName"]
except KeyError:
pass
_basic(data, stats)
for k in ("xg_home", "xg_away"):
if stats[k] is None:
stats[k] = 0
return stats
DETAIL_COLUMNS = [
"match_id", "match_date", "home_team", "away_team", "home_goals", "away_goals",
"xg_home", "xg_away", "xa_home", "xa_away", "xg_per_shot_home", "xg_per_shot_away",
"xg_setplay_home", "xg_setplay_away", "total_shots_home", "total_shots_away",
"shots_on_target_home", "shots_on_target_away", "clearances_home", "clearances_away",
"interceptions_home", "interceptions_away", "tackles_won_home", "tackles_won_away",
"tackles_attempted_home", "tackles_attempted_away", "blocks_home", "blocks_away",
"recoveries_home", "recoveries_away", "possession_home", "possession_away",
"accurate_passes_home", "accurate_passes_away", "corners_home", "corners_away",
"keeper_saves_home", "keeper_saves_away", "yellow_cards_home", "yellow_cards_away",
"red_cards_home", "red_cards_away", "CBIT_home", "CBIT_away", "CBITR_home", "CBITR_away",
]
def _tackles(data):
"""(won_home, won_away, attempted_home, attempted_away) from the Defence block.
Two formats, because Fotmob changed this in 2025-26:
"Tackles won": "8 (67%)" the count with its success rate, so attempts
have to be divided back out.
"Tackles": 8 a plain total, with no rate published.
The plain total is taken as attempts, not as tackles won. CBIT is built
from attempts, and keeping that column meaning the same thing across
seasons matters more than populating tackles_won - which nothing reads -
for the seasons where Fotmob no longer gives us the split.
"""
cell = _raw(data, "Defence", "Tackles won", "Tackles")
if cell is None:
return 0, 0, 0, 0
counts = [safe_float_convert(c) for c in cell[:2]]
rates = []
for c in cell[:2]:
try:
rates.append(safe_float_convert(str(c).split("(")[1].split("%")[0]) / 100)
except (IndexError, AttributeError, TypeError):
rates.append(0.0)
if any(rates):
attempted = [round(n / r) if r > 0 else 0 for n, r in zip(counts, rates)]
return counts[0], counts[1], attempted[0], attempted[1]
return 0, 0, counts[0], counts[1]
def _player_totals(data, stats):
"""xA and recoveries, which Fotmob only reports per player."""
if "playerStats" not in data or not stats.get("home_team") or not stats.get("away_team"):
return
# playerStats uses the short club name where the lineup uses the full one.
home = "Bournemouth" if stats["home_team"] == "AFC Bournemouth" else stats["home_team"]
away = "Bournemouth" if stats["away_team"] == "AFC Bournemouth" else stats["away_team"]
for player_data in data["playerStats"].values():
team = player_data.get("teamName")
side = "home" if team == home else ("away" if team == away else None)
if side is None:
continue
for category in player_data.get("stats", []):
for stat_info in (category.get("stats") or {}).values():
key = stat_info.get("key")
value = stat_info.get("stat", {}).get("value")
if value is None:
continue
if key == "expected_assists":
stats[f"xa_{side}"] += safe_float_convert(value)
elif key == "recoveries":
stats[f"recoveries_{side}"] += safe_float_convert(value)
def extract_detail(raw_json):
"""match_data.csv row: the full team-stat line for one match."""
try:
data = json.loads(raw_json)
except (ValueError, TypeError):
return None
stats = {c: 0 for c in DETAIL_COLUMNS}
stats.update({"match_date": None, "home_team": None, "away_team": None})
stats["match_id"] = safe_float_convert(data.get("matchFacts", {}).get("matchId"))
_basic(data, stats)
if stats["xg_home"] is None:
stats["xg_home"], stats["xg_away"] = 0, 0
stats["xg_setplay_home"], stats["xg_setplay_away"] = _pair(
data, "Expected goals (xG)", "xG set play")
stats["possession_home"], stats["possession_away"] = _pair(
data, "Top stats", "Ball possession")
stats["total_shots_home"], stats["total_shots_away"] = _pair(
data, "Top stats", "Total shots")
stats["shots_on_target_home"], stats["shots_on_target_away"] = _pair(
data, "Top stats", "Shots on target")
# The Passes block carries this too and is the more stable home for it.
stats["accurate_passes_home"], stats["accurate_passes_away"] = _pair(
data, "Passes", "Accurate passes")
if stats["accurate_passes_home"] is None:
stats["accurate_passes_home"], stats["accurate_passes_away"] = _pair(
data, "Top stats", "Accurate passes")
stats["corners_home"], stats["corners_away"] = _pair(data, "Top stats", "Corners")
(stats["tackles_won_home"], stats["tackles_won_away"],
stats["tackles_attempted_home"], stats["tackles_attempted_away"]) = _tackles(data)
stats["interceptions_home"], stats["interceptions_away"] = _pair(data, "Defence", "Interceptions")
stats["blocks_home"], stats["blocks_away"] = _pair(data, "Defence", "Blocks")
stats["clearances_home"], stats["clearances_away"] = _pair(data, "Defence", "Clearances")
stats["keeper_saves_home"], stats["keeper_saves_away"] = _pair(data, "Defence", "Keeper saves")
stats["yellow_cards_home"], stats["yellow_cards_away"] = _pair(data, "Discipline", "Yellow cards")
stats["red_cards_home"], stats["red_cards_away"] = _pair(data, "Discipline", "Red cards")
for column in DETAIL_COLUMNS:
if stats.get(column) is None:
stats[column] = 0
_player_totals(data, stats)
for side in ("home", "away"):
if stats[f"total_shots_{side}"] > 0:
stats[f"xg_per_shot_{side}"] = stats[f"xg_{side}"] / stats[f"total_shots_{side}"]
stats[f"CBIT_{side}"] = (stats[f"clearances_{side}"] + stats[f"blocks_{side}"]
+ stats[f"interceptions_{side}"] + stats[f"tackles_attempted_{side}"])
stats[f"CBITR_{side}"] = stats[f"CBIT_{side}"] + stats[f"recoveries_{side}"]
return stats
def _build(leagues, extractor):
rows, failed = [], 0
for league in leagues:
for path in glob(f"{league}/**/*.json", recursive=True):
try:
raw = Path(path).read_text(encoding="utf-8")
except OSError:
failed += 1
continue
row = extractor(raw)
if row is None:
failed += 1
continue
rows.append(row)
return pd.DataFrame(rows), failed
def _write(df, output, failed, label, columns=None):
"""Write, unless the new file would drop most of what the old one held."""
existing = 0
if Path(output).exists():
try:
existing = len(pd.read_csv(output))
except Exception:
existing = 0
if existing and len(df) < existing * MIN_RETAINED_FRACTION:
raise RuntimeError(
f"{output}: rebuild produced {len(df)} matches against {existing} "
f"already on file. That is a loss, not an update - refusing to "
f"overwrite. Check that data/ is intact."
)
if columns:
df = df.reindex(columns=columns)
df.to_csv(output, index=False)
summary = (f"{label}: {len(df)} matches"
+ (f" (was {existing})" if existing else "")
+ (f", {failed} unreadable" if failed else ""))
print(f"[wrote] {output} - {summary}")
return {"output": output, "matches": len(df), "previous": existing,
"failed": failed, "summary": summary}
def rebuild(match_data_output=MATCH_DATA_OUTPUT, newdata_output=NEWDATA_OUTPUT) -> dict:
"""Rebuild both CSVs from data/. Returns a summary dict for the caller."""
detail, detail_failed = _build(MATCH_DATA_LEAGUES, extract_detail)
summary, summary_failed = _build(NEWDATA_LEAGUES, extract_summary)
return {
"match_data": _write(detail, match_data_output, detail_failed,
"match_data", DETAIL_COLUMNS),
"newdata": _write(summary, newdata_output, summary_failed, "newdata"),
}
if __name__ == "__main__":
result = rebuild()
for part in result.values():
print(part["summary"])