MLB-2025-ChatML-Matchups / scripts /build_dataset.py
clarkkitchen22's picture
Add MLB 2025 ChatML matchup dataset
af467a1 verified
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import json
import random
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlencode
import pyarrow as pa
import pyarrow.parquet as pq
import requests
BASE_URL = "https://statsapi.mlb.com/api/v1"
SEASON = 2025
DEFAULT_START = "2025-03-01"
DEFAULT_END = "2025-11-30"
STAT_KEYS = [
"gamesPlayed",
"runs",
"hits",
"doubles",
"triples",
"homeRuns",
"rbi",
"baseOnBalls",
"strikeOuts",
"stolenBases",
"caughtStealing",
"avg",
"obp",
"slg",
"ops",
"era",
"whip",
"inningsPitched",
"earnedRuns",
"battersFaced",
"groundOuts",
"airOuts",
"leftOnBase",
]
@dataclass
class ApiMetrics:
network_requests: int = 0
cache_hits: int = 0
retries: int = 0
rate_limited: int = 0
class RateLimiter:
def __init__(self, max_rps: float) -> None:
if max_rps <= 0:
raise ValueError("--max-rps must be positive")
self.min_interval = 1.0 / max_rps
self.last_request_at = 0.0
def wait(self) -> None:
elapsed = time.monotonic() - self.last_request_at
remaining = self.min_interval - elapsed
if remaining > 0:
time.sleep(remaining)
self.last_request_at = time.monotonic()
class MlbApiClient:
def __init__(
self,
cache_dir: Path,
max_rps: float,
force_refresh: bool = False,
timeout: int = 30,
max_retries: int = 5,
) -> None:
self.cache_dir = cache_dir
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.force_refresh = force_refresh
self.timeout = timeout
self.max_retries = max_retries
self.rate_limiter = RateLimiter(max_rps=max_rps)
self.metrics = ApiMetrics()
self.session = requests.Session()
self.session.headers.update(
{
"Accept": "application/json",
"User-Agent": (
"mlb-chatml-2025-dataset/0.1 "
"(research dataset builder; contact: Clark Kitchen)"
),
}
)
def get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
params = params or {}
url = f"{BASE_URL}{path}"
cache_path = self._cache_path(url, params)
if cache_path.exists() and not self.force_refresh:
self.metrics.cache_hits += 1
return json.loads(cache_path.read_text())
query = urlencode(sorted(params.items()))
full_url = f"{url}?{query}" if query else url
last_error: Exception | None = None
for attempt in range(self.max_retries + 1):
if attempt:
self.metrics.retries += 1
sleep_seconds = min(60.0, (2**attempt) + random.uniform(0.0, 0.5))
time.sleep(sleep_seconds)
self.rate_limiter.wait()
self.metrics.network_requests += 1
try:
response = self.session.get(full_url, timeout=self.timeout)
if response.status_code == 429:
self.metrics.rate_limited += 1
retry_after = response.headers.get("Retry-After")
if retry_after:
time.sleep(min(float(retry_after), 120.0))
continue
if response.status_code >= 500:
continue
response.raise_for_status()
data = response.json()
cache_path.write_text(json.dumps(data, sort_keys=True))
return data
except (requests.RequestException, json.JSONDecodeError) as exc:
last_error = exc
continue
raise RuntimeError(f"MLB API request failed after retries: {full_url}") from last_error
def _cache_path(self, url: str, params: dict[str, Any]) -> Path:
cache_key = json.dumps({"url": url, "params": sorted(params.items())}, sort_keys=True)
digest = hashlib.sha256(cache_key.encode("utf-8")).hexdigest()
return self.cache_dir / f"{digest}.json"
def compact_stat_dict(stats: dict[str, Any]) -> dict[str, Any]:
return {key: stats[key] for key in STAT_KEYS if key in stats}
def load_schedule(client: MlbApiClient, start_date: str, end_date: str) -> list[dict[str, Any]]:
data = client.get(
"/schedule",
{
"sportId": 1,
"season": SEASON,
"gameType": "R",
"startDate": start_date,
"endDate": end_date,
},
)
games_by_pk: dict[int, dict[str, Any]] = {}
for date_block in data.get("dates", []):
for game in date_block.get("games", []):
status = game.get("status", {})
has_scores = (
game.get("teams", {}).get("away", {}).get("score") is not None
and game.get("teams", {}).get("home", {}).get("score") is not None
)
if status.get("statusCode") == "F" and has_scores:
game_pk = int(game["gamePk"])
previous = games_by_pk.get(game_pk)
if previous is None or game["gameDate"] > previous["gameDate"]:
games_by_pk[game_pk] = game
return sorted(games_by_pk.values(), key=lambda game: (game["gameDate"], int(game["gamePk"])))
def load_season_team_stats(client: MlbApiClient) -> dict[int, dict[str, dict[str, Any]]]:
data = client.get(
"/teams/stats",
{
"season": SEASON,
"sportIds": 1,
"group": "hitting,pitching",
"stats": "season",
},
)
team_stats: dict[int, dict[str, dict[str, Any]]] = {}
for stat_block in data.get("stats", []):
group = stat_block.get("group", {}).get("displayName")
if group not in {"hitting", "pitching"}:
continue
for split in stat_block.get("splits", []):
team_id = int(split["team"]["id"])
team_stats.setdefault(team_id, {})[group] = compact_stat_dict(split.get("stat", {}))
return team_stats
def score_for_side(game: dict[str, Any], side: str) -> int | None:
value = game.get("teams", {}).get(side, {}).get("score")
return int(value) if value is not None else None
def result_for(team_runs: int | None, opponent_runs: int | None) -> str:
if team_runs is None or opponent_runs is None:
return "unknown"
if team_runs > opponent_runs:
return "win"
if team_runs < opponent_runs:
return "loss"
return "tie"
def json_dumps(data: Any) -> str:
return json.dumps(data, sort_keys=True, separators=(",", ":"))
def matchup_assistant_payload(
game: dict[str, Any],
side: str,
opponent_side: str,
team_stats: dict[int, dict[str, dict[str, Any]]],
boxscore: dict[str, Any],
) -> dict[str, Any]:
team = game["teams"][side]["team"]
opponent = game["teams"][opponent_side]["team"]
team_id = int(team["id"])
opponent_id = int(opponent["id"])
team_box = boxscore["teams"][side]
opponent_box = boxscore["teams"][opponent_side]
team_runs = score_for_side(game, side)
opponent_runs = score_for_side(game, opponent_side)
return {
"season": SEASON,
"game_pk": game["gamePk"],
"game_date": game["gameDate"],
"team": {"id": team_id, "name": team["name"], "side": side},
"opponent": {"id": opponent_id, "name": opponent["name"], "side": opponent_side},
"score": {
"team_runs": team_runs,
"opponent_runs": opponent_runs,
"result": result_for(team_runs, opponent_runs),
},
"team_game": {
"batting": compact_stat_dict(team_box.get("teamStats", {}).get("batting", {})),
"pitching": compact_stat_dict(team_box.get("teamStats", {}).get("pitching", {})),
"fielding": compact_stat_dict(team_box.get("teamStats", {}).get("fielding", {})),
},
"opponent_game": {
"batting": compact_stat_dict(opponent_box.get("teamStats", {}).get("batting", {})),
"pitching": compact_stat_dict(opponent_box.get("teamStats", {}).get("pitching", {})),
"fielding": compact_stat_dict(opponent_box.get("teamStats", {}).get("fielding", {})),
},
"team_season": team_stats.get(team_id, {}),
"opponent_season": team_stats.get(opponent_id, {}),
}
def build_messages(payload: dict[str, Any]) -> list[dict[str, str]]:
team = payload["team"]["name"]
opponent = payload["opponent"]["name"]
game_date = payload["game_date"][:10]
return [
{
"role": "system",
"content": (
"You are an MLB matchup analyst. Use only the supplied 2025 MLB Stats API "
"facts and answer in compact JSON."
),
},
{
"role": "user",
"content": (
f"Build a pitching and offense matchup brief for {team} vs {opponent} "
f"on {game_date}."
),
},
{"role": "assistant", "content": json_dumps(payload)},
]
def build_rows(
games: list[dict[str, Any]],
team_stats: dict[int, dict[str, dict[str, Any]]],
client: MlbApiClient,
limit_games: int | None,
) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
selected_games = games[:limit_games] if limit_games else games
for index, game in enumerate(selected_games, start=1):
if index == 1 or index % 100 == 0 or index == len(selected_games):
print(f"fetching boxscores {index}/{len(selected_games)} gamePk={game['gamePk']}")
boxscore = client.get(f"/game/{game['gamePk']}/boxscore")
for side, opponent_side in (("away", "home"), ("home", "away")):
payload = matchup_assistant_payload(game, side, opponent_side, team_stats, boxscore)
team = payload["team"]
opponent = payload["opponent"]
team_runs = payload["score"]["team_runs"]
opponent_runs = payload["score"]["opponent_runs"]
row = {
"row_id": f"mlb-2025-{game['gamePk']}-{side}",
"season": SEASON,
"game_pk": int(game["gamePk"]),
"game_date": game["gameDate"][:10],
"game_datetime_utc": game["gameDate"],
"team_id": int(team["id"]),
"team_name": team["name"],
"team_side": side,
"opponent_id": int(opponent["id"]),
"opponent_name": opponent["name"],
"opponent_side": opponent_side,
"team_runs": team_runs,
"opponent_runs": opponent_runs,
"result": payload["score"]["result"],
"messages": build_messages(payload),
"assistant_payload_json": json_dumps(payload),
"team_game_batting_json": json_dumps(payload["team_game"]["batting"]),
"team_game_pitching_json": json_dumps(payload["team_game"]["pitching"]),
"opponent_game_batting_json": json_dumps(payload["opponent_game"]["batting"]),
"opponent_game_pitching_json": json_dumps(payload["opponent_game"]["pitching"]),
"team_season_hitting_json": json_dumps(payload["team_season"].get("hitting", {})),
"team_season_pitching_json": json_dumps(payload["team_season"].get("pitching", {})),
"opponent_season_hitting_json": json_dumps(
payload["opponent_season"].get("hitting", {})
),
"opponent_season_pitching_json": json_dumps(
payload["opponent_season"].get("pitching", {})
),
}
rows.append(row)
return rows
def write_parquet(rows: list[dict[str, Any]], output_path: Path) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
schema = pa.schema(
[
("row_id", pa.string()),
("season", pa.int16()),
("game_pk", pa.int64()),
("game_date", pa.string()),
("game_datetime_utc", pa.string()),
("team_id", pa.int64()),
("team_name", pa.string()),
("team_side", pa.string()),
("opponent_id", pa.int64()),
("opponent_name", pa.string()),
("opponent_side", pa.string()),
("team_runs", pa.int16()),
("opponent_runs", pa.int16()),
("result", pa.string()),
(
"messages",
pa.list_(pa.struct([("role", pa.string()), ("content", pa.string())])),
),
("assistant_payload_json", pa.string()),
("team_game_batting_json", pa.string()),
("team_game_pitching_json", pa.string()),
("opponent_game_batting_json", pa.string()),
("opponent_game_pitching_json", pa.string()),
("team_season_hitting_json", pa.string()),
("team_season_pitching_json", pa.string()),
("opponent_season_hitting_json", pa.string()),
("opponent_season_pitching_json", pa.string()),
]
)
table = pa.Table.from_pylist(rows, schema=schema)
pq.write_table(table, output_path, compression="zstd")
def write_manifest(
manifest_path: Path,
output_path: Path,
games: list[dict[str, Any]],
rows: list[dict[str, Any]],
client: MlbApiClient,
) -> None:
manifest = {
"created_at": datetime.now(timezone.utc).isoformat(),
"season": SEASON,
"source": "https://statsapi.mlb.com/api/v1",
"regular_season_final_games": len(games),
"rows": len(rows),
"output_path": str(output_path),
"api_metrics": client.metrics.__dict__,
}
manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--start-date", default=DEFAULT_START)
parser.add_argument("--end-date", default=DEFAULT_END)
parser.add_argument("--cache-dir", type=Path, default=Path(".cache/mlb_api"))
parser.add_argument(
"--output",
type=Path,
default=Path("data/processed/mlb_2025_chatml_matchups.parquet"),
)
parser.add_argument(
"--manifest",
type=Path,
default=Path("data/processed/mlb_2025_chatml_matchups.manifest.json"),
)
parser.add_argument("--max-rps", type=float, default=4.0)
parser.add_argument("--force-refresh", action="store_true")
parser.add_argument("--limit-games", type=int, default=None)
return parser.parse_args()
def main() -> None:
args = parse_args()
client = MlbApiClient(
cache_dir=args.cache_dir,
max_rps=args.max_rps,
force_refresh=args.force_refresh,
)
games = load_schedule(client, args.start_date, args.end_date)
print(f"loaded {len(games)} final regular-season games")
team_stats = load_season_team_stats(client)
if len(team_stats) != 30:
raise RuntimeError(f"expected 30 teams with season stats, got {len(team_stats)}")
rows = build_rows(games, team_stats, client, args.limit_games)
if not rows:
raise RuntimeError("no rows built")
write_parquet(rows, args.output)
write_manifest(args.manifest, args.output, games, rows, client)
print(f"wrote {len(rows)} rows to {args.output}")
print(f"api metrics: {client.metrics.__dict__}")
if __name__ == "__main__":
main()