LOBench-A-share-processed / code /experiments /tbd_revision /scripts /run_label_threshold_retraining.py
mythezone's picture
Add accepted-paper code, reproduction guide, and provisional citation
3f316da verified
Raw History Blame Contribute Delete
3.94 kB
#!/usr/bin/env python3
"""Retrain the five-stock prediction comparison under alternate labels."""
from __future__ import annotations
import argparse
import copy
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
SCRIPT_DIR = ROOT / "experiments/tbd_revision/scripts"
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
from train_representation_baselines import run_one, summarize # noqa: E402
STOCKS = ("asset_001", "asset_002", "asset_017", "asset_005", "asset_033")
METHODS = ("timae", "lobgrid_timae", "simlob2026")
SEEDS = (2026, 2027, 2028)
THRESHOLDS = {
"threshold0001": 0.0001,
"threshold0005": 0.0005,
"threshold0010": 0.0010,
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-config", type=Path, required=True)
parser.add_argument("--output-root", type=Path, required=True)
parser.add_argument(
"--variants",
nargs="+",
choices=tuple(THRESHOLDS),
required=True,
)
parser.add_argument("--force", action="store_true")
return parser.parse_args()
def resolved(path: Path) -> Path:
return path if path.is_absolute() else ROOT / path
def require_pretraining(config: dict) -> None:
directory = resolved(Path(config["pretrain_dir"]))
pretrain_id = str(config["pretrain_id"])
missing = []
for method in METHODS:
for seed in SEEDS:
stem = directory / f"{pretrain_id}_{method}_seed{seed}_encoder"
for suffix in (".pt", ".pretrain.json"):
path = stem.with_suffix(suffix)
if not path.is_file():
missing.append(str(path))
if missing:
raise FileNotFoundError(
"The retained pooled checkpoints must be complete before label "
f"retraining. Missing examples: {missing[:3]}"
)
def main() -> None:
args = parse_args()
base = json.loads(resolved(args.base_config).read_text(encoding="utf-8"))
require_pretraining(base)
output_root = resolved(args.output_root)
output_root.mkdir(parents=True, exist_ok=True)
for variant in args.variants:
config = copy.deepcopy(base)
threshold = THRESHOLDS[variant]
config.setdefault("data", {})["label_threshold"] = threshold
config["data"]["relabel_from_future_returns"] = True
result_dir = output_root / variant
config["results_dir"] = str(result_dir)
config["stocks"] = list(STOCKS)
config["methods"] = list(METHODS)
config["settings"] = ["from_scratch", "fine_tune"]
config["seeds"] = list(SEEDS)
config["label_budgets"] = [0.5]
config["purpose"] = (
"Exploratory five-stock, three-seed prediction retraining under "
f"label threshold {threshold:g}; the pooled checkpoint is fixed."
)
result_dir.mkdir(parents=True, exist_ok=True)
(result_dir / "resolved_config.json").write_text(
json.dumps(config, indent=2) + "\n",
encoding="utf-8",
)
total = len(STOCKS) * len(METHODS) * len(SEEDS)
completed = 0
for stock in STOCKS:
for method in METHODS:
for seed in SEEDS:
completed += 1
print(
f"THRESHOLD {variant} {completed}/{total} "
f"{stock} {method} seed={seed}",
flush=True,
)
run_one(
config,
stock,
method,
seed,
0.5,
config["settings"],
force=args.force,
)
summarize(config, f"label_{variant}")
if __name__ == "__main__":
main()