LOBench-A-share-processed / code /experiments /tbd_revision /scripts /summarize_label_threshold_sensitivity.py
mythezone's picture
Add accepted-paper code, reproduction guide, and provisional citation
3f316da verified
Raw History Blame Contribute Delete
3.61 kB
#!/usr/bin/env python3
"""Summarize how the predefined A-share thresholds change natural labels."""
from __future__ import annotations
import argparse
import csv
import statistics
from collections import defaultdict
from pathlib import Path
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 - weight) + ordered[upper] * weight
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--split", default="test")
return parser.parse_args()
def main() -> None:
args = parse_args()
grouped: dict[float, list[dict[str, str]]] = defaultdict(list)
with args.input.open(newline="", encoding="utf-8") as handle:
for row in csv.DictReader(handle):
if row["split"] == args.split:
grouped[float(row["threshold"])].append(row)
rows = []
for threshold, cases in sorted(grouped.items()):
stationary_rates = [
int(row["stationary"]) / int(row["n_windows"]) for row in cases
]
pooled_n = sum(int(row["n_windows"]) for row in cases)
pooled_down = sum(int(row["down"]) for row in cases)
pooled_stationary = sum(int(row["stationary"]) for row in cases)
pooled_up = sum(int(row["up"]) for row in cases)
rows.append(
{
"split": args.split,
"threshold": threshold,
"n_stocks": len(cases),
"pooled_windows": pooled_n,
"pooled_down_rate": pooled_down / pooled_n,
"pooled_stationary_rate": pooled_stationary / pooled_n,
"pooled_up_rate": pooled_up / pooled_n,
"stock_stationary_rate_mean": statistics.fmean(stationary_rates),
"stock_stationary_rate_q1": percentile(stationary_rates, 0.25),
"stock_stationary_rate_median": statistics.median(stationary_rates),
"stock_stationary_rate_q3": percentile(stationary_rates, 0.75),
}
)
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
markdown = args.output.with_suffix(".md")
lines = [
"# Predefined label-threshold sensitivity",
"",
f"Natural `{args.split}` split; no resampling or model-selection outcome is used.",
"",
"| threshold | stocks | pooled windows | down | stationary | up | stock stationary median [IQR] |",
"|---:|---:|---:|---:|---:|---:|---:|",
]
for row in rows:
lines.append(
f"| {row['threshold']:.4f} | {row['n_stocks']} | "
f"{row['pooled_windows']} | {row['pooled_down_rate']:.3f} | "
f"{row['pooled_stationary_rate']:.3f} | {row['pooled_up_rate']:.3f} | "
f"{row['stock_stationary_rate_median']:.3f} "
f"[{row['stock_stationary_rate_q1']:.3f}, "
f"{row['stock_stationary_rate_q3']:.3f}] |"
)
markdown.write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"wrote {args.output} and {markdown}")
if __name__ == "__main__":
main()