quantinvbench / scripts /validate.py
ywliu
Publish QuantInvBench dataset
8f8fb44 verified
Raw History Blame
8.79 kB
#!/usr/bin/env python3
"""Strict validation for a generated QuantInvBench release."""
from __future__ import annotations
import argparse
import json
import math
import re
import sys
from datetime import datetime, timedelta
from pathlib import Path
import pandas as pd
from common import ASSETS, REBALANCE_DAYS, STRATEGIES, WEIGHT_TOLERANCE, read_jsonl, sha256_file
ID_PATTERN = re.compile(r"^quantinv_(train|validation|test)_\d{4}_\d{8}$")
REQUIRED_FIELDS = {
"id",
"split",
"as_of",
"execution_at",
"assets",
"strategy_proposals",
"next_7d_returns",
}
class Validation:
def __init__(self) -> None:
self.checks = 0
self.errors: list[str] = []
def check(self, condition: bool, message: str) -> None:
self.checks += 1
if not condition:
self.errors.append(message)
def parse_timestamp(value: object, label: str) -> datetime:
if not isinstance(value, str):
raise ValueError(f"{label}: timestamp must be a string")
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.tzinfo is None:
raise ValueError(f"{label}: timestamp must include a timezone")
return parsed
def validate_weights(values: object, label: str, result: Validation) -> None:
result.check(isinstance(values, list), f"{label}: weights must be a list")
if not isinstance(values, list):
return
result.check(len(values) == len(ASSETS), f"{label}: expected five weights")
if len(values) != len(ASSETS):
return
numeric = all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in values)
result.check(numeric, f"{label}: weights must be numeric")
if not numeric:
return
finite = all(math.isfinite(float(value)) for value in values)
result.check(finite, f"{label}: weights contain NaN or Infinity")
if not finite:
return
result.check(all(value >= 0 for value in values), f"{label}: weights must be non-negative")
result.check(
abs(sum(values) - 1.0) <= WEIGHT_TOLERANCE,
f"{label}: weights sum to {sum(values)}, not 1",
)
def validate_record(record: dict, split: str, index: int, result: Validation) -> datetime | None:
label = f"{split}[{index}]"
result.check(set(record) == REQUIRED_FIELDS, f"{label}: fields do not match schema")
result.check(record.get("split") == split, f"{label}: wrong split value")
identifier = record.get("id")
result.check(isinstance(identifier, str) and bool(ID_PATTERN.fullmatch(identifier)), f"{label}: invalid id")
result.check(record.get("assets") == list(ASSETS), f"{label}: asset roster/order changed")
try:
as_of = parse_timestamp(record.get("as_of"), f"{label}.as_of")
execution = parse_timestamp(record.get("execution_at"), f"{label}.execution_at")
result.check(as_of < execution, f"{label}: as_of must precede execution_at")
result.check(execution - as_of <= timedelta(seconds=1), f"{label}: unexpected decision gap")
except (TypeError, ValueError) as exc:
result.check(False, str(exc))
execution = None
proposals = record.get("strategy_proposals")
result.check(isinstance(proposals, list), f"{label}: strategy_proposals must be a list")
if isinstance(proposals, list):
result.check(len(proposals) == len(STRATEGIES), f"{label}: expected nine strategies")
names = [proposal.get("strategy") for proposal in proposals if isinstance(proposal, dict)]
result.check(names == list(STRATEGIES), f"{label}: strategy roster/order changed")
for proposal_index, proposal in enumerate(proposals):
proposal_label = f"{label}.strategy_proposals[{proposal_index}]"
result.check(isinstance(proposal, dict), f"{proposal_label}: must be an object")
if isinstance(proposal, dict):
result.check(set(proposal) == {"strategy", "weights"}, f"{proposal_label}: invalid fields")
validate_weights(proposal.get("weights"), proposal_label, result)
returns = record.get("next_7d_returns")
result.check(isinstance(returns, list) and len(returns) == len(ASSETS), f"{label}: invalid returns")
if isinstance(returns, list) and len(returns) == len(ASSETS):
result.check(
all(isinstance(value, (int, float)) and math.isfinite(float(value)) for value in returns),
f"{label}: returns contain invalid values",
)
return execution
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("data_dir", type=Path, nargs="?", default=Path(__file__).resolve().parents[1] / "data")
parser.add_argument(
"--source-data-dir",
type=Path,
help="Optional original hourly data directory for replaying next_7d_returns",
)
args = parser.parse_args()
data_dir = args.data_dir.resolve()
result = Validation()
manifest_path = data_dir / "manifest.json"
result.check(manifest_path.exists(), f"missing {manifest_path}")
manifest = {}
if manifest_path.exists():
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
result.check(False, f"invalid manifest: {exc}")
seen_ids = set()
split_ranges = {}
all_records = []
for split in ("train", "validation", "test"):
path = data_dir / f"{split}.jsonl"
result.check(path.exists(), f"missing {path}")
if not path.exists():
continue
try:
records = read_jsonl(path)
except ValueError as exc:
result.check(False, str(exc))
continue
all_records.extend(records)
result.check(bool(records), f"{split}: split is empty")
execution_times = []
for index, record in enumerate(records):
result.check(isinstance(record, dict), f"{split}[{index}]: record must be an object")
if not isinstance(record, dict):
continue
execution = validate_record(record, split, index, result)
if execution is not None:
execution_times.append(execution)
identifier = record.get("id")
result.check(identifier not in seen_ids, f"duplicate id: {identifier}")
seen_ids.add(identifier)
result.check(execution_times == sorted(execution_times), f"{split}: records are not sorted")
for left, right in zip(execution_times, execution_times[1:]):
result.check(right - left == timedelta(days=REBALANCE_DAYS), f"{split}: rebalance interval is not seven days")
if execution_times:
split_ranges[split] = (execution_times[0], execution_times[-1])
expected_count = manifest.get("splits", {}).get(split)
result.check(expected_count == len(records), f"{split}: manifest count does not match")
expected_hash = manifest.get("data_sha256", {}).get(path.name)
result.check(expected_hash == sha256_file(path), f"{split}: SHA-256 does not match manifest")
ordered_ranges = [split_ranges.get(split) for split in ("train", "validation", "test")]
if all(ordered_ranges):
result.check(ordered_ranges[0][1] < ordered_ranges[1][0], "train overlaps validation")
result.check(ordered_ranges[1][1] < ordered_ranges[2][0], "validation overlaps test")
if args.source_data_dir:
from generate import load_daily_data, scalar_at
frames = load_daily_data(args.source_data_dir.resolve())
for record in all_records:
execution = parse_timestamp(record["execution_at"], record["id"])
execution_date = pd.Timestamp(execution)
exit_date = execution_date + pd.Timedelta(days=REBALANCE_DAYS)
for asset_index, coin in enumerate(("bitcoin", "ethereum", "tether", "xrp", "bnb")):
entry = scalar_at(frames[coin], execution_date, "open")
exit_price = scalar_at(frames[coin], exit_date, "open")
expected = exit_price / entry - 1.0
actual = record["next_7d_returns"][asset_index]
result.check(
abs(expected - actual) <= 1e-9,
f"{record['id']}: {ASSETS[asset_index]} next_7d_returns does not match source",
)
if result.errors:
for error in result.errors:
print(f"[FAIL] {error}", file=sys.stderr)
print(f"Validation failed: {len(result.errors)} errors across {result.checks} checks", file=sys.stderr)
return 1
print(f"Validation passed: {result.checks} checks, {len(seen_ids)} records")
return 0
if __name__ == "__main__":
raise SystemExit(main())