quantinvbench / scripts /common.py
ywliu
Publish QuantInvBench dataset
8f8fb44 verified
Raw History Blame
2.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))
STRATEGIES = (
"Momentum",
"MaxSharpe",
"TSMom14",
"TSMom60",
"RiskParity",
"NewsSentiment",
"Size",
"ValueNVT",
"Liquidity",
)
REBALANCE_DAYS = 7
TRANSACTION_COST = 0.001
WEIGHT_TOLERANCE = 1e-6
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}