File size: 2,970 Bytes
8f8fb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""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}