Coverage for scripts/build_filing_signals.py: 100%

153 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Earnings-announcement dates and 10-K / 10-Q similarity for round 4E (V6.6.4): the inputs of q01, q02 and q06. 

2 

3Runs on the PC only. SEC refuses a client with no contact, and the contact comes from AQ_SEC_CONTACT for this process alone: it is never written anywhere, and the run ends by searching 

4every file it wrote for it. A filing is read once and reduced to hashed word counts; no filing text is stored. Each ticker's rows are cached as it finishes, so a reaped or interrupted run 

5resumes where it stopped. 

6 

7 AQ_SEC_CONTACT=... python scripts/build_filing_signals.py [--scope selection|full] [--limit N] 

8 

9`--scope selection` (the default) takes side-A names only and nothing filed after 2018-12-31, which is all cell S reads. `--scope full` adds side B and runs to 2026-11-02, and is run only 

10for a candidate that has been frozen (the holdouts need those years). 

11""" 

12 

13from __future__ import annotations 

14 

15import argparse 

16import gzip 

17import json 

18import os 

19import sys 

20import time as _time 

21from collections import Counter 

22from pathlib import Path 

23 

24import pandas as pd 

25 

26ROOT = Path(__file__).resolve().parents[1] 

27sys.path.insert(0, str(ROOT)) 

28 

29from data_pipeline import filing_text, net_retry # noqa: E402 

30from data_pipeline.edgar_facts import CONTACT_ENV, SUBMISSIONS_URL, TICKERS_URL # noqa: E402 

31 

32WIDE = ROOT / "data_wide" 

33REFERENCE = WIDE / "reference" 

34CACHE = WIDE / "_cache" / "filings" 

35DOCUMENT_URL = "https://www.sec.gov/Archives/edgar/data/{cik}/{accession}/{document}" 

36OLDER_PAGE_URL = "https://data.sec.gov/submissions/{name}" 

37SELECTION_WINDOW = ("2009-01-01", "2018-12-31") 

38FULL_WINDOW = ("2009-01-01", "2026-11-02") 

39PAUSE_SECONDS = 0.13 # under SEC's 10 requests a second 

40MAX_DOCUMENT_BYTES = 40_000_000 

41 

42 

43def sec_headers() -> dict[str, str]: 

44 contact = os.environ.get(CONTACT_ENV, "").strip() 

45 if not contact: 

46 raise SystemExit(f"{CONTACT_ENV} is not set: SEC refuses a client with no contact") 

47 return {"User-Agent": f"AetherQuantResearch/6.6 {contact}", "Accept-Encoding": "gzip"} 

48 

49 

50def names_in_scope(scope: str) -> list[str]: 

51 """Member tickers of the wide root; side A only for a selection run.""" 

52 from evaluation.research_cells import name_side 

53 from evaluation.wide_context import project_tickers 

54 

55 manifest = json.loads((WIDE / "wide_manifest.json").read_text(encoding="utf-8")) 

56 members = sorted(ticker for ticker, entry in manifest["tickers"].items() if entry.get("member")) 

57 if scope == "full": 

58 return members 

59 base = json.loads((ROOT / "config.json").read_text(encoding="utf-8")) 

60 project = project_tickers(base, "equity") 

61 return [ticker for ticker in members if name_side(ticker, project) == "A"] 

62 

63 

64class Fetcher: 

65 def __init__(self, headers: dict[str, str]) -> None: 

66 import requests 

67 

68 self.session = requests.Session() 

69 self.session.headers.update(headers) 

70 self.requests = 0 

71 

72 def get(self, url: str): 

73 response = net_retry.fetch(url, get=self.session.get, timeout=120.0) 

74 self.requests += 1 

75 _time.sleep(PAUSE_SECONDS) 

76 return response 

77 

78 def json(self, url: str) -> dict | None: 

79 response = self.get(url) 

80 return None if response is None else response.json() 

81 

82 def counts(self, cik: int, row: dict) -> dict[int, int] | None: 

83 url = DOCUMENT_URL.format(cik=cik, accession=str(row["accessionNumber"]).replace("-", ""), document=row["primaryDocument"]) 

84 response = self.get(url) 

85 if response is None or len(response.content) > MAX_DOCUMENT_BYTES: 

86 return None 

87 return filing_text.hashed_counts(filing_text.tokens(response.content.decode("utf-8", errors="replace"))) or None 

88 

89 

90def build_ticker(fetcher: Fetcher, cik: int, window: tuple[str, str]) -> dict: 

91 submissions = fetcher.json(SUBMISSIONS_URL.format(cik=cik)) or {} 

92 pages = [submissions] 

93 for entry in (submissions.get("filings") or {}).get("files") or []: 

94 if str(entry.get("filingTo", "9999")) >= window[0]: 

95 page = fetcher.json(OLDER_PAGE_URL.format(name=entry["name"])) 

96 if page: 

97 pages.append(page) 

98 filings = [row for row in filing_text.merge_pages(pages) if row["filingDate"] <= window[1]] 

99 earnings = [row for row in filing_text.earnings_rows(filings) if row["filed"] >= window[0]] 

100 in_window = [row for row in filings if row["filingDate"] >= window[0]] 

101 cache: dict[str, dict[int, int] | None] = {} 

102 

103 def counts_of(row: dict): 

104 key = str(row["accessionNumber"]) 

105 if key not in cache: 

106 cache[key] = fetcher.counts(cik, row) 

107 return cache[key] 

108 

109 wanted = [(current, earlier) for current, earlier in filing_text.prior_year_pairs(filings) if current["filingDate"] >= window[0] and current in in_window] 

110 similarity = [] 

111 for current, earlier in wanted: 

112 now, then = counts_of(current), counts_of(earlier) 

113 value = filing_text.cosine(now, then) if now and then else None 

114 if value is not None: 

115 similarity.append({"form": str(current["form"]), "period_end": str(current["reportDate"]), "filed": str(current["filingDate"]), "similarity": float(value)}) 

116 return {"earnings": earnings, "similarity": sorted(similarity, key=lambda row: row["filed"])} 

117 

118 

119def write_outputs(cache_dir: Path, scope: str) -> dict: 

120 earnings, similarity = [], [] 

121 for path in sorted(cache_dir.glob("*.json")): 

122 ticker = path.stem.upper() 

123 saved = json.loads(path.read_text(encoding="utf-8")) 

124 earnings += [{"ticker": ticker, **row} for row in saved["earnings"]] 

125 similarity += [{"ticker": ticker, **row} for row in saved["similarity"]] 

126 REFERENCE.mkdir(parents=True, exist_ok=True) 

127 earn_frame = pd.DataFrame(earnings, columns=["ticker", "accepted", "filed"]) 

128 sim_frame = pd.DataFrame(similarity, columns=["ticker", "form", "period_end", "filed", "similarity"]) 

129 earn_frame.to_csv(REFERENCE / "earnings_dates.csv.gz", index=False, lineterminator="\n", compression="gzip") 

130 sim_frame.to_csv(REFERENCE / "filing_similarity.csv.gz", index=False, lineterminator="\n", compression="gzip") 

131 by_year_names = lambda frame: {str(year): int(count) for year, count in frame.assign(year=frame["filed"].str[:4]).groupby("year")["ticker"].nunique().items()} # noqa: E731 

132 report = { 

133 "scope": scope, "tickers_cached": len(list(cache_dir.glob("*.json"))), "earnings_rows": len(earn_frame), "similarity_rows": len(sim_frame), 

134 "names_with_earnings_by_year": by_year_names(earn_frame), "names_with_similarity_by_year": by_year_names(sim_frame), 

135 } 

136 (REFERENCE / "filing_signals_report.json").write_text(json.dumps(report, indent=1), encoding="utf-8", newline="\n") 

137 return report 

138 

139 

140def assert_contact_not_written() -> None: 

141 """The run ends by searching what it wrote for the contact, as build_wide_info.py does.""" 

142 contact = os.environ.get(CONTACT_ENV, "").strip() 

143 if not contact: 

144 return 

145 needle = contact.encode("utf-8") 

146 paths = [REFERENCE / "earnings_dates.csv.gz", REFERENCE / "filing_similarity.csv.gz", REFERENCE / "filing_signals_report.json", *CACHE.glob("*.json")] 

147 for path in paths: 

148 if not path.exists(): 

149 continue 

150 data = gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes() 

151 if needle in data: 

152 raise SystemExit(f"the SEC contact was found in {path}: delete the output and report this") 

153 

154 

155def main(argv: list[str] | None = None) -> int: 

156 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

157 parser.add_argument("--scope", choices=["selection", "full"], default="selection") 

158 parser.add_argument("--limit", type=int, default=None, help="only the first N tickers (a trial run)") 

159 args = parser.parse_args(argv) 

160 headers = sec_headers() 

161 window = SELECTION_WINDOW if args.scope == "selection" else FULL_WINDOW 

162 cache_dir = CACHE / args.scope 

163 cache_dir.mkdir(parents=True, exist_ok=True) 

164 fetcher = Fetcher(headers) 

165 directory = fetcher.json(TICKERS_URL) or {} 

166 cik_by_ticker = {str(item["ticker"]).upper().replace("-", "."): int(item["cik_str"]) for item in directory.values()} 

167 tickers = names_in_scope(args.scope)[: args.limit] 

168 missing = Counter() 

169 for position, ticker in enumerate(tickers, 1): 

170 cached = cache_dir / f"{ticker.lower()}.json" 

171 if cached.exists(): 

172 continue 

173 cik = cik_by_ticker.get(ticker.upper()) 

174 if cik is None: 

175 missing["no_cik"] += 1 

176 cached.write_text(json.dumps({"earnings": [], "similarity": []}), encoding="utf-8", newline="\n") 

177 continue 

178 try: 

179 saved = build_ticker(fetcher, cik, window) 

180 except net_retry.NetworkOutage as error: 

181 print(f"stopped at {ticker}: {error}. Everything cached is kept; run again to resume.", flush=True) 

182 return 2 

183 except Exception as error: # one failed company must not lose the others; it is retried on the next run 

184 print(f"{ticker}: {type(error).__name__}", flush=True) 

185 missing["failed"] += 1 

186 continue 

187 cached.write_text(json.dumps(saved, separators=(",", ":")), encoding="utf-8", newline="\n") 

188 print(f"[{position}/{len(tickers)}] {ticker}: {len(saved['earnings'])} announcements, {len(saved['similarity'])} similarities", flush=True) 

189 report = write_outputs(cache_dir, args.scope) 

190 report["not_found_or_failed"] = dict(missing) 

191 (REFERENCE / "filing_signals_report.json").write_text(json.dumps(report, indent=1), encoding="utf-8", newline="\n") 

192 assert_contact_not_written() 

193 print(json.dumps({key: report[key] for key in ("scope", "tickers_cached", "earnings_rows", "similarity_rows", "not_found_or_failed")}, indent=1)) 

194 return 0 

195 

196 

197if __name__ == "__main__": 

198 raise SystemExit(main())