File size: 16,387 Bytes
8c5b9c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | #!/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"
DEFAULT_SEASON = 2025
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 default_start_date(season: int) -> str:
return f"{season}-03-01"
def default_end_date(season: int) -> str:
return f"{season}-11-30"
def load_schedule(
client: MlbApiClient, season: int, 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, season: int
) -> 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],
season: int,
) -> 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], season: int) -> list[dict[str, str]]:
team = payload["team"]["name"]
opponent = payload["opponent"]["name"]
game_date = payload["game_date"][:10]
return [
{
"role": "system",
"content": (
f"You are an MLB matchup analyst. Use only the supplied {season} 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,
season: int,
) -> 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, season
)
team = payload["team"]
opponent = payload["opponent"]
team_runs = payload["score"]["team_runs"]
opponent_runs = payload["score"]["opponent_runs"]
row = {
"row_id": f"mlb-{season}-{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, season),
"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,
season: int,
) -> 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("--season", type=int, default=DEFAULT_SEASON)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--cache-dir", type=Path, default=Path(".cache/mlb_api"))
parser.add_argument(
"--output",
type=Path,
default=None,
)
parser.add_argument(
"--manifest",
type=Path,
default=None,
)
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()
start_date = args.start_date or default_start_date(args.season)
end_date = args.end_date or default_end_date(args.season)
output = args.output or Path(f"data/processed/mlb_{args.season}_chatml_matchups.parquet")
manifest = args.manifest or Path(
f"data/processed/mlb_{args.season}_chatml_matchups.manifest.json"
)
client = MlbApiClient(
cache_dir=args.cache_dir,
max_rps=args.max_rps,
force_refresh=args.force_refresh,
)
games = load_schedule(client, args.season, start_date, end_date)
print(f"loaded {len(games)} final regular-season games")
team_stats = load_season_team_stats(client, args.season)
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, args.season)
if not rows:
raise RuntimeError("no rows built")
write_parquet(rows, output)
write_manifest(manifest, output, games, rows, client, args.season)
print(f"wrote {len(rows)} rows to {output}")
print(f"api metrics: {client.metrics.__dict__}")
if __name__ == "__main__":
main()
|