File size: 6,010 Bytes
3f316da | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | #!/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()
|