File size: 14,143 Bytes
8f8fb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc98e7
 
 
 
 
 
 
 
 
 
 
 
 
 
8f8fb44
 
 
 
 
 
 
 
bcc98e7
8f8fb44
 
bcc98e7
8f8fb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc98e7
 
 
 
 
 
8f8fb44
 
 
 
 
 
 
 
 
 
bcc98e7
8f8fb44
 
bcc98e7
 
 
 
 
 
 
8f8fb44
 
 
bcc98e7
8f8fb44
 
 
 
bcc98e7
 
 
 
8f8fb44
 
 
 
 
 
 
 
 
 
 
bcc98e7
8f8fb44
bcc98e7
 
 
 
 
 
8f8fb44
bcc98e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f8fb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc98e7
 
 
 
 
 
 
 
 
 
 
 
8f8fb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc98e7
8f8fb44
 
 
 
bcc98e7
 
 
8f8fb44
 
 
 
bcc98e7
8f8fb44
bcc98e7
 
 
 
 
 
 
 
 
 
 
8f8fb44
bcc98e7
8f8fb44
 
 
bcc98e7
 
 
 
 
 
 
 
 
 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env python3
"""Strict validation for a generated QuantInvBench release."""

from __future__ import annotations

import argparse
import json
import math
import re
import sys
from datetime import datetime, timedelta
from pathlib import Path

import pandas as pd

from common import (
    ASSETS,
    ATTACK_PROTOCOL_VERSION,
    BENCHMARK_VERSION,
    EVALUATION_PROTOCOL,
    EXPECTED_SPLIT_COUNTS,
    EXPECTED_SPLIT_RANGES,
    REBALANCE_DAYS,
    STRATEGIES,
    TRANSACTION_COST,
    WEIGHT_TOLERANCE,
    read_jsonl,
    sha256_file,
)


ID_PATTERN = re.compile(r"^quantinv_(train|validation|test)_\d{4}_\d{8}$")
REQUIRED_FIELDS = {
    "id",
    "split",
    "as_of",
    "execution_at",
    "label_end_at",
    "assets",
    "strategy_proposals",
    "next_7d_daily_returns",
    "next_7d_returns",
}


class Validation:
    def __init__(self) -> None:
        self.checks = 0
        self.errors: list[str] = []

    def check(self, condition: bool, message: str) -> None:
        self.checks += 1
        if not condition:
            self.errors.append(message)


def parse_timestamp(value: object, label: str) -> datetime:
    if not isinstance(value, str):
        raise ValueError(f"{label}: timestamp must be a string")
    parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if parsed.tzinfo is None:
        raise ValueError(f"{label}: timestamp must include a timezone")
    return parsed


def validate_weights(values: object, label: str, result: Validation) -> None:
    result.check(isinstance(values, list), f"{label}: weights must be a list")
    if not isinstance(values, list):
        return
    result.check(len(values) == len(ASSETS), f"{label}: expected five weights")
    if len(values) != len(ASSETS):
        return
    numeric = all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in values)
    result.check(numeric, f"{label}: weights must be numeric")
    if not numeric:
        return
    finite = all(math.isfinite(float(value)) for value in values)
    result.check(finite, f"{label}: weights contain NaN or Infinity")
    if not finite:
        return
    result.check(all(value >= 0 for value in values), f"{label}: weights must be non-negative")
    result.check(
        abs(sum(values) - 1.0) <= WEIGHT_TOLERANCE,
        f"{label}: weights sum to {sum(values)}, not 1",
    )


def validate_record(
    record: dict,
    split: str,
    index: int,
    result: Validation,
) -> tuple[datetime | None, datetime | None]:
    label = f"{split}[{index}]"
    result.check(set(record) == REQUIRED_FIELDS, f"{label}: fields do not match schema")
    result.check(record.get("split") == split, f"{label}: wrong split value")
    identifier = record.get("id")
    result.check(isinstance(identifier, str) and bool(ID_PATTERN.fullmatch(identifier)), f"{label}: invalid id")
    result.check(record.get("assets") == list(ASSETS), f"{label}: asset roster/order changed")

    try:
        as_of = parse_timestamp(record.get("as_of"), f"{label}.as_of")
        execution = parse_timestamp(record.get("execution_at"), f"{label}.execution_at")
        label_end = parse_timestamp(record.get("label_end_at"), f"{label}.label_end_at")
        result.check(as_of < execution, f"{label}: as_of must precede execution_at")
        result.check(execution - as_of <= timedelta(seconds=1), f"{label}: unexpected decision gap")
        result.check(
            label_end - execution == timedelta(days=REBALANCE_DAYS),
            f"{label}: label horizon is not seven days",
        )
        if isinstance(identifier, str):
            expected_id = f"quantinv_{split}_{index:04d}_{execution:%Y%m%d}"
            result.check(identifier == expected_id, f"{label}: id does not match split/index/date")
    except (TypeError, ValueError) as exc:
        result.check(False, str(exc))
        execution = None
        label_end = None

    proposals = record.get("strategy_proposals")
    result.check(isinstance(proposals, list), f"{label}: strategy_proposals must be a list")
    if isinstance(proposals, list):
        result.check(
            len(proposals) == len(STRATEGIES),
            f"{label}: expected {len(STRATEGIES)} strategies",
        )
        names = [proposal.get("strategy") for proposal in proposals if isinstance(proposal, dict)]
        result.check(names == list(STRATEGIES), f"{label}: strategy roster/order changed")
        for proposal_index, proposal in enumerate(proposals):
            proposal_label = f"{label}.strategy_proposals[{proposal_index}]"
            result.check(isinstance(proposal, dict), f"{proposal_label}: must be an object")
            if isinstance(proposal, dict):
                result.check(set(proposal) == {"strategy", "weights"}, f"{proposal_label}: invalid fields")
                validate_weights(proposal.get("weights"), proposal_label, result)

    returns = record.get("next_7d_returns")
    result.check(isinstance(returns, list) and len(returns) == len(ASSETS), f"{label}: invalid returns")
    endpoint_returns_valid = False
    if isinstance(returns, list) and len(returns) == len(ASSETS):
        endpoint_returns_valid = all(
            isinstance(value, (int, float))
            and not isinstance(value, bool)
            and math.isfinite(float(value))
            and float(value) > -1.0
            for value in returns
        )
        result.check(endpoint_returns_valid, f"{label}: returns contain invalid values")

    daily_returns = record.get("next_7d_daily_returns")
    result.check(
        isinstance(daily_returns, list) and len(daily_returns) == REBALANCE_DAYS,
        f"{label}: next_7d_daily_returns must contain seven rows",
    )
    daily_returns_valid = False
    if isinstance(daily_returns, list) and len(daily_returns) == REBALANCE_DAYS:
        rows_valid = []
        for day_index, row in enumerate(daily_returns):
            row_valid = (
                isinstance(row, list)
                and len(row) == len(ASSETS)
                and all(
                    isinstance(value, (int, float))
                    and not isinstance(value, bool)
                    and math.isfinite(float(value))
                    and float(value) > -1.0
                    for value in row
                )
            )
            result.check(row_valid, f"{label}.next_7d_daily_returns[{day_index}]: invalid row")
            rows_valid.append(row_valid)
        daily_returns_valid = all(rows_valid)

    if endpoint_returns_valid and daily_returns_valid:
        for asset_index, asset in enumerate(ASSETS):
            compounded = math.prod(
                1.0 + float(daily_returns[day_index][asset_index])
                for day_index in range(REBALANCE_DAYS)
            ) - 1.0
            result.check(
                abs(compounded - float(returns[asset_index])) <= 1e-8,
                f"{label}: {asset} endpoint return does not compound from daily returns",
            )
    return execution, label_end


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("data_dir", type=Path, nargs="?", default=Path(__file__).resolve().parents[1] / "data")
    parser.add_argument(
        "--source-data-dir",
        type=Path,
        help="Optional original hourly data directory for replaying next_7d_returns",
    )
    args = parser.parse_args()
    data_dir = args.data_dir.resolve()
    result = Validation()

    manifest_path = data_dir / "manifest.json"
    result.check(manifest_path.exists(), f"missing {manifest_path}")
    manifest = {}
    if manifest_path.exists():
        try:
            manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            result.check(False, f"invalid manifest: {exc}")

    result.check(manifest.get("dataset") == "QuantInvBench", "manifest: wrong dataset name")
    result.check(manifest.get("version") == BENCHMARK_VERSION, f"manifest: expected benchmark version {BENCHMARK_VERSION}")
    result.check(manifest.get("assets") == list(ASSETS), "manifest: asset roster/order changed")
    result.check(manifest.get("strategies") == list(STRATEGIES), "manifest: strategy roster/order changed")
    result.check(manifest.get("rebalance_days") == REBALANCE_DAYS, "manifest: wrong rebalance period")
    result.check(manifest.get("label_horizon_days") == REBALANCE_DAYS, "manifest: wrong label horizon")
    result.check(manifest.get("transaction_cost") == TRANSACTION_COST, "manifest: wrong transaction cost")
    result.check(manifest.get("splits") == EXPECTED_SPLIT_COUNTS, "manifest: wrong fixed split counts")
    result.check(manifest.get("split_ranges") == EXPECTED_SPLIT_RANGES, "manifest: wrong fixed split ranges")
    result.check(manifest.get("evaluation_protocol") == EVALUATION_PROTOCOL, "manifest: wrong evaluation protocol")
    result.check(manifest.get("attack_protocol") == ATTACK_PROTOCOL_VERSION, "manifest: wrong attack protocol")

    seen_ids = set()
    split_ranges = {}
    all_records = []
    for split in ("train", "validation", "test"):
        path = data_dir / f"{split}.jsonl"
        result.check(path.exists(), f"missing {path}")
        if not path.exists():
            continue
        try:
            records = read_jsonl(path)
        except ValueError as exc:
            result.check(False, str(exc))
            continue
        all_records.extend(records)
        result.check(bool(records), f"{split}: split is empty")
        periods = []
        for index, record in enumerate(records):
            result.check(isinstance(record, dict), f"{split}[{index}]: record must be an object")
            if not isinstance(record, dict):
                continue
            execution, label_end = validate_record(record, split, index, result)
            if execution is not None and label_end is not None:
                periods.append((execution, label_end))
            identifier = record.get("id")
            result.check(identifier not in seen_ids, f"duplicate id: {identifier}")
            seen_ids.add(identifier)

        execution_times = [execution for execution, _ in periods]
        result.check(execution_times == sorted(execution_times), f"{split}: records are not sorted")
        for (left_execution, left_end), (right_execution, _) in zip(periods, periods[1:]):
            result.check(
                right_execution - left_execution == timedelta(days=REBALANCE_DAYS),
                f"{split}: rebalance interval is not seven days",
            )
            result.check(
                left_end == right_execution,
                f"{split}: holding periods are not contiguous",
            )
        if periods:
            split_ranges[split] = (periods[0][0], periods[-1][1])

        expected_count = EXPECTED_SPLIT_COUNTS[split]
        result.check(expected_count == len(records), f"{split}: manifest count does not match")
        expected_hash = manifest.get("data_sha256", {}).get(path.name)
        result.check(expected_hash == sha256_file(path), f"{split}: SHA-256 does not match manifest")
        if periods:
            expected_range = {
                "execution_start": records[0]["execution_at"],
                "execution_end": records[-1]["execution_at"],
                "label_end": records[-1]["label_end_at"],
            }
            result.check(
                manifest.get("split_ranges", {}).get(split) == expected_range,
                f"{split}: manifest range does not match records",
            )

    ordered_ranges = [split_ranges.get(split) for split in ("train", "validation", "test")]
    if all(ordered_ranges):
        result.check(ordered_ranges[0][1] < ordered_ranges[1][0], "train labels overlap validation")
        result.check(ordered_ranges[1][1] < ordered_ranges[2][0], "validation labels overlap test")

    if args.source_data_dir:
        from generate import load_daily_data, scalar_at

        frames = load_daily_data(args.source_data_dir.resolve())
        for record in all_records:
            execution = parse_timestamp(record["execution_at"], record["id"])
            execution_date = pd.Timestamp(execution)
            exit_date = execution_date + pd.Timedelta(days=REBALANCE_DAYS)
            label_end = parse_timestamp(record["label_end_at"], record["id"])
            result.check(pd.Timestamp(label_end) == exit_date, f"{record['id']}: wrong label_end_at")
            for asset_index, coin in enumerate(("bitcoin", "ethereum", "tether", "xrp", "bnb")):
                entry = scalar_at(frames[coin], execution_date, "open")
                exit_price = scalar_at(frames[coin], exit_date, "open")
                expected = exit_price / entry - 1.0
                actual = record["next_7d_returns"][asset_index]
                result.check(
                    abs(expected - actual) <= 1e-9,
                    f"{record['id']}: {ASSETS[asset_index]} next_7d_returns does not match source",
                )
                for day_index in range(REBALANCE_DAYS):
                    day_start = execution_date + pd.Timedelta(days=day_index)
                    day_end = day_start + pd.Timedelta(days=1)
                    start_price = scalar_at(frames[coin], day_start, "open")
                    end_price = scalar_at(frames[coin], day_end, "open")
                    expected_daily = end_price / start_price - 1.0
                    actual_daily = record["next_7d_daily_returns"][day_index][asset_index]
                    result.check(
                        abs(expected_daily - actual_daily) <= 1e-9,
                        f"{record['id']}: {ASSETS[asset_index]} day {day_index} return does not match source",
                    )

    if result.errors:
        for error in result.errors:
            print(f"[FAIL] {error}", file=sys.stderr)
        print(f"Validation failed: {len(result.errors)} errors across {result.checks} checks", file=sys.stderr)
        return 1
    print(f"Validation passed: {result.checks} checks, {len(seen_ids)} records")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())