Coverage for scripts/feature_parity_audit.py: 100%

221 statements  

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

1"""V5.3.6 Workstream A - CLI driver for the feature-parity audit. 

2 

3Usage: 

4 python scripts/feature_parity_audit.py [--output ml/evaluation/feature_parity_report.json] 

5 

6Runs three offline checks and writes a structured report: 

7 

81. **synthetic_formula_parity** - the pure replicas in 

9 evaluation/feature_parity.py are diffed against train.py's OWN 

10 implementations (engineer_features / add_liquidity_features / 

11 build_macro_features_by_date) on randomized synthetic data. Proves the 

12 replicas are faithful before they are trusted anywhere else. 

132. **artifact_consistency** - on the REAL dataset: recompute every raw 

14 OHLCV-recomputable model input, push it through the shipped scaler 

15 artifact in the forward direction, and compare against the scaled column 

16 stored in full_dataset.csv. A stale `scaler_stats.json` after a dataset 

17 rebuild shows up here as systematic mismatches (#100-class risk). 

183. **structured_verdicts** - families that cannot be recomputed offline 

19 (regime chain, alt FRED inputs, sensitivity regressions, bond treasury 

20 inputs, topology/peer graphs) get explicit per-family verdicts recording 

21 whether BOTH sides call one shared `features/*.py` function (inspection- 

22 verified) so residual risk is call-site parameters only. 

23""" 

24 

25from __future__ import annotations 

26 

27import argparse 

28import json 

29import sys 

30import time 

31from pathlib import Path 

32 

33import numpy as np 

34import pandas as pd 

35 

36ROOT_DIR = Path(__file__).resolve().parents[1] 

37sys.path.insert(0, str(ROOT_DIR)) 

38 

39from evaluation.feature_parity import ( # noqa: E402 

40 BASE_TECHNICAL_FEATURES, 

41 DEFAULT_LONG_LOOKBACK_WINDOW_BARS, 

42 INDICATOR_FEATURES, 

43 LIQUIDITY_FEATURES, 

44 build_momentum_pool, 

45 compute_base_technicals_replica, 

46 compute_cs_momentum_rank_replica, 

47 compute_liquidity_replica, 

48 compute_macro_proxies_replica, 

49 forward_scale, 

50 load_scaler_mapping, 

51 summarize_comparison, 

52) 

53 

54WARMUP_ROWS_SHORT_WINDOW = 46 # 20d lookback + dropped-first-row offset + safety 

55WARMUP_ROWS_SPREAD_PROXY = 27 # 25-bar window + dropped-first-row offset 

56 

57 

58def _synthetic_frame(rows: int = 320, seed: int = 7) -> pd.DataFrame: 

59 rng = np.random.default_rng(seed) 

60 close = 100.0 * np.exp(np.cumsum(rng.normal(0.0, 0.01, rows))) 

61 high = close * (1 + np.abs(rng.normal(0, 0.004, rows))) 

62 low = close * (1 - np.abs(rng.normal(0, 0.004, rows))) 

63 open_ = np.clip(close * (1 + rng.normal(0, 0.002, rows)), low, high) 

64 volume = rng.integers(50_000, 5_000_000, rows).astype(float) 

65 return pd.DataFrame( 

66 { 

67 "date": pd.bdate_range("2019-01-01", periods=rows).strftime("%Y-%m-%d"), 

68 "open": open_, 

69 "high": high, 

70 "low": low, 

71 "close": close, 

72 "volume": volume, 

73 } 

74 ) 

75 

76 

77def check_synthetic_formula_parity() -> dict: 

78 """Replicas vs train.py's own implementations on randomized data.""" 

79 result: dict[str, dict] = {} 

80 try: 

81 import train as train_module # heavy: pulls torch once 

82 

83 frame = _synthetic_frame() 

84 # engineer_features() assigns each row's split via assign_split(), 

85 # which requires the full phase1.windows shape - wide bounds so every 

86 # synthetic row lands somewhere valid. 

87 windows = { 

88 "training": {"start": "1900-01-01", "end": "2099-12-31"}, 

89 "validation": {"start": "1900-01-01", "end": "2099-12-31"}, 

90 "backtest": {"start": "1900-01-01", "end": "2099-12-31"}, 

91 } 

92 

93 reference = train_module.engineer_features(frame.copy(), [], windows) 

94 replica = compute_base_technicals_replica(frame, long_window_bars=getattr(train_module, "LONG_LOOKBACK_WINDOW_BARS", DEFAULT_LONG_LOOKBACK_WINDOW_BARS)) 

95 # V5.5.0: engineer_features() drops rows (the forward-return label guard), 

96 # so `reference` is shorter than `frame` and the replica - computed over 

97 # every input row - must be indexed by DATE before comparing. The 

98 # positional comparison raised a broadcast ValueError that the blanket 

99 # except below turned into "SKIPPED", i.e. this whole check had been 

100 # silently dead while the audit still printed PASS. 

101 row_by_date = {date: position for position, date in enumerate(frame["date"])} 

102 reference_rows = [row_by_date[date] for date in reference["date"]] 

103 for name in BASE_TECHNICAL_FEATURES + INDICATOR_FEATURES: 

104 ref_col = reference[name].to_numpy(dtype=float) 

105 rep_col = np.asarray(replica[name], dtype=float)[reference_rows] 

106 valid = ~(np.isnan(ref_col) | np.isnan(rep_col)) 

107 delta = float(np.max(np.abs(ref_col[valid] - rep_col[valid]))) if valid.any() else 0.0 

108 result[name] = { 

109 "verdict": "PASS" if delta <= 1e-12 else "FAIL", 

110 "max_abs_delta": delta, 

111 "n_nan_reference": int(np.isnan(ref_col).sum()), 

112 "n_nan_replica": int(np.isnan(rep_col).sum()), 

113 } 

114 

115 liquidity_reference = train_module.add_liquidity_features(frame.copy(), "equity") 

116 liquidity_replica = compute_liquidity_replica(frame, security_type="equity") 

117 for name in LIQUIDITY_FEATURES: 

118 ref_col = liquidity_reference[name].to_numpy(dtype=float) 

119 rep_col = liquidity_replica[name] 

120 delta = float(np.max(np.abs(ref_col - rep_col))) 

121 result[name] = { 

122 "verdict": "PASS" if delta <= 1e-12 else "FAIL", 

123 "max_abs_delta": delta, 

124 "n_nan_reference": int(np.isnan(ref_col).sum()), 

125 "n_nan_replica": int(np.isnan(rep_col).sum()), 

126 } 

127 

128 macro_frames = {} 

129 for ticker in ("TLT", "SHY", "HYG", "LQD", "BTCUSD"): 

130 ticker_frame = _synthetic_frame(rows=260, seed=abs(hash(ticker)) % 1000) 

131 engineered = train_module.engineer_features(ticker_frame.copy(), [], windows) 

132 macro_frames[ticker] = engineered[["date", "close", "momentum_20d"]].reset_index(drop=True) 

133 macro_reference_by_ticker = train_module.build_macro_features_by_date(macro_frames, {}) 

134 momentum_long = pd.concat( 

135 [frame_for_ticker.assign(ticker=ticker) for ticker, frame_for_ticker in macro_frames.items()], 

136 ignore_index=True, 

137 ) 

138 macro_replica = compute_macro_proxies_replica(momentum_long) 

139 

140 macro_columns = ["macro_yield_curve_slope_proxy", "macro_credit_spread_proxy", "macro_crypto_risk_appetite_proxy"] 

141 reference_long = pd.concat( 

142 [frame_for_ticker.assign(ticker=ticker) for ticker, frame_for_ticker in macro_reference_by_ticker.items()], 

143 ignore_index=True, 

144 ).set_index(["ticker", "date"])[macro_columns].sort_index() 

145 replica_long = macro_replica.set_index(["ticker", "date"])[macro_columns].sort_index() 

146 joined = reference_long.join(replica_long, how="inner", lsuffix="_ref") 

147 for base_name in macro_columns: 

148 ref_col = joined[f"{base_name}_ref"].to_numpy(dtype=float) 

149 rep_col = joined[base_name].to_numpy(dtype=float) 

150 delta = float(np.nanmax(np.abs(ref_col - rep_col))) if len(joined) else float("nan") 

151 result[base_name] = { 

152 "verdict": "PASS" if delta <= 1e-12 else "FAIL", 

153 "max_abs_delta": delta, 

154 "n_compared": int(len(joined)), 

155 } 

156 result["_status"] = "OK" 

157 except Exception as error: 

158 result["_status"] = f"SKIPPED: {type(error).__name__}: {error}" 

159 return result 

160 

161 

162def check_artifact_consistency( 

163 dataset: pd.DataFrame, scaler_mapping: dict[str, tuple[float, float, float]], long_window_bars: int, forex_holidays: frozenset[int] = frozenset(), 

164) -> tuple[dict, dict]: 

165 """Real-data forward check: replica raw -> scaler artifact -> stored column. 

166 

167 Residual mismatches are POSITIONALLY CLASSIFIED per ticker: 

168 - warmup rows (excluded entirely), 

169 - "boundary artifact": within `long_window_bars` rows after a mid-series 

170 date gap (label-guard row drops create holes that build-time trailing 

171 windows legitimately spanned but a gapped replica cannot see), 

172 - anything else is UNEXPLAINED and fails the audit. This distinction is 

173 the whole point: boundary artifacts are expected consequences of 

174 auditing against a post-processed dataset, while unexplained 

175 mismatches would indicate genuine live-path drift.""" 

176 results: dict[str, dict] = {} 

177 

178 def _merge(existing: dict | None, comparison: dict) -> dict: 

179 if existing is None: 

180 return comparison 

181 merged = dict(existing) 

182 for key in ("n_compared", "n_mismatch_gt_1e-9", "n_saturated_at_clip", 

183 "n_boundary_artifact", "n_unexplained"): 

184 merged[key] = merged.get(key, 0) + comparison.get(key, 0) 

185 if comparison.get("max_abs_delta") is not None: 

186 merged["max_abs_delta"] = max(merged.get("max_abs_delta") or 0.0, comparison["max_abs_delta"]) 

187 merged["verdict"] = "FAIL" if merged.get("n_unexplained", 0) > 0 else ( 

188 "PASS" if merged.get("n_mismatch_gt_1e-9", 0) == 0 else "PASS_BOUNDARY_ARTIFACTS_ONLY" 

189 ) 

190 return merged 

191 

192 def _classify(bad_indices: np.ndarray, holes: set[int], warmup: int, memory_rows: int) -> tuple[int, int]: 

193 boundary = unexplained = 0 

194 for i in bad_indices: 

195 if i < warmup: 

196 continue # already excluded upstream; defensive 

197 if any(h <= i <= h + memory_rows for h in holes): # the first row after a gap reads across it too 

198 boundary += 1 

199 else: 

200 unexplained += 1 

201 return boundary, unexplained 

202 

203 for _ticker, group in dataset.groupby("ticker"): 

204 group = group.sort_values("date").reset_index(drop=True) 

205 security_type = str(group["security_type"].iloc[0]) if "security_type" in group.columns else "equity" 

206 dates = pd.to_datetime(group["date"]) 

207 # a crypto market trades every day, so any skipped day is a hole (a label-guard drop); equities and forex skip weekends 

208 holes = set(np.where(dates.diff().dt.days > (1 if security_type == "crypto" else 3))[0]) 

209 

210 ohlcv = group[["open", "high", "low", "close", "volume"]] 

211 row_positions = None 

212 if security_type == "forex": 

213 # Forex rows are engineered on Lean's fill-forward calendar (train.engineer_forex_features_on_lean_calendar): 

214 # replicate on the filled frame, then read the replica at the dataset's own dates. 

215 import train as train_module 

216 

217 filled = train_module.fill_forward_forex_frame(group[["date", "open", "high", "low", "close", "volume"]].assign(date=dates.to_numpy()), forex_holidays) 

218 row_positions = np.flatnonzero(filled["date"].isin(set(dates)).to_numpy()) 

219 ohlcv = filled[["open", "high", "low", "close", "volume"]] 

220 base = compute_base_technicals_replica(ohlcv, long_window_bars=long_window_bars) 

221 liquidity = compute_liquidity_replica(ohlcv, security_type=security_type) 

222 if row_positions is not None: 

223 base = {name: np.asarray(values)[row_positions] for name, values in base.items()} 

224 liquidity = {name: np.asarray(values)[row_positions] for name, values in liquidity.items()} 

225 

226 families = [ 

227 (name, base[name], long_window_bars + 1 if name in ("macd_histogram_norm", "dist_52w_high") else WARMUP_ROWS_SHORT_WINDOW) 

228 for name in BASE_TECHNICAL_FEATURES + INDICATOR_FEATURES 

229 ] + [ 

230 (name, liquidity[name], WARMUP_ROWS_SPREAD_PROXY if name == "liquidity_spread_proxy" else 0) 

231 for name in LIQUIDITY_FEATURES 

232 ] 

233 

234 for name, raw_values, warmup in families: 

235 stored = group[f"{name}_scaled"].to_numpy(dtype=float) 

236 raw = raw_values 

237 mean, scale, clip = scaler_mapping[name] 

238 valid = ~(np.isnan(stored) | np.isnan(raw)) 

239 n_compared = int(valid.sum()) 

240 expected = forward_scale(raw[valid], mean, scale, clip) 

241 delta = np.abs(expected - stored[valid]) 

242 bad_local = np.where(delta > 1e-9)[0] 

243 # map back to absolute indices among valid rows 

244 abs_valid_indices = np.where(valid)[0] 

245 bad_abs = abs_valid_indices[bad_local] 

246 boundary, unexplained = _classify(bad_abs, holes, warmup, memory_rows=long_window_bars) 

247 saturated = int(np.sum(np.abs(stored[valid]) >= clip - 1e-9)) 

248 comparison = { 

249 "n_compared": n_compared, 

250 "warmup_excluded_per_ticker": warmup, 

251 "max_abs_delta": float(delta.max()) if delta.size else None, 

252 "mean_abs_delta": float(delta.mean()) if delta.size else None, 

253 "n_mismatch_gt_1e-9": int(len(bad_local)), 

254 "n_saturated_at_clip": saturated, 

255 "n_boundary_artifact": boundary, 

256 "n_unexplained": unexplained, 

257 "verdict": ("FAIL" if unexplained else ("PASS_BOUNDARY_ARTIFACTS_ONLY" if len(bad_local) else "PASS")), 

258 } 

259 results[name] = _merge(results.get(name), comparison) 

260 

261 return results, {} 

262 

263 

264def check_cross_sectional_and_macro(dataset: pd.DataFrame, scaler_mapping: dict[str, tuple[float, float, float]]) -> dict: 

265 """cs_momentum_rank_20 + the three macro proxies against stored columns, 

266 using per-ticker OWN-calendar momentum (never a union pivot).""" 

267 

268 results: dict[str, dict] = {} 

269 security_types = ( 

270 dataset.drop_duplicates("ticker").set_index("ticker")["security_type"].astype(str).to_dict() 

271 if "security_type" in dataset.columns 

272 else {} 

273 ) 

274 from features.cross_asset_timing import resolve_forex_lean_holidays 

275 

276 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

277 momentum_long = build_momentum_pool(dataset, security_types, resolve_forex_lean_holidays(config)) 

278 dataset = dataset.assign(date=pd.to_datetime(dataset["date"])) 

279 

280 # V6.6.10: the warm-up is the dataset's first 45 sessions (the pool needs every name's history, which starts there), not its 

281 # first 45 rows; and a session that follows any name's hole (a label-guard drop: a skipped day for crypto, more than three 

282 # for the rest) pools that name's stale momentum, a boundary artifact like the per-ticker ones 

283 sessions = sorted(dataset["date"].unique()) 

284 warm = dataset["date"].isin(set(sessions[:45])).to_numpy() 

285 hole_dates: set = set() 

286 for ticker, group in dataset.groupby("ticker"): 

287 dates = group["date"].sort_values() 

288 hole_dates |= set(dates[dates.diff().dt.days > (1 if security_types.get(ticker) == "crypto" else 3)]) 

289 

290 def compare(merged: pd.DataFrame, column: str, mean: float, scale: float, clip: float) -> dict: 

291 keep = ~warm 

292 boundary = keep & merged["date"].isin(hole_dates).to_numpy() 

293 clean = keep & ~boundary 

294 stored, recomputed = merged[column].to_numpy(dtype=float), merged["recomputed"].to_numpy(dtype=float) 

295 result = summarize_comparison(stored[clean], recomputed[clean], mean, scale, clip, warmup_excluded=45) 

296 edge = summarize_comparison(stored[boundary], recomputed[boundary], mean, scale, clip) 

297 result["n_boundary_artifact"] = edge["n_mismatch_gt_1e-9"] 

298 if result["verdict"] == "PASS" and result["n_boundary_artifact"]: 

299 result["verdict"] = "PASS_BOUNDARY_ARTIFACTS_ONLY" 

300 return result 

301 

302 ranks = compute_cs_momentum_rank_replica(momentum_long, security_types) 

303 merged = dataset.merge(ranks.rename(columns={"cs_momentum_rank_recomputed": "recomputed"}), on=["date", "ticker"], how="left") 

304 name = "cs_momentum_rank_20" 

305 results[name] = compare(merged, f"{name}_scaled", *scaler_mapping[name]) 

306 

307 macro = compute_macro_proxies_replica(momentum_long, security_types) 

308 for feature in ("macro_yield_curve_slope_proxy", "macro_credit_spread_proxy", "macro_crypto_risk_appetite_proxy"): 

309 merged_f = dataset.merge(macro[["date", "ticker", feature]].rename(columns={feature: "recomputed"}), on=["date", "ticker"], how="left") 

310 results[feature] = compare(merged_f, f"{feature}_scaled", *scaler_mapping[feature]) 

311 

312 return results 

313 

314 

315STRUCTURED_VERDICTS = { 

316 "regime_signal_confidence|trend_score|risk_score + regime one-hots": { 

317 "offline": "train.add_regime_features()/_encode_regime_row()", 

318 "live": "main._build_regime_payload()", 

319 "shared_function": False, 

320 "verdict": "DUPLICATED_LOGIC - structural inspection this round found matching inputs (base technicals + average_correlation); no numeric replay: it would need the regime detector's state, which this audit cannot rebuild", 

321 }, 

322 "alt_implied_volatility_level|term_structure|financial_conditions_change": { 

323 "offline": "features/derivatives_macro_features.py + alt_data_features.py", 

324 "live": "same shared functions imported at main.py:179-209", 

325 "shared_function": True, 

326 "verdict": "SHARED_OK - identical function objects both sides; neutral-default constants match", 

327 }, 

328 "sens_* betas/interactions": { 

329 "offline": "features/cross_asset_sensitivity.py::rolling_sensitivity/sensitivity_interaction", 

330 "live": "main._cross_asset_sensitivity_for_symbol() calling the SAME shared functions (main.py:179-209 import block)", 

331 "shared_function": True, 

332 "verdict": "SHARED_OK_INSPECTED - residual risk is driver-series construction only", 

333 }, 

334 "bond_yield_curve_*|credit_spread_level|analytic_*|dv01": { 

335 "offline": "features/bond_features.py", 

336 "live": "same shared functions imported at main.py:179-209", 

337 "shared_function": True, 

338 "verdict": "SHARED_OK_INSPECTED", 

339 }, 

340 "bond_empirical_duration_beta": { 

341 "offline": "features/bond_features.py::empirical_duration_beta (full history)", 

342 "live": "main._bond_empirical_duration_beta_for_symbol() with V5.2.5's permanent lock-in cache", 

343 "shared_function": True, 

344 "verdict": "SHARED_OK - drift root-caused and fixed in V5.2.5 (Problems.md lineage)", 

345 }, 

346 "topology_correlation_strength + topology_risk one-hots + peer_rank*/mean": { 

347 "offline": "train.build_topology_features_by_date() -> market_topology.build_market_topology() over features.cross_asset_timing.CrossAssetTimeline", 

348 "live": "main._build_topology_payload() -> features.cross_asset_timing.cross_asset_inputs() -> the SAME market_topology module", 

349 "shared_function": True, 

350 "verdict": "SHARED_OK - window/return/momentum construction is one function and tests/test_cross_asset_timing.py replays main.py's tick order (Problems.md #135)", 

351 }, 

352 "asset_class one-hots": { 

353 "offline": "train.add_asset_class_context_features() from phase1.universe config", 

354 "live": "asset_lookup built from the same config block", 

355 "shared_function": False, 

356 "verdict": "TRIVIAL_CONSTANT - config-derived, drift would break loudly", 

357 }, 

358} 

359 

360 

361def main() -> int: 

362 parser = argparse.ArgumentParser(description=__doc__) 

363 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv")) 

364 parser.add_argument("--scaler-stats", default=str(ROOT_DIR / "ml" / "scaler_stats.json")) 

365 parser.add_argument("--schema", default=str(ROOT_DIR / "ml" / "feature_schema.json")) 

366 parser.add_argument("--output", default=str(ROOT_DIR / "ml" / "evaluation" / "feature_parity_report.json")) 

367 parser.add_argument("--skip-synthetic", action="store_true", help="Skip the torch-importing train-side formula check") 

368 parser.add_argument( 

369 "--synthetic-only", action="store_true", 

370 help="V5.5.0 (CI parity-smoke): run ONLY check 1 (replica vs train.py formulas on synthetic data) - needs no " 

371 "dataset/scaler/schema files, so it runs on a fresh checkout. Mutually exclusive with --skip-synthetic.", 

372 ) 

373 args = parser.parse_args() 

374 

375 started = time.time() 

376 if args.synthetic_only: 

377 if args.skip_synthetic: 

378 parser.error("--synthetic-only and --skip-synthetic are mutually exclusive") 

379 print("[1/1] Synthetic formula parity (replicas vs train.py implementations)...") 

380 synthetic = check_synthetic_formula_parity() 

381 failures = [k for k, v in synthetic.items() if isinstance(v, dict) and v.get("verdict") == "FAIL"] 

382 print(f" status={synthetic.get('_status')} failures={failures or 'none'}") 

383 if synthetic.get("_status") != "OK": 

384 # A SKIPPED check proves nothing; the full audit tolerates it (no torch on some 

385 # machines) but a dedicated synthetic-only run must not report PASS on a dead check. 

386 failures.append(f"check_did_not_run ({synthetic.get('_status')})") 

387 output_path = Path(args.output) 

388 output_path.parent.mkdir(parents=True, exist_ok=True) 

389 output_path.write_text( 

390 json.dumps({"synthetic_formula_parity": synthetic, "runtime_seconds": round(time.time() - started, 1)}, indent=2, default=str), 

391 encoding="utf-8", 

392 ) 

393 print("OVERALL:", "FAIL (" + ", ".join(failures) + ")" if failures else "PASS") 

394 return 1 if failures else 0 

395 

396 print(f"Loading dataset: {args.dataset}") 

397 dataset = pd.read_csv(args.dataset) 

398 scaler_stats = json.loads(Path(args.scaler_stats).read_text(encoding="utf-8")) 

399 schema_names = json.loads(Path(args.schema).read_text(encoding="utf-8"))["model_input_names"] 

400 

401 scaler_mapping, _uncovered = load_scaler_mapping(scaler_stats) 

402 # Schema model_input_names carry a "_scaled" suffix for every 

403 # StandardScaler-ed feature; binary one-hots have no suffix by design. 

404 one_hots = sorted(name for name in schema_names if not name.endswith("_scaled")) 

405 unmapped = [name for name in schema_names 

406 if name.endswith("_scaled") and name[: -len("_scaled")] not in scaler_mapping] 

407 if unmapped: 

408 print(f"ERROR: schema inputs whose base name is missing from scaler_stats: {unmapped}") 

409 return 2 

410 

411 print(f"Schema: {len(schema_names)} model inputs | scaler covers {len(scaler_mapping)} continuous " 

412 f"| {len(one_hots)} unscaled one-hots ({', '.join(one_hots[:6])}...)") 

413 

414 report: dict = { 

415 "schema_input_count": len(schema_names), 

416 "scaler_continuous_count": len(scaler_mapping), 

417 "unscaled_one_hots": one_hots, 

418 } 

419 

420 print("\n[1/3] Synthetic formula parity (replicas vs train.py implementations)...") 

421 report["synthetic_formula_parity"] = {} if args.skip_synthetic else check_synthetic_formula_parity() 

422 if not args.skip_synthetic: 

423 failures = [k for k, v in report["synthetic_formula_parity"].items() 

424 if isinstance(v, dict) and v.get("verdict") == "FAIL"] 

425 print(f" status={report['synthetic_formula_parity'].get('_status')} failures={failures or 'none'}") 

426 

427 print("\n[2/3] Real-data artifact consistency...") 

428 import train as train_module 

429 

430 forex_holidays = train_module.resolve_forex_lean_holidays(json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))) 

431 artifact_results, _slices = check_artifact_consistency(dataset, scaler_mapping, DEFAULT_LONG_LOOKBACK_WINDOW_BARS, forex_holidays) 

432 report["artifact_consistency"] = artifact_results 

433 for name, stats in artifact_results.items(): 

434 print(f" {name:<32} {stats['verdict']:<5} n={stats['n_compared']:>7} " 

435 f"max_delta={stats['max_abs_delta']} mismatch={stats['n_mismatch_gt_1e-9']} saturated={stats['n_saturated_at_clip']}") 

436 

437 print("\n[3/3] Cross-sectional + macro families...") 

438 cross_results = check_cross_sectional_and_macro(dataset, scaler_mapping) 

439 report["cross_sectional_macro"] = cross_results 

440 for name, stats in cross_results.items(): 

441 print(f" {name:<36} {stats['verdict']:<5} n={stats['n_compared']:>7} max_delta={stats['max_abs_delta']} mismatch={stats['n_mismatch_gt_1e-9']}") 

442 

443 report["structured_verdicts"] = STRUCTURED_VERDICTS 

444 report["runtime_seconds"] = round(time.time() - started, 1) 

445 

446 output_path = Path(args.output) 

447 output_path.parent.mkdir(parents=True, exist_ok=True) 

448 output_path.write_text(json.dumps(report, indent=2, default=str), encoding="utf-8") 

449 print(f"\nReport written: {output_path}") 

450 

451 all_failures = [n for section in ("artifact_consistency", "cross_sectional_macro") 

452 for n, s in report[section].items() if s.get("verdict") == "FAIL"] 

453 synth = report.get("synthetic_formula_parity", {}) 

454 if isinstance(synth, dict): 

455 all_failures += [f"synthetic:{k}" for k, v in synth.items() if isinstance(v, dict) and v.get("verdict") == "FAIL"] 

456 print("OVERALL:", "FAIL (" + ", ".join(all_failures) + ")" if all_failures else "PASS") 

457 return 1 if all_failures else 0 

458 

459 

460if __name__ == "__main__": 

461 sys.exit(main())