Download scripts/common.py from anonymous-quantinv/quantinvbench: direct link, hf CLI and curl.
- Browser
- Download file 3.97 kB
-
https://huggingface.co/datasets/anonymous-quantinv/quantinvbench/resolve/main/scripts/common.py
- Command line
-
hf download hf://datasets/anonymous-quantinv/quantinvbench/scripts/common.py
-
curl -L -o common.py https://huggingface.co/datasets/anonymous-quantinv/quantinvbench/resolve/main/scripts/common.py
3.97 kB
| """Shared constants and JSONL helpers for the QuantInvBench release.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| from typing import Iterable, Mapping, Sequence | |
| COINS = ("bitcoin", "ethereum", "tether", "xrp", "bnb") | |
| ASSETS = ("BTC", "ETH", "USDT", "XRP", "BNB") | |
| COIN_TO_ASSET = dict(zip(COINS, ASSETS)) | |
| BENCHMARK_VERSION = "2.0.0" | |
| ATTACK_PROTOCOL_VERSION = "quantinv-byzantine-v1" | |
| STRATEGIES = ( | |
| "Momentum", | |
| "MaxSharpe", | |
| "TSMom14", | |
| "TSMom60", | |
| "RiskParity", | |
| "MinVar", | |
| "NewsSentiment", | |
| "Size", | |
| "ValueNVT", | |
| "Liquidity", | |
| ) | |
| REBALANCE_DAYS = 7 | |
| TRANSACTION_COST = 0.001 | |
| WEIGHT_TOLERANCE = 1e-6 | |
| EXPECTED_SPLIT_COUNTS = {"train": 297, "validation": 52, "test": 52} | |
| EXPECTED_SPLIT_RANGES = { | |
| "train": { | |
| "execution_start": "2018-07-04T00:00:00Z", | |
| "execution_end": "2024-03-06T00:00:00Z", | |
| "label_end": "2024-03-13T00:00:00Z", | |
| }, | |
| "validation": { | |
| "execution_start": "2024-03-16T00:00:00Z", | |
| "execution_end": "2025-03-08T00:00:00Z", | |
| "label_end": "2025-03-15T00:00:00Z", | |
| }, | |
| "test": { | |
| "execution_start": "2025-03-16T00:00:00Z", | |
| "execution_end": "2026-03-08T00:00:00Z", | |
| "label_end": "2026-03-15T00:00:00Z", | |
| }, | |
| } | |
| EVALUATION_PROTOCOL = { | |
| "initial_portfolio": "equal_weight", | |
| "submitted_methods": "rebalance_every_record", | |
| "equal_weight_baseline": "buy_and_hold", | |
| "turnover": "half_l1_target_vs_return_drifted_holdings", | |
| "sharpe": "weekly_returns_sqrt_52_ddof_0", | |
| "max_drawdown": "daily_nav", | |
| } | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for block in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def read_jsonl(path: Path) -> list[dict]: | |
| records = [] | |
| with path.open(encoding="utf-8") as handle: | |
| for line_number, line in enumerate(handle, start=1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| records.append(json.loads(line)) | |
| except json.JSONDecodeError as exc: | |
| raise ValueError(f"{path}:{line_number}: invalid JSON: {exc}") from exc | |
| return records | |
| def write_jsonl(path: Path, records: Iterable[dict]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8", newline="\n") as handle: | |
| for record in records: | |
| handle.write(json.dumps(record, ensure_ascii=False, allow_nan=False)) | |
| handle.write("\n") | |
| def validated_weights( | |
| values: Mapping[str, float] | Sequence[float], | |
| *, | |
| label: str, | |
| ) -> list[float]: | |
| if isinstance(values, Mapping): | |
| weights = [float(values[coin]) for coin in COINS] | |
| else: | |
| weights = [float(value) for value in values] | |
| if len(weights) != len(ASSETS): | |
| raise ValueError(f"{label}: expected {len(ASSETS)} weights, got {len(weights)}") | |
| if not all(math.isfinite(value) for value in weights): | |
| raise ValueError(f"{label}: weights contain NaN or Infinity") | |
| if any(value < -WEIGHT_TOLERANCE for value in weights): | |
| raise ValueError(f"{label}: weights must be non-negative: {weights}") | |
| weights = [max(0.0, value) for value in weights] | |
| total = sum(weights) | |
| if total <= 0: | |
| raise ValueError(f"{label}: weights sum to zero") | |
| normalized = [value / total for value in weights] | |
| rounded = [round(value, 10) for value in normalized] | |
| largest_index = max(range(len(rounded)), key=rounded.__getitem__) | |
| rounded[largest_index] = round( | |
| rounded[largest_index] + (1.0 - sum(rounded)), 10 | |
| ) | |
| if abs(sum(rounded) - 1.0) > WEIGHT_TOLERANCE: | |
| raise ValueError(f"{label}: normalized weights do not sum to one") | |
| return rounded | |
| def usdt_fallback() -> dict[str, float]: | |
| return {coin: (1.0 if coin == "tether" else 0.0) for coin in COINS} | |