LOBench-A-share-processed / code /experiments /tbd_revision /scripts /summarize_label_threshold_retraining.py
Download code/experiments/tbd_revision/scripts/summarize_label_threshold_retraining.py from mythezone/LOBench-A-share-processed: direct link, hf CLI and curl.
- Browser
- Download file 8.44 kB
-
https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/summarize_label_threshold_retraining.py
- Command line
-
hf download hf://datasets/mythezone/LOBench-A-share-processed/code/experiments/tbd_revision/scripts/summarize_label_threshold_retraining.py
-
curl -L -o summarize_label_threshold_retraining.py https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/summarize_label_threshold_retraining.py
8.44 kB
| #!/usr/bin/env python3 | |
| """Summarize prediction retraining across four movement thresholds.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import random | |
| import statistics | |
| from pathlib import Path | |
| METHODS = ("timae", "lobgrid_timae", "simlob2026") | |
| STOCKS = ("asset_001", "asset_002", "asset_017", "asset_005", "asset_033") | |
| SEEDS = (2026, 2027, 2028) | |
| THRESHOLDS = ( | |
| (0.0001, "threshold0001"), | |
| (0.0003, "baseline"), | |
| (0.0005, "threshold0005"), | |
| (0.0010, "threshold0010"), | |
| ) | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--baseline-dir", type=Path, required=True) | |
| parser.add_argument("--alternate-root", type=Path, required=True) | |
| parser.add_argument("--processed-dir", type=Path, required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| return parser.parse_args() | |
| def percentile(values: list[float], probability: float) -> float: | |
| ordered = sorted(values) | |
| position = probability * (len(ordered) - 1) | |
| lower = int(position) | |
| upper = min(lower + 1, len(ordered) - 1) | |
| weight = position - lower | |
| return ordered[lower] * (1.0 - weight) + ordered[upper] * weight | |
| def bootstrap_ci(values: list[float], seed: int) -> tuple[float, float]: | |
| rng = random.Random(seed) | |
| draws = sorted( | |
| statistics.fmean(values[rng.randrange(len(values))] for _ in values) | |
| for _ in range(20_000) | |
| ) | |
| return percentile(draws, 0.025), percentile(draws, 0.975) | |
| def load_cases(directory: Path) -> dict[tuple[str, str, int, str], dict]: | |
| cases = {} | |
| for path in sorted(directory.glob("*.json")): | |
| if path.name.endswith(".pretrain.json") or path.name == "resolved_config.json": | |
| continue | |
| payload = json.loads(path.read_text(encoding="utf-8")) | |
| if ( | |
| payload.get("stock") not in STOCKS | |
| or payload.get("method") not in METHODS | |
| or int(payload.get("seed", -1)) not in SEEDS | |
| or abs(float(payload.get("label_budget", -1.0)) - 0.5) > 1e-12 | |
| or payload.get("setting") not in {"from_scratch", "fine_tune"} | |
| ): | |
| continue | |
| key = ( | |
| str(payload["stock"]), | |
| str(payload["method"]), | |
| int(payload["seed"]), | |
| str(payload["setting"]), | |
| ) | |
| if key in cases: | |
| raise ValueError(f"Duplicate threshold case in {directory}: {key}") | |
| cases[key] = payload | |
| expected = { | |
| (stock, method, seed, setting) | |
| for stock in STOCKS | |
| for method in METHODS | |
| for seed in SEEDS | |
| for setting in ("from_scratch", "fine_tune") | |
| } | |
| if set(cases) != expected: | |
| raise ValueError( | |
| f"{directory} is incomplete; missing examples: " | |
| f"{sorted(expected - set(cases))[:5]}" | |
| ) | |
| return cases | |
| def label_shares(processed_dir: Path, threshold: float) -> dict[str, float]: | |
| import numpy as np | |
| counts = [0, 0, 0] | |
| for stock in STOCKS: | |
| with np.load(processed_dir / f"{stock}_pilot.npz") as data: | |
| returns = data["future_returns"][data["test_idx"]] | |
| labels = np.where( | |
| returns > threshold, | |
| 2, | |
| np.where(returns < -threshold, 0, 1), | |
| ) | |
| for class_id in range(3): | |
| counts[class_id] += int((labels == class_id).sum()) | |
| total = sum(counts) | |
| return { | |
| "test_down_share": counts[0] / total, | |
| "test_neutral_share": counts[1] / total, | |
| "test_up_share": counts[2] / total, | |
| } | |
| def write_csv(path: Path, rows: list[dict[str, object]]) -> 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() | |
| directories = { | |
| variant: args.baseline_dir if variant == "baseline" else args.alternate_root / variant | |
| for _, variant in THRESHOLDS | |
| } | |
| cases = {variant: load_cases(directory) for variant, directory in directories.items()} | |
| rows = [] | |
| stock_rows = [] | |
| for threshold_index, (threshold, variant) in enumerate(THRESHOLDS): | |
| shares = label_shares(args.processed_dir, threshold) | |
| for method_index, method in enumerate(METHODS): | |
| stock_scratch = [] | |
| stock_tuned = [] | |
| stock_deltas = [] | |
| for stock in STOCKS: | |
| scratch = [ | |
| float(cases[variant][(stock, method, seed, "from_scratch")]["test"]["macro_f1"]) | |
| for seed in SEEDS | |
| ] | |
| tuned = [ | |
| float(cases[variant][(stock, method, seed, "fine_tune")]["test"]["macro_f1"]) | |
| for seed in SEEDS | |
| ] | |
| delta = [candidate - baseline for candidate, baseline in zip(tuned, scratch)] | |
| stock_scratch.append(statistics.fmean(scratch)) | |
| stock_tuned.append(statistics.fmean(tuned)) | |
| stock_deltas.append(statistics.fmean(delta)) | |
| stock_rows.append( | |
| { | |
| "threshold": threshold, | |
| "variant": variant, | |
| "method": method, | |
| "stock": stock, | |
| "scratch_macro_f1_mean": statistics.fmean(scratch), | |
| "pooled_macro_f1_mean": statistics.fmean(tuned), | |
| "paired_delta_mean": statistics.fmean(delta), | |
| "paired_delta_seed_sd": statistics.stdev(delta), | |
| } | |
| ) | |
| low, high = bootstrap_ci( | |
| stock_deltas, | |
| 20260802 + 10 * threshold_index + method_index, | |
| ) | |
| rows.append( | |
| { | |
| "threshold": threshold, | |
| "variant": variant, | |
| "method": method, | |
| "n_stocks": len(STOCKS), | |
| "seeds_per_stock": len(SEEDS), | |
| **shares, | |
| "scratch_macro_f1_mean": statistics.fmean(stock_scratch), | |
| "pooled_macro_f1_mean": statistics.fmean(stock_tuned), | |
| "paired_delta_mean": statistics.fmean(stock_deltas), | |
| "ci95_low": low, | |
| "ci95_high": high, | |
| "wins": sum(value > 0 for value in stock_deltas), | |
| } | |
| ) | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| write_csv(args.output_dir / "label_threshold_retraining.csv", rows) | |
| write_csv(args.output_dir / "label_threshold_retraining_stock.csv", stock_rows) | |
| payload = { | |
| "design": { | |
| "thresholds": [threshold for threshold, _ in THRESHOLDS], | |
| "retained_threshold": 0.0003, | |
| "stocks": list(STOCKS), | |
| "methods": list(METHODS), | |
| "seeds": list(SEEDS), | |
| "label_budget": 0.5, | |
| "pretraining_checkpoint": "fixed retained pooled checkpoint", | |
| "role": "exploratory label-definition robustness", | |
| }, | |
| "rows": rows, | |
| } | |
| (args.output_dir / "label_threshold_retraining.json").write_text( | |
| json.dumps(payload, indent=2) + "\n", | |
| encoding="utf-8", | |
| ) | |
| lines = [ | |
| "# Label-threshold retraining", | |
| "", | |
| "The pooled checkpoint is fixed. Every downstream condition is retrained after regenerating labels from continuous future returns.", | |
| "", | |
| "| threshold | model | test D/N/U | scratch F1 | pooled F1 | paired delta [95% stock interval] | wins/5 |", | |
| "|---:|---|---:|---:|---:|---:|---:|", | |
| ] | |
| for row in rows: | |
| lines.append( | |
| f"| {row['threshold']:.4f} | {row['method']} | " | |
| f"{row['test_down_share']:.3f}/{row['test_neutral_share']:.3f}/{row['test_up_share']:.3f} | " | |
| f"{row['scratch_macro_f1_mean']:.4f} | {row['pooled_macro_f1_mean']:.4f} | " | |
| f"{row['paired_delta_mean']:+.4f} " | |
| f"[{row['ci95_low']:+.4f}, {row['ci95_high']:+.4f}] | " | |
| f"{row['wins']}/5 |" | |
| ) | |
| (args.output_dir / "label_threshold_retraining.md").write_text( | |
| "\n".join(lines) + "\n", | |
| encoding="utf-8", | |
| ) | |
| print(f"wrote {len(rows)} threshold summaries") | |
| if __name__ == "__main__": | |
| main() | |