Coverage for data_pipeline/filing_text.py: 100%
70 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"""Filing text as hashed word counts, and the dates around them (V6.6.4): the inputs of round 4E's q01, q02 and q06.
3A 10-K or 10-Q is reduced to a sparse count of hashed words the moment it is read, and the text is dropped: nothing here stores a filing. The similarity of a filing to the same form a
4year earlier is the cosine of their counts (Cohen, Malloy and Nguyen's "lazy prices", in a cheap form). An 8-K carrying Item 2.02 is an earnings release; its acceptance time dates the
5announcement. Pure functions, stdlib only apart from the parsed submissions JSON they are handed.
6"""
8from __future__ import annotations
10import hashlib
11import math
12import re
13from collections.abc import Mapping, Sequence
14from typing import TYPE_CHECKING, Any
16if TYPE_CHECKING:
17 from collections.abc import Callable
19BUCKETS = 1 << 18
20_TAG = re.compile(r"<[^>]*>")
21_ENTITY = re.compile(r"&[#a-zA-Z0-9]+;")
22_WORD = re.compile(r"[a-z]{3,}")
23ANNUAL_FORMS = ("10-K", "10-K405", "10-KSB")
24QUARTERLY_FORMS = ("10-Q",)
25YEAR_DAYS = (330, 400)
28def tokens(html: str) -> list[str]:
29 """Lower-case words of three letters or more, with tags and entities removed."""
30 text = _ENTITY.sub(" ", _TAG.sub(" ", html or ""))
31 return _WORD.findall(text.lower())
34def hashed_counts(words: Sequence[str], buckets: int = BUCKETS) -> dict[int, int]:
35 """Word counts keyed by a stable hash (blake2b, so it doesn't change between runs or machines)."""
36 counts: dict[int, int] = {}
37 for word in words:
38 key = int.from_bytes(hashlib.blake2b(word.encode("utf-8"), digest_size=4).digest(), "big") % buckets
39 counts[key] = counts.get(key, 0) + 1
40 return counts
43def cosine(left: Mapping[int, int], right: Mapping[int, int]) -> float | None:
44 """The cosine of two count vectors, or None when either is empty."""
45 if not left or not right:
46 return None
47 small, large = (left, right) if len(left) <= len(right) else (right, left)
48 dot = sum(count * large.get(key, 0) for key, count in small.items())
49 norm = math.sqrt(sum(count * count for count in left.values())) * math.sqrt(sum(count * count for count in right.values()))
50 return dot / norm if norm > 0.0 else None
53def _rows_of(submissions: Mapping[str, Any]) -> list[dict]:
54 recent = ((submissions or {}).get("filings") or {}).get("recent") or {}
55 columns = {key: list(recent.get(key) or []) for key in ("accessionNumber", "filingDate", "acceptanceDateTime", "form", "primaryDocument", "items", "reportDate")}
56 length = len(columns["accessionNumber"])
57 return [{key: (values[position] if position < len(values) else "") for key, values in columns.items()} for position in range(length)]
60def merge_pages(pages: Sequence[Mapping]) -> list[dict]:
61 """Filing rows from the recent block and any older pages (SEC's `filings.files`), oldest first, one row per accession."""
62 seen: dict[str, dict] = {}
63 for page in pages:
64 rows = _rows_of(page if "filings" in page else {"filings": {"recent": page}})
65 for row in rows:
66 seen.setdefault(row["accessionNumber"], row)
67 return sorted(seen.values(), key=lambda row: (row["filingDate"], row["accessionNumber"]))
70def earnings_rows(filings: Sequence[Mapping]) -> list[dict]:
71 """8-Ks that carry Item 2.02 (results of operations): `accepted` is the acceptance timestamp, `filed` the filing date."""
72 out = []
73 for row in filings:
74 if str(row.get("form")) != "8-K":
75 continue
76 if "2.02" not in {item.strip() for item in str(row.get("items") or "").split(",")}:
77 continue
78 out.append({"accepted": str(row.get("acceptanceDateTime") or row.get("filingDate")), "filed": str(row["filingDate"])})
79 return sorted(out, key=lambda row: row["accepted"])
82def _days(first: str, second: str) -> int:
83 import datetime
85 return (datetime.date.fromisoformat(second[:10]) - datetime.date.fromisoformat(first[:10])).days
88def prior_year_pairs(filings: Sequence[Mapping]) -> list[tuple[Mapping, Mapping]]:
89 """(this filing, the same form a year earlier) for each 10-K and 10-Q that has one, matched on the report date: 330 to 400 days apart, the nearest to a year. Never a later filing."""
90 pairs = []
91 for forms in (ANNUAL_FORMS, QUARTERLY_FORMS):
92 group = [row for row in filings if str(row.get("form")) in forms and row.get("reportDate") and row.get("primaryDocument")]
93 for row in group:
94 candidates = [other for other in group if YEAR_DAYS[0] <= _days(str(other["reportDate"]), str(row["reportDate"])) <= YEAR_DAYS[1]]
95 if candidates:
96 pairs.append((row, min(candidates, key=lambda other: abs(_days(str(other["reportDate"]), str(row["reportDate"])) - 365))))
97 return pairs
100def similarity_rows(filings: Sequence[Mapping], counts_of: Callable[[Mapping[str, Any]], Mapping[str, int] | None]) -> list[dict]:
101 """One row per filing that has a year-earlier twin: ticker-free `{form, period_end, filed, similarity}`. `counts_of(row)` returns that filing's hashed counts (or None when it can't be read)."""
102 rows = []
103 for current, earlier in prior_year_pairs(filings):
104 now, then = counts_of(current), counts_of(earlier)
105 value = cosine(now, then) if now and then else None
106 if value is not None:
107 rows.append({"form": str(current["form"]), "period_end": str(current["reportDate"]), "filed": str(current["filingDate"]), "similarity": float(value)})
108 return sorted(rows, key=lambda row: row["filed"])