#!/usr/bin/env python3 """Generate causal QuantInvBench JSONL splits for Hugging Face.""" from __future__ import annotations import argparse import json from datetime import datetime, timedelta, timezone from pathlib import Path import numpy as np import pandas as pd from common import ( ASSETS, COINS, REBALANCE_DAYS, STRATEGIES, TRANSACTION_COST, sha256_file, write_jsonl, ) from strategies import SentimentIndex, compute_proposals PROJECT_ROOT = Path(__file__).resolve().parents[3] RELEASE_ROOT = Path(__file__).resolve().parents[1] SPLIT_BOUNDS = { "train": (None, pd.Timestamp("2024-03-15", tz="UTC")), "validation": ( pd.Timestamp("2024-03-16", tz="UTC"), pd.Timestamp("2025-03-15", tz="UTC"), ), "test": ( pd.Timestamp("2025-03-16", tz="UTC"), pd.Timestamp("2026-03-15", tz="UTC"), ), } def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data-dir", type=Path, default=PROJECT_ROOT / "data") parser.add_argument( "--sentiment-file", type=Path, default=RELEASE_ROOT / "cache" / "crypto_news_sentiment.json", ) parser.add_argument("--output-dir", type=Path, default=RELEASE_ROOT / "data") return parser.parse_args() def load_daily_data(data_dir: Path) -> dict[str, pd.DataFrame]: frames = {} required_columns = { "date", "open", "high", "low", "close", "volume", "quote_volume", } for coin in COINS: path = data_dir / f"{coin}_prices_1h.csv" if not path.exists(): raise FileNotFoundError(f"Missing source data: {path}") hourly = pd.read_csv(path) missing = required_columns - set(hourly.columns) if missing: raise ValueError(f"{path}: missing columns {sorted(missing)}") hourly["date"] = pd.to_datetime(hourly["date"], utc=True) for column in required_columns - {"date"}: hourly[column] = pd.to_numeric(hourly[column], errors="raise") if hourly["date"].duplicated().any(): raise ValueError(f"{path}: duplicate hourly timestamps") if not hourly["date"].is_monotonic_increasing: hourly = hourly.sort_values("date") daily = ( hourly.set_index("date") .resample("1D") .agg( { "open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum", "quote_volume": "sum", } ) .dropna() ) if not np.isfinite(daily.to_numpy(dtype=float)).all(): raise ValueError(f"{path}: daily data contains NaN or Infinity") if (daily[["open", "high", "low", "close"]] <= 0).any().any(): raise ValueError(f"{path}: source contains non-positive prices") frames[coin] = daily common_dates = frames[COINS[0]].index for coin in COINS[1:]: common_dates = common_dates.intersection(frames[coin].index) if common_dates.empty: raise ValueError("The five assets have no common daily dates") return {coin: frame.loc[common_dates].copy() for coin, frame in frames.items()} def scalar_at(frame: pd.DataFrame, date: pd.Timestamp, column: str) -> float: try: value = frame.at[date, column] except KeyError as exc: raise ValueError(f"Missing {column} for {date.date()}") from exc if isinstance(value, pd.Series): raise ValueError(f"Duplicate value for {date.date()}") return float(value) def split_dates( split: str, common_dates: pd.DatetimeIndex, ) -> list[pd.Timestamp]: configured_start, configured_end = SPLIT_BOUNDS[split] history_ready = common_dates.min() + pd.Timedelta(days=61) start = max(history_ready, configured_start) if configured_start is not None else history_ready latest_execution = common_dates.max() - pd.Timedelta(days=REBALANCE_DAYS) end = min(configured_end, latest_execution) if start > end: raise ValueError(f"{split}: no dates available between {start} and {end}") dates = list(pd.date_range(start=start, end=end, freq=f"{REBALANCE_DAYS}D")) common_set = set(common_dates) for execution in dates: if execution not in common_set: raise ValueError(f"{split}: missing execution date {execution.date()}") exit_date = execution + pd.Timedelta(days=REBALANCE_DAYS) if exit_date not in common_set: raise ValueError(f"{split}: missing exit date {exit_date.date()}") return dates def make_record( split: str, index: int, execution: pd.Timestamp, frames: dict[str, pd.DataFrame], sentiment: SentimentIndex, ) -> dict: history = {coin: frame.loc[frame.index < execution] for coin, frame in frames.items()} if min(len(frame) for frame in history.values()) < 61: raise ValueError(f"{execution.date()}: insufficient causal history") as_of_timestamp = execution.to_pydatetime() - timedelta(microseconds=1) exit_date = execution + pd.Timedelta(days=REBALANCE_DAYS) next_returns = [] for coin in COINS: entry = scalar_at(frames[coin], execution, "open") exit_price = scalar_at(frames[coin], exit_date, "open") next_returns.append(round(exit_price / entry - 1.0, 10)) proposals = compute_proposals(history, sentiment, as_of_timestamp) if [proposal["strategy"] for proposal in proposals] != list(STRATEGIES): raise ValueError(f"{execution.date()}: strategy roster changed") return { "id": f"quantinv_{split}_{index:04d}_{execution:%Y%m%d}", "split": split, "as_of": as_of_timestamp.astimezone(timezone.utc).isoformat().replace("+00:00", "Z"), "execution_at": execution.isoformat().replace("+00:00", "Z"), "assets": list(ASSETS), "strategy_proposals": proposals, "next_7d_returns": next_returns, } def main() -> None: args = parse_args() data_dir = args.data_dir.resolve() sentiment_file = args.sentiment_file.resolve() output_dir = args.output_dir.resolve() frames = load_daily_data(data_dir) sentiment = SentimentIndex(sentiment_file) common_dates = frames[COINS[0]].index split_records = {} for split in SPLIT_BOUNDS: dates = split_dates(split, common_dates) records = [ make_record(split, index, execution, frames, sentiment) for index, execution in enumerate(dates) ] split_records[split] = records output_dir.mkdir(parents=True, exist_ok=True) for split, records in split_records.items(): write_jsonl(output_dir / f"{split}.jsonl", records) source_hashes = { f"{coin}_prices_1h.csv": sha256_file(data_dir / f"{coin}_prices_1h.csv") for coin in COINS } source_hashes[sentiment_file.name] = sha256_file(sentiment_file) manifest = { "dataset": "QuantInvBench", "version": "1.0.0", "generated_at": datetime.now(timezone.utc).isoformat(), "assets": list(ASSETS), "strategies": list(STRATEGIES), "rebalance_days": REBALANCE_DAYS, "transaction_cost": TRANSACTION_COST, "splits": {split: len(records) for split, records in split_records.items()}, "data_sha256": { f"{split}.jsonl": sha256_file(output_dir / f"{split}.jsonl") for split in split_records }, "source_sha256": source_hashes, "notes": {"USDT": "synthetic cash-like series in the current source data"}, } with (output_dir / "manifest.json").open("w", encoding="utf-8") as handle: json.dump(manifest, handle, indent=2, ensure_ascii=False, allow_nan=False) handle.write("\n") counts = ", ".join(f"{split}={len(records)}" for split, records in split_records.items()) print(f"Generated QuantInvBench in {output_dir} ({counts})") if __name__ == "__main__": main()