LOBench-A-share-processed / code /experiments /tbd_revision /scripts /summarize_structural_ablation.py
Download code/experiments/tbd_revision/scripts/summarize_structural_ablation.py from mythezone/LOBench-A-share-processed: direct link, hf CLI and curl.
- Browser
- Download file 6.01 kB
-
https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/summarize_structural_ablation.py
- Command line
-
hf download hf://datasets/mythezone/LOBench-A-share-processed/code/experiments/tbd_revision/scripts/summarize_structural_ablation.py
-
curl -L -o summarize_structural_ablation.py https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/summarize_structural_ablation.py
6.01 kB
| #!/usr/bin/env python3 | |
| """Summarize the fixed-seed same-encoder MSE versus soft-constraint ablation.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import statistics | |
| from pathlib import Path | |
| METHODS = { | |
| "timae": ("Ti-MAE-style", "MSE"), | |
| "timae_softlobloss": ("Ti-MAE-style", "MSE + soft penalty"), | |
| "simlob2026": ("SimLOB-style", "MSE"), | |
| "simlob2026_softlobloss": ("SimLOB-style", "MSE + soft penalty"), | |
| } | |
| METRICS = [ | |
| "raw_price_mae", | |
| "raw_volume_mae", | |
| "bid_order_strict_valid_rate", | |
| "ask_order_strict_valid_rate", | |
| "spread_valid_rate", | |
| "price_positive_valid_rate", | |
| "volume_nonnegative_valid_rate", | |
| "all_lob_constraints_valid_rate", | |
| ] | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--results-dir", type=Path, required=True) | |
| parser.add_argument("--out-dir", type=Path, required=True) | |
| parser.add_argument("--stocks", nargs="+", required=True) | |
| parser.add_argument("--seed", type=int, default=2026) | |
| return parser.parse_args() | |
| def write_csv(path: Path, rows: list[dict]) -> None: | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def main() -> None: | |
| args = parse_args() | |
| case_rows = [] | |
| for method, (encoder, loss) in METHODS.items(): | |
| for stock in args.stocks: | |
| path = ( | |
| args.results_dir | |
| / f"{stock}_{method}_reconstruction_seed{args.seed}.json" | |
| ) | |
| if not path.exists(): | |
| raise FileNotFoundError(path) | |
| data = json.loads(path.read_text(encoding="utf-8")) | |
| metrics = data["test_lob_metrics"] | |
| missing = [metric for metric in METRICS if metric not in metrics] | |
| if missing: | |
| raise ValueError(f"{path} is missing raw-unit metrics {missing}") | |
| case_rows.append( | |
| { | |
| "encoder": encoder, | |
| "loss": loss, | |
| "method": method, | |
| "stock": stock, | |
| "seed": args.seed, | |
| "normalized_mse": float(data["test_mse"]), | |
| "downstream_macro_f1": float( | |
| data["downstream_after_reconstruction"]["test"]["macro_f1"] | |
| ), | |
| **{metric: float(metrics[metric]) for metric in METRICS}, | |
| } | |
| ) | |
| summary_rows = [] | |
| for method, (encoder, loss) in METHODS.items(): | |
| rows = [row for row in case_rows if row["method"] == method] | |
| summary = { | |
| "encoder": encoder, | |
| "loss": loss, | |
| "method": method, | |
| "n_stocks": len(rows), | |
| } | |
| for metric in ["normalized_mse", "downstream_macro_f1", *METRICS]: | |
| values = [row[metric] for row in rows] | |
| summary[f"{metric}_mean"] = statistics.fmean(values) | |
| summary[f"{metric}_stock_sd"] = ( | |
| statistics.stdev(values) if len(values) > 1 else 0.0 | |
| ) | |
| summary_rows.append(summary) | |
| paired_rows = [] | |
| for encoder, plain_method, soft_method in ( | |
| ("Ti-MAE-style", "timae", "timae_softlobloss"), | |
| ("SimLOB-style", "simlob2026", "simlob2026_softlobloss"), | |
| ): | |
| for stock in args.stocks: | |
| plain = next( | |
| row | |
| for row in case_rows | |
| if row["method"] == plain_method and row["stock"] == stock | |
| ) | |
| soft = next( | |
| row | |
| for row in case_rows | |
| if row["method"] == soft_method and row["stock"] == stock | |
| ) | |
| paired_rows.append( | |
| { | |
| "encoder": encoder, | |
| "stock": stock, | |
| **{ | |
| f"soft_minus_mse_{metric}": soft[metric] - plain[metric] | |
| for metric in [ | |
| "normalized_mse", | |
| "downstream_macro_f1", | |
| *METRICS, | |
| ] | |
| }, | |
| } | |
| ) | |
| args.out_dir.mkdir(parents=True, exist_ok=True) | |
| write_csv(args.out_dir / "structural_case_results.csv", case_rows) | |
| write_csv(args.out_dir / "structural_method_summary.csv", summary_rows) | |
| write_csv(args.out_dir / "structural_paired_deltas.csv", paired_rows) | |
| lines = [ | |
| "# Same-encoder structural-loss ablation", | |
| "", | |
| "One fixed seed is used for this controlled diagnostic. Values are mean ± " | |
| "sample SD across five prespecified stocks; price and volume errors are " | |
| "inverse-transformed raw-unit MAE.", | |
| "", | |
| "| encoder | loss | price MAE | volume MAE | bid valid | ask valid | spread valid | price valid | volume valid | all valid | downstream F1 |", | |
| "|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|", | |
| ] | |
| for row in summary_rows: | |
| lines.append( | |
| f"| {row['encoder']} | {row['loss']} | " | |
| f"{row['raw_price_mae_mean']:.4f} ± {row['raw_price_mae_stock_sd']:.4f} | " | |
| f"{row['raw_volume_mae_mean']:.2f} ± {row['raw_volume_mae_stock_sd']:.2f} | " | |
| f"{row['bid_order_strict_valid_rate_mean']:.3f} | " | |
| f"{row['ask_order_strict_valid_rate_mean']:.3f} | " | |
| f"{row['spread_valid_rate_mean']:.3f} | " | |
| f"{row['price_positive_valid_rate_mean']:.3f} | " | |
| f"{row['volume_nonnegative_valid_rate_mean']:.3f} | " | |
| f"{row['all_lob_constraints_valid_rate_mean']:.3f} | " | |
| f"{row['downstream_macro_f1_mean']:.3f} |" | |
| ) | |
| (args.out_dir / "summary.md").write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| print(f"wrote structural ablation summary to {args.out_dir}") | |
| if __name__ == "__main__": | |
| main() | |