Download scripts/generate.py from anonymous-quantinv/quantinvbench: direct link, hf CLI and curl.
- Browser
- Download file 9.74 kB
-
https://huggingface.co/datasets/anonymous-quantinv/quantinvbench/resolve/main/scripts/generate.py
- Command line
-
hf download hf://datasets/anonymous-quantinv/quantinvbench/scripts/generate.py
-
curl -L -o generate.py https://huggingface.co/datasets/anonymous-quantinv/quantinvbench/resolve/main/scripts/generate.py
9.74 kB
| #!/usr/bin/env python3 | |
| """Generate causal QuantInvBench JSONL splits for Hugging Face.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from datetime import timedelta, timezone | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from common import ( | |
| ASSETS, | |
| ATTACK_PROTOCOL_VERSION, | |
| BENCHMARK_VERSION, | |
| COINS, | |
| EVALUATION_PROTOCOL, | |
| EXPECTED_SPLIT_COUNTS, | |
| EXPECTED_SPLIT_RANGES, | |
| 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_source_execution = common_dates.max() - pd.Timedelta(days=REBALANCE_DAYS) | |
| latest_split_execution = configured_end - pd.Timedelta(days=REBALANCE_DAYS) | |
| end = min(latest_split_execution, latest_source_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) | |
| daily_returns = [] | |
| for offset in range(REBALANCE_DAYS): | |
| entry_date = execution + pd.Timedelta(days=offset) | |
| daily_exit_date = entry_date + pd.Timedelta(days=1) | |
| daily_returns.append( | |
| [ | |
| round( | |
| scalar_at(frames[coin], daily_exit_date, "open") | |
| / scalar_at(frames[coin], entry_date, "open") | |
| - 1.0, | |
| 10, | |
| ) | |
| for coin in COINS | |
| ] | |
| ) | |
| next_returns = np.prod(1.0 + np.asarray(daily_returns), axis=0) - 1.0 | |
| next_returns = [round(float(value), 10) for value in next_returns] | |
| 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"), | |
| "label_end_at": exit_date.isoformat().replace("+00:00", "Z"), | |
| "assets": list(ASSETS), | |
| "strategy_proposals": proposals, | |
| "next_7d_daily_returns": daily_returns, | |
| "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 | |
| actual_counts = { | |
| split: len(records) for split, records in split_records.items() | |
| } | |
| if actual_counts != EXPECTED_SPLIT_COUNTS: | |
| raise ValueError( | |
| f"split counts changed: expected {EXPECTED_SPLIT_COUNTS}, got {actual_counts}" | |
| ) | |
| 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) | |
| split_ranges = { | |
| split: { | |
| "execution_start": records[0]["execution_at"], | |
| "execution_end": records[-1]["execution_at"], | |
| "label_end": records[-1]["label_end_at"], | |
| } | |
| for split, records in split_records.items() | |
| } | |
| if split_ranges != EXPECTED_SPLIT_RANGES: | |
| raise ValueError( | |
| f"split ranges changed: expected {EXPECTED_SPLIT_RANGES}, got {split_ranges}" | |
| ) | |
| manifest = { | |
| "dataset": "QuantInvBench", | |
| "version": BENCHMARK_VERSION, | |
| "assets": list(ASSETS), | |
| "strategies": list(STRATEGIES), | |
| "rebalance_days": REBALANCE_DAYS, | |
| "label_horizon_days": REBALANCE_DAYS, | |
| "transaction_cost": TRANSACTION_COST, | |
| "splits": actual_counts, | |
| "split_ranges": split_ranges, | |
| "evaluation_protocol": EVALUATION_PROTOCOL, | |
| "attack_protocol": ATTACK_PROTOCOL_VERSION, | |
| "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() | |