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