LOBench-A-share-processed / code /experiments /tbd_revision /scripts /audit_preprocessed_lob_validity.py
Download code/experiments/tbd_revision/scripts/audit_preprocessed_lob_validity.py from mythezone/LOBench-A-share-processed: direct link, hf CLI and curl.
- Browser
- Download file 4.28 kB
-
https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/audit_preprocessed_lob_validity.py
- Command line
-
hf download hf://datasets/mythezone/LOBench-A-share-processed/code/experiments/tbd_revision/scripts/audit_preprocessed_lob_validity.py
-
curl -L -o audit_preprocessed_lob_validity.py https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/audit_preprocessed_lob_validity.py
4.28 kB
| #!/usr/bin/env python3 | |
| """Audit LOB ordering and volume ranges in preprocessed NPZ windows.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| def audit_file(path: Path) -> dict: | |
| data = np.load(path, allow_pickle=False) | |
| x = data["x"] | |
| bid_p = x[:, :, :10][:, :, ::-1] | |
| ask_p = x[:, :, 10:20] | |
| volume = x[:, :, 20:40] | |
| spread_bad = bid_p[:, :, 0] >= ask_p[:, :, 0] | |
| bid_bad = (bid_p[:, :, 1:] >= bid_p[:, :, :-1]).any(axis=-1) | |
| ask_bad = (ask_p[:, :, 1:] <= ask_p[:, :, :-1]).any(axis=-1) | |
| any_price_bad = spread_bad | bid_bad | ask_bad | |
| return { | |
| "stock": path.stem.replace("_pilot", ""), | |
| "path": str(path), | |
| "n_windows": int(x.shape[0]), | |
| "seq_len": int(x.shape[1]), | |
| "features": int(x.shape[2]), | |
| "price_min": float(np.nanmin(x[:, :, :20])), | |
| "price_max": float(np.nanmax(x[:, :, :20])), | |
| "volume_min": float(np.nanmin(volume)), | |
| "volume_max": float(np.nanmax(volume)), | |
| "volume_negative_rate": float((volume < 0).mean()), | |
| "target_spread_cross_rate": float(spread_bad.mean()), | |
| "target_bid_order_bad_rate": float(bid_bad.mean()), | |
| "target_ask_order_bad_rate": float(ask_bad.mean()), | |
| "target_any_price_bad_rate": float(any_price_bad.mean()), | |
| } | |
| def write_csv(path: Path, rows: list[dict]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", newline="", encoding="utf-8") as fh: | |
| writer = csv.DictWriter(fh, fieldnames=list(rows[0].keys())) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def write_md(path: Path, rows: list[dict], title: str) -> None: | |
| lines = [f"# {title}", ""] | |
| lines += [ | |
| "| stock | windows | normalized volume <0 rate* | target spread bad | target strict bid bad | target strict ask bad | target any price bad |", | |
| "|---|---:|---:|---:|---:|---:|---:|", | |
| ] | |
| for row in rows: | |
| lines.append( | |
| f"| `{row['stock']}` | {row['n_windows']} | {row['volume_negative_rate']:.4f} | " | |
| f"{row['target_spread_cross_rate']:.4f} | {row['target_bid_order_bad_rate']:.4f} | " | |
| f"{row['target_ask_order_bad_rate']:.4f} | {row['target_any_price_bad_rate']:.4f} |" | |
| ) | |
| lines.extend( | |
| [ | |
| "", | |
| "\\* Negative normalized volume is expected after training-only affine " | |
| "normalization and is not a raw-volume validity failure.", | |
| ] | |
| ) | |
| path.write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--processed-dir", type=Path, default=Path("experiments/tbd_revision/outputs/mixed_windows")) | |
| parser.add_argument( | |
| "--stocks", | |
| nargs="+", | |
| help="Asset ids. If omitted, infer every asset from manifest.json.", | |
| ) | |
| parser.add_argument("--out-name", default="mixed_windows_5stock_preprocessed_lob_validity") | |
| parser.add_argument("--out-dir", type=Path, default=Path("experiments/tbd_revision/outputs/summary")) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| if args.stocks: | |
| stocks = args.stocks | |
| else: | |
| manifest_path = args.processed_dir / "manifest.json" | |
| if manifest_path.exists(): | |
| stocks = sorted( | |
| json.loads(manifest_path.read_text(encoding="utf-8")).keys() | |
| ) | |
| else: | |
| stocks = sorted( | |
| path.stem.removesuffix("_pilot") | |
| for path in args.processed_dir.glob("*_pilot.npz") | |
| ) | |
| if not stocks: | |
| raise SystemExit(f"No assets found under {args.processed_dir}") | |
| rows = [] | |
| for stock in stocks: | |
| path = args.processed_dir / f"{stock}_pilot.npz" | |
| if not path.exists(): | |
| raise SystemExit(f"Missing NPZ for {stock}: {path}") | |
| rows.append(audit_file(path)) | |
| csv_path = args.out_dir / f"{args.out_name}.csv" | |
| md_path = args.out_dir / f"{args.out_name}.md" | |
| write_csv(csv_path, rows) | |
| write_md(md_path, rows, args.out_name) | |
| print(f"wrote {csv_path}") | |
| print(f"wrote {md_path}") | |
| if __name__ == "__main__": | |
| main() | |