File size: 4,279 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
#!/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()