File size: 3,968 Bytes
8f8fb44
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc98e7
 
8f8fb44
 
 
 
 
 
bcc98e7
8f8fb44
 
 
 
 
 
 
 
bcc98e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""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}