#!/usr/bin/env python3 """Summarize source-separated FI-2010 and LOBSTER prediction evidence.""" from __future__ import annotations import argparse import csv import json from pathlib import Path import numpy as np METHODS = ("timae", "lobgrid_timae", "simlob2026") METHOD_LABELS = { "timae": "Ti-MAE-style", "lobgrid_timae": "LOBGrid--Ti-MAE-style", "simlob2026": "SimLOB-style", } SEEDS = (2026, 2027, 2028) SETTINGS = ("from_scratch", "fine_tune") CLASS_FIELDS = tuple( f"{metric}_{name}" for metric in ("precision", "recall", "f1") for name in ("down", "stationary", "up") ) def load_results(directory: Path) -> list[dict]: rows = [] for path in sorted(directory.glob("*.json")): if path.name.endswith(".pretrain.json"): continue payload = json.loads(path.read_text(encoding="utf-8")) if payload.get("setting") in SETTINGS and "test" in payload: payload["_path"] = str(path) rows.append(payload) return rows def validate(rows: list[dict], assets: int, source: str) -> None: expected = assets * len(METHODS) * len(SEEDS) * len(SETTINGS) keys = [(r["stock"], r["method"], r["seed"], r["setting"]) for r in rows] if len(keys) != expected or len(set(keys)) != expected: raise ValueError(f"{source}: found {len(keys)} unique cases; expected {expected}") if {r["method"] for r in rows} != set(METHODS): raise ValueError(f"{source}: method set is incomplete") if {int(r["seed"]) for r in rows} != set(SEEDS): raise ValueError(f"{source}: seed set is incomplete") def bootstrap(values: list[float], seed: int = 20260801) -> list[float]: array = np.asarray(values, dtype=np.float64) rng = np.random.default_rng(seed) draws = rng.choice(array, size=(10000, len(array)), replace=True).mean(axis=1) return [float(x) for x in np.quantile(draws, [0.025, 0.975])] def condition_metrics(rows: list[dict]) -> dict: result = { "macro_f1_mean": float(np.mean([r["test"]["macro_f1"] for r in rows])), "macro_f1_sd": float(np.std([r["test"]["macro_f1"] for r in rows], ddof=1)), "balanced_accuracy_mean": float( np.mean([r["test"]["balanced_accuracy"] for r in rows]) ), "stopped_epoch_mean": float(np.mean([r.get("stopped_epoch", 0) for r in rows])), "optimizer_steps_mean": float(np.mean([r.get("optimizer_steps", 0) for r in rows])), } for field in CLASS_FIELDS: result[field] = ( float(np.mean([r["test"][field] for r in rows])) if all(field in r["test"] for r in rows) else None ) result["pooled_confusion_rows_true_cols_pred"] = ( np.asarray( [r["test_confusion"]["matrix_rows_true_cols_pred"] for r in rows], dtype=np.int64, ).sum(axis=0).tolist() if all("test_confusion" in r for r in rows) else None ) return result def paired_source_summary(rows: list[dict], source: str) -> dict: index = { (r["stock"], r["method"], int(r["seed"]), r["setting"]): r for r in rows } assets = sorted({r["stock"] for r in rows}) output = {} for method in METHODS: asset_seed = {} for asset in assets: for seed in SEEDS: scratch = index[(asset, method, seed, "from_scratch")] tuned = index[(asset, method, seed, "fine_tune")] asset_seed[(asset, seed)] = float( tuned["test"]["macro_f1"] - scratch["test"]["macro_f1"] ) asset_means = { asset: float(np.mean([asset_seed[(asset, seed)] for seed in SEEDS])) for asset in assets } unit_values = list(asset_means.values()) if len(assets) > 1 else list(asset_seed.values()) day_effects = {} sample = next( (r for r in rows if r["method"] == method and r.get("test_by_group")), None, ) for day in sorted(sample["test_by_group"] if sample else {}): values = [] for asset in assets: for seed in SEEDS: scratch = index[(asset, method, seed, "from_scratch")] tuned = index[(asset, method, seed, "fine_tune")] values.append( float( tuned["test_by_group"][day]["metrics"]["macro_f1"] - scratch["test_by_group"][day]["metrics"]["macro_f1"] ) ) day_effects[day] = { "mean": float(np.mean(values)), "sd": float(np.std(values, ddof=1)), } method_rows = [r for r in rows if r["method"] == method] output[method] = { "model": METHOD_LABELS[method], "source": source, "reporting_unit": "initialization seed" if len(assets) == 1 else "asset after seed averaging", "mean_delta": float(np.mean(unit_values)), "sd_delta": float(np.std(unit_values, ddof=1)), "unit_resampling_interval_95": bootstrap(unit_values), "wins": int(sum(x > 0 for x in unit_values)), "units": len(unit_values), "asset_mean_deltas": asset_means, "asset_seed_deltas": {f"{a}|{s}": v for (a, s), v in asset_seed.items()}, "test_day_effects": day_effects, "conditions": { setting: condition_metrics([r for r in method_rows if r["setting"] == setting]) for setting in SETTINGS }, } return output def write_csv(path: Path, rows: list[dict]) -> None: fields = [] for row in rows: for field in row: if field not in fields: fields.append(field) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() writer.writerows(rows) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--fi-dir", required=True) parser.add_argument("--lobster-dir", required=True) parser.add_argument("--fi-zscore-dir") parser.add_argument("--output-dir", required=True) args = parser.parse_args() fi_rows = load_results(Path(args.fi_dir)) lobster_rows = load_results(Path(args.lobster_dir)) validate(fi_rows, assets=1, source="FI-2010 DecPre train-only") validate(lobster_rows, assets=4, source="LOBSTER") payload = { "FI-2010 DecPre train-only": paired_source_summary( fi_rows, "FI-2010 DecPre train-only" ), "LOBSTER": paired_source_summary(lobster_rows, "LOBSTER"), } if args.fi_zscore_dir: zscore_rows = load_results(Path(args.fi_zscore_dir)) validate(zscore_rows, assets=1, source="FI-2010 official Zscore sensitivity") payload["FI-2010 official Zscore sensitivity"] = paired_source_summary( zscore_rows, "FI-2010 official Zscore sensitivity" ) output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "external_source_evidence.json").write_text( json.dumps(payload, indent=2), encoding="utf-8" ) flat_rows = [] for source, methods in payload.items(): for method, summary in methods.items(): scratch = summary["conditions"]["from_scratch"] tuned = summary["conditions"]["fine_tune"] flat_rows.append( { "source": source, "method": method, "model": summary["model"], "scratch_macro_f1": scratch["macro_f1_mean"], "target_local_macro_f1": tuned["macro_f1_mean"], "paired_delta": summary["mean_delta"], "paired_delta_sd": summary["sd_delta"], "ci_low": summary["unit_resampling_interval_95"][0], "ci_high": summary["unit_resampling_interval_95"][1], "wins": summary["wins"], "units": summary["units"], } ) write_csv(output_dir / "external_source_evidence.csv", flat_rows) paired_case_rows = [] for source, rows in ( ("FI-2010 DecPre train-only", fi_rows), ("LOBSTER", lobster_rows), ): index = { (row["stock"], row["method"], int(row["seed"]), row["setting"]): row for row in rows } for stock in sorted({row["stock"] for row in rows}): for method in METHODS: for seed in SEEDS: scratch = index[(stock, method, seed, "from_scratch")] tuned = index[(stock, method, seed, "fine_tune")] paired_case_rows.append( { "source": source, "unit": stock, "method": method, "seed": seed, "scratch_macro_f1": scratch["test"]["macro_f1"], "target_local_macro_f1": tuned["test"]["macro_f1"], "paired_delta": ( tuned["test"]["macro_f1"] - scratch["test"]["macro_f1"] ), "scratch_stopped_epoch": scratch.get("stopped_epoch"), "scratch_optimizer_steps": scratch.get("optimizer_steps"), "target_local_stopped_epoch": tuned.get("stopped_epoch"), "target_local_optimizer_steps": tuned.get("optimizer_steps"), } ) write_csv(output_dir / "external_paired_seed_cases.csv", paired_case_rows) class_rows = [] day_rows = [] for source in ("FI-2010 DecPre train-only", "LOBSTER"): for method, summary in payload[source].items(): for setting, condition in summary["conditions"].items(): class_rows.append( { "source": source, "method": method, "setting": setting, **{field: condition[field] for field in CLASS_FIELDS}, "confusion_rows_true_cols_pred": json.dumps( condition["pooled_confusion_rows_true_cols_pred"] ), "mean_stopped_epoch": condition["stopped_epoch_mean"], "mean_optimizer_steps": condition["optimizer_steps_mean"], } ) for day, day_summary in summary["test_day_effects"].items(): day_rows.append( { "source": source, "method": method, "test_day": day, "mean_delta": day_summary["mean"], "sd_delta": day_summary["sd"], } ) write_csv(output_dir / "external_class_and_stopping_metrics.csv", class_rows) write_csv(output_dir / "external_test_day_effects.csv", day_rows) lines = [ "# Source-separated external evidence", "", "| source | model | scratch F1 | local F1 | paired delta ± SD | wins |", "|---|---|---:|---:|---:|---:|", ] for row in flat_rows: lines.append( f"| {row['source']} | {row['model']} | {row['scratch_macro_f1']:.4f} " f"| {row['target_local_macro_f1']:.4f} | {row['paired_delta']:+.4f}" f"±{row['paired_delta_sd']:.4f} | {row['wins']}/{row['units']} |" ) (output_dir / "external_source_evidence.md").write_text( "\n".join(lines) + "\n", encoding="utf-8" ) if __name__ == "__main__": main()