clarkkitchen22 commited on
Commit
8c5b9c6
·
verified ·
1 Parent(s): 17e4255

Add MLB 2024 ChatML matchup dataset

Browse files

Upload verified 2024 MLB ChatML matchup Parquet split, schema, manifest, reproducibility scripts, and a polished dataset card.

README.md ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - en
5
+ task_categories:
6
+ - text-generation
7
+ - question-answering
8
+ tags:
9
+ - mlb
10
+ - baseball
11
+ - sports-analytics
12
+ - chatml
13
+ - parquet
14
+ - instruction-tuning
15
+ - matchup-analysis
16
+ - structured-output
17
+ - statsapi
18
+ size_categories:
19
+ - 1K<n<10K
20
+ pretty_name: MLB 2024 ChatML Matchups
21
+ configs:
22
+ - config_name: default
23
+ data_files:
24
+ - split: train
25
+ path: data/train-00000-of-00001.parquet
26
+ ---
27
+
28
+ # MLB 2024 ChatML Matchups
29
+
30
+ MLB 2024 ChatML Matchups is a compact, inspection-friendly instruction dataset derived from the public MLB Stats API for the 2024 Major League Baseball regular season. It converts structured game, offense, and pitching data into ChatML-style examples that can be used to study grounded sports reasoning, structured response generation, and retrieval-conditioned assistant behavior.
31
+
32
+ The dataset is intentionally small enough to audit directly, but structured enough to support serious supervised fine-tuning experiments. Each row asks an assistant to build a pitching and offense matchup brief for one team against its opponent on a specific date. The target answer is a compact JSON object containing the exact facts supplied by the data pipeline.
33
+
34
+ ## Executive Summary
35
+
36
+ | Property | Value |
37
+ |---|---:|
38
+ | Season | 2024 MLB regular season |
39
+ | Source | Public MLB Stats API |
40
+ | Completed unique games | 2,425 |
41
+ | Rows | 4,850 |
42
+ | Teams | 30 |
43
+ | Format | Parquet |
44
+ | Split | `train` |
45
+ | Primary training column | `messages` |
46
+ | Unit of observation | One team perspective for one completed game |
47
+ | Target format | JSON inside the assistant message |
48
+
49
+ Each completed game emits two examples: one from the away team's perspective and one from the home team's perspective. Postponed placeholders are excluded. Suspended or continued games that appear on multiple schedule dates are deduplicated by MLB `gamePk`.
50
+
51
+ ## Motivation
52
+
53
+ Sports analytics work often lives at the boundary between structured records and natural-language reasoning. A model may need to answer a seemingly simple question such as "How did the Dodgers match up with the Padres?" while preserving numerical context about offense, pitching, final score, and opponent strength.
54
+
55
+ This dataset is designed for that boundary. It teaches the model to:
56
+
57
+ - condition on explicit facts rather than unsupported memory
58
+ - preserve team, opponent, score, batting, and pitching context
59
+ - reason from a team-specific point of view
60
+ - emit structured, machine-checkable assistant outputs
61
+ - keep sports analysis grounded in the supplied record
62
+
63
+ The result is a useful dataset for fine-tuning and evaluation workflows where the goal is not just fluent commentary, but disciplined use of retrieved or supplied sports data.
64
+
65
+ ## What Is In Each Row
66
+
67
+ Every row includes:
68
+
69
+ - game identity and date
70
+ - team and opponent identity
71
+ - home/away side
72
+ - final score from the row team's perspective
73
+ - game-level batting statistics for both teams
74
+ - game-level pitching statistics for both teams
75
+ - full-season 2024 hitting statistics for both teams
76
+ - full-season 2024 pitching statistics for both teams
77
+ - a ChatML `messages` field containing `system`, `user`, and `assistant` turns
78
+
79
+ The assistant answer is JSON. This makes the target easy to validate, parse, score, and transform into downstream prose if desired.
80
+
81
+ ## Data Sources And Construction
82
+
83
+ The dataset was built from the public MLB Stats API:
84
+
85
+ - `https://statsapi.mlb.com/api/v1/schedule`
86
+ - `https://statsapi.mlb.com/api/v1/teams/stats`
87
+ - `https://statsapi.mlb.com/api/v1/game/{gamePk}/boxscore`
88
+
89
+ The builder performs a sequential, rate-limited scrape with a local disk cache, retry/backoff behavior, and explicit `429` handling. The completed run used 2,427 network requests, had zero retries, and received zero rate-limit responses.
90
+
91
+ The season team statistics are full-season 2024 aggregates. They are included as context for model learning and matchup framing, not as a pregame-only feature matrix.
92
+
93
+ ## Row Example
94
+
95
+ ```json
96
+ [
97
+ {
98
+ "role": "system",
99
+ "content": "You are an MLB matchup analyst. Use only the supplied 2024 MLB Stats API facts and answer in compact JSON."
100
+ },
101
+ {
102
+ "role": "user",
103
+ "content": "Build a pitching and offense matchup brief for Los Angeles Dodgers vs San Diego Padres on 2024-03-20."
104
+ },
105
+ {
106
+ "role": "assistant",
107
+ "content": "{\"season\":2024,\"game_pk\":745444,\"team\":{\"name\":\"Los Angeles Dodgers\",...}}"
108
+ }
109
+ ]
110
+ ```
111
+
112
+ ## Column Schema
113
+
114
+ | Column | Description |
115
+ |---|---|
116
+ | `row_id` | Stable identifier: `mlb-2024-{game_pk}-{side}` |
117
+ | `season` | Season year, always `2024` |
118
+ | `game_pk` | MLB game identifier |
119
+ | `game_date` | UTC date as `YYYY-MM-DD` |
120
+ | `game_datetime_utc` | Full UTC game datetime from MLB schedule data |
121
+ | `team_id`, `team_name`, `team_side` | Team identity and row perspective |
122
+ | `opponent_id`, `opponent_name`, `opponent_side` | Opponent identity and side |
123
+ | `team_runs`, `opponent_runs` | Final score from the row team's perspective |
124
+ | `result` | `win`, `loss`, or `tie` |
125
+ | `messages` | ChatML-style `system`, `user`, `assistant` messages |
126
+ | `assistant_payload_json` | Full assistant target payload as JSON text |
127
+ | `team_game_batting_json` | Team game batting line |
128
+ | `team_game_pitching_json` | Team game pitching line |
129
+ | `opponent_game_batting_json` | Opponent game batting line |
130
+ | `opponent_game_pitching_json` | Opponent game pitching line |
131
+ | `team_season_hitting_json` | Team full-season hitting context |
132
+ | `team_season_pitching_json` | Team full-season pitching context |
133
+ | `opponent_season_hitting_json` | Opponent full-season hitting context |
134
+ | `opponent_season_pitching_json` | Opponent full-season pitching context |
135
+
136
+ ## Loading The Dataset
137
+
138
+ ### Hugging Face Datasets
139
+
140
+ ```python
141
+ from datasets import load_dataset
142
+
143
+ ds = load_dataset("clarkkitchen22/MLB-2024-ChatML-Matchups", split="train")
144
+ row = ds[0]
145
+
146
+ messages = row["messages"]
147
+ assistant_payload = row["assistant_payload_json"]
148
+ ```
149
+
150
+ ### Pandas
151
+
152
+ ```python
153
+ import pandas as pd
154
+
155
+ df = pd.read_parquet(
156
+ "hf://datasets/clarkkitchen22/MLB-2024-ChatML-Matchups/data/train-00000-of-00001.parquet"
157
+ )
158
+
159
+ print(df[["team_name", "opponent_name", "team_runs", "opponent_runs", "result"]].head())
160
+ ```
161
+
162
+ ## How To Use This Dataset
163
+
164
+ For supervised fine-tuning, use the `messages` column directly if your trainer accepts ChatML-style conversations. If your model requires a single text field, render each message list through the tokenizer's chat template before training.
165
+
166
+ Recommended experiments:
167
+
168
+ - Train a small instruct model to preserve structured baseball facts in JSON.
169
+ - Evaluate structured-output faithfulness by parsing `assistant_payload_json`.
170
+ - Test retrieval-augmented pipelines where the retrieved Parquet row becomes the grounding context.
171
+ - Compare prose-generation prompts against JSON-first prompts for sports analytics reliability.
172
+ - Build a lightweight matchup assistant that can cite team offense and pitching context.
173
+
174
+ The cleanest research use is to treat this as a controlled structured-output dataset: the model is asked for analysis, but the target is deliberately fact-shaped and parseable.
175
+
176
+ ## Why This Dataset Matters
177
+
178
+ Many sports datasets are either raw tables or free-form text. Raw tables are easy to compute over but awkward for chat-model training. Free-form text is easy to train on but hard to audit for factual grounding. This dataset sits between those extremes: every example is conversational at the surface and structured at the target.
179
+
180
+ That design makes it useful for a practical machine-learning question: can a model learn to be conversational while staying bound to supplied statistical evidence?
181
+
182
+ ## Verification
183
+
184
+ The dataset was verified with `scripts/verify_dataset.py`.
185
+
186
+ Verification summary:
187
+
188
+ - `rows`: 4,850
189
+ - `games`: 2,425
190
+ - `teams`: 30
191
+ - `rows_match_schedule_x2`: true
192
+ - `unique_row_ids`: true
193
+ - `all_games_present`: true
194
+ - `all_30_teams_present`: true
195
+ - `season_matches`: true
196
+ - `chatml_roles_valid`: true
197
+ - `pitching_fields_present`: true
198
+
199
+ ## Limitations
200
+
201
+ - This dataset reflects MLB Stats API responses available at build time.
202
+ - Season team statistics are full-season 2024 totals, not strictly pregame rolling features.
203
+ - The assistant targets are structured JSON, not finished editorial scouting prose.
204
+ - It does not include player-level pitch-by-pitch events, betting odds, injuries, weather, umpires, lineups, or park-factor adjustments.
205
+ - It is not suitable by itself for causal claims about team quality or predictive wagering.
206
+ - Commercial use and redistribution should be evaluated against applicable MLB data terms and policies.
207
+
208
+ ## Responsible Use
209
+
210
+ Use this dataset for sports analytics research, instruction tuning, retrieval prototypes, and structured-output evaluation. Do not present model outputs as official MLB commentary, real-time predictions, injury guidance, or betting advice.
211
+
212
+ ## Attribution
213
+
214
+ Data was collected from the public MLB Stats API. This dataset is not affiliated with, endorsed by, or sponsored by Major League Baseball, MLB Advanced Media, or any MLB club.
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9df8e2a8cbbbc04853b21ef992c40260cf0f2d63dd900656c0930c184ba89592
3
+ size 1884925
mlb_2024_chatml_matchups.manifest.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "api_metrics": {
3
+ "cache_hits": 0,
4
+ "network_requests": 2427,
5
+ "rate_limited": 0,
6
+ "retries": 0
7
+ },
8
+ "created_at": "2026-05-14T01:35:56.947999+00:00",
9
+ "output_path": "data/processed/mlb_2024_chatml_matchups.parquet",
10
+ "regular_season_final_games": 2425,
11
+ "rows": 4850,
12
+ "season": 2024,
13
+ "source": "https://statsapi.mlb.com/api/v1"
14
+ }
schema.json ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "MLB 2024 ChatML Matchup Row",
4
+ "type": "object",
5
+ "required": [
6
+ "row_id",
7
+ "season",
8
+ "game_pk",
9
+ "game_date",
10
+ "game_datetime_utc",
11
+ "team_id",
12
+ "team_name",
13
+ "team_side",
14
+ "opponent_id",
15
+ "opponent_name",
16
+ "opponent_side",
17
+ "team_runs",
18
+ "opponent_runs",
19
+ "result",
20
+ "messages",
21
+ "assistant_payload_json",
22
+ "team_game_batting_json",
23
+ "team_game_pitching_json",
24
+ "opponent_game_batting_json",
25
+ "opponent_game_pitching_json",
26
+ "team_season_hitting_json",
27
+ "team_season_pitching_json",
28
+ "opponent_season_hitting_json",
29
+ "opponent_season_pitching_json"
30
+ ],
31
+ "properties": {
32
+ "row_id": {
33
+ "type": "string",
34
+ "pattern": "^mlb-2024-[0-9]+-(away|home)$"
35
+ },
36
+ "season": {
37
+ "const": 2024
38
+ },
39
+ "game_pk": {
40
+ "type": "integer"
41
+ },
42
+ "game_date": {
43
+ "type": "string",
44
+ "format": "date"
45
+ },
46
+ "game_datetime_utc": {
47
+ "type": "string"
48
+ },
49
+ "team_id": {
50
+ "type": "integer"
51
+ },
52
+ "team_name": {
53
+ "type": "string"
54
+ },
55
+ "team_side": {
56
+ "enum": ["away", "home"]
57
+ },
58
+ "opponent_id": {
59
+ "type": "integer"
60
+ },
61
+ "opponent_name": {
62
+ "type": "string"
63
+ },
64
+ "opponent_side": {
65
+ "enum": ["away", "home"]
66
+ },
67
+ "team_runs": {
68
+ "type": "integer"
69
+ },
70
+ "opponent_runs": {
71
+ "type": "integer"
72
+ },
73
+ "result": {
74
+ "enum": ["win", "loss", "tie"]
75
+ },
76
+ "messages": {
77
+ "type": "array",
78
+ "minItems": 3,
79
+ "maxItems": 3,
80
+ "items": {
81
+ "type": "object",
82
+ "required": ["role", "content"],
83
+ "properties": {
84
+ "role": {
85
+ "enum": ["system", "user", "assistant"]
86
+ },
87
+ "content": {
88
+ "type": "string"
89
+ }
90
+ }
91
+ }
92
+ },
93
+ "assistant_payload_json": {
94
+ "type": "string"
95
+ },
96
+ "team_game_batting_json": {
97
+ "type": "string"
98
+ },
99
+ "team_game_pitching_json": {
100
+ "type": "string"
101
+ },
102
+ "opponent_game_batting_json": {
103
+ "type": "string"
104
+ },
105
+ "opponent_game_pitching_json": {
106
+ "type": "string"
107
+ },
108
+ "team_season_hitting_json": {
109
+ "type": "string"
110
+ },
111
+ "team_season_pitching_json": {
112
+ "type": "string"
113
+ },
114
+ "opponent_season_hitting_json": {
115
+ "type": "string"
116
+ },
117
+ "opponent_season_pitching_json": {
118
+ "type": "string"
119
+ }
120
+ }
121
+ }
scripts/build_dataset.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import hashlib
6
+ import json
7
+ import random
8
+ import time
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urlencode
14
+
15
+ import pyarrow as pa
16
+ import pyarrow.parquet as pq
17
+ import requests
18
+
19
+
20
+ BASE_URL = "https://statsapi.mlb.com/api/v1"
21
+ DEFAULT_SEASON = 2025
22
+
23
+ STAT_KEYS = [
24
+ "gamesPlayed",
25
+ "runs",
26
+ "hits",
27
+ "doubles",
28
+ "triples",
29
+ "homeRuns",
30
+ "rbi",
31
+ "baseOnBalls",
32
+ "strikeOuts",
33
+ "stolenBases",
34
+ "caughtStealing",
35
+ "avg",
36
+ "obp",
37
+ "slg",
38
+ "ops",
39
+ "era",
40
+ "whip",
41
+ "inningsPitched",
42
+ "earnedRuns",
43
+ "battersFaced",
44
+ "groundOuts",
45
+ "airOuts",
46
+ "leftOnBase",
47
+ ]
48
+
49
+
50
+ @dataclass
51
+ class ApiMetrics:
52
+ network_requests: int = 0
53
+ cache_hits: int = 0
54
+ retries: int = 0
55
+ rate_limited: int = 0
56
+
57
+
58
+ class RateLimiter:
59
+ def __init__(self, max_rps: float) -> None:
60
+ if max_rps <= 0:
61
+ raise ValueError("--max-rps must be positive")
62
+ self.min_interval = 1.0 / max_rps
63
+ self.last_request_at = 0.0
64
+
65
+ def wait(self) -> None:
66
+ elapsed = time.monotonic() - self.last_request_at
67
+ remaining = self.min_interval - elapsed
68
+ if remaining > 0:
69
+ time.sleep(remaining)
70
+ self.last_request_at = time.monotonic()
71
+
72
+
73
+ class MlbApiClient:
74
+ def __init__(
75
+ self,
76
+ cache_dir: Path,
77
+ max_rps: float,
78
+ force_refresh: bool = False,
79
+ timeout: int = 30,
80
+ max_retries: int = 5,
81
+ ) -> None:
82
+ self.cache_dir = cache_dir
83
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
84
+ self.force_refresh = force_refresh
85
+ self.timeout = timeout
86
+ self.max_retries = max_retries
87
+ self.rate_limiter = RateLimiter(max_rps=max_rps)
88
+ self.metrics = ApiMetrics()
89
+ self.session = requests.Session()
90
+ self.session.headers.update(
91
+ {
92
+ "Accept": "application/json",
93
+ "User-Agent": (
94
+ "mlb-chatml-2025-dataset/0.1 "
95
+ "(research dataset builder; contact: Clark Kitchen)"
96
+ ),
97
+ }
98
+ )
99
+
100
+ def get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
101
+ params = params or {}
102
+ url = f"{BASE_URL}{path}"
103
+ cache_path = self._cache_path(url, params)
104
+ if cache_path.exists() and not self.force_refresh:
105
+ self.metrics.cache_hits += 1
106
+ return json.loads(cache_path.read_text())
107
+
108
+ query = urlencode(sorted(params.items()))
109
+ full_url = f"{url}?{query}" if query else url
110
+ last_error: Exception | None = None
111
+ for attempt in range(self.max_retries + 1):
112
+ if attempt:
113
+ self.metrics.retries += 1
114
+ sleep_seconds = min(60.0, (2**attempt) + random.uniform(0.0, 0.5))
115
+ time.sleep(sleep_seconds)
116
+ self.rate_limiter.wait()
117
+ self.metrics.network_requests += 1
118
+ try:
119
+ response = self.session.get(full_url, timeout=self.timeout)
120
+ if response.status_code == 429:
121
+ self.metrics.rate_limited += 1
122
+ retry_after = response.headers.get("Retry-After")
123
+ if retry_after:
124
+ time.sleep(min(float(retry_after), 120.0))
125
+ continue
126
+ if response.status_code >= 500:
127
+ continue
128
+ response.raise_for_status()
129
+ data = response.json()
130
+ cache_path.write_text(json.dumps(data, sort_keys=True))
131
+ return data
132
+ except (requests.RequestException, json.JSONDecodeError) as exc:
133
+ last_error = exc
134
+ continue
135
+ raise RuntimeError(f"MLB API request failed after retries: {full_url}") from last_error
136
+
137
+ def _cache_path(self, url: str, params: dict[str, Any]) -> Path:
138
+ cache_key = json.dumps({"url": url, "params": sorted(params.items())}, sort_keys=True)
139
+ digest = hashlib.sha256(cache_key.encode("utf-8")).hexdigest()
140
+ return self.cache_dir / f"{digest}.json"
141
+
142
+
143
+ def compact_stat_dict(stats: dict[str, Any]) -> dict[str, Any]:
144
+ return {key: stats[key] for key in STAT_KEYS if key in stats}
145
+
146
+
147
+ def default_start_date(season: int) -> str:
148
+ return f"{season}-03-01"
149
+
150
+
151
+ def default_end_date(season: int) -> str:
152
+ return f"{season}-11-30"
153
+
154
+
155
+ def load_schedule(
156
+ client: MlbApiClient, season: int, start_date: str, end_date: str
157
+ ) -> list[dict[str, Any]]:
158
+ data = client.get(
159
+ "/schedule",
160
+ {
161
+ "sportId": 1,
162
+ "season": season,
163
+ "gameType": "R",
164
+ "startDate": start_date,
165
+ "endDate": end_date,
166
+ },
167
+ )
168
+ games_by_pk: dict[int, dict[str, Any]] = {}
169
+ for date_block in data.get("dates", []):
170
+ for game in date_block.get("games", []):
171
+ status = game.get("status", {})
172
+ has_scores = (
173
+ game.get("teams", {}).get("away", {}).get("score") is not None
174
+ and game.get("teams", {}).get("home", {}).get("score") is not None
175
+ )
176
+ if status.get("statusCode") == "F" and has_scores:
177
+ game_pk = int(game["gamePk"])
178
+ previous = games_by_pk.get(game_pk)
179
+ if previous is None or game["gameDate"] > previous["gameDate"]:
180
+ games_by_pk[game_pk] = game
181
+ return sorted(games_by_pk.values(), key=lambda game: (game["gameDate"], int(game["gamePk"])))
182
+
183
+
184
+ def load_season_team_stats(
185
+ client: MlbApiClient, season: int
186
+ ) -> dict[int, dict[str, dict[str, Any]]]:
187
+ data = client.get(
188
+ "/teams/stats",
189
+ {
190
+ "season": season,
191
+ "sportIds": 1,
192
+ "group": "hitting,pitching",
193
+ "stats": "season",
194
+ },
195
+ )
196
+ team_stats: dict[int, dict[str, dict[str, Any]]] = {}
197
+ for stat_block in data.get("stats", []):
198
+ group = stat_block.get("group", {}).get("displayName")
199
+ if group not in {"hitting", "pitching"}:
200
+ continue
201
+ for split in stat_block.get("splits", []):
202
+ team_id = int(split["team"]["id"])
203
+ team_stats.setdefault(team_id, {})[group] = compact_stat_dict(split.get("stat", {}))
204
+ return team_stats
205
+
206
+
207
+ def score_for_side(game: dict[str, Any], side: str) -> int | None:
208
+ value = game.get("teams", {}).get(side, {}).get("score")
209
+ return int(value) if value is not None else None
210
+
211
+
212
+ def result_for(team_runs: int | None, opponent_runs: int | None) -> str:
213
+ if team_runs is None or opponent_runs is None:
214
+ return "unknown"
215
+ if team_runs > opponent_runs:
216
+ return "win"
217
+ if team_runs < opponent_runs:
218
+ return "loss"
219
+ return "tie"
220
+
221
+
222
+ def json_dumps(data: Any) -> str:
223
+ return json.dumps(data, sort_keys=True, separators=(",", ":"))
224
+
225
+
226
+ def matchup_assistant_payload(
227
+ game: dict[str, Any],
228
+ side: str,
229
+ opponent_side: str,
230
+ team_stats: dict[int, dict[str, dict[str, Any]]],
231
+ boxscore: dict[str, Any],
232
+ season: int,
233
+ ) -> dict[str, Any]:
234
+ team = game["teams"][side]["team"]
235
+ opponent = game["teams"][opponent_side]["team"]
236
+ team_id = int(team["id"])
237
+ opponent_id = int(opponent["id"])
238
+ team_box = boxscore["teams"][side]
239
+ opponent_box = boxscore["teams"][opponent_side]
240
+ team_runs = score_for_side(game, side)
241
+ opponent_runs = score_for_side(game, opponent_side)
242
+ return {
243
+ "season": season,
244
+ "game_pk": game["gamePk"],
245
+ "game_date": game["gameDate"],
246
+ "team": {"id": team_id, "name": team["name"], "side": side},
247
+ "opponent": {"id": opponent_id, "name": opponent["name"], "side": opponent_side},
248
+ "score": {
249
+ "team_runs": team_runs,
250
+ "opponent_runs": opponent_runs,
251
+ "result": result_for(team_runs, opponent_runs),
252
+ },
253
+ "team_game": {
254
+ "batting": compact_stat_dict(team_box.get("teamStats", {}).get("batting", {})),
255
+ "pitching": compact_stat_dict(team_box.get("teamStats", {}).get("pitching", {})),
256
+ "fielding": compact_stat_dict(team_box.get("teamStats", {}).get("fielding", {})),
257
+ },
258
+ "opponent_game": {
259
+ "batting": compact_stat_dict(opponent_box.get("teamStats", {}).get("batting", {})),
260
+ "pitching": compact_stat_dict(opponent_box.get("teamStats", {}).get("pitching", {})),
261
+ "fielding": compact_stat_dict(opponent_box.get("teamStats", {}).get("fielding", {})),
262
+ },
263
+ "team_season": team_stats.get(team_id, {}),
264
+ "opponent_season": team_stats.get(opponent_id, {}),
265
+ }
266
+
267
+
268
+ def build_messages(payload: dict[str, Any], season: int) -> list[dict[str, str]]:
269
+ team = payload["team"]["name"]
270
+ opponent = payload["opponent"]["name"]
271
+ game_date = payload["game_date"][:10]
272
+ return [
273
+ {
274
+ "role": "system",
275
+ "content": (
276
+ f"You are an MLB matchup analyst. Use only the supplied {season} MLB Stats API "
277
+ "facts and answer in compact JSON."
278
+ ),
279
+ },
280
+ {
281
+ "role": "user",
282
+ "content": (
283
+ f"Build a pitching and offense matchup brief for {team} vs {opponent} "
284
+ f"on {game_date}."
285
+ ),
286
+ },
287
+ {"role": "assistant", "content": json_dumps(payload)},
288
+ ]
289
+
290
+
291
+ def build_rows(
292
+ games: list[dict[str, Any]],
293
+ team_stats: dict[int, dict[str, dict[str, Any]]],
294
+ client: MlbApiClient,
295
+ limit_games: int | None,
296
+ season: int,
297
+ ) -> list[dict[str, Any]]:
298
+ rows: list[dict[str, Any]] = []
299
+ selected_games = games[:limit_games] if limit_games else games
300
+ for index, game in enumerate(selected_games, start=1):
301
+ if index == 1 or index % 100 == 0 or index == len(selected_games):
302
+ print(f"fetching boxscores {index}/{len(selected_games)} gamePk={game['gamePk']}")
303
+ boxscore = client.get(f"/game/{game['gamePk']}/boxscore")
304
+ for side, opponent_side in (("away", "home"), ("home", "away")):
305
+ payload = matchup_assistant_payload(
306
+ game, side, opponent_side, team_stats, boxscore, season
307
+ )
308
+ team = payload["team"]
309
+ opponent = payload["opponent"]
310
+ team_runs = payload["score"]["team_runs"]
311
+ opponent_runs = payload["score"]["opponent_runs"]
312
+ row = {
313
+ "row_id": f"mlb-{season}-{game['gamePk']}-{side}",
314
+ "season": season,
315
+ "game_pk": int(game["gamePk"]),
316
+ "game_date": game["gameDate"][:10],
317
+ "game_datetime_utc": game["gameDate"],
318
+ "team_id": int(team["id"]),
319
+ "team_name": team["name"],
320
+ "team_side": side,
321
+ "opponent_id": int(opponent["id"]),
322
+ "opponent_name": opponent["name"],
323
+ "opponent_side": opponent_side,
324
+ "team_runs": team_runs,
325
+ "opponent_runs": opponent_runs,
326
+ "result": payload["score"]["result"],
327
+ "messages": build_messages(payload, season),
328
+ "assistant_payload_json": json_dumps(payload),
329
+ "team_game_batting_json": json_dumps(payload["team_game"]["batting"]),
330
+ "team_game_pitching_json": json_dumps(payload["team_game"]["pitching"]),
331
+ "opponent_game_batting_json": json_dumps(payload["opponent_game"]["batting"]),
332
+ "opponent_game_pitching_json": json_dumps(payload["opponent_game"]["pitching"]),
333
+ "team_season_hitting_json": json_dumps(payload["team_season"].get("hitting", {})),
334
+ "team_season_pitching_json": json_dumps(payload["team_season"].get("pitching", {})),
335
+ "opponent_season_hitting_json": json_dumps(
336
+ payload["opponent_season"].get("hitting", {})
337
+ ),
338
+ "opponent_season_pitching_json": json_dumps(
339
+ payload["opponent_season"].get("pitching", {})
340
+ ),
341
+ }
342
+ rows.append(row)
343
+ return rows
344
+
345
+
346
+ def write_parquet(rows: list[dict[str, Any]], output_path: Path) -> None:
347
+ output_path.parent.mkdir(parents=True, exist_ok=True)
348
+ schema = pa.schema(
349
+ [
350
+ ("row_id", pa.string()),
351
+ ("season", pa.int16()),
352
+ ("game_pk", pa.int64()),
353
+ ("game_date", pa.string()),
354
+ ("game_datetime_utc", pa.string()),
355
+ ("team_id", pa.int64()),
356
+ ("team_name", pa.string()),
357
+ ("team_side", pa.string()),
358
+ ("opponent_id", pa.int64()),
359
+ ("opponent_name", pa.string()),
360
+ ("opponent_side", pa.string()),
361
+ ("team_runs", pa.int16()),
362
+ ("opponent_runs", pa.int16()),
363
+ ("result", pa.string()),
364
+ (
365
+ "messages",
366
+ pa.list_(pa.struct([("role", pa.string()), ("content", pa.string())])),
367
+ ),
368
+ ("assistant_payload_json", pa.string()),
369
+ ("team_game_batting_json", pa.string()),
370
+ ("team_game_pitching_json", pa.string()),
371
+ ("opponent_game_batting_json", pa.string()),
372
+ ("opponent_game_pitching_json", pa.string()),
373
+ ("team_season_hitting_json", pa.string()),
374
+ ("team_season_pitching_json", pa.string()),
375
+ ("opponent_season_hitting_json", pa.string()),
376
+ ("opponent_season_pitching_json", pa.string()),
377
+ ]
378
+ )
379
+ table = pa.Table.from_pylist(rows, schema=schema)
380
+ pq.write_table(table, output_path, compression="zstd")
381
+
382
+
383
+ def write_manifest(
384
+ manifest_path: Path,
385
+ output_path: Path,
386
+ games: list[dict[str, Any]],
387
+ rows: list[dict[str, Any]],
388
+ client: MlbApiClient,
389
+ season: int,
390
+ ) -> None:
391
+ manifest = {
392
+ "created_at": datetime.now(timezone.utc).isoformat(),
393
+ "season": season,
394
+ "source": "https://statsapi.mlb.com/api/v1",
395
+ "regular_season_final_games": len(games),
396
+ "rows": len(rows),
397
+ "output_path": str(output_path),
398
+ "api_metrics": client.metrics.__dict__,
399
+ }
400
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
401
+ manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True))
402
+
403
+
404
+ def parse_args() -> argparse.Namespace:
405
+ parser = argparse.ArgumentParser(description=__doc__)
406
+ parser.add_argument("--season", type=int, default=DEFAULT_SEASON)
407
+ parser.add_argument("--start-date", default=None)
408
+ parser.add_argument("--end-date", default=None)
409
+ parser.add_argument("--cache-dir", type=Path, default=Path(".cache/mlb_api"))
410
+ parser.add_argument(
411
+ "--output",
412
+ type=Path,
413
+ default=None,
414
+ )
415
+ parser.add_argument(
416
+ "--manifest",
417
+ type=Path,
418
+ default=None,
419
+ )
420
+ parser.add_argument("--max-rps", type=float, default=4.0)
421
+ parser.add_argument("--force-refresh", action="store_true")
422
+ parser.add_argument("--limit-games", type=int, default=None)
423
+ return parser.parse_args()
424
+
425
+
426
+ def main() -> None:
427
+ args = parse_args()
428
+ start_date = args.start_date or default_start_date(args.season)
429
+ end_date = args.end_date or default_end_date(args.season)
430
+ output = args.output or Path(f"data/processed/mlb_{args.season}_chatml_matchups.parquet")
431
+ manifest = args.manifest or Path(
432
+ f"data/processed/mlb_{args.season}_chatml_matchups.manifest.json"
433
+ )
434
+ client = MlbApiClient(
435
+ cache_dir=args.cache_dir,
436
+ max_rps=args.max_rps,
437
+ force_refresh=args.force_refresh,
438
+ )
439
+ games = load_schedule(client, args.season, start_date, end_date)
440
+ print(f"loaded {len(games)} final regular-season games")
441
+ team_stats = load_season_team_stats(client, args.season)
442
+ if len(team_stats) != 30:
443
+ raise RuntimeError(f"expected 30 teams with season stats, got {len(team_stats)}")
444
+ rows = build_rows(games, team_stats, client, args.limit_games, args.season)
445
+ if not rows:
446
+ raise RuntimeError("no rows built")
447
+ write_parquet(rows, output)
448
+ write_manifest(manifest, output, games, rows, client, args.season)
449
+ print(f"wrote {len(rows)} rows to {output}")
450
+ print(f"api metrics: {client.metrics.__dict__}")
451
+
452
+
453
+ if __name__ == "__main__":
454
+ main()
scripts/verify_dataset.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import pyarrow.parquet as pq
9
+
10
+ from build_dataset import MlbApiClient, default_end_date, default_start_date, load_schedule
11
+
12
+
13
+ def parse_args() -> argparse.Namespace:
14
+ parser = argparse.ArgumentParser(description="Verify the generated MLB ChatML parquet dataset.")
15
+ parser.add_argument(
16
+ "--parquet",
17
+ type=Path,
18
+ default=None,
19
+ )
20
+ parser.add_argument("--season", type=int, default=2025)
21
+ parser.add_argument("--start-date", default=None)
22
+ parser.add_argument("--end-date", default=None)
23
+ parser.add_argument("--cache-dir", type=Path, default=Path(".cache/mlb_api"))
24
+ parser.add_argument("--max-rps", type=float, default=4.0)
25
+ return parser.parse_args()
26
+
27
+
28
+ def main() -> None:
29
+ args = parse_args()
30
+ parquet_path = args.parquet or Path(
31
+ f"data/processed/mlb_{args.season}_chatml_matchups.parquet"
32
+ )
33
+ if not parquet_path.exists():
34
+ raise SystemExit(f"missing parquet file: {parquet_path}")
35
+
36
+ table = pq.read_table(parquet_path)
37
+ rows = table.to_pylist()
38
+ client = MlbApiClient(cache_dir=args.cache_dir, max_rps=args.max_rps)
39
+ start_date = args.start_date or default_start_date(args.season)
40
+ end_date = args.end_date or default_end_date(args.season)
41
+ games = load_schedule(client, args.season, start_date, end_date)
42
+ expected_rows = len(games) * 2
43
+
44
+ row_ids = [row["row_id"] for row in rows]
45
+ game_pks = {row["game_pk"] for row in rows}
46
+ team_ids = {row["team_id"] for row in rows}
47
+ seasons = {row["season"] for row in rows}
48
+ bad_messages = [
49
+ row["row_id"]
50
+ for row in rows
51
+ if [message["role"] for message in row["messages"]] != ["system", "user", "assistant"]
52
+ ]
53
+ missing_pitching = [
54
+ row["row_id"]
55
+ for row in rows
56
+ if not json.loads(row["team_game_pitching_json"])
57
+ or not json.loads(row["team_season_pitching_json"])
58
+ or not json.loads(row["opponent_game_pitching_json"])
59
+ ]
60
+
61
+ checks = {
62
+ "rows_match_schedule_x2": len(rows) == expected_rows,
63
+ "unique_row_ids": len(row_ids) == len(set(row_ids)),
64
+ "all_games_present": len(game_pks) == len(games),
65
+ "all_30_teams_present": len(team_ids) == 30,
66
+ "season_matches": seasons == {args.season},
67
+ "chatml_roles_valid": not bad_messages,
68
+ "pitching_fields_present": not missing_pitching,
69
+ }
70
+ print(
71
+ json.dumps(
72
+ {
73
+ "parquet": str(parquet_path),
74
+ "season": args.season,
75
+ "rows": len(rows),
76
+ "expected_rows": expected_rows,
77
+ "games": len(games),
78
+ "teams": len(team_ids),
79
+ "checks": checks,
80
+ "api_metrics": client.metrics.__dict__,
81
+ },
82
+ indent=2,
83
+ sort_keys=True,
84
+ )
85
+ )
86
+ failed = [name for name, passed in checks.items() if not passed]
87
+ if failed:
88
+ raise SystemExit(f"verification failed: {failed}")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()