Coverage for data_pipeline/edgar_facts.py: 100%
401 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Point-in-time quarterly earnings per share from SEC EDGAR (V6.5.0, free, no account).
3`companyfacts` keeps every filing of a figure with its `filed` date, so a backtest can see what was public on a day and
4not what was later restated: a quarter's first filing is kept, and it is usable on the first session after that date.
6SEC requires a contact in the client name: set AQ_SEC_CONTACT for the run, so that no address enters the repository. Requests stay
7under SEC's limit of 10 per second.
9 python -m data_pipeline.edgar_facts --apply
10 python -m data_pipeline.edgar_facts --apply --splits
11"""
13from __future__ import annotations
15import argparse
16import csv
17import json
18import os
19import time as _time
20from collections.abc import Callable, Iterable
21from datetime import date
22from pathlib import Path
23from typing import Any
25import numpy as np
26import pandas as pd
28OUTPUT = Path(__file__).resolve().parent.parent / "data" / "reference" / "edgar_eps.csv"
29TICKERS_URL = "https://www.sec.gov/files/company_tickers.json"
30FACTS_URL = "https://data.sec.gov/api/xbrl/companyfacts/CIK{cik:010d}.json"
31USER_AGENT = "AetherQuantResearch/6.5 (github.com/leon1706-lol/Aether-quant)"
32CONTACT_ENV = "AQ_SEC_CONTACT"
33TICKER_ALIASES = {"FB": "META"} # the universe keeps the old ticker; SEC's list has only the new one
34EPS_TAGS = ("EarningsPerShareDiluted", "EarningsPerShareBasic")
35MIN_QUARTER_DAYS, MAX_QUARTER_DAYS = 75, 105
36SURPRISE_HISTORY, MIN_SURPRISE_HISTORY = 8, 4
37YEAR_MIN_DAYS, YEAR_MAX_DAYS = 350, 380
38SPLITS_OUTPUT = OUTPUT.with_name("equity_splits.csv")
41def quarterly_first_filings(facts: dict[str, Any]) -> list[dict]:
42 """{period_start, period_end, filed, eps} for every standalone quarter, first filing only. Year-to-date and annual
43 figures are dropped by their duration; the first tag with data wins."""
44 usgaap = ((facts or {}).get("facts") or {}).get("us-gaap") or {}
45 for tag in EPS_TAGS:
46 units = (usgaap.get(tag) or {}).get("units") or {}
47 entries = units.get("USD/shares") or []
48 first: dict[tuple[str, str], dict] = {}
49 for entry in entries:
50 start, end, filed, value = entry.get("start"), entry.get("end"), entry.get("filed"), entry.get("val")
51 if not (start and end and filed) or value is None:
52 continue
53 days = (date.fromisoformat(end) - date.fromisoformat(start)).days
54 if not MIN_QUARTER_DAYS <= days <= MAX_QUARTER_DAYS:
55 continue
56 key = (start, end)
57 if key not in first or filed < first[key]["filed"]:
58 first[key] = {"period_start": start, "period_end": end, "filed": filed, "eps": float(value)}
59 if first:
60 return sorted(first.values(), key=lambda row: row["period_end"])
61 return []
64# Annual figures of the wide universe (V6.6.0). The first tag with data wins, per fiscal year: filers change tags over time.
65FUNDAMENTAL_TAGS = {
66 "assets": (("us-gaap", "Assets"),),
67 "equity": (("us-gaap", "StockholdersEquity"), ("us-gaap", "StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest")),
68 "gross_profit": (("us-gaap", "GrossProfit"),),
69 "revenue": (("us-gaap", "Revenues"), ("us-gaap", "RevenueFromContractWithCustomerExcludingAssessedTax"), ("us-gaap", "SalesRevenueNet")),
70 "cost_of_revenue": (("us-gaap", "CostOfRevenue"), ("us-gaap", "CostOfGoodsAndServicesSold"), ("us-gaap", "CostOfGoodsSold")),
71 "net_income": (("us-gaap", "NetIncomeLoss"),),
72 "operating_cash_flow": (("us-gaap", "NetCashProvidedByUsedInOperatingActivities"),),
73 "long_term_debt": (("us-gaap", "LongTermDebt"), ("us-gaap", "LongTermDebtNoncurrent")),
74 # `dei`, not `us-gaap`: the cover page's count, which `quarterly_first_filings` above never reads.
75 "shares_outstanding": (("dei", "EntityCommonStockSharesOutstanding"),),
76}
77ANNUAL_FORMS = ("10-K", "10-K/A", "20-F", "40-F", "10-KT")
78SUBMISSIONS_URL = "https://data.sec.gov/submissions/CIK{cik:010d}.json"
79FUNDAMENTALS_COLUMNS = ["ticker", "field", "period_end", "filed", "form", "value"]
80WIDE_USER_AGENT_VERSION = "6.6"
83def first_filings_annual(facts: dict[str, Any], tag: str, *, taxonomy: str = "us-gaap") -> list[dict]:
84 """{period_end, filed, form, value} per fiscal year, first filing only, from annual forms: what was public, not what a later
85 restatement says. A figure may appear in many later filings as a comparative; only the earliest counts."""
86 concept = ((facts or {}).get("facts") or {}).get(taxonomy, {}).get(tag) or {}
87 first: dict[str, dict] = {}
88 for entries in (concept.get("units") or {}).values():
89 for entry in entries:
90 end, filed, value, form = entry.get("end"), entry.get("filed"), entry.get("val"), entry.get("form")
91 if not end or not filed or value is None or form not in ANNUAL_FORMS:
92 continue
93 start = entry.get("start")
94 if start is not None:
95 days = (date.fromisoformat(end) - date.fromisoformat(start)).days
96 if not YEAR_MIN_DAYS <= days <= YEAR_MAX_DAYS:
97 continue # a quarter or a part-year comparative inside a 10-K
98 if end not in first or filed < first[end]["filed"]:
99 first[end] = {"period_end": end, "filed": filed, "form": form, "value": float(value)}
100 return sorted(first.values(), key=lambda row: row["period_end"])
103def fundamentals_rows(facts: dict[str, Any]) -> list[dict]:
104 """Every field's annual first filings. For a field with several tags, an earlier tag wins a fiscal year; a later one only fills
105 years it doesn't have."""
106 rows: list[dict] = []
107 for field, tags in FUNDAMENTAL_TAGS.items():
108 by_period: dict[str, dict] = {}
109 for taxonomy, tag in tags:
110 for row in first_filings_annual(facts, tag, taxonomy=taxonomy):
111 by_period.setdefault(row["period_end"], row)
112 rows.extend({"field": field, **row} for _, row in sorted(by_period.items()))
113 return rows
116# V6.6.1: annual fields for net operating assets and capital spending, and the quarterly figures behind trailing-twelve-month accruals.
117EXTENDED_ANNUAL_TAGS = {
118 "cash": (("us-gaap", "CashAndCashEquivalentsAtCarryingValue"), ("us-gaap", "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents")),
119 "short_term_debt": (("us-gaap", "DebtCurrent"), ("us-gaap", "LongTermDebtCurrent"), ("us-gaap", "ShortTermBorrowings")),
120 "capex": (("us-gaap", "PaymentsToAcquirePropertyPlantAndEquipment"), ("us-gaap", "PaymentsToAcquireProductiveAssets")),
121 "rd_expense": (("us-gaap", "ResearchAndDevelopmentExpense"),),
122}
123TTM_TAGS = {"ttm_net_income": ("NetIncomeLoss",), "ttm_operating_cash_flow": ("NetCashProvidedByUsedInOperatingActivities",)}
124QUARTERLY_FORMS = ("10-Q", "10-Q/A", *ANNUAL_FORMS)
125COMPARATIVE_TOLERANCE_DAYS = 7
128def _first_filed_durations(facts: dict[str, Any], tag: str, *, taxonomy: str = "us-gaap") -> dict[tuple[str, str], dict]:
129 """{(start, end): first filing} of a flow figure, across annual and quarterly forms."""
130 concept = ((facts or {}).get("facts") or {}).get(taxonomy, {}).get(tag) or {}
131 first: dict[tuple[str, str], dict] = {}
132 for entries in (concept.get("units") or {}).values():
133 for entry in entries:
134 start, end, filed, value, form = entry.get("start"), entry.get("end"), entry.get("filed"), entry.get("val"), entry.get("form")
135 if not start or not end or not filed or value is None or form not in QUARTERLY_FORMS:
136 continue
137 key = (start, end)
138 if key not in first or filed < first[key]["filed"]:
139 first[key] = {"filed": filed, "form": form, "value": float(value)}
140 return first
143def _days_between(first: str, second: str) -> int:
144 return (date.fromisoformat(second) - date.fromisoformat(first)).days
147def _ttm_rows(durations: dict[tuple[str, str], dict]) -> list[dict]:
148 """A trailing twelve months per period end: a full year as filed, else last year + this year to date - last year to date. A filing's
149 cash-flow figures are year to date, so standalone quarters can't simply be summed. Usable from the latest filing among its parts."""
150 annual = {end: row for (start, end), row in durations.items() if YEAR_MIN_DAYS <= _days_between(start, end) <= YEAR_MAX_DAYS}
151 best: dict[str, dict] = {}
153 def offer(end: str, row: dict[str, Any]) -> None:
154 if end not in best or row["filed"] < best[end]["filed"]:
155 best[end] = {"period_end": end, **row}
157 for end, row in annual.items():
158 offer(end, row)
159 ytd_spans = [(start, end, row) for (start, end), row in durations.items() if _days_between(start, end) < YEAR_MIN_DAYS]
160 for start, end, row in ytd_spans:
161 # A year-to-date figure starts the day after a fiscal year ended; a standalone second quarter doesn't, so it finds no year here.
162 year = next((annual[candidate] for candidate in annual if abs(_days_between(candidate, start) - 1) <= COMPARATIVE_TOLERANCE_DAYS), None)
163 if year is None:
164 continue
165 comparative = next(
166 (
167 other for other_start, other_end, other in ytd_spans
168 if abs(_days_between(other_start, start) - 365) <= COMPARATIVE_TOLERANCE_DAYS and abs(_days_between(other_end, end) - 365) <= COMPARATIVE_TOLERANCE_DAYS
169 ),
170 None,
171 )
172 if comparative is None:
173 continue
174 offer(end, {
175 "filed": max(row["filed"], year["filed"], comparative["filed"]), "form": row["form"],
176 "value": year["value"] + row["value"] - comparative["value"],
177 })
178 return sorted(best.values(), key=lambda item: item["period_end"])
181def _first_filed_instants(facts: dict[str, Any], tag: str, *, taxonomy: str = "us-gaap") -> list[dict]:
182 """A balance-sheet figure per period end, first filing only, from annual and quarterly forms."""
183 concept = ((facts or {}).get("facts") or {}).get(taxonomy, {}).get(tag) or {}
184 first: dict[str, dict] = {}
185 for entries in (concept.get("units") or {}).values():
186 for entry in entries:
187 end, filed, value, form = entry.get("end"), entry.get("filed"), entry.get("val"), entry.get("form")
188 if not end or not filed or value is None or form not in QUARTERLY_FORMS:
189 continue
190 if end not in first or filed < first[end]["filed"]:
191 first[end] = {"period_end": end, "filed": filed, "form": form, "value": float(value)}
192 return sorted(first.values(), key=lambda row: row["period_end"])
195def quarterly_ttm_rows(facts: dict[str, Any]) -> list[dict]:
196 """`ttm_net_income`, `ttm_operating_cash_flow` and `assets_q`, in FUNDAMENTALS_COLUMNS' shape without the ticker."""
197 rows: list[dict] = []
198 for field, tags in TTM_TAGS.items():
199 by_period: dict[str, dict] = {}
200 for tag in tags:
201 for row in _ttm_rows(_first_filed_durations(facts, tag)):
202 by_period.setdefault(row["period_end"], row)
203 rows.extend({"field": field, **row} for _, row in sorted(by_period.items()))
204 rows.extend({"field": "assets_q", **row} for row in _first_filed_instants(facts, "Assets"))
205 return rows
208def extended_rows(facts: dict[str, Any]) -> list[dict]:
209 """Every V6.6.1 field. For a field with several tags, an earlier tag wins a fiscal year, as in `fundamentals_rows`."""
210 rows = list(quarterly_ttm_rows(facts))
211 for field, tags in EXTENDED_ANNUAL_TAGS.items():
212 by_period: dict[str, dict] = {}
213 for taxonomy, tag in tags:
214 for row in first_filings_annual(facts, tag, taxonomy=taxonomy):
215 by_period.setdefault(row["period_end"], row)
216 rows.extend({"field": field, **row} for _, row in sorted(by_period.items()))
217 return rows
220def fetch_extended(
221 tickers: Iterable[str], get_json: Callable[[str], dict] | None = None, pause_seconds: float = 0.15, cache_dir: Path | None = None,
222) -> tuple[list[dict], list[str]]:
223 """(rows with a `ticker`, tickers with nothing). Each company's parsed body is dropped once its rows are read, and a run with `cache_dir` resumes."""
224 get_json = get_json or _get_json
225 directory = get_json(TICKERS_URL)
226 cik_by_ticker = {str(item["ticker"]).upper().replace("-", "."): int(item["cik_str"]) for item in directory.values()}
227 rows: list[dict] = []
228 missing: list[str] = []
229 for ticker in tickers:
230 cached = Path(cache_dir) / f"{ticker.lower()}.json" if cache_dir else None
231 if cached is not None and cached.exists():
232 saved = json.loads(cached.read_text(encoding="utf-8"))
233 else:
234 cik = cik_by_ticker.get(str(ticker).upper())
235 if cik is None:
236 missing.append(ticker)
237 continue
238 try:
239 saved = extended_rows(get_json(FACTS_URL.format(cik=cik)))
240 except Exception as error: # one failed company must not lose the others
241 print(f"{ticker}: {type(error).__name__}", flush=True)
242 missing.append(ticker)
243 continue
244 if cached is not None:
245 cached.parent.mkdir(parents=True, exist_ok=True)
246 cached.write_text(json.dumps(saved, separators=(",", ":")), encoding="utf-8", newline="\n")
247 if pause_seconds:
248 _time.sleep(pause_seconds)
249 if not saved:
250 missing.append(ticker)
251 rows.extend({"ticker": ticker, **row} for row in saved)
252 return rows, missing
255def sector_for_sic(sic: int | str | None) -> str:
256 """A sector label from a SEC SIC code, in the GICS sector names. Coarse, and today's code rather than the code at each date: it
257 only sets which names are ranked together. A company with no code is `unknown`, which is never traded."""
258 try:
259 code = int(sic)
260 except (TypeError, ValueError):
261 return "unknown"
262 if code <= 0:
263 return "unknown"
264 if code in (1311, 1381, 1382, 1389, 2911, 2990, 2992, 5171, 5172) or 2900 <= code <= 2999 or code in (4610, 4612, 4613):
265 return "energy"
266 if 2830 <= code <= 2836 or 3841 <= code <= 3851 or 8000 <= code <= 8099 or code == 5912 or code == 5122:
267 return "health_care"
268 if 3570 <= code <= 3579 or 3660 <= code <= 3679 or 3810 <= code <= 3829 or 7370 <= code <= 7379:
269 return "information_technology"
270 if 4800 <= code <= 4899 or 2700 <= code <= 2799 or code in (7812, 7819, 7822, 7829, 7830, 7841):
271 return "communication_services"
272 if 4900 <= code <= 4999:
273 return "utilities"
274 if code == 6798 or 6500 <= code <= 6553:
275 return "real_estate"
276 if 6000 <= code <= 6799:
277 return "financials"
278 if 2000 <= code <= 2199 or 5400 <= code <= 5499 or code in (5140, 5141, 5149, 5180, 5181, 5182, 5194) or 2840 <= code <= 2844:
279 return "consumer_staples"
280 if 2200 <= code <= 2399 or 2500 <= code <= 2599 or 3630 <= code <= 3652 or 3711 <= code <= 3716 or 3900 <= code <= 3999 or 5200 <= code <= 5399 or 5500 <= code <= 5999 or 7000 <= code <= 7299 or 7800 <= code <= 7999 or code == 3140:
281 return "consumer_discretionary"
282 if 1000 <= code <= 1499 or 2400 <= code <= 2499 or 2600 <= code <= 2699 or 2800 <= code <= 2829 or 2845 <= code <= 2899 or 3000 <= code <= 3299 or 3300 <= code <= 3399:
283 return "materials"
284 return "industrials"
287def fetch_fundamentals(
288 tickers: Iterable[str], get_json: Callable[[str], dict] | None = None, pause_seconds: float = 0.15, cache_dir: Path | None = None,
289) -> tuple[list[dict], dict[str, str], list[str]]:
290 """(rows with a `ticker`, {ticker: sector}, tickers SEC has no data for). SEC's ticker list holds current tickers only, so a
291 name that no longer trades has none: such a name reads as missing, and R-SURV1 counts it. A run with `cache_dir` resumes."""
292 get_json = get_json or _get_json
293 directory = get_json(TICKERS_URL)
294 cik_by_ticker = {str(item["ticker"]).upper().replace("-", "."): int(item["cik_str"]) for item in directory.values()}
295 rows: list[dict] = []
296 sectors: dict[str, str] = {}
297 missing: list[str] = []
298 for ticker in tickers:
299 cached = Path(cache_dir) / f"{ticker.lower()}.json" if cache_dir else None
300 if cached is not None and cached.exists():
301 saved = json.loads(cached.read_text(encoding="utf-8"))
302 else:
303 cik = cik_by_ticker.get(str(ticker).upper())
304 if cik is None:
305 missing.append(ticker)
306 continue
307 try:
308 facts = get_json(FACTS_URL.format(cik=cik))
309 saved = {
310 "rows": fundamentals_rows(facts),
311 "eps": quarterly_first_filings(facts),
312 "sector": sector_for_sic(get_json(SUBMISSIONS_URL.format(cik=cik)).get("sic")),
313 }
314 except Exception as error: # one failed company must not lose the others
315 print(f"{ticker}: {type(error).__name__}")
316 missing.append(ticker)
317 continue
318 if cached is not None:
319 cached.parent.mkdir(parents=True, exist_ok=True)
320 cached.write_text(json.dumps(saved, separators=(",", ":")), encoding="utf-8", newline="\n")
321 if pause_seconds:
322 _time.sleep(pause_seconds)
323 sectors[ticker] = saved["sector"]
324 if not saved["rows"]:
325 missing.append(ticker)
326 rows.extend({"ticker": ticker, **row} for row in saved["rows"])
327 return rows, sectors, missing
330def collect_cached_eps(tickers: Iterable[str], cache_dir: Path) -> list[dict]:
331 """The quarterly EPS rows `fetch_fundamentals` saved, in `read_eps`'s shape: the same download serves both."""
332 rows: list[dict] = []
333 for ticker in tickers:
334 cached = Path(cache_dir) / f"{ticker.lower()}.json"
335 if cached.exists():
336 rows.extend({"ticker": ticker, **row} for row in json.loads(cached.read_text(encoding="utf-8")).get("eps", []))
337 return rows
340def write_fundamentals(rows: list[dict], path: Path) -> None:
341 """Write fundamentals rows as a gzipped CSV in the canonical column order, creating the folder."""
342 frame = pd.DataFrame(rows, columns=FUNDAMENTALS_COLUMNS)
343 Path(path).parent.mkdir(parents=True, exist_ok=True)
344 frame.to_csv(path, index=False, lineterminator="\n", compression="gzip")
347def read_fundamentals(path: Path) -> pd.DataFrame:
348 """Read a cached EDGAR fundamentals table, with its keys and dates as strings."""
349 return pd.read_csv(path, dtype={"ticker": str, "field": str, "period_end": str, "filed": str, "form": str, "value": float})
352def fundamentals_table(rows: pd.DataFrame, sessions: list[str], columns: list[str], field: str, *, lag_sessions: int = 1) -> pd.DataFrame:
353 """Session x ticker, each cell the latest fiscal year's value filed by then. A filing dated D is usable a session later: it can
354 arrive after the close. Nothing filed later shows, whatever fiscal year it covers."""
355 table = pd.DataFrame(np.nan, index=sessions, columns=columns, dtype=float)
356 subset = rows[rows["field"] == field]
357 positions = pd.Index(sessions)
358 for ticker, group in subset.groupby("ticker"):
359 if ticker not in table.columns:
360 continue
361 ordered = group.sort_values(["filed", "period_end"])
362 # a late filing of an older year must not replace a newer year already public
363 ordered = ordered[ordered["period_end"] >= ordered["period_end"].cummax()]
364 location = positions.searchsorted(ordered["filed"].to_numpy(), side="left") + lag_sessions
365 keep = location < len(sessions)
366 series = pd.Series(np.nan, index=sessions, dtype=float)
367 series.iloc[location[keep]] = ordered["value"].to_numpy()[keep]
368 table[ticker] = series.ffill()
369 return table
372def split_factor_after(splits: pd.DataFrame, ticker: str, filed: str) -> float:
373 """Product of the ticker's split ratios after `filed`, up to today: what turns a share count as filed into Yahoo's units."""
374 if splits is None or splits.empty:
375 return 1.0
376 subset = splits[(splits["ticker"] == ticker) & (splits["date"] > filed)]
377 return float(subset["ratio"].prod()) if len(subset) else 1.0
380def market_cap_table(raw_closes: pd.DataFrame, rows: pd.DataFrame, splits: pd.DataFrame, *, lag_sessions: int = 1) -> pd.DataFrame:
381 """Close x shares outstanding, as of each session. `raw_closes` are Yahoo's split-adjusted closes without dividends, so a count
382 as filed is restated by the splits after its filing date to match: the product can't depend on any later split or dividend. An
383 adjusted close would embed later dividends, and valuation ratios built on it would read the future."""
384 shares = rows[rows["field"] == "shares_outstanding"].copy()
385 if not shares.empty:
386 factors = {
387 (ticker, filed): split_factor_after(splits, ticker, filed)
388 for ticker, filed in shares[["ticker", "filed"]].drop_duplicates().itertuples(index=False)
389 }
390 shares["value"] = [value * factors[(ticker, filed)] for ticker, filed, value in shares[["ticker", "filed", "value"]].itertuples(index=False)]
391 held = fundamentals_table(shares, list(raw_closes.index), list(raw_closes.columns), "shares_outstanding", lag_sessions=lag_sessions)
392 return raw_closes * held
395def user_agent() -> str:
396 """SEC refuses a client with no contact. The address comes from the environment so that it never enters the repository."""
397 contact = os.environ.get(CONTACT_ENV, "").strip()
398 return f"AetherQuantResearch/6.5 {contact}" if contact else USER_AGENT
401def _get_json(url: str) -> dict[str, Any]:
402 import requests
404 response = requests.get(url, timeout=60, headers={"User-Agent": user_agent(), "Accept": "application/json"})
405 response.raise_for_status()
406 return response.json()
409def fetch_eps(tickers: Iterable[str], get_json: Callable[[str], dict] = _get_json, pause_seconds: float = 0.15) -> tuple[list[dict], list[str]]:
410 """(rows with a `ticker`, tickers with no data). A ticker that fails is reported, never guessed."""
411 directory = get_json(TICKERS_URL)
412 cik_by_ticker = {str(item["ticker"]).upper(): int(item["cik_str"]) for item in directory.values()}
413 rows: list[dict] = []
414 missing: list[str] = []
415 for ticker in tickers:
416 cik = cik_by_ticker.get(TICKER_ALIASES.get(str(ticker).upper(), str(ticker).upper()))
417 if cik is None:
418 missing.append(ticker)
419 continue
420 try:
421 quarters = quarterly_first_filings(get_json(FACTS_URL.format(cik=cik)))
422 except Exception as error: # one failed company must not lose the others
423 print(f"{ticker}: {error}")
424 quarters = []
425 if not quarters:
426 missing.append(ticker)
427 rows.extend({"ticker": ticker, **quarter} for quarter in quarters)
428 if pause_seconds:
429 _time.sleep(pause_seconds)
430 return rows, missing
433def write_eps(rows: list[dict], path: Path = OUTPUT) -> None:
434 with Path(path).open("w", newline="\n", encoding="utf-8") as handle:
435 writer = csv.DictWriter(handle, fieldnames=["ticker", "period_start", "period_end", "filed", "eps"], lineterminator="\n")
436 writer.writeheader()
437 writer.writerows(rows)
440def read_eps(path: Path = OUTPUT) -> pd.DataFrame:
441 """Read the cached EDGAR earnings-per-share table, with its date columns as strings."""
442 return pd.read_csv(path, dtype={"ticker": str, "period_start": str, "period_end": str, "filed": str})
445def fetch_splits(tickers: Iterable[str]) -> list[dict]:
446 """{ticker, date, ratio} from Yahoo. A ticker that fails stops the run: a silently missing split reads as a large miss."""
447 import yfinance
449 rows: list[dict] = []
450 for ticker in tickers:
451 splits = yfinance.Ticker(TICKER_ALIASES.get(ticker, ticker)).splits
452 rows.extend({"ticker": ticker, "date": day.strftime("%Y-%m-%d"), "ratio": float(ratio)} for day, ratio in splits.items() if float(ratio) > 0.0)
453 return rows
456def fetch_splits_tolerant(tickers: Iterable[str]) -> tuple[list[dict], list[str]]:
457 """`fetch_splits` for the wide universe, where one failed name mustn't stop 1,000: (rows, tickers that failed). The caller treats a
458 failed name's market cap as unknown rather than guessing it had no split."""
459 import yfinance
461 rows: list[dict] = []
462 failed: list[str] = []
463 for ticker in tickers:
464 try:
465 splits = yfinance.Ticker(str(ticker).replace(".", "-")).splits
466 except Exception:
467 failed.append(ticker)
468 continue
469 rows.extend({"ticker": ticker, "date": day.strftime("%Y-%m-%d"), "ratio": float(ratio)} for day, ratio in splits.items() if float(ratio) > 0.0)
470 return rows, failed
473def write_splits(rows: list[dict], path: Path = SPLITS_OUTPUT) -> None:
474 with Path(path).open("w", newline="\n", encoding="utf-8") as handle:
475 writer = csv.DictWriter(handle, fieldnames=["ticker", "date", "ratio"], lineterminator="\n")
476 writer.writeheader()
477 writer.writerows(rows)
480def read_splits(path: Path = SPLITS_OUTPUT) -> pd.DataFrame:
481 """Read the cached stock-split table, with ticker and date as strings."""
482 return pd.read_csv(path, dtype={"ticker": str, "date": str})
485def split_adjusted_eps(eps: pd.DataFrame, splits: pd.DataFrame) -> pd.DataFrame:
486 """EPS on one share basis per ticker. A first filing states EPS on the shares at its filing date, so it is divided by
487 the splits after that date. A later split scales a ticker's whole history alike, so a standardised ratio sees no future."""
488 adjusted = eps.copy()
489 by_ticker = {ticker: group for ticker, group in splits.groupby("ticker")} # noqa: C416 # dict(GroupBy) reads its .keys attribute (a column name) as a method
491 def divisor(row) -> float:
492 group = by_ticker.get(row["ticker"])
493 if group is None:
494 return 1.0
495 return float(group.loc[group["date"] > row["filed"], "ratio"].prod())
497 if len(adjusted):
498 adjusted["eps"] = adjusted["eps"] / adjusted.apply(divisor, axis=1)
499 return adjusted
502def standardised_surprises(group: pd.DataFrame) -> np.ndarray:
503 """One ticker's rows sorted by period end: the change from the same quarter a year earlier, over the spread of the
504 latest earlier changes. Every input was filed by this row's filing date."""
505 ends = pd.to_datetime(group["period_end"]).to_numpy()
506 filed = group["filed"].to_numpy(dtype=str)
507 values = group["eps"].to_numpy(dtype=float)
508 size = len(group)
509 changes = np.full(size, np.nan)
510 surprises = np.full(size, np.nan)
511 for row in range(size):
512 for earlier in range(row - 1, -1, -1):
513 days = int((ends[row] - ends[earlier]) / np.timedelta64(1, "D"))
514 if days > YEAR_MAX_DAYS:
515 break
516 if days >= YEAR_MIN_DAYS and filed[earlier] <= filed[row]:
517 changes[row] = values[row] - values[earlier]
518 break
519 past = [changes[earlier] for earlier in range(row) if np.isfinite(changes[earlier]) and filed[earlier] <= filed[row]][-SURPRISE_HISTORY:]
520 if np.isfinite(changes[row]) and len(past) >= MIN_SURPRISE_HISTORY:
521 spread = float(np.std(past, ddof=1))
522 if spread > 0.0:
523 surprises[row] = changes[row] / spread
524 return surprises
527def surprise_table(eps: pd.DataFrame, sessions: list[str], columns: list[str], *, hold_sessions: int) -> pd.DataFrame:
528 """session x ticker: `standardised_surprises` of the latest filing, from the session after it was filed for
529 `hold_sessions` sessions; NaN otherwise, so a ticker is ranked only while its news is recent. Pass split-adjusted EPS."""
530 sorted_sessions = np.asarray(sessions)
531 table = pd.DataFrame(np.nan, index=sessions, columns=columns, dtype=float)
532 for ticker, group in eps.groupby("ticker"):
533 if ticker not in table.columns:
534 continue
535 group = group.sort_values("period_end").reset_index(drop=True)
536 surprise = standardised_surprises(group)
537 for row in range(len(group)):
538 value = surprise[row]
539 if not np.isfinite(value):
540 continue
541 first = int(np.searchsorted(sorted_sessions, group["filed"].iloc[row], side="right"))
542 if first >= len(sessions):
543 continue
544 stop = min(first + hold_sessions, len(sessions))
545 table.iloc[first:stop, table.columns.get_loc(ticker)] = float(value)
546 return table
549def main(argv: list[str] | None = None) -> int:
550 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
551 parser.add_argument("--apply", action="store_true")
552 parser.add_argument("--splits", action="store_true", help="with --apply: refresh the split list from Yahoo instead of the EPS file")
553 parser.add_argument("--config", default=str(Path(__file__).resolve().parent.parent / "config.json"))
554 args = parser.parse_args(argv)
555 config = json.loads(Path(args.config).read_text(encoding="utf-8"))
556 tickers = [str(asset["ticker"]) for asset in config["phase1"]["universe"]["assets"]
557 if asset.get("security_type") == "equity" and not asset.get("asset_class")]
558 if not args.apply:
559 print(f"would fetch {len(tickers)} tickers into {OUTPUT}")
560 return 0
561 if args.splits:
562 rows = fetch_splits(tickers)
563 write_splits(rows)
564 print(f"{len(rows)} splits for {len({row['ticker'] for row in rows})} tickers -> {SPLITS_OUTPUT}")
565 return 0
566 rows, missing = fetch_eps(tickers)
567 write_eps(rows)
568 print(f"{len(rows)} quarters for {len(tickers) - len(missing)} tickers -> {OUTPUT}; no data for: {missing}")
569 return 0
572if __name__ == "__main__":
573 raise SystemExit(main())