Coverage for data_pipeline/data_audit.py: 100%
173 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"""Lean daily-data audit and file manifest (V5.8.0).
3V5.8.0 rewrites every universe zip from one Yahoo pull to extend the window to 2026. A rewrite that silently drops a
4month, writes an unadjusted split or a spinoff gap, or leaves a quote zip stopping years early (BTC's ended 2018-12-24)
5would poison the dataset the way #130 (double-adjusted factor files) and #141 (Codespace-only FRED files) did. This module
6reads each zip the way Lean does and reports, per ticker:
8 * coverage: first/last date, rows, missing weekdays per year (equity/forex) or missing days (crypto, 7-day calendar),
9 * suspicious moves: |1-day close return| above a per-class threshold (a split or spinoff the source did not adjust),
10 * OHLC sanity (low <= open/close <= high, all > 0) and long flat runs,
11 * quote-zip coverage against the trade zip (crypto) and factor-file presence (equity).
13`build_data_manifest` / `compare_manifests` give a size + SHA-256 file list so local `data/` and the Codespace copy can
14be proven identical file-for-file. Pure stdlib + pandas; reading only.
15"""
17from __future__ import annotations
19import hashlib
20import io
21import zipfile
22from pathlib import Path
24import numpy as np
25import pandas as pd
27# |1-day close return| above which a move is flagged for a manual look (a missed split/spinoff, a bad print)
28OUTLIER_RETURN_BY_CLASS = {"equity": 0.25, "bond": 0.12, "crypto": 0.60, "forex": 0.08}
29# NYSE has ~9-10 holidays a year; more missing weekdays than this per year is a coverage gap
30MAX_MISSING_WEEKDAYS_PER_YEAR = {"equity": 12.0, "bond": 12.0, "forex": 6.0}
31FLAT_RUN_FLAG = 5
34def read_lean_daily_zip(path: Path, security_type: str) -> pd.DataFrame:
35 """date/open/high/low/close/volume from a Lean daily zip. Equity prices are stored x10000; forex quote rows are
36 bid OHLC, bid size, ask OHLC, ask size (midpoint returned); crypto trade rows are plain decimals."""
37 with zipfile.ZipFile(path) as archive:
38 names = archive.namelist()
39 if not names:
40 return pd.DataFrame(columns=["date", "open", "high", "low", "close", "volume"])
41 text = archive.read(names[0]).decode("utf-8", errors="replace")
42 raw = pd.read_csv(io.StringIO(text), header=None)
43 dates = pd.to_datetime(raw[0].astype(str).str[:8], format="%Y%m%d")
44 if security_type == "forex":
45 bid = raw[[1, 2, 3, 4]].to_numpy(float)
46 ask = raw[[6, 7, 8, 9]].to_numpy(float) if raw.shape[1] >= 10 else bid
47 mid = (bid + ask) / 2.0
48 frame = pd.DataFrame({"date": dates, "open": mid[:, 0], "high": mid[:, 1], "low": mid[:, 2], "close": mid[:, 3]})
49 frame["volume"] = 0.0
50 return frame
51 frame = pd.DataFrame(
52 {"date": dates, "open": raw[1].astype(float), "high": raw[2].astype(float), "low": raw[3].astype(float),
53 "close": raw[4].astype(float), "volume": raw[5].astype(float) if raw.shape[1] > 5 else 0.0}
54 )
55 if security_type == "equity":
56 for column in ("open", "high", "low", "close"):
57 frame[column] = frame[column] / 10_000.0
58 return frame
61def _longest_flat_run(closes: np.ndarray) -> int:
62 longest = current = 1 if len(closes) else 0
63 for index in range(1, len(closes)):
64 current = current + 1 if closes[index] == closes[index - 1] else 1
65 longest = max(longest, current)
66 return longest
69def audit_series(frame: pd.DataFrame, asset_class: str, *, start: str | None = None, end: str | None = None) -> dict:
70 """Coverage, outlier, OHLC and flat-run findings for one ticker's frame (read_lean_daily_zip output)."""
71 data = frame.sort_values("date").drop_duplicates("date")
72 if start:
73 data = data[data["date"] >= pd.Timestamp(start)]
74 if end:
75 data = data[data["date"] <= pd.Timestamp(end)]
76 if data.empty:
77 return {"rows": 0, "problems": ["no rows in window"]}
78 problems: list[str] = []
79 first, last = data["date"].iloc[0], data["date"].iloc[-1]
80 years = max((last - first).days / 365.25, 1e-9)
81 present = set(data["date"].dt.normalize())
82 if asset_class == "crypto":
83 expected = pd.date_range(first, last, freq="D")
84 missing = [day for day in expected if day not in present]
85 missing_per_year = len(missing) / years
86 if missing:
87 problems.append(f"{len(missing)} missing calendar days")
88 else:
89 expected = pd.bdate_range(first, last)
90 missing = [day for day in expected if day not in present]
91 missing_per_year = len(missing) / years
92 limit = MAX_MISSING_WEEKDAYS_PER_YEAR.get(asset_class, 12.0)
93 if missing_per_year > limit:
94 problems.append(f"{missing_per_year:.1f} missing weekdays/year (> {limit})")
95 gaps = data["date"].diff().dt.days.dropna()
96 largest_gap = int(gaps.max()) if len(gaps) else 0
97 closes = data["close"].to_numpy(float)
98 returns = closes[1:] / closes[:-1] - 1.0 if len(closes) > 1 else np.array([])
99 threshold = OUTLIER_RETURN_BY_CLASS.get(asset_class, 0.25)
100 outlier_index = np.nonzero(np.abs(returns) > threshold)[0]
101 outliers = [
102 {"date": data["date"].iloc[i + 1].date().isoformat(), "return": round(float(returns[i]), 4)} for i in outlier_index
103 ]
104 if outliers:
105 problems.append(f"{len(outliers)} |1d return| > {threshold:.0%}")
106 ohlc = data[["open", "high", "low", "close"]].to_numpy(float)
107 nonpositive = int((ohlc <= 0).any(axis=1).sum())
108 tolerance = 1e-9
109 inconsistent = int(
110 ((ohlc[:, 2] > ohlc[:, [0, 3]].min(axis=1) + tolerance) | (ohlc[:, 1] + tolerance < ohlc[:, [0, 3]].max(axis=1))).sum()
111 )
112 if nonpositive:
113 problems.append(f"{nonpositive} rows with a non-positive price")
114 if inconsistent:
115 problems.append(f"{inconsistent} rows with low/high outside open/close")
116 flat_run = _longest_flat_run(closes)
117 if flat_run >= FLAT_RUN_FLAG and asset_class != "forex":
118 problems.append(f"flat close run of {flat_run} bars")
119 return {
120 "rows": int(len(data)),
121 "first": first.date().isoformat(),
122 "last": last.date().isoformat(),
123 "missing_per_year": round(float(missing_per_year), 2),
124 "largest_gap_days": largest_gap,
125 "outliers": outliers,
126 "nonpositive_rows": nonpositive,
127 "ohlc_inconsistent_rows": inconsistent,
128 "longest_flat_run": int(flat_run),
129 "problems": problems,
130 }
133def asset_zip_paths(asset: dict, data_root: Path) -> dict[str, Path]:
134 """{'trade': path[, 'quote': path]} for a config universe asset (its `data_path` is relative to the repo root and
135 starts with 'data/')."""
136 relative = Path(asset["data_path"])
137 trade = Path(data_root) / Path(*relative.parts[1:])
138 paths = {"trade": trade}
139 if asset.get("security_type") == "crypto" and trade.name.endswith("_trade.zip"):
140 paths["quote"] = trade.with_name(trade.name.replace("_trade.zip", "_quote.zip"))
141 return paths
144def audit_universe(config: dict, data_root: Path, *, start: str | None = None, end: str | None = None) -> dict:
145 """Audits every `phase1.universe.assets` entry under `data_root`. `end` defaults to none (whole file)."""
146 data_root = Path(data_root)
147 factor_dir = data_root / "equity" / "usa" / "factor_files"
148 report: dict = {"data_root": str(data_root), "window": {"start": start, "end": end}, "assets": {}}
149 flagged = []
150 for asset in config["phase1"]["universe"]["assets"]:
151 ticker = str(asset["ticker"])
152 security_type = str(asset.get("security_type", "equity"))
153 asset_class = str(asset.get("asset_class") or security_type)
154 paths = asset_zip_paths(asset, data_root)
155 entry: dict = {"security_type": security_type, "asset_class": asset_class}
156 if not paths["trade"].exists():
157 entry["problems"] = [f"missing zip {paths['trade']}"]
158 else:
159 frame = read_lean_daily_zip(paths["trade"], security_type)
160 entry.update(audit_series(frame, asset_class, start=start, end=end))
161 if "quote" in paths:
162 if paths["quote"].exists():
163 quote = read_lean_daily_zip(paths["quote"], "forex")
164 quote_last = quote["date"].max().date().isoformat() if len(quote) else None
165 entry["quote_last"] = quote_last
166 if entry.get("last") and quote_last and quote_last < entry["last"]:
167 entry["problems"].append(f"quote zip ends {quote_last} before trade zip {entry['last']}")
168 else:
169 entry["problems"].append("missing quote zip")
170 if security_type == "equity":
171 entry["factor_file"] = (factor_dir / f"{ticker.lower()}.csv").exists()
172 if entry.get("problems"):
173 flagged.append(ticker)
174 report["assets"][ticker] = entry
175 report["num_assets"] = len(report["assets"])
176 report["flagged"] = flagged
177 return report
180NON_DAILY_RESOLUTIONS = ("hour", "minute", "second", "tick")
183def _last_bar_date(path: Path) -> str | None:
184 """YYYY-MM-DD of the last bar in a Lean zip: the file name for per-day zips (`20131011_trade.zip`), else the last
185 csv row's leading YYYYMMDD."""
186 stem = path.name.split("_", 1)[0]
187 if len(stem) == 8 and stem.isdigit():
188 return f"{stem[:4]}-{stem[4:6]}-{stem[6:8]}"
189 try:
190 with zipfile.ZipFile(path) as archive:
191 members = [name for name in archive.namelist() if name.endswith(".csv")]
192 if not members:
193 return None
194 rows = [row for row in archive.read(sorted(members)[-1]).decode("utf-8", "replace").splitlines() if row.strip()]
195 except (OSError, zipfile.BadZipFile):
196 return None
197 if not rows:
198 return None
199 stamp = rows[-1].split(",", 1)[0].strip()[:8]
200 return f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]}" if stamp.isdigit() else None
203def audit_non_daily_files(config: dict, data_root: Path) -> dict:
204 """Every hour/minute/second/tick zip under `data_root` with its last bar date and whether a run reads it.
206 The universe trades daily bars, so a non-daily file is read only as Lean's default benchmark (an internal hourly SPY
207 feed) while `runtime.benchmark_ticker` is unset; the rest are Lean's own sample data, kept for Lean."""
208 data_root = Path(data_root)
209 resolution = str(config.get("phase1", {}).get("universe", {}).get("resolution", "Daily")).lower()
210 benchmark_set = bool((config.get("runtime") or {}).get("benchmark_ticker"))
211 files = []
212 for path in sorted(data_root.rglob("*.zip")):
213 parts = path.relative_to(data_root).parts
214 found = next((part for part in parts[:-1] if part in NON_DAILY_RESOLUTIONS), None)
215 if found is None:
216 continue
217 relative = "/".join(parts)
218 read_by = None
219 if relative == "equity/usa/hour/spy.zip" and not benchmark_set:
220 read_by = "lean_default_benchmark"
221 elif found == resolution:
222 read_by = "universe_resolution"
223 files.append({"path": relative, "resolution": found, "bytes": path.stat().st_size, "last": _last_bar_date(path), "read_by": read_by})
224 return {"num_files": len(files), "read": [entry["path"] for entry in files if entry["read_by"]], "files": files}
227def build_data_manifest(root: Path, *, subdirs: tuple[str, ...] = ("crypto", "equity", "forex", "reference")) -> dict:
228 """{relative posix path: {"size", "sha256"}} for every file under root/<subdir>."""
229 root = Path(root)
230 manifest: dict[str, dict] = {}
231 for subdir in subdirs:
232 base = root / subdir
233 if not base.exists():
234 continue
235 for path in sorted(p for p in base.rglob("*") if p.is_file()):
236 digest = hashlib.sha256()
237 with path.open("rb") as handle:
238 for block in iter(lambda: handle.read(1 << 20), b""):
239 digest.update(block)
240 manifest[path.relative_to(root).as_posix()] = {"size": path.stat().st_size, "sha256": digest.hexdigest()}
241 return manifest
244def compare_manifests(left: dict, right: dict) -> dict:
245 """Files only on one side and files whose hash differs."""
246 only_left = sorted(set(left) - set(right))
247 only_right = sorted(set(right) - set(left))
248 differing = sorted(path for path in set(left) & set(right) if left[path]["sha256"] != right[path]["sha256"])
249 return {
250 "only_left": only_left,
251 "only_right": only_right,
252 "differing": differing,
253 "identical": not (only_left or only_right or differing),
254 }