espn-odds-scraper 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Oronto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: espn_odds_scraper
3
+ Version: 0.2.0
4
+ Summary: A package for scraping historical and live MLB odds from ESPN's public API
5
+ Author-email: Oronto <vile319@gmail.com>
6
+ Project-URL: Homepage, https://github.com/Oronto/espn_odds_scraper
7
+ Project-URL: Bug Tracker, https://github.com/Oronto/espn_odds_scraper/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: pandas>=1.0.0
15
+ Requires-Dist: requests>=2.0.0
16
+ Requires-Dist: MLB-StatsAPI>=1.0.0
17
+ Dynamic: license-file
18
+
19
+ # espn_odds_scraper
20
+
21
+ Scrape historical and live MLB odds from ESPN's public (undocumented) API. No API key, no Selenium — plain JSON requests.
22
+
23
+ Successor to `mlb_odds_scraper` (OddsPortal/Selenium based). ESPN carries per-book odds (DraftKings, FanDuel, Caesars, MGM, Bet365, ...; older seasons carry BOVADA, 5Dimes, etc.), moneyline + run line + total in a single request per game, and timestamped line-movement history on its consensus feed.
24
+
25
+ **Coverage:** solid from ~2015 onward. Earlier seasons exist but are degraded (moneylines often missing).
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install espn_odds_scraper
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ```python
36
+ from espn_odds_scraper import scrape_espn_mlb, scrape_espn_mlb_years
37
+
38
+ # One day, every book — one row per game x sportsbook
39
+ df = scrape_espn_mlb("2023-07-14")
40
+
41
+ # Date range, only certain books
42
+ df = scrape_espn_mlb("2023-07-01", "2023-07-31", providers=["DraftKings", "FanDuel"])
43
+
44
+ # With full timestamped line movement (opt-in, ~3 extra requests per game)
45
+ odds, movement = scrape_espn_mlb("2023-07-14", include_history=True)
46
+
47
+ # Whole seasons
48
+ df = scrape_espn_mlb_years(2018, 2024)
49
+ ```
50
+
51
+ ### Odds DataFrame columns
52
+
53
+ `game_id, game_datetime (UTC), status, completed, home_team_abbr, away_team_abbr, home_team_name, away_team_name, home_team_espn_id, away_team_espn_id, home_score, away_score, provider_id, provider, home_ml, away_ml, spread (home line), home_spread_odds, away_spread_odds, total, over_odds, under_odds, open_* (8 cols), close_* (8 cols), moneyline_winner, spread_winner`
54
+
55
+ For completed games, per-book odds are the lines frozen at game time — effectively **closing lines**. In-game "Live Odds" feeds are dropped by default (`exclude_live=False` to keep them).
56
+
57
+ ### Opening / closing lines & line movement
58
+
59
+ ESPN's data comes in two eras:
60
+
61
+ - **2024+ (ESPN BET / DraftKings era):** each book carries real `open_*` and `close_*` snapshots (moneyline, spread + prices, total + prices) directly in the odds row — no extra requests. Fewer books, though (often just one).
62
+ - **≤2023 (multi-book era):** `open_*`/`close_*` are empty (ESPN stored junk there), but full **timestamped line movement** exists on the consensus feed:
63
+
64
+ ```python
65
+ from espn_odds_scraper import fetch_line_history, get_open_close
66
+
67
+ movement = fetch_line_history("401472391") # timestamped rows per market
68
+ oc = get_open_close(movement) # one row per market: open_* and close_*
69
+ ```
70
+
71
+ Movement rows: `game_id, market (moneyline/spread/total), line_date (UTC), away_odds, home_odds, over_odds, under_odds, line`. First row per market is the opener, last is the closer. ESPN dropped this feed after the 2023 season.
72
+
73
+ ### Drop-in compatibility with mlb_odds_scraper
74
+
75
+ ```python
76
+ from espn_odds_scraper import to_legacy_format, clean_game_data
77
+
78
+ legacy = to_legacy_format(df) # game_date, game_datetime, home_team/away_team
79
+ # (statsapi ids), home_odds/away_odds, scores, abbrs
80
+ merged = clean_game_data(cleaned_schedule, legacy) # same merge helper as before
81
+ ```
82
+
83
+ ## Request footprint
84
+
85
+ - 1 request per day (schedule + scores)
86
+ - 1 request per game (all books, all markets)
87
+ - optional: 3 requests per game (line movement)
88
+
89
+ A full season is roughly 2,600 requests without history. Requests run through a thread pool (`max_workers=8` by default). Be polite; this is an undocumented API.
90
+
91
+ ## License
92
+
93
+ MIT
@@ -0,0 +1,75 @@
1
+ # espn_odds_scraper
2
+
3
+ Scrape historical and live MLB odds from ESPN's public (undocumented) API. No API key, no Selenium — plain JSON requests.
4
+
5
+ Successor to `mlb_odds_scraper` (OddsPortal/Selenium based). ESPN carries per-book odds (DraftKings, FanDuel, Caesars, MGM, Bet365, ...; older seasons carry BOVADA, 5Dimes, etc.), moneyline + run line + total in a single request per game, and timestamped line-movement history on its consensus feed.
6
+
7
+ **Coverage:** solid from ~2015 onward. Earlier seasons exist but are degraded (moneylines often missing).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install espn_odds_scraper
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ from espn_odds_scraper import scrape_espn_mlb, scrape_espn_mlb_years
19
+
20
+ # One day, every book — one row per game x sportsbook
21
+ df = scrape_espn_mlb("2023-07-14")
22
+
23
+ # Date range, only certain books
24
+ df = scrape_espn_mlb("2023-07-01", "2023-07-31", providers=["DraftKings", "FanDuel"])
25
+
26
+ # With full timestamped line movement (opt-in, ~3 extra requests per game)
27
+ odds, movement = scrape_espn_mlb("2023-07-14", include_history=True)
28
+
29
+ # Whole seasons
30
+ df = scrape_espn_mlb_years(2018, 2024)
31
+ ```
32
+
33
+ ### Odds DataFrame columns
34
+
35
+ `game_id, game_datetime (UTC), status, completed, home_team_abbr, away_team_abbr, home_team_name, away_team_name, home_team_espn_id, away_team_espn_id, home_score, away_score, provider_id, provider, home_ml, away_ml, spread (home line), home_spread_odds, away_spread_odds, total, over_odds, under_odds, open_* (8 cols), close_* (8 cols), moneyline_winner, spread_winner`
36
+
37
+ For completed games, per-book odds are the lines frozen at game time — effectively **closing lines**. In-game "Live Odds" feeds are dropped by default (`exclude_live=False` to keep them).
38
+
39
+ ### Opening / closing lines & line movement
40
+
41
+ ESPN's data comes in two eras:
42
+
43
+ - **2024+ (ESPN BET / DraftKings era):** each book carries real `open_*` and `close_*` snapshots (moneyline, spread + prices, total + prices) directly in the odds row — no extra requests. Fewer books, though (often just one).
44
+ - **≤2023 (multi-book era):** `open_*`/`close_*` are empty (ESPN stored junk there), but full **timestamped line movement** exists on the consensus feed:
45
+
46
+ ```python
47
+ from espn_odds_scraper import fetch_line_history, get_open_close
48
+
49
+ movement = fetch_line_history("401472391") # timestamped rows per market
50
+ oc = get_open_close(movement) # one row per market: open_* and close_*
51
+ ```
52
+
53
+ Movement rows: `game_id, market (moneyline/spread/total), line_date (UTC), away_odds, home_odds, over_odds, under_odds, line`. First row per market is the opener, last is the closer. ESPN dropped this feed after the 2023 season.
54
+
55
+ ### Drop-in compatibility with mlb_odds_scraper
56
+
57
+ ```python
58
+ from espn_odds_scraper import to_legacy_format, clean_game_data
59
+
60
+ legacy = to_legacy_format(df) # game_date, game_datetime, home_team/away_team
61
+ # (statsapi ids), home_odds/away_odds, scores, abbrs
62
+ merged = clean_game_data(cleaned_schedule, legacy) # same merge helper as before
63
+ ```
64
+
65
+ ## Request footprint
66
+
67
+ - 1 request per day (schedule + scores)
68
+ - 1 request per game (all books, all markets)
69
+ - optional: 3 requests per game (line movement)
70
+
71
+ A full season is roughly 2,600 requests without history. Requests run through a thread pool (`max_workers=8` by default). Be polite; this is an undocumented API.
72
+
73
+ ## License
74
+
75
+ MIT
@@ -0,0 +1,35 @@
1
+ """ESPN MLB odds scraper package."""
2
+
3
+ from .scraper import (
4
+ scrape_espn_mlb,
5
+ scrape_espn_mlb_years,
6
+ get_games,
7
+ get_odds,
8
+ fetch_line_history,
9
+ get_open_close,
10
+ to_legacy_format,
11
+ clean_game_data,
12
+ )
13
+ from .pipeline import (
14
+ scrape,
15
+ scrape_line_movement,
16
+ add_game_ids,
17
+ get_mlb_team_map,
18
+ )
19
+
20
+ __version__ = "0.2.0"
21
+
22
+ __all__ = [
23
+ "scrape",
24
+ "scrape_line_movement",
25
+ "add_game_ids",
26
+ "get_mlb_team_map",
27
+ "scrape_espn_mlb",
28
+ "scrape_espn_mlb_years",
29
+ "get_games",
30
+ "get_odds",
31
+ "fetch_line_history",
32
+ "get_open_close",
33
+ "to_legacy_format",
34
+ "clean_game_data",
35
+ ]
@@ -0,0 +1,453 @@
1
+ """STATSAPI V2 pipeline integration: sbr_odds-style output with MLB game_ids.
2
+
3
+ Usage in Main.ipynb:
4
+
5
+ import espn_odds_scraper as espn
6
+
7
+ if update_espn_odds:
8
+ espn_odds = espn.scrape(fetch_start_date, fetch_end_date, engine)
9
+ pdu.to_sql_upsert(espn_odds, 'espn_odds', engine,
10
+ ['game_id', 'sportsbook', 'odds_type'])
11
+
12
+ # one-time historical movement backfill (ESPN carries this <=2023 only):
13
+ # movement = espn.scrape_line_movement('2015-04-01', '2023-11-01', engine)
14
+ # pdu.to_sql_upsert(movement, 'espn_line_movement', engine,
15
+ # ['espn_game_id', 'market', 'timestamp'])
16
+ """
17
+
18
+ import re
19
+ import time
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+ from typing import Iterable
22
+
23
+ import pandas as pd
24
+ import requests
25
+
26
+ from .scraper import (
27
+ CORE_BASE,
28
+ BET_TYPES,
29
+ HISTORY_PROVIDER_ID,
30
+ SCOREBOARD_URL,
31
+ _daterange,
32
+ _date_str,
33
+ _get_json,
34
+ _pick,
35
+ _to_num,
36
+ )
37
+
38
+ TEAM_NAME_ALIASES = {
39
+ "d-backs": "diamondbacks",
40
+ "diamondbacks": "diamondbacks",
41
+ "athletics": "athletics",
42
+ "a's": "athletics",
43
+ "oakland athletics": "athletics",
44
+ }
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Schedule (includes venue) and per-book odds with open/current snapshots
49
+ # ---------------------------------------------------------------------------
50
+
51
+ def _get_games_pipeline(date):
52
+ data = _get_json(SCOREBOARD_URL, params={"dates": _date_str(date)})
53
+ if not data:
54
+ return []
55
+ games = []
56
+ for event in data.get("events", []):
57
+ try:
58
+ comp = event["competitions"][0]
59
+ status = comp.get("status", {}).get("type", {})
60
+ row = {
61
+ "espn_game_id": event["id"],
62
+ "game_datetime": event.get("date"),
63
+ "status": status.get("name", ""),
64
+ "completed": bool(status.get("completed", False)),
65
+ "venue": _pick(comp, "venue", "fullName") or "",
66
+ }
67
+ for side in comp.get("competitors", []):
68
+ prefix = "home" if side.get("homeAway") == "home" else "away"
69
+ team = side.get("team", {})
70
+ row[f"{prefix}_team"] = team.get("displayName", "")
71
+ row[f"{prefix}_team_short"] = team.get("abbreviation", "")
72
+ score = side.get("score", "")
73
+ row[f"{prefix}_score"] = (
74
+ pd.to_numeric(score, errors="coerce") if score != "" else None
75
+ )
76
+ games.append(row)
77
+ except Exception as e: # noqa: BLE001
78
+ print(f"Error parsing ESPN event on {date}: {e}")
79
+ return games
80
+
81
+
82
+ def _parse_phase_flat(item, phase):
83
+ home = _pick(item, "homeTeamOdds", phase) or {}
84
+ away = _pick(item, "awayTeamOdds", phase) or {}
85
+ totals = item.get(phase) or {}
86
+ return {
87
+ "home_ml": _to_num(_pick(home, "moneyLine", "american")),
88
+ "away_ml": _to_num(_pick(away, "moneyLine", "american")),
89
+ "spread": _to_num(_pick(home, "pointSpread", "american")),
90
+ "home_spread_odds": _to_num(_pick(home, "spread", "american")),
91
+ "away_spread_odds": _to_num(_pick(away, "spread", "american")),
92
+ "total": _to_num(_pick(totals, "total", "american")),
93
+ "over_odds": _to_num(_pick(totals, "over", "american")),
94
+ "under_odds": _to_num(_pick(totals, "under", "american")),
95
+ }
96
+
97
+
98
+ def _get_odds_pipeline(espn_game_id):
99
+ url = f"{CORE_BASE}/events/{espn_game_id}/competitions/{espn_game_id}/odds"
100
+ data = _get_json(url)
101
+ if not data:
102
+ return []
103
+ rows = []
104
+ for item in data.get("items", []):
105
+ try:
106
+ provider = item.get("provider", {})
107
+ cur = _parse_phase_flat(item, "current")
108
+ opn = _parse_phase_flat(item, "open")
109
+ if cur["home_ml"] is None:
110
+ cur["home_ml"] = _to_num(_pick(item, "homeTeamOdds", "moneyLine"))
111
+ if cur["away_ml"] is None:
112
+ cur["away_ml"] = _to_num(_pick(item, "awayTeamOdds", "moneyLine"))
113
+ if cur["total"] is None:
114
+ cur["total"] = _to_num(item.get("overUnder"))
115
+ if cur["over_odds"] is None:
116
+ cur["over_odds"] = _to_num(item.get("overOdds"))
117
+ if cur["under_odds"] is None:
118
+ cur["under_odds"] = _to_num(item.get("underOdds"))
119
+ rows.append(
120
+ {
121
+ "espn_game_id": str(espn_game_id),
122
+ "sportsbook": provider.get("name", ""),
123
+ "sportsbook_id": provider.get("id", ""),
124
+ "current": cur,
125
+ "open": opn,
126
+ }
127
+ )
128
+ except Exception as e: # noqa: BLE001
129
+ print(f"Error parsing odds for ESPN game {espn_game_id}: {e}")
130
+ return rows
131
+
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # MLB game_id mapping (same approach as picktheodds_scraper.add_game_ids)
135
+ # ---------------------------------------------------------------------------
136
+
137
+ def _normalize_team_name(name: str) -> str:
138
+ normalized = re.sub(r"[^a-z0-9]+", " ", str(name).lower()).strip()
139
+ normalized = re.sub(r"\s+", " ", normalized)
140
+ return TEAM_NAME_ALIASES.get(normalized, normalized)
141
+
142
+
143
+ def get_mlb_team_map() -> pd.DataFrame:
144
+ response = requests.get(
145
+ "https://statsapi.mlb.com/api/v1/teams?sportId=1", timeout=30
146
+ )
147
+ response.raise_for_status()
148
+ rows = []
149
+ for team in response.json().get("teams", []):
150
+ team_id = team.get("id")
151
+ names = {
152
+ team.get("name"),
153
+ team.get("teamName"),
154
+ team.get("clubName"),
155
+ team.get("shortName"),
156
+ team.get("abbreviation"),
157
+ }
158
+ for name in names:
159
+ if name:
160
+ rows.append(
161
+ {"team_name_key": _normalize_team_name(name),
162
+ "mlb_team_id": team_id}
163
+ )
164
+ return pd.DataFrame(rows).drop_duplicates("team_name_key")
165
+
166
+
167
+ def add_game_ids(
168
+ espn_games: pd.DataFrame,
169
+ engine,
170
+ schedule_table: str = "cleaned_schedule",
171
+ tz: str = "US/Eastern",
172
+ tolerance_hrs: int = 12,
173
+ ) -> pd.DataFrame:
174
+ """Attach MLB statsapi game_id to ESPN games via the schedule table."""
175
+ if espn_games.empty or engine is None:
176
+ espn_games = espn_games.copy()
177
+ espn_games["game_id"] = None
178
+ return espn_games
179
+
180
+ try:
181
+ schedule = pd.read_sql_table(schedule_table, engine)
182
+ except ValueError:
183
+ schedule = pd.read_sql_table("processed_schedule", engine)
184
+
185
+ team_map = get_mlb_team_map()
186
+ espn_games = espn_games.copy()
187
+ espn_games["home_team_key"] = espn_games["home_team"].apply(_normalize_team_name)
188
+ espn_games["away_team_key"] = espn_games["away_team"].apply(_normalize_team_name)
189
+
190
+ espn_games = espn_games.merge(
191
+ team_map.rename(columns={"team_name_key": "home_team_key",
192
+ "mlb_team_id": "home_mlb_team_id"}),
193
+ on="home_team_key", how="left",
194
+ )
195
+ espn_games = espn_games.merge(
196
+ team_map.rename(columns={"team_name_key": "away_team_key",
197
+ "mlb_team_id": "away_mlb_team_id"}),
198
+ on="away_team_key", how="left",
199
+ )
200
+
201
+ schedule = schedule[
202
+ ["game_id", "game_datetime", "home_team", "away_team"]
203
+ ].copy()
204
+ schedule.rename(
205
+ columns={"home_team": "home_mlb_team_id", "away_team": "away_mlb_team_id"},
206
+ inplace=True,
207
+ )
208
+ schedule["merge_datetime"] = (
209
+ pd.to_datetime(schedule["game_datetime"], utc=True)
210
+ .dt.tz_convert(tz)
211
+ .dt.tz_localize(None)
212
+ .astype("datetime64[us]")
213
+ )
214
+ schedule = schedule.drop(columns=["game_datetime"]).sort_values("merge_datetime")
215
+
216
+ espn_games["merge_datetime"] = (
217
+ pd.to_datetime(espn_games["game_datetime"], utc=True)
218
+ .dt.tz_convert(tz)
219
+ .dt.tz_localize(None)
220
+ .astype("datetime64[us]")
221
+ )
222
+ espn_games.sort_values("merge_datetime", inplace=True)
223
+
224
+ espn_games = pd.merge_asof(
225
+ espn_games,
226
+ schedule,
227
+ on="merge_datetime",
228
+ by=["home_mlb_team_id", "away_mlb_team_id"],
229
+ direction="nearest",
230
+ tolerance=pd.Timedelta(f"{tolerance_hrs}hr"),
231
+ )
232
+ espn_games.drop(columns=["home_team_key", "away_team_key", "merge_datetime"],
233
+ inplace=True)
234
+ espn_games["_has_game_id"] = espn_games["game_id"].notna()
235
+ espn_games.sort_values(["espn_game_id", "_has_game_id"],
236
+ ascending=[True, False], inplace=True)
237
+ espn_games.drop_duplicates("espn_game_id", keep="first", inplace=True)
238
+ espn_games.drop(columns=["_has_game_id"], inplace=True)
239
+
240
+ mapped = espn_games["game_id"].notna().sum()
241
+ if mapped < len(espn_games):
242
+ missing = espn_games.loc[espn_games["game_id"].isna(), "game_datetime"]
243
+ missing_dates = sorted(pd.to_datetime(missing).dt.date.unique())
244
+ print(
245
+ f"Mapped {mapped}/{len(espn_games)} ESPN games to MLB game_id. "
246
+ f"Missing dates in {schedule_table}: {missing_dates[:5]}"
247
+ )
248
+ return espn_games
249
+
250
+
251
+ # ---------------------------------------------------------------------------
252
+ # Main entry point (sbr_odds-style long output)
253
+ # ---------------------------------------------------------------------------
254
+
255
+ ESPN_ODDS_COLUMNS = [
256
+ "game_id", "espn_game_id", "date", "game_datetime",
257
+ "away_team", "away_team_short", "home_team", "home_team_short",
258
+ "away_score", "home_score", "venue", "status",
259
+ "sportsbook", "sportsbook_id", "odds_type",
260
+ "opening_home_odds", "opening_away_odds", "opening_line",
261
+ "current_home_odds", "current_away_odds", "current_line",
262
+ "scraped_at",
263
+ ]
264
+
265
+
266
+ def scrape(
267
+ start_date: str,
268
+ end_date: str,
269
+ engine=None,
270
+ odds_types: Iterable[str] = ("moneyline", "spread", "total"),
271
+ exclude_live: bool = True,
272
+ max_workers: int = 8,
273
+ schedule_table: str = "cleaned_schedule",
274
+ ) -> pd.DataFrame:
275
+ """Scrape ESPN MLB odds shaped like the sbr_odds table.
276
+
277
+ One row per game x sportsbook x odds_type. For totals, home = over and
278
+ away = under. 'current' odds are the closing line for completed games.
279
+ Opening odds are real from ~2024 onward; for <=2023 openers use
280
+ scrape_line_movement.
281
+
282
+ Upsert with keys ['game_id', 'sportsbook', 'odds_type'].
283
+ """
284
+ dates = _daterange(start_date, end_date)
285
+
286
+ games = []
287
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
288
+ for result in pool.map(_get_games_pipeline, dates):
289
+ games.extend(result)
290
+ print(f"Found {len(games)} ESPN games between {start_date} and {end_date}")
291
+ if not games:
292
+ return pd.DataFrame(columns=ESPN_ODDS_COLUMNS)
293
+
294
+ games_df = pd.DataFrame(games)
295
+ games_df = add_game_ids(games_df, engine, schedule_table=schedule_table)
296
+
297
+ odds_rows = []
298
+ ids = games_df["espn_game_id"].tolist()
299
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
300
+ futures = {pool.submit(_get_odds_pipeline, gid): gid for gid in ids}
301
+ for future in as_completed(futures):
302
+ odds_rows.extend(future.result())
303
+ print(f"Fetched odds for {len(ids)} games: {len(odds_rows)} book entries")
304
+
305
+ if exclude_live:
306
+ odds_rows = [
307
+ r for r in odds_rows if "live odds" not in r["sportsbook"].lower()
308
+ ]
309
+
310
+ games_idx = games_df.set_index("espn_game_id")
311
+ scraped_at = int(time.time())
312
+ rows = []
313
+ for entry in odds_rows:
314
+ gid = entry["espn_game_id"]
315
+ if gid not in games_idx.index:
316
+ continue
317
+ game = games_idx.loc[gid]
318
+ base = {
319
+ "game_id": game["game_id"],
320
+ "espn_game_id": gid,
321
+ "date": pd.to_datetime(game["game_datetime"], utc=True)
322
+ .tz_convert("US/Eastern").strftime("%Y-%m-%d"),
323
+ "game_datetime": game["game_datetime"],
324
+ "away_team": game["away_team"],
325
+ "away_team_short": game["away_team_short"],
326
+ "home_team": game["home_team"],
327
+ "home_team_short": game["home_team_short"],
328
+ "away_score": game["away_score"],
329
+ "home_score": game["home_score"],
330
+ "venue": game["venue"],
331
+ "status": game["status"],
332
+ "sportsbook": entry["sportsbook"],
333
+ "sportsbook_id": entry["sportsbook_id"],
334
+ "scraped_at": scraped_at,
335
+ }
336
+ cur, opn = entry["current"], entry["open"]
337
+ market_fields = {
338
+ "moneyline": {
339
+ "opening_home_odds": opn["home_ml"],
340
+ "opening_away_odds": opn["away_ml"],
341
+ "opening_line": None,
342
+ "current_home_odds": cur["home_ml"],
343
+ "current_away_odds": cur["away_ml"],
344
+ "current_line": None,
345
+ },
346
+ "spread": {
347
+ "opening_home_odds": opn["home_spread_odds"],
348
+ "opening_away_odds": opn["away_spread_odds"],
349
+ "opening_line": opn["spread"],
350
+ "current_home_odds": cur["home_spread_odds"],
351
+ "current_away_odds": cur["away_spread_odds"],
352
+ "current_line": cur["spread"],
353
+ },
354
+ # totals: home = over, away = under
355
+ "total": {
356
+ "opening_home_odds": opn["over_odds"],
357
+ "opening_away_odds": opn["under_odds"],
358
+ "opening_line": opn["total"],
359
+ "current_home_odds": cur["over_odds"],
360
+ "current_away_odds": cur["under_odds"],
361
+ "current_line": cur["total"],
362
+ },
363
+ }
364
+ for odds_type in odds_types:
365
+ fields = market_fields.get(odds_type)
366
+ if fields is None:
367
+ print(f"Unknown odds_type '{odds_type}', skipping")
368
+ continue
369
+ if all(v is None for v in fields.values()):
370
+ continue
371
+ rows.append({**base, "odds_type": odds_type, **fields})
372
+
373
+ result = pd.DataFrame(rows, columns=ESPN_ODDS_COLUMNS)
374
+ print(f"Built {len(result)} espn_odds rows.")
375
+ return result
376
+
377
+
378
+ # ---------------------------------------------------------------------------
379
+ # Line movement for the pipeline (<=2023 only)
380
+ # ---------------------------------------------------------------------------
381
+
382
+ def _fetch_history_pipeline(espn_game_id, mlb_game_id=None,
383
+ markets=("moneyline", "spread", "total")):
384
+ rows = []
385
+ for market in markets:
386
+ bet_type = BET_TYPES.get(market)
387
+ if bet_type is None:
388
+ continue
389
+ url = (
390
+ f"{CORE_BASE}/events/{espn_game_id}/competitions/{espn_game_id}"
391
+ f"/odds/{HISTORY_PROVIDER_ID}/history/{bet_type}/movement"
392
+ )
393
+ data = _get_json(url, params={"limit": 1000})
394
+ if not data:
395
+ continue
396
+ for item in data.get("items", []):
397
+ rows.append(
398
+ {
399
+ "game_id": mlb_game_id,
400
+ "espn_game_id": str(espn_game_id),
401
+ "market": market,
402
+ "timestamp": item.get("lineDate"),
403
+ "away_odds": _to_num(item.get("awayOdds")),
404
+ "home_odds": _to_num(item.get("homeOdds")),
405
+ "over_odds": _to_num(item.get("overOdds")),
406
+ "under_odds": _to_num(item.get("underOdds")),
407
+ "line": item.get("line"),
408
+ }
409
+ )
410
+ df = pd.DataFrame(rows)
411
+ if not df.empty:
412
+ df = df.sort_values(["market", "timestamp"]).reset_index(drop=True)
413
+ return df
414
+
415
+
416
+ def scrape_line_movement(
417
+ start_date: str,
418
+ end_date: str,
419
+ engine=None,
420
+ max_workers: int = 8,
421
+ schedule_table: str = "cleaned_schedule",
422
+ ) -> pd.DataFrame:
423
+ """Timestamped line movement for every game in the range (<=2023 only).
424
+
425
+ Upsert with keys ['espn_game_id', 'market', 'timestamp'].
426
+ """
427
+ dates = _daterange(start_date, end_date)
428
+ games = []
429
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
430
+ for result in pool.map(_get_games_pipeline, dates):
431
+ games.extend(result)
432
+ if not games:
433
+ return pd.DataFrame()
434
+ games_df = add_game_ids(pd.DataFrame(games), engine,
435
+ schedule_table=schedule_table)
436
+
437
+ frames = []
438
+ pairs = list(zip(games_df["espn_game_id"], games_df["game_id"]))
439
+ print(f"Fetching line movement for {len(pairs)} games...")
440
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
441
+ futures = {
442
+ pool.submit(_fetch_history_pipeline, egid, gid): egid
443
+ for egid, gid in pairs
444
+ }
445
+ for future in as_completed(futures):
446
+ df = future.result()
447
+ if not df.empty:
448
+ frames.append(df)
449
+ movement = (
450
+ pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
451
+ )
452
+ print(f"Fetched {len(movement)} line-movement rows.")
453
+ return movement