Coverage for scripts/build_wide_info.py: 100%

152 statements  

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

1"""Everything non-price the wide root holds (V6.6.0): EDGAR fundamentals and sectors, splits, insider trades, short volume, factor returns. 

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 

4written anywhere, and the run ends by checking that. Each part resumes or skips if its output exists. 

5 

6 AQ_SEC_CONTACT=... python scripts/build_wide_info.py [--parts fundamentals splits insiders short factors extended] 

7""" 

8 

9from __future__ import annotations 

10 

11import argparse 

12import gzip 

13import json 

14import os 

15import sys 

16import time as _time 

17from pathlib import Path 

18 

19import pandas as pd 

20 

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

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

23 

24from data_pipeline import edgar_facts, factor_library, finra_short_volume, net_retry, sec_form345 # noqa: E402 

25from data_pipeline.edgar_facts import CONTACT_ENV # noqa: E402 

26 

27WIDE = ROOT / "data_wide" 

28REFERENCE = WIDE / "reference" 

29CACHE = WIDE / "_cache" 

30ALL_PARTS = ("fundamentals", "splits", "insiders", "short", "factors", "extended") 

31DEFAULT_PARTS = ("fundamentals", "splits", "insiders", "short", "factors") 

32 

33 

34def member_tickers(root: Path = WIDE) -> list[str]: 

35 manifest = json.loads((root / "wide_manifest.json").read_text(encoding="utf-8")) 

36 return sorted(ticker for ticker, entry in manifest["tickers"].items() if entry.get("member")) 

37 

38 

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

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

41 if not contact: 

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

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

44 

45 

46def build_fundamentals(tickers: list[str]) -> dict: 

47 rows, sectors, missing = edgar_facts.fetch_fundamentals(tickers, cache_dir=CACHE / "edgar") 

48 edgar_facts.write_fundamentals(rows, REFERENCE / "edgar_fundamentals.csv.gz") 

49 (REFERENCE / "sectors.json").write_text(json.dumps(dict(sorted(sectors.items())), indent=1), encoding="utf-8", newline="\n") 

50 eps = edgar_facts.collect_cached_eps(tickers, CACHE / "edgar") 

51 pd.DataFrame(eps, columns=["ticker", "period_start", "period_end", "filed", "eps"]).to_csv(REFERENCE / "edgar_eps.csv.gz", index=False, lineterminator="\n", compression="gzip") 

52 return {"fundamental_rows": len(rows), "tickers_with_sector": len(sectors), "no_sec_data": sorted(missing)} 

53 

54 

55def build_extended(tickers: list[str]) -> dict: 

56 """V6.6.1's quarterly figures and new fields, in their own file, so the file every earlier trial read stays byte-identical.""" 

57 rows, missing = edgar_facts.fetch_extended(tickers, cache_dir=CACHE / "edgar_ext") 

58 edgar_facts.write_fundamentals(rows, REFERENCE / "edgar_fundamentals_ext.csv.gz") 

59 return {"extended_rows": len(rows), "no_sec_data": sorted(missing)} 

60 

61 

62def build_splits(tickers: list[str]) -> dict: 

63 rows, failed = edgar_facts.fetch_splits_tolerant(tickers) 

64 pd.DataFrame(rows, columns=["ticker", "date", "ratio"]).to_csv(REFERENCE / "equity_splits.csv", index=False, lineterminator="\n") 

65 return {"split_rows": len(rows), "split_lookup_failed": sorted(failed)} 

66 

67 

68def _sec_get_bytes(headers: dict[str, str]): 

69 import requests 

70 

71 def get(url: str) -> bytes | None: 

72 response = net_retry.fetch(url, get=requests.get, headers=headers, timeout=180.0) 

73 return None if response is None else response.content 

74 

75 return get 

76 

77 

78def build_insiders(tickers: list[str]) -> dict: 

79 get = _sec_get_bytes(sec_headers()) 

80 wanted = set(tickers) 

81 pieces = [] 

82 (CACHE / "form345").mkdir(parents=True, exist_ok=True) 

83 for year, quarter in sec_form345.quarters(2006, 2026, 3): 

84 cached = CACHE / "form345" / f"{year}q{quarter}.csv.gz" 

85 if cached.exists(): 

86 saved = pd.read_csv(cached, dtype=str) 

87 if not saved.empty: 

88 pieces.append(saved) 

89 continue 

90 frame = sec_form345.fetch_trades([(year, quarter)], get, wanted) 

91 if frame.empty: 

92 # A quarter of S&P 500 issuers always has trades: an empty one is a failure to read, and a cached empty would hide it for good. 

93 print(f"form345 {year}q{quarter}: no trades, not cached", flush=True) 

94 continue 

95 frame.to_csv(cached, index=False, lineterminator="\n", compression="gzip") 

96 pieces.append(frame.astype(str)) 

97 print(f"form345 {year}q{quarter}: {len(frame)} trades", flush=True) 

98 _time.sleep(0.2) 

99 trades = pd.concat(pieces, ignore_index=True) 

100 trades.to_csv(REFERENCE / "insider_trades.csv.gz", index=False, lineterminator="\n", compression="gzip") 

101 return {"insider_trades": len(trades)} 

102 

103 

104def build_short(tickers: list[str]) -> dict: 

105 import requests 

106 

107 session = requests.Session() 

108 session.headers["User-Agent"] = "AetherQuantResearch/6.6 (github.com/leon1706-lol/Aether-quant)" 

109 

110 def get_text(url: str) -> str | None: 

111 # A date with no file is a 403 here, not a 404. Anything else is a failed fetch: it waits, or stops the run. 

112 response = net_retry.fetch(url, get=session.get, absent_codes=(403, 404), timeout=60.0) 

113 return None if response is None else response.text 

114 

115 cache = CACHE / "finra" 

116 cache.mkdir(parents=True, exist_ok=True) 

117 pieces = [] 

118 for month in pd.period_range("2018-08", "2026-11", freq="M"): 

119 cached = cache / f"{month}.parquet" 

120 if cached.exists(): 

121 pieces.append(pd.read_parquet(cached)) 

122 continue 

123 days = [day.strftime("%Y-%m-%d") for day in pd.bdate_range(month.start_time, min(month.end_time, pd.Timestamp("2026-11-02")))] 

124 frame = finra_short_volume.fetch_ratios(days, get_text, tickers) 

125 if frame.empty: 

126 print(f"finra {month}: no files, not cached", flush=True) 

127 continue 

128 frame.astype("float32").to_parquet(cached) 

129 pieces.append(frame) 

130 print(f"finra {month}: {len(frame)} days", flush=True) 

131 ratios = pd.concat(pieces).sort_index() 

132 if ratios.empty: 

133 raise SystemExit("no short-volume file read at all: this is a failure, not an absence") 

134 ratios.astype("float32").to_parquet(REFERENCE / "short_ratio.parquet") 

135 return {"short_ratio_days": len(ratios), "short_ratio_first": str(ratios.index.min()), "short_ratio_last": str(ratios.index.max())} 

136 

137 

138def build_factors() -> dict: 

139 import requests 

140 

141 def get(url: str) -> bytes: 

142 response = requests.get(url, timeout=180, headers={"User-Agent": "AetherQuantResearch/6.6 (github.com/leon1706-lol/Aether-quant)"}) 

143 response.raise_for_status() 

144 return response.content 

145 

146 frame = factor_library.fetch_factors(get) 

147 frame.to_parquet(REFERENCE / "factors_daily.parquet") 

148 return {"factors": list(frame.columns), "factors_first": str(frame.index.min()), "factors_last": {column: str(frame[column].dropna().index.max()) for column in frame.columns}} 

149 

150 

151def contact_leaks(root: Path, contact: str) -> list[str]: 

152 """Files under the root holding the contact, gzip included. An address must never be stored, by this script or a library it called.""" 

153 if not contact: 

154 return [] 

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

156 hits = [] 

157 for path in root.rglob("*"): 

158 if not path.is_file() or path.stat().st_size > 200_000_000: 

159 continue 

160 try: 

161 payload = path.read_bytes() 

162 if path.suffix == ".gz": 

163 payload = gzip.decompress(payload) 

164 except OSError: 

165 continue 

166 if needle in payload: 

167 hits.append(str(path)) 

168 return hits 

169 

170 

171def main() -> int: 

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

173 parser.add_argument("--parts", nargs="+", default=list(DEFAULT_PARTS), choices=ALL_PARTS) 

174 parser.add_argument("--refresh", action="store_true", help="extended only: drop the per-company cache first, so new quarterly filings are read (a forward decision needs them)") 

175 args = parser.parse_args() 

176 if args.refresh and "extended" in args.parts: 

177 import shutil 

178 

179 shutil.rmtree(CACHE / "edgar_ext", ignore_errors=True) 

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

181 tickers = member_tickers() 

182 report_path = REFERENCE / "wide_info_report.json" 

183 report = json.loads(report_path.read_text(encoding="utf-8")) if report_path.exists() else {} 

184 builders = { 

185 "fundamentals": lambda: build_fundamentals(tickers), "splits": lambda: build_splits(tickers), "insiders": lambda: build_insiders(tickers), 

186 "short": lambda: build_short(tickers), "factors": build_factors, "extended": lambda: build_extended(tickers), 

187 } 

188 for part in args.parts: 

189 try: 

190 report[part] = builders[part]() 

191 except net_retry.NetworkOutage as error: 

192 print(f"{part}: stopped by a network outage, rerun to resume: {error}", file=sys.stderr, flush=True) 

193 return 3 

194 report_path.write_text(json.dumps(report, indent=1), encoding="utf-8", newline="\n") 

195 print(part, json.dumps({key: value for key, value in report[part].items() if not isinstance(value, list)}), flush=True) 

196 leaks = contact_leaks(WIDE / "reference", os.environ.get(CONTACT_ENV, "").strip()) + contact_leaks(CACHE, os.environ.get(CONTACT_ENV, "").strip()) 

197 if leaks: 

198 print(f"CONTACT FOUND IN {len(leaks)} FILE(S): remove before anything else", file=sys.stderr) 

199 return 2 

200 return 0 

201 

202 

203if __name__ == "__main__": 

204 raise SystemExit(main())