anonymous-quantinv commited on
Commit
bcc98e7
·
verified ·
1 Parent(s): 8f8fb44

Publish QuantInvBench dataset

Browse files
README.md CHANGED
@@ -22,99 +22,200 @@ configs:
22
 
23
  # QuantInvBench
24
 
25
- QuantInvBench is a chronological benchmark for aggregating nine cryptocurrency
26
- portfolio strategies. At each weekly decision point, a system receives nine
27
- portfolio proposals over BTC, ETH, USDT, XRP, and BNB and returns one final
28
- long-only weight vector.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- ## Dataset Structure
 
 
 
 
 
31
 
32
- Each record contains:
 
 
33
 
34
- - `id`: stable sample identifier;
35
- - `split`: chronological split name;
36
- - `as_of`: latest timestamp that strategies may observe;
37
- - `execution_at`: portfolio execution timestamp;
38
- - `assets`: fixed asset order;
39
- - `strategy_proposals`: nine named five-weight proposals;
40
- - `next_7d_returns`: open-to-open asset returns over the following seven days.
41
 
42
- There is no single gold portfolio. Use `next_7d_returns` and the included
43
- evaluator to measure cumulative return, annualized Sharpe ratio, maximum
44
- drawdown, and turnover. The public test labels support reproducible research;
45
- they are not suitable for a hidden leaderboard.
46
 
47
- ## Load
 
 
48
 
49
- ```python
50
- from datasets import load_dataset
 
 
 
 
51
 
52
- dataset = load_dataset("YOUR_ORG/quantinvbench")
53
- print(dataset)
54
- print(dataset["test"][0])
55
  ```
56
 
57
- ## Reproduce
 
 
 
 
 
 
 
 
 
 
58
 
59
- Run these commands from the original Crypto-MAD project root:
 
 
 
 
 
 
 
 
 
60
 
61
  ```bash
62
- conda env create -f QuantInv/hf_release/environment.yml
63
- conda activate quantinv-hf
64
- python QuantInv/hf_release/scripts/compute_sentiment.py
65
- python QuantInv/hf_release/scripts/generate.py
66
- python QuantInv/hf_release/scripts/validate.py --source-data-dir data
67
- python QuantInv/hf_release/scripts/evaluate.py --baseline equal_weight
68
- python QuantInv/hf_release/scripts/evaluate.py --baseline simple_avg
69
  ```
70
 
71
- If the model has already been downloaded, rerun the first command with
72
- `--local-files-only` to prevent another network lookup:
73
 
74
  ```bash
75
- python QuantInv/hf_release/scripts/compute_sentiment.py --local-files-only
 
76
  ```
77
 
78
- The generator uses only data strictly earlier than `execution_at` for strategy
79
- inputs. The realized return starts at the execution-day open and ends at the
80
- open seven calendar days later.
81
 
82
- ## Submission Format
83
 
84
- To evaluate a method, write one JSON object per line:
 
85
 
86
- ```json
87
- {"id": "quantinv_test_0000_20250316", "weights": [0.2, 0.2, 0.2, 0.2, 0.2]}
88
  ```
89
 
90
- Then run:
91
 
92
- ```bash
93
- python scripts/evaluate.py --predictions predictions.jsonl
 
 
94
  ```
95
 
96
- ## Splits
97
 
98
- Splits are chronological. Training ends on 2024-03-15, validation covers the
99
- following year, and test begins on 2025-03-16. The final usable sample must
100
- have a complete seven-day forward return, so it can precede the raw data's
101
- last date. Exact counts and SHA-256 values are stored in `data/manifest.json`.
102
 
103
- ## Sources and Limitations
 
 
104
 
105
- BTC, ETH, XRP, and BNB hourly OHLCV data are identified as Binance data in the
106
- source project. The current USDT series is synthetic and serves as a cash-like
107
- asset; it must not be interpreted as observed Binance market data.
 
 
 
 
 
 
 
 
 
108
 
109
- The news proposal uses derived FinBERT scores from English-language GDELT news
110
- records. Article text, titles, URLs, and publisher content are not included in
111
- this dataset.
 
112
 
113
- The benchmark has survivorship bias, covers only five assets, uses a fixed
114
- 0.1% transaction-cost model, and does not model slippage or market impact.
115
- It is a research benchmark and not investment advice.
116
 
117
- ## License
 
 
 
 
118
 
119
- The release scripts are MIT licensed. Source data and derived dataset records
120
- remain subject to their source providers' terms; see `DATA_LICENSE.md`.
 
 
 
22
 
23
  # QuantInvBench
24
 
25
+ QuantInvBench is the companion benchmark for evaluating multi-agent portfolio
26
+ aggregation on five assets in the fixed order `BTC`, `ETH`, `USDT`, `XRP`,
27
+ `BNB`. At each seven-day execution event, a method receives ten long-only,
28
+ fully invested strategy proposals and must return one portfolio weight vector.
29
+
30
+ The ten strategy identities, in canonical order, are `Momentum`, `MaxSharpe`,
31
+ `TSMom14`, `TSMom60`, `RiskParity`, `MinVar`, `NewsSentiment`, `Size`,
32
+ `ValueNVT`, and `Liquidity`. Equal-weight buy-and-hold (EWBH) is a passive
33
+ evaluation baseline, not an eleventh agent.
34
+
35
+ ## Record Schema
36
+
37
+ Every JSONL record has exactly these fields:
38
+
39
+ | Field | Type | Meaning |
40
+ | --- | --- | --- |
41
+ | `id` | string | Stable `quantinv_<split>_<index>_<YYYYMMDD>` identifier. |
42
+ | `split` | string | `train`, `validation`, or `test`. |
43
+ | `as_of` | UTC timestamp | Latest instant visible when proposals are formed; strictly earlier than execution. |
44
+ | `execution_at` | UTC timestamp | Execution-day open and start of the holding period. |
45
+ | `label_end_at` | UTC timestamp | Open exactly seven days after `execution_at`; end of the label interval. |
46
+ | `assets` | list of 5 strings | Always `["BTC", "ETH", "USDT", "XRP", "BNB"]`. |
47
+ | `strategy_proposals` | list of 10 objects | Ordered objects with exactly `strategy` and `weights`; each weight vector is non-negative and sums to one. |
48
+ | `next_7d_daily_returns` | 7 x 5 numbers | Seven consecutive open-to-next-open daily asset returns in asset order. |
49
+ | `next_7d_returns` | list of 5 numbers | Execution-open to label-end-open asset returns, compounded from the seven daily rows. |
50
+
51
+ For asset `j`, the endpoint label satisfies
52
+ `next_7d_returns[j] = product(1 + next_7d_daily_returns[d][j], d=0..6) - 1`.
53
+
54
+ ## Splits and Label Isolation
55
+
56
+ Splits are chronological and include only records whose complete forward label
57
+ is contained on their side of the next split boundary.
58
+
59
+ | Split | Records | First execution | Last execution | Final `label_end_at` |
60
+ | --- | ---: | --- | --- | --- |
61
+ | train | 297 | 2018-07-04 | 2024-03-06 | 2024-03-13 |
62
+ | validation | 52 | 2024-03-16 | 2025-03-08 | 2025-03-15 |
63
+ | test | 52 | 2025-03-16 | 2026-03-08 | 2026-03-15 |
64
+
65
+ Strategy generation reads only observations strictly earlier than
66
+ `execution_at`. No training label reaches validation, and no validation label
67
+ reaches test.
68
+
69
+ The two return fields are public scoring labels, not method inputs. When
70
+ producing validation or test predictions, pass only record metadata and
71
+ `strategy_proposals` to the method; do not expose `next_7d_daily_returns` or
72
+ `next_7d_returns`. Byzantine identity/role labels are likewise evaluator-only
73
+ and are written to a separate audit file, never into attacked method records.
74
+
75
+ ## Evaluation Protocol
76
+
77
+ The included evaluator follows the paper protocol:
78
+
79
+ - Capital starts in an already established equal-weight portfolio: 20% in
80
+ each asset at the first execution open.
81
+ - EWBH holds those initial asset units for the full evaluation window and
82
+ never rebalances, so its weights drift with returns and its turnover is zero.
83
+ - `simple_avg` and submitted methods target a new portfolio every seven days.
84
+ The first trade starts from equal weights; later trades start from the
85
+ return-drifted holdings left by the preceding period.
86
+ - Turnover is `0.5 * sum(abs(target - pre_trade_drifted_weights))`. A one-way
87
+ cost of `0.001 * turnover` (0.1%) is deducted at each rebalance.
88
+ - Cumulative return includes transaction costs. Maximum drawdown is computed
89
+ from daily NAV, including rebalance costs. Annualized Sharpe uses weekly net
90
+ returns, zero risk-free rate, population standard deviation, and `sqrt(52)`
91
+ scaling. Average turnover includes the first rebalance.
92
+
93
+ Run the clean baselines from the repository root:
94
 
95
+ ```bash
96
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/evaluate.py \
97
+ --baseline equal_weight
98
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/evaluate.py \
99
+ --baseline simple_avg
100
+ ```
101
 
102
+ Use `--data PATH` to score another compatible split or an attacked view, and
103
+ `--transaction-cost RATE` to override the default only for an explicitly
104
+ declared protocol variant.
105
 
106
+ ## Submission Format
 
 
 
 
 
 
107
 
108
+ A submission is JSONL with exactly one object for every evaluated record:
 
 
 
109
 
110
+ ```json
111
+ {"id": "quantinv_test_0000_20250316", "weights": [0.2, 0.2, 0.2, 0.2, 0.2]}
112
+ ```
113
 
114
+ Each object must contain exactly `id` and `weights`. IDs must be unique and
115
+ match the evaluation data exactly. `weights` must be five finite JSON numbers
116
+ in canonical asset order, all non-negative, and already sum to one within
117
+ `1e-6`. Booleans, strings, missing or extra IDs, extra fields, and invalid
118
+ simplex vectors are rejected; the evaluator never clips or normalizes a
119
+ submission.
120
 
121
+ ```bash
122
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/evaluate.py \
123
+ --predictions predictions.jsonl
124
  ```
125
 
126
+ ## Byzantine Views
127
+
128
+ The checked-in splits are the clean benchmark. `attacks.py` deterministically
129
+ creates a replace-mode Byzantine view: the population remains `n=10`, while a
130
+ static set of `f` identities is replaced for the entire ordered run. The
131
+ constraint is `0 <= f < 5`. A seed selects the identities and the fixed Drift
132
+ targets; identities can instead be fixed explicitly by repeating
133
+ `--malicious-id` exactly `f` times.
134
+
135
+ Let `h_t` be the mean proposal of the honest identities, `d=5`, and `e_BTC` the
136
+ BTC one-hot vector. The frozen `quantinv-byzantine-v1` attacks are:
137
 
138
+ - Reverse: `(1 - h_t) / (d - 1)`.
139
+ - Bias: `0.9 * h_t + 0.1 * e_BTC`.
140
+ - Drift: use that identity's clean proposal for rounds 1-20, then use
141
+ `(1 - alpha_t) * clean_t + alpha_t * target`, where
142
+ `alpha_t = min(1, 0.02 * (t - 20))` and `target` is a seeded,
143
+ identity-specific `Dirichlet(1)` portfolio.
144
+ - Mixed: assign Reverse, Bias, and Drift cyclically to the ordered static
145
+ malicious identities.
146
+
147
+ Generate a view and its evaluator-only audit metadata separately:
148
 
149
  ```bash
150
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/attacks.py \
151
+ --data QuantInv/hf_release/data/test.jsonl \
152
+ --output attacked-test.jsonl \
153
+ --audit-output attacked-test.audit.json \
154
+ --attack mixed --f 3 --seed 42
 
 
155
  ```
156
 
157
+ Do not provide the audit file or either return-label field to the method. Score
158
+ predictions against the attacked view with:
159
 
160
  ```bash
161
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/evaluate.py \
162
+ --data attacked-test.jsonl --predictions predictions.jsonl
163
  ```
164
 
165
+ ## Loading
 
 
166
 
167
+ Local repository checkout:
168
 
169
+ ```python
170
+ from datasets import load_dataset
171
 
172
+ dataset = load_dataset("QuantInv/hf_release")
 
173
  ```
174
 
175
+ After publication to the Hub:
176
 
177
+ ```python
178
+ from datasets import load_dataset
179
+
180
+ dataset = load_dataset("YOUR_ORG/quantinvbench")
181
  ```
182
 
183
+ ## Reproduction and Validation
184
 
185
+ Run from the Crypto-MAD repository root. Creating the pinned environment is a
186
+ one-time step:
 
 
187
 
188
+ ```bash
189
+ conda env create -f QuantInv/hf_release/environment.yml
190
+ ```
191
 
192
+ The clean generator expects the five hourly market files under `data/` and the
193
+ derived sentiment cache at its default release path; both can be overridden
194
+ with `--data-dir` and `--sentiment-file`.
195
+
196
+ ```bash
197
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/generate.py
198
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/validate.py \
199
+ QuantInv/hf_release/data --source-data-dir data
200
+ conda run -n quantinv-hf python -m unittest discover \
201
+ -s QuantInv/hf_release/tests -v
202
+ conda run -n quantinv-hf python QuantInv/hf_release/scripts/attacks.py --self-test
203
+ ```
204
 
205
+ Without the original hourly sources, omit `--source-data-dir`; schema, split,
206
+ hash, compounding, and manifest checks still run. `data/manifest.json` records
207
+ the benchmark version, counts, protocol constants, and SHA-256 hashes needed
208
+ to audit a generation.
209
 
210
+ ## Limitations and License
 
 
211
 
212
+ This is a public-label offline benchmark, not a hidden leaderboard. It covers
213
+ five surviving assets and one fixed test window, so it has survivorship and
214
+ regime-selection limitations. The USDT series is synthetic and cash-like.
215
+ The fixed transaction model omits slippage, market impact, liquidity limits,
216
+ and order-book execution. It is not investment advice.
217
 
218
+ Release code is covered by the [MIT license](LICENSE). Dataset records and
219
+ source-derived artifacts remain subject to provider terms; see
220
+ [DATA_LICENSE.md](DATA_LICENSE.md). The Dataset Card therefore uses
221
+ `license: other`.
data/manifest.json CHANGED
@@ -1,7 +1,6 @@
1
  {
2
  "dataset": "QuantInvBench",
3
- "version": "1.0.0",
4
- "generated_at": "2026-08-20T06:20:34.246262+00:00",
5
  "assets": [
6
  "BTC",
7
  "ETH",
@@ -15,22 +14,50 @@
15
  "TSMom14",
16
  "TSMom60",
17
  "RiskParity",
 
18
  "NewsSentiment",
19
  "Size",
20
  "ValueNVT",
21
  "Liquidity"
22
  ],
23
  "rebalance_days": 7,
 
24
  "transaction_cost": 0.001,
25
  "splits": {
26
- "train": 298,
27
- "validation": 53,
28
  "test": 52
29
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  "data_sha256": {
31
- "train.jsonl": "c50cc31524e1cecfa53193a2117d7fdf0f2e52be198a68cf743b3bdd1420cde5",
32
- "validation.jsonl": "c97ce46d06d907146709787ccd74fc864e38c4645d6875a6eb140017565e5f68",
33
- "test.jsonl": "aafcc5aea0f2f6d1108e7f9f617f91722b1d4ee53cf6f4a379dd9dd6302a19f7"
34
  },
35
  "source_sha256": {
36
  "bitcoin_prices_1h.csv": "408cc935b616c98f4acf1afeb86da87d1da65772294793e227dabace589d2637",
 
1
  {
2
  "dataset": "QuantInvBench",
3
+ "version": "2.0.0",
 
4
  "assets": [
5
  "BTC",
6
  "ETH",
 
14
  "TSMom14",
15
  "TSMom60",
16
  "RiskParity",
17
+ "MinVar",
18
  "NewsSentiment",
19
  "Size",
20
  "ValueNVT",
21
  "Liquidity"
22
  ],
23
  "rebalance_days": 7,
24
+ "label_horizon_days": 7,
25
  "transaction_cost": 0.001,
26
  "splits": {
27
+ "train": 297,
28
+ "validation": 52,
29
  "test": 52
30
  },
31
+ "split_ranges": {
32
+ "train": {
33
+ "execution_start": "2018-07-04T00:00:00Z",
34
+ "execution_end": "2024-03-06T00:00:00Z",
35
+ "label_end": "2024-03-13T00:00:00Z"
36
+ },
37
+ "validation": {
38
+ "execution_start": "2024-03-16T00:00:00Z",
39
+ "execution_end": "2025-03-08T00:00:00Z",
40
+ "label_end": "2025-03-15T00:00:00Z"
41
+ },
42
+ "test": {
43
+ "execution_start": "2025-03-16T00:00:00Z",
44
+ "execution_end": "2026-03-08T00:00:00Z",
45
+ "label_end": "2026-03-15T00:00:00Z"
46
+ }
47
+ },
48
+ "evaluation_protocol": {
49
+ "initial_portfolio": "equal_weight",
50
+ "submitted_methods": "rebalance_every_record",
51
+ "equal_weight_baseline": "buy_and_hold",
52
+ "turnover": "half_l1_target_vs_return_drifted_holdings",
53
+ "sharpe": "weekly_returns_sqrt_52_ddof_0",
54
+ "max_drawdown": "daily_nav"
55
+ },
56
+ "attack_protocol": "quantinv-byzantine-v1",
57
  "data_sha256": {
58
+ "train.jsonl": "47d7eabb6831a64f451bfe27be47d4144e5ebac7035612d4eb66e5543d99e686",
59
+ "validation.jsonl": "298ca970d598df3971bc81abf2a8b38802ef19077455ececde74b3748b3063c1",
60
+ "test.jsonl": "9570ebe58fd85fcfd5e4ec0d392e3cd853126f8bfa6e4365afbb5f586a8cf22e"
61
  },
62
  "source_sha256": {
63
  "bitcoin_prices_1h.csv": "408cc935b616c98f4acf1afeb86da87d1da65772294793e227dabace589d2637",
data/test.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
data/train.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
data/validation.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
scripts/attacks.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Deterministic Byzantine attack reference for QuantInvBench.
3
+
4
+ The clean dataset remains the canonical artifact. This module creates an
5
+ attacked view in *replace* mode: the population stays fixed at ten strategies,
6
+ and a seed-selected, static subset of ``f`` strategy identities is replaced.
7
+ Attack labels are returned separately from the attacked records so benchmark
8
+ methods do not need to receive the malicious identities.
9
+
10
+ Frozen v1 attacks (``h`` is the mean proposal of the honest identities):
11
+
12
+ * Reverse: ``(1 - h) / (d - 1)``.
13
+ * Bias: ``0.9 * h + 0.1 * one_hot(BTC)``.
14
+ * Drift: keep the selected strategy's clean proposal for rounds 1--20, then
15
+ interpolate toward a seed-and-identity-specific Dirichlet(1) target with
16
+ ``alpha_t = min(1, 0.02 * (t - 20))``.
17
+ * Mixed: assign Reverse, Bias, and Drift cyclically to the static malicious
18
+ identities.
19
+
20
+ The public API is :func:`apply_attacks`. Run ``python attacks.py --help`` for
21
+ the JSONL command-line interface.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import copy
28
+ import hashlib
29
+ import json
30
+ import math
31
+ from dataclasses import dataclass
32
+ from pathlib import Path
33
+ from typing import Mapping, Sequence
34
+
35
+ try: # Package import and direct-script execution are both supported.
36
+ from .common import (
37
+ ASSETS,
38
+ ATTACK_PROTOCOL_VERSION,
39
+ read_jsonl,
40
+ validated_weights,
41
+ write_jsonl,
42
+ )
43
+ except ImportError: # pragma: no cover - exercised by the CLI invocation
44
+ from common import (
45
+ ASSETS,
46
+ ATTACK_PROTOCOL_VERSION,
47
+ read_jsonl,
48
+ validated_weights,
49
+ write_jsonl,
50
+ )
51
+
52
+
53
+ PROTOCOL_VERSION = ATTACK_PROTOCOL_VERSION
54
+ POPULATION_SIZE = 10
55
+ ATTACKS = ("reverse", "bias", "drift", "mixed")
56
+ MIXED_ROLES = ("reverse", "bias", "drift")
57
+ BIAS_DELTA = 0.1
58
+ BIAS_ASSET = "BTC"
59
+ DRIFT_WARMUP_ROUNDS = 20
60
+ DRIFT_RATE = 0.02
61
+ SIMPLEX_TOLERANCE = 1e-6
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class AttackBatch:
66
+ """An attacked dataset view and its evaluator-only audit metadata."""
67
+
68
+ records: list[dict]
69
+ audit: dict
70
+
71
+
72
+ def _stable_digest(*parts: object) -> bytes:
73
+ payload = "\x1f".join(str(part) for part in parts).encode("utf-8")
74
+ return hashlib.sha256(payload).digest()
75
+
76
+
77
+ def _stable_identity_order(strategy_ids: Sequence[str], seed: int) -> list[str]:
78
+ """Return a seed-dependent ordering that is stable across Python versions."""
79
+
80
+ return sorted(
81
+ strategy_ids,
82
+ key=lambda strategy_id: (
83
+ _stable_digest(PROTOCOL_VERSION, "identity", seed, strategy_id),
84
+ strategy_id,
85
+ ),
86
+ )
87
+
88
+
89
+ def select_malicious_ids(
90
+ strategy_ids: Sequence[str],
91
+ *,
92
+ f: int,
93
+ seed: int,
94
+ ) -> tuple[str, ...]:
95
+ """Select the static malicious identities for a benchmark run."""
96
+
97
+ ids = list(strategy_ids)
98
+ if len(ids) != POPULATION_SIZE or len(set(ids)) != POPULATION_SIZE:
99
+ raise ValueError(
100
+ f"expected {POPULATION_SIZE} unique strategy identities, got {len(ids)}"
101
+ )
102
+ _validate_f(f)
103
+ return tuple(_stable_identity_order(ids, seed)[:f])
104
+
105
+
106
+ def assign_attack_roles(
107
+ malicious_ids: Sequence[str],
108
+ *,
109
+ attack: str,
110
+ ) -> dict[str, str]:
111
+ """Assign one frozen role to each malicious identity."""
112
+
113
+ if attack not in ATTACKS:
114
+ raise ValueError(f"unknown attack {attack!r}; expected one of {ATTACKS}")
115
+ if len(set(malicious_ids)) != len(malicious_ids):
116
+ raise ValueError("malicious identities must be unique")
117
+ if attack == "mixed":
118
+ return {
119
+ strategy_id: MIXED_ROLES[index % len(MIXED_ROLES)]
120
+ for index, strategy_id in enumerate(malicious_ids)
121
+ }
122
+ return {strategy_id: attack for strategy_id in malicious_ids}
123
+
124
+
125
+ def _validate_f(f: int) -> None:
126
+ if isinstance(f, bool) or not isinstance(f, int):
127
+ raise ValueError("f must be an integer")
128
+ if f < 0 or POPULATION_SIZE <= 2 * f:
129
+ raise ValueError(
130
+ f"f must satisfy 0 <= f < {POPULATION_SIZE}/2 for n={POPULATION_SIZE}"
131
+ )
132
+
133
+
134
+ def _validate_seed(seed: int) -> None:
135
+ if isinstance(seed, bool) or not isinstance(seed, int):
136
+ raise ValueError("seed must be an integer")
137
+
138
+
139
+ def _record_proposals(record: Mapping[str, object], index: int) -> list[dict]:
140
+ proposals = record.get("strategy_proposals")
141
+ if not isinstance(proposals, list):
142
+ raise ValueError(f"record {index}: strategy_proposals must be a list")
143
+ if len(proposals) != POPULATION_SIZE:
144
+ raise ValueError(
145
+ f"record {index}: replace mode requires exactly {POPULATION_SIZE} "
146
+ f"proposals, got {len(proposals)}"
147
+ )
148
+
149
+ checked: list[dict] = []
150
+ seen: set[str] = set()
151
+ for proposal_index, proposal in enumerate(proposals):
152
+ if not isinstance(proposal, dict):
153
+ raise ValueError(
154
+ f"record {index} proposal {proposal_index}: expected an object"
155
+ )
156
+ strategy_id = proposal.get("strategy")
157
+ if not isinstance(strategy_id, str) or not strategy_id or strategy_id in seen:
158
+ raise ValueError(
159
+ f"record {index} proposal {proposal_index}: invalid or duplicate strategy"
160
+ )
161
+ seen.add(strategy_id)
162
+ weights = proposal.get("weights")
163
+ if not isinstance(weights, (list, tuple)):
164
+ raise ValueError(
165
+ f"record {index} strategy {strategy_id}: weights must be a sequence"
166
+ )
167
+ validated_weights(
168
+ weights,
169
+ label=f"record {index} strategy {strategy_id}",
170
+ )
171
+ checked.append(proposal)
172
+ return checked
173
+
174
+
175
+ def _validate_records(records: Sequence[dict]) -> tuple[str, ...]:
176
+ if not records:
177
+ raise ValueError("cannot attack an empty dataset")
178
+ if not isinstance(records[0], dict):
179
+ raise ValueError("record 0: expected an object")
180
+
181
+ first_proposals = _record_proposals(records[0], 0)
182
+ roster = tuple(proposal["strategy"] for proposal in first_proposals)
183
+ roster_set = set(roster)
184
+
185
+ for index, record in enumerate(records):
186
+ if not isinstance(record, dict):
187
+ raise ValueError(f"record {index}: expected an object")
188
+ identifier = record.get("id")
189
+ if not isinstance(identifier, str) or not identifier:
190
+ raise ValueError(f"record {index}: id must be a non-empty string")
191
+ assets = record.get("assets")
192
+ if assets != list(ASSETS):
193
+ raise ValueError(
194
+ f"record {index}: assets must use the fixed order {list(ASSETS)}"
195
+ )
196
+ proposals = _record_proposals(record, index)
197
+ current_roster = {proposal["strategy"] for proposal in proposals}
198
+ if current_roster != roster_set:
199
+ raise ValueError(f"record {index}: strategy roster differs from record 0")
200
+ return roster
201
+
202
+
203
+ def _resolve_malicious_ids(
204
+ roster: Sequence[str],
205
+ *,
206
+ f: int,
207
+ seed: int,
208
+ malicious_ids: Sequence[str] | None,
209
+ ) -> tuple[str, ...]:
210
+ if malicious_ids is None:
211
+ return select_malicious_ids(roster, f=f, seed=seed)
212
+
213
+ selected = tuple(malicious_ids)
214
+ if len(selected) != f:
215
+ raise ValueError(
216
+ f"expected exactly f={f} explicit malicious identities, got {len(selected)}"
217
+ )
218
+ if len(set(selected)) != len(selected):
219
+ raise ValueError("explicit malicious identities must be unique")
220
+ unknown = set(selected) - set(roster)
221
+ if unknown:
222
+ raise ValueError(f"unknown malicious identities: {sorted(unknown)}")
223
+ return selected
224
+
225
+
226
+ def _honest_mean(proposals: Sequence[dict], malicious_ids: set[str]) -> list[float]:
227
+ honest = [
228
+ validated_weights(
229
+ proposal["weights"], label=f"honest proposal {proposal['strategy']}"
230
+ )
231
+ for proposal in proposals
232
+ if proposal["strategy"] not in malicious_ids
233
+ ]
234
+ if not honest:
235
+ raise ValueError("at least one honest proposal is required")
236
+ return [sum(values) / len(honest) for values in zip(*honest)]
237
+
238
+
239
+ def _dirichlet_one_target(seed: int, strategy_id: str) -> list[float]:
240
+ """Generate a stable Dirichlet(1) draw without mutable global RNG state."""
241
+
242
+ draws = []
243
+ for asset in ASSETS:
244
+ digest = _stable_digest(
245
+ PROTOCOL_VERSION, "drift-target", seed, strategy_id, asset
246
+ )
247
+ integer = int.from_bytes(digest[:8], byteorder="big", signed=False)
248
+ uniform = (integer + 0.5) / (2**64)
249
+ draws.append(-math.log(uniform))
250
+ total = sum(draws)
251
+ return validated_weights(
252
+ [draw / total for draw in draws], label=f"drift target {strategy_id}"
253
+ )
254
+
255
+
256
+ def _reverse(honest_mean: Sequence[float]) -> list[float]:
257
+ dimension = len(honest_mean)
258
+ if dimension < 2:
259
+ raise ValueError("reverse attack requires at least two dimensions")
260
+ return validated_weights(
261
+ [(1.0 - value) / (dimension - 1) for value in honest_mean],
262
+ label="reverse attack",
263
+ )
264
+
265
+
266
+ def _bias(honest_mean: Sequence[float]) -> list[float]:
267
+ btc_index = ASSETS.index(BIAS_ASSET)
268
+ biased = [(1.0 - BIAS_DELTA) * value for value in honest_mean]
269
+ biased[btc_index] += BIAS_DELTA
270
+ return validated_weights(biased, label="bias attack")
271
+
272
+
273
+ def _drift(
274
+ clean_weights: Sequence[float],
275
+ *,
276
+ target: Sequence[float],
277
+ round_number: int,
278
+ ) -> list[float]:
279
+ clean = validated_weights(clean_weights, label="drift clean proposal")
280
+ alpha = min(
281
+ 1.0,
282
+ DRIFT_RATE * max(0, round_number - DRIFT_WARMUP_ROUNDS),
283
+ )
284
+ if alpha == 0.0:
285
+ # The frozen protocol says the warmup proposal is the agent's clean
286
+ # proposal, including its serialized floating-point representation.
287
+ return [float(value) for value in clean_weights]
288
+ return validated_weights(
289
+ [
290
+ (1.0 - alpha) * clean_value + alpha * target_value
291
+ for clean_value, target_value in zip(clean, target)
292
+ ],
293
+ label="drift attack",
294
+ )
295
+
296
+
297
+ def _attack_weights(
298
+ role: str,
299
+ *,
300
+ clean_weights: Sequence[float],
301
+ honest_mean: Sequence[float],
302
+ drift_target: Sequence[float] | None,
303
+ round_number: int,
304
+ ) -> list[float]:
305
+ if role == "reverse":
306
+ return _reverse(honest_mean)
307
+ if role == "bias":
308
+ return _bias(honest_mean)
309
+ if role == "drift":
310
+ if drift_target is None: # Defensive: roles and targets are built together.
311
+ raise ValueError("drift target is required for the drift attack")
312
+ return _drift(
313
+ clean_weights,
314
+ target=drift_target,
315
+ round_number=round_number,
316
+ )
317
+ raise ValueError(f"unsupported attack role: {role}")
318
+
319
+
320
+ def _assert_simplex(weights: Sequence[float], label: str) -> None:
321
+ if len(weights) != len(ASSETS):
322
+ raise AssertionError(f"{label}: wrong dimension")
323
+ if any(not math.isfinite(value) or value < -SIMPLEX_TOLERANCE for value in weights):
324
+ raise AssertionError(f"{label}: weights are not finite and non-negative")
325
+ if abs(sum(weights) - 1.0) > SIMPLEX_TOLERANCE:
326
+ raise AssertionError(f"{label}: weights do not sum to one")
327
+
328
+
329
+ def apply_attacks(
330
+ records: Sequence[dict],
331
+ *,
332
+ attack: str = "mixed",
333
+ f: int = 3,
334
+ seed: int = 42,
335
+ malicious_ids: Sequence[str] | None = None,
336
+ ) -> AttackBatch:
337
+ """Create a deterministic attacked view of clean QuantInvBench records.
338
+
339
+ Args:
340
+ records: Chronologically ordered clean benchmark records.
341
+ attack: One of ``reverse``, ``bias``, ``drift``, or ``mixed``.
342
+ f: Number of replaced strategy identities. Must satisfy ``10 > 2f``.
343
+ seed: Selects the static identities and fixed Drift targets.
344
+ malicious_ids: Optional explicit identities. When omitted, ``seed``
345
+ deterministically selects them once for the complete run.
346
+
347
+ Returns:
348
+ :class:`AttackBatch`; ``records`` contain no malicious labels, while
349
+ ``audit`` contains the evaluator-only identities, roles, and protocol
350
+ parameters.
351
+ """
352
+
353
+ _validate_f(f)
354
+ _validate_seed(seed)
355
+ if attack not in ATTACKS:
356
+ raise ValueError(f"unknown attack {attack!r}; expected one of {ATTACKS}")
357
+
358
+ clean_records = list(records)
359
+ roster = _validate_records(clean_records)
360
+ selected = _resolve_malicious_ids(
361
+ roster,
362
+ f=f,
363
+ seed=seed,
364
+ malicious_ids=malicious_ids,
365
+ )
366
+ roles = assign_attack_roles(selected, attack=attack)
367
+ selected_set = set(selected)
368
+ drift_targets = {
369
+ strategy_id: _dirichlet_one_target(seed, strategy_id)
370
+ for strategy_id, role in roles.items()
371
+ if role == "drift"
372
+ }
373
+
374
+ attacked_records: list[dict] = []
375
+ for record_index, clean_record in enumerate(clean_records):
376
+ round_number = record_index + 1
377
+ clean_proposals = clean_record["strategy_proposals"]
378
+ honest_mean = _honest_mean(clean_proposals, selected_set)
379
+ attacked_record = copy.deepcopy(clean_record)
380
+
381
+ for proposal in attacked_record["strategy_proposals"]:
382
+ strategy_id = proposal["strategy"]
383
+ role = roles.get(strategy_id)
384
+ if role is None:
385
+ continue
386
+ proposal["weights"] = _attack_weights(
387
+ role,
388
+ clean_weights=proposal["weights"],
389
+ honest_mean=honest_mean,
390
+ drift_target=drift_targets.get(strategy_id),
391
+ round_number=round_number,
392
+ )
393
+ _assert_simplex(
394
+ proposal["weights"],
395
+ f"record {clean_record['id']} strategy {strategy_id}",
396
+ )
397
+ attacked_records.append(attacked_record)
398
+
399
+ audit = {
400
+ "protocol_version": PROTOCOL_VERSION,
401
+ "population_mode": "replace",
402
+ "n": POPULATION_SIZE,
403
+ "f": f,
404
+ "seed": seed,
405
+ "attack": attack,
406
+ "malicious_ids": list(selected),
407
+ "attack_roles": roles,
408
+ "parameters": {
409
+ "reverse": "(1 - honest_mean) / (d - 1)",
410
+ "bias": {
411
+ "formula": "(1 - delta) * honest_mean + delta * one_hot(asset)",
412
+ "delta": BIAS_DELTA,
413
+ "asset": BIAS_ASSET,
414
+ },
415
+ "drift": {
416
+ "formula": (
417
+ "(1 - alpha_t) * clean_agent_proposal_t + "
418
+ "alpha_t * fixed_dirichlet_target"
419
+ ),
420
+ "warmup_rounds": DRIFT_WARMUP_ROUNDS,
421
+ "rate": DRIFT_RATE,
422
+ "alpha": "min(1, rate * max(0, round_number - warmup_rounds))",
423
+ "target_distribution": "Dirichlet(1)",
424
+ },
425
+ },
426
+ "drift_targets": drift_targets,
427
+ "sample_ids": [record["id"] for record in clean_records],
428
+ }
429
+ return AttackBatch(records=attacked_records, audit=audit)
430
+
431
+
432
+ def _synthetic_records(rounds: int = 25) -> list[dict]:
433
+ records = []
434
+ strategies = [f"strategy_{index}" for index in range(POPULATION_SIZE)]
435
+ for round_index in range(rounds):
436
+ proposals = []
437
+ for strategy_index, strategy_id in enumerate(strategies):
438
+ raw = [
439
+ 1.0 + ((strategy_index + asset_index + round_index) % len(ASSETS))
440
+ for asset_index in range(len(ASSETS))
441
+ ]
442
+ total = sum(raw)
443
+ proposals.append(
444
+ {
445
+ "strategy": strategy_id,
446
+ "weights": [value / total for value in raw],
447
+ }
448
+ )
449
+ records.append(
450
+ {
451
+ "id": f"synthetic_{round_index:04d}",
452
+ "assets": list(ASSETS),
453
+ "strategy_proposals": proposals,
454
+ }
455
+ )
456
+ return records
457
+
458
+
459
+ def run_self_test() -> None:
460
+ """Exercise determinism, replace semantics, audit separation, and simplex."""
461
+
462
+ clean = _synthetic_records()
463
+ first = apply_attacks(clean, attack="mixed", f=3, seed=17)
464
+ second = apply_attacks(clean, attack="mixed", f=3, seed=17)
465
+ if first != second:
466
+ raise AssertionError("same seed did not reproduce identical output")
467
+ if first.records == clean:
468
+ raise AssertionError("mixed attack did not modify the dataset")
469
+ if "attack_roles" in first.records[0] or "malicious_ids" in first.records[0]:
470
+ raise AssertionError("attack labels leaked into method-facing records")
471
+
472
+ roles = first.audit["attack_roles"]
473
+ if sorted(roles.values()) != sorted(MIXED_ROLES):
474
+ raise AssertionError("mixed attack did not assign one of each role for f=3")
475
+ drift_id = next(strategy_id for strategy_id, role in roles.items() if role == "drift")
476
+ malicious = set(first.audit["malicious_ids"])
477
+
478
+ for record_index, (clean_record, attacked_record) in enumerate(
479
+ zip(clean, first.records)
480
+ ):
481
+ if len(attacked_record["strategy_proposals"]) != POPULATION_SIZE:
482
+ raise AssertionError("replace mode changed the population size")
483
+ clean_by_id = {
484
+ proposal["strategy"]: proposal for proposal in clean_record["strategy_proposals"]
485
+ }
486
+ for proposal in attacked_record["strategy_proposals"]:
487
+ _assert_simplex(proposal["weights"], proposal["strategy"])
488
+ if proposal["strategy"] not in malicious:
489
+ if proposal != clean_by_id[proposal["strategy"]]:
490
+ raise AssertionError("an honest proposal was modified")
491
+
492
+ attacked_by_id = {
493
+ proposal["strategy"]: proposal
494
+ for proposal in attacked_record["strategy_proposals"]
495
+ }
496
+ drift_clean = clean_by_id[drift_id]["weights"]
497
+ drift_attacked = attacked_by_id[drift_id]["weights"]
498
+ if record_index < DRIFT_WARMUP_ROUNDS and drift_attacked != drift_clean:
499
+ raise AssertionError("drift modified a proposal during its warmup")
500
+ if record_index == DRIFT_WARMUP_ROUNDS and drift_attacked == drift_clean:
501
+ raise AssertionError("drift did not begin after its warmup")
502
+
503
+
504
+ def parse_args() -> argparse.Namespace:
505
+ parser = argparse.ArgumentParser(description=__doc__)
506
+ parser.add_argument(
507
+ "--data",
508
+ type=Path,
509
+ default=Path(__file__).resolve().parents[1] / "data" / "test.jsonl",
510
+ help="Clean QuantInvBench JSONL (default: data/test.jsonl)",
511
+ )
512
+ parser.add_argument("--output", type=Path, help="Method-facing attacked JSONL")
513
+ parser.add_argument(
514
+ "--audit-output",
515
+ type=Path,
516
+ help="Evaluator-only attack identities, roles, and parameters JSON",
517
+ )
518
+ parser.add_argument("--attack", choices=ATTACKS, default="mixed")
519
+ parser.add_argument("--f", type=int, default=3)
520
+ parser.add_argument("--seed", type=int, default=42)
521
+ parser.add_argument(
522
+ "--malicious-id",
523
+ action="append",
524
+ dest="malicious_ids",
525
+ help="Explicit static malicious strategy ID; repeat exactly f times",
526
+ )
527
+ parser.add_argument(
528
+ "--self-test",
529
+ action="store_true",
530
+ help="Run built-in deterministic invariants without reading data",
531
+ )
532
+ return parser.parse_args()
533
+
534
+
535
+ def main() -> None:
536
+ args = parse_args()
537
+ if args.self_test:
538
+ run_self_test()
539
+ print(json.dumps({"self_test": "passed", "protocol": PROTOCOL_VERSION}))
540
+ return
541
+
542
+ if args.output is None or args.audit_output is None:
543
+ raise SystemExit("--output and --audit-output are required unless --self-test is used")
544
+ data_path = args.data.resolve()
545
+ output_path = args.output.resolve()
546
+ audit_path = args.audit_output.resolve()
547
+ if len({data_path, output_path, audit_path}) != 3:
548
+ raise ValueError("data, output, and audit-output must be three different paths")
549
+
550
+ batch = apply_attacks(
551
+ read_jsonl(data_path),
552
+ attack=args.attack,
553
+ f=args.f,
554
+ seed=args.seed,
555
+ malicious_ids=args.malicious_ids,
556
+ )
557
+ write_jsonl(output_path, batch.records)
558
+ audit_path.parent.mkdir(parents=True, exist_ok=True)
559
+ with audit_path.open("w", encoding="utf-8", newline="\n") as handle:
560
+ json.dump(batch.audit, handle, indent=2, ensure_ascii=False, allow_nan=False)
561
+ handle.write("\n")
562
+
563
+ print(
564
+ json.dumps(
565
+ {
566
+ "records": len(batch.records),
567
+ "output": str(output_path),
568
+ "audit_output": str(audit_path),
569
+ "malicious_ids": batch.audit["malicious_ids"],
570
+ "attack_roles": batch.audit["attack_roles"],
571
+ },
572
+ indent=2,
573
+ allow_nan=False,
574
+ )
575
+ )
576
+
577
+
578
+ if __name__ == "__main__":
579
+ main()
scripts/common.py CHANGED
@@ -12,12 +12,15 @@ from typing import Iterable, Mapping, Sequence
12
  COINS = ("bitcoin", "ethereum", "tether", "xrp", "bnb")
13
  ASSETS = ("BTC", "ETH", "USDT", "XRP", "BNB")
14
  COIN_TO_ASSET = dict(zip(COINS, ASSETS))
 
 
15
  STRATEGIES = (
16
  "Momentum",
17
  "MaxSharpe",
18
  "TSMom14",
19
  "TSMom60",
20
  "RiskParity",
 
21
  "NewsSentiment",
22
  "Size",
23
  "ValueNVT",
@@ -26,6 +29,32 @@ STRATEGIES = (
26
  REBALANCE_DAYS = 7
27
  TRANSACTION_COST = 0.001
28
  WEIGHT_TOLERANCE = 1e-6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  def sha256_file(path: Path) -> str:
 
12
  COINS = ("bitcoin", "ethereum", "tether", "xrp", "bnb")
13
  ASSETS = ("BTC", "ETH", "USDT", "XRP", "BNB")
14
  COIN_TO_ASSET = dict(zip(COINS, ASSETS))
15
+ BENCHMARK_VERSION = "2.0.0"
16
+ ATTACK_PROTOCOL_VERSION = "quantinv-byzantine-v1"
17
  STRATEGIES = (
18
  "Momentum",
19
  "MaxSharpe",
20
  "TSMom14",
21
  "TSMom60",
22
  "RiskParity",
23
+ "MinVar",
24
  "NewsSentiment",
25
  "Size",
26
  "ValueNVT",
 
29
  REBALANCE_DAYS = 7
30
  TRANSACTION_COST = 0.001
31
  WEIGHT_TOLERANCE = 1e-6
32
+ EXPECTED_SPLIT_COUNTS = {"train": 297, "validation": 52, "test": 52}
33
+ EXPECTED_SPLIT_RANGES = {
34
+ "train": {
35
+ "execution_start": "2018-07-04T00:00:00Z",
36
+ "execution_end": "2024-03-06T00:00:00Z",
37
+ "label_end": "2024-03-13T00:00:00Z",
38
+ },
39
+ "validation": {
40
+ "execution_start": "2024-03-16T00:00:00Z",
41
+ "execution_end": "2025-03-08T00:00:00Z",
42
+ "label_end": "2025-03-15T00:00:00Z",
43
+ },
44
+ "test": {
45
+ "execution_start": "2025-03-16T00:00:00Z",
46
+ "execution_end": "2026-03-08T00:00:00Z",
47
+ "label_end": "2026-03-15T00:00:00Z",
48
+ },
49
+ }
50
+ EVALUATION_PROTOCOL = {
51
+ "initial_portfolio": "equal_weight",
52
+ "submitted_methods": "rebalance_every_record",
53
+ "equal_weight_baseline": "buy_and_hold",
54
+ "turnover": "half_l1_target_vs_return_drifted_holdings",
55
+ "sharpe": "weekly_returns_sqrt_52_ddof_0",
56
+ "max_drawdown": "daily_nav",
57
+ }
58
 
59
 
60
  def sha256_file(path: Path) -> str:
scripts/evaluate.py CHANGED
@@ -5,81 +5,291 @@ from __future__ import annotations
5
 
6
  import argparse
7
  import json
 
8
  from pathlib import Path
 
9
 
10
  import numpy as np
11
 
12
- from common import ASSETS, TRANSACTION_COST, read_jsonl, validated_weights
 
 
 
13
 
14
 
15
  def parse_args() -> argparse.Namespace:
16
  parser = argparse.ArgumentParser(description=__doc__)
17
- parser.add_argument("--data", type=Path, default=Path(__file__).resolve().parents[1] / "data" / "test.jsonl")
 
 
 
 
18
  group = parser.add_mutually_exclusive_group(required=True)
19
- group.add_argument("--baseline", choices=("equal_weight", "simple_avg"))
20
- group.add_argument("--predictions", type=Path, help="JSONL records with id and weights")
21
- parser.add_argument("--transaction-cost", type=float, default=TRANSACTION_COST)
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  return parser.parse_args()
23
 
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def baseline_weights(record: dict, baseline: str) -> list[float]:
26
  if baseline == "equal_weight":
27
- return [1.0 / len(ASSETS)] * len(ASSETS)
28
- proposals = [proposal["weights"] for proposal in record["strategy_proposals"]]
29
- return validated_weights(np.mean(proposals, axis=0).tolist(), label="simple_avg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def load_predictions(path: Path) -> dict[str, list[float]]:
33
- predictions = {}
34
  for index, record in enumerate(read_jsonl(path)):
35
- if set(record) != {"id", "weights"}:
36
- raise ValueError(f"prediction {index}: expected only id and weights")
 
 
37
  identifier = record["id"]
38
- if not isinstance(identifier, str) or identifier in predictions:
39
- raise ValueError(f"prediction {index}: invalid or duplicate id")
40
- predictions[identifier] = validated_weights(record["weights"], label=identifier)
 
 
 
 
41
  return predictions
42
 
43
 
44
- def evaluate(records: list[dict], weights_by_id: dict[str, list[float]], transaction_cost: float) -> dict:
45
- if not 0 <= transaction_cost < 1:
46
- raise ValueError("transaction cost must be in [0, 1)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  capital = 1.0
48
  peak = capital
49
  maximum_drawdown = 0.0
50
- previous_weights = np.full(len(ASSETS), 1.0 / len(ASSETS))
51
- period_returns = []
52
  turnovers = []
 
53
 
54
- for record in records:
55
- identifier = record["id"]
56
- if identifier not in weights_by_id:
57
- raise ValueError(f"missing prediction for {identifier}")
58
- weights = np.asarray(weights_by_id[identifier], dtype=float)
59
- asset_returns = np.asarray(record["next_7d_returns"], dtype=float)
60
- turnover = float(np.abs(weights - previous_weights).sum() / 2.0)
61
- gross_return = float(weights @ asset_returns)
62
- net_growth = (1.0 - transaction_cost * turnover) * (1.0 + gross_return)
63
- if net_growth <= 0:
64
- raise ValueError(f"{identifier}: portfolio value became non-positive")
65
- net_return = net_growth - 1.0
66
- capital *= net_growth
67
- peak = max(peak, capital)
68
- maximum_drawdown = max(maximum_drawdown, 1.0 - capital / peak)
69
- period_returns.append(net_return)
70
  turnovers.append(turnover)
71
- previous_weights = weights
72
 
73
- returns = np.asarray(period_returns, dtype=float)
74
- volatility = float(returns.std(ddof=1)) if len(returns) > 1 else 0.0
75
- sharpe = float(returns.mean() / volatility * np.sqrt(52)) if volatility > 0 else 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  return {
77
  "samples": len(records),
78
  "cumulative_return": round(capital - 1.0, 10),
79
  "annualized_sharpe": round(sharpe, 10),
80
  "max_drawdown": round(maximum_drawdown, 10),
81
  "average_turnover": round(float(np.mean(turnovers)), 10),
82
- "transaction_cost": transaction_cost,
83
  }
84
 
85
 
@@ -95,18 +305,20 @@ def main() -> None:
95
  for record in records
96
  }
97
  method = args.baseline
 
98
  else:
99
  weights_by_id = load_predictions(args.predictions.resolve())
100
- expected_ids = {record["id"] for record in records}
101
- extra_ids = set(weights_by_id) - expected_ids
102
- if extra_ids:
103
- raise ValueError(f"predictions contain unknown ids: {sorted(extra_ids)[:3]}")
104
  method = str(args.predictions)
 
105
 
106
- metrics = evaluate(records, weights_by_id, args.transaction_cost)
 
 
 
 
 
107
  print(json.dumps({"method": method, **metrics}, indent=2, allow_nan=False))
108
 
109
 
110
  if __name__ == "__main__":
111
  main()
112
-
 
5
 
6
  import argparse
7
  import json
8
+ import math
9
  from pathlib import Path
10
+ from typing import Sequence
11
 
12
  import numpy as np
13
 
14
+ from common import ASSETS, REBALANCE_DAYS, TRANSACTION_COST, WEIGHT_TOLERANCE, read_jsonl
15
+
16
+
17
+ EQUAL_WEIGHTS = np.full(len(ASSETS), 1.0 / len(ASSETS), dtype=float)
18
 
19
 
20
  def parse_args() -> argparse.Namespace:
21
  parser = argparse.ArgumentParser(description=__doc__)
22
+ parser.add_argument(
23
+ "--data",
24
+ type=Path,
25
+ default=Path(__file__).resolve().parents[1] / "data" / "test.jsonl",
26
+ )
27
  group = parser.add_mutually_exclusive_group(required=True)
28
+ group.add_argument(
29
+ "--baseline",
30
+ choices=("equal_weight", "simple_avg"),
31
+ help="equal_weight is buy-and-hold; simple_avg rebalances every seven days",
32
+ )
33
+ group.add_argument(
34
+ "--predictions",
35
+ type=Path,
36
+ help="JSONL records with exactly id and weights",
37
+ )
38
+ parser.add_argument(
39
+ "--transaction-cost",
40
+ type=float,
41
+ default=TRANSACTION_COST,
42
+ help="one-way proportional cost applied to half-L1 turnover (default: 0.001)",
43
+ )
44
  return parser.parse_args()
45
 
46
 
47
+ def strict_weights(values: object, *, label: str) -> list[float]:
48
+ """Validate a submitted simplex vector without clipping or normalizing it."""
49
+ if not isinstance(values, list):
50
+ raise ValueError(
51
+ f"{label}: weights must be a JSON array in {list(ASSETS)} order"
52
+ )
53
+ if len(values) != len(ASSETS):
54
+ raise ValueError(
55
+ f"{label}: expected {len(ASSETS)} weights in {list(ASSETS)} order, "
56
+ f"got {len(values)}"
57
+ )
58
+
59
+ weights: list[float] = []
60
+ for index, value in enumerate(values):
61
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
62
+ raise ValueError(f"{label}: weight {index} must be a JSON number")
63
+ weight = float(value)
64
+ if not math.isfinite(weight):
65
+ raise ValueError(f"{label}: weight {index} is NaN or Infinity")
66
+ if weight < 0.0:
67
+ raise ValueError(f"{label}: weight {index} must be non-negative")
68
+ weights.append(weight)
69
+
70
+ total = math.fsum(weights)
71
+ if not math.isclose(total, 1.0, rel_tol=0.0, abs_tol=WEIGHT_TOLERANCE):
72
+ raise ValueError(
73
+ f"{label}: weights must sum to 1 (got {total:.12g}); "
74
+ "the evaluator does not clip or normalize predictions"
75
+ )
76
+ return weights
77
+
78
+
79
  def baseline_weights(record: dict, baseline: str) -> list[float]:
80
  if baseline == "equal_weight":
81
+ return EQUAL_WEIGHTS.tolist()
82
+ if baseline != "simple_avg":
83
+ raise ValueError(f"unknown baseline: {baseline}")
84
+
85
+ proposals = record.get("strategy_proposals")
86
+ if not isinstance(proposals, list) or not proposals:
87
+ raise ValueError(f"{record.get('id', '<unknown>')}: missing strategy proposals")
88
+
89
+ proposal_weights = []
90
+ for index, proposal in enumerate(proposals):
91
+ if not isinstance(proposal, dict) or "weights" not in proposal:
92
+ raise ValueError(
93
+ f"{record.get('id', '<unknown>')}: strategy proposal {index} "
94
+ "must contain weights"
95
+ )
96
+ proposal_weights.append(
97
+ strict_weights(
98
+ proposal["weights"],
99
+ label=f"{record.get('id', '<unknown>')}.strategy_proposals[{index}]",
100
+ )
101
+ )
102
+
103
+ averaged = np.mean(np.asarray(proposal_weights, dtype=float), axis=0).tolist()
104
+ return strict_weights(averaged, label=f"{record.get('id', '<unknown>')}.simple_avg")
105
 
106
 
107
  def load_predictions(path: Path) -> dict[str, list[float]]:
108
+ predictions: dict[str, list[float]] = {}
109
  for index, record in enumerate(read_jsonl(path)):
110
+ if not isinstance(record, dict) or set(record) != {"id", "weights"}:
111
+ raise ValueError(
112
+ f"prediction {index}: expected exactly the fields id and weights"
113
+ )
114
  identifier = record["id"]
115
+ if not isinstance(identifier, str) or not identifier:
116
+ raise ValueError(f"prediction {index}: id must be a non-empty string")
117
+ if identifier in predictions:
118
+ raise ValueError(f"prediction {index}: duplicate id {identifier!r}")
119
+ predictions[identifier] = strict_weights(
120
+ record["weights"], label=f"prediction {identifier!r}"
121
+ )
122
  return predictions
123
 
124
 
125
+ def _daily_returns(record: dict) -> np.ndarray:
126
+ identifier = record.get("id", "<unknown>")
127
+ if "next_7d_daily_returns" not in record:
128
+ if "next_7d_returns" in record:
129
+ raise ValueError(
130
+ f"{identifier}: legacy record has next_7d_returns but no "
131
+ "next_7d_daily_returns; regenerate the dataset because weekly "
132
+ "returns cannot reproduce daily NAV and maximum drawdown"
133
+ )
134
+ raise ValueError(f"{identifier}: missing next_7d_daily_returns")
135
+
136
+ values = record["next_7d_daily_returns"]
137
+ if not isinstance(values, list) or len(values) != REBALANCE_DAYS:
138
+ length = len(values) if isinstance(values, list) else "non-list"
139
+ raise ValueError(
140
+ f"{identifier}: next_7d_daily_returns must contain exactly "
141
+ f"{REBALANCE_DAYS} daily rows (got {length})"
142
+ )
143
+
144
+ rows: list[list[float]] = []
145
+ for day_index, row in enumerate(values):
146
+ if not isinstance(row, list) or len(row) != len(ASSETS):
147
+ length = len(row) if isinstance(row, list) else "non-list"
148
+ raise ValueError(
149
+ f"{identifier}: next_7d_daily_returns[{day_index}] must contain "
150
+ f"{len(ASSETS)} returns in {list(ASSETS)} order (got {length})"
151
+ )
152
+ parsed_row = []
153
+ for asset_index, value in enumerate(row):
154
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
155
+ raise ValueError(
156
+ f"{identifier}: daily return [{day_index}][{asset_index}] "
157
+ "must be a JSON number"
158
+ )
159
+ parsed = float(value)
160
+ if not math.isfinite(parsed):
161
+ raise ValueError(
162
+ f"{identifier}: daily return [{day_index}][{asset_index}] "
163
+ "is NaN or Infinity"
164
+ )
165
+ if parsed <= -1.0:
166
+ raise ValueError(
167
+ f"{identifier}: daily return [{day_index}][{asset_index}] "
168
+ "must be greater than -1"
169
+ )
170
+ parsed_row.append(parsed)
171
+ rows.append(parsed_row)
172
+ return np.asarray(rows, dtype=float)
173
+
174
+
175
+ def _update_drawdown(capital: float, peak: float, maximum: float) -> tuple[float, float]:
176
+ peak = max(peak, capital)
177
+ return peak, max(maximum, 1.0 - capital / peak)
178
+
179
+
180
+ def evaluate(
181
+ records: Sequence[dict],
182
+ weights_by_id: dict[str, list[float]],
183
+ transaction_cost: float,
184
+ *,
185
+ buy_and_hold: bool = False,
186
+ ) -> dict:
187
+ """Run the weekly-rebalanced portfolio simulation.
188
+
189
+ The paper starts every method from an already established equal-weight
190
+ portfolio. Regular methods trade from that portfolio at the first event and
191
+ subsequently trade from the return-drifted holdings. With ``buy_and_hold``
192
+ set, that initial equal-weight portfolio is never traded.
193
+ """
194
+ if (
195
+ isinstance(transaction_cost, bool)
196
+ or not isinstance(transaction_cost, (int, float))
197
+ or not math.isfinite(float(transaction_cost))
198
+ or not 0.0 <= float(transaction_cost) < 1.0
199
+ ):
200
+ raise ValueError("transaction cost must be a finite number in [0, 1)")
201
+ if not records:
202
+ raise ValueError("cannot evaluate an empty dataset")
203
+ if not isinstance(weights_by_id, dict):
204
+ raise ValueError("weights_by_id must be a mapping from record id to weights")
205
+
206
+ identifiers = []
207
+ seen_ids = set()
208
+ for index, record in enumerate(records):
209
+ if not isinstance(record, dict):
210
+ raise ValueError(f"record {index}: expected an object")
211
+ identifier = record.get("id")
212
+ if not isinstance(identifier, str) or not identifier:
213
+ raise ValueError(f"record {index}: id must be a non-empty string")
214
+ if identifier in seen_ids:
215
+ raise ValueError(f"record {index}: duplicate id {identifier!r}")
216
+ if "assets" in record and record["assets"] != list(ASSETS):
217
+ raise ValueError(
218
+ f"{identifier}: assets must be in canonical order {list(ASSETS)}"
219
+ )
220
+ seen_ids.add(identifier)
221
+ identifiers.append(identifier)
222
+
223
+ prediction_ids = set(weights_by_id)
224
+ missing_ids = seen_ids - prediction_ids
225
+ if missing_ids:
226
+ raise ValueError(f"missing prediction for {sorted(missing_ids)[0]}")
227
+ extra_ids = prediction_ids - seen_ids
228
+ if extra_ids:
229
+ raise ValueError(f"predictions contain unknown ids: {sorted(extra_ids)[:3]}")
230
+
231
+ validated_targets = {
232
+ identifier: np.asarray(
233
+ strict_weights(weights_by_id[identifier], label=f"prediction {identifier!r}"),
234
+ dtype=float,
235
+ )
236
+ for identifier in identifiers
237
+ }
238
+ daily_returns = [_daily_returns(record) for record in records]
239
+
240
  capital = 1.0
241
  peak = capital
242
  maximum_drawdown = 0.0
243
+ current_weights = EQUAL_WEIGHTS.copy()
244
+ weekly_net_returns = []
245
  turnovers = []
246
+ cost = float(transaction_cost)
247
 
248
+ for identifier, return_matrix in zip(identifiers, daily_returns):
249
+ period_start_capital = capital
250
+
251
+ if buy_and_hold:
252
+ turnover = 0.0
253
+ else:
254
+ target_weights = validated_targets[identifier]
255
+ turnover = float(np.abs(target_weights - current_weights).sum() / 2.0)
256
+ capital *= 1.0 - cost * turnover
257
+ peak, maximum_drawdown = _update_drawdown(
258
+ capital, peak, maximum_drawdown
259
+ )
260
+ current_weights = target_weights.copy()
 
 
 
261
  turnovers.append(turnover)
 
262
 
263
+ for day_index, asset_returns in enumerate(return_matrix):
264
+ asset_growth = 1.0 + asset_returns
265
+ portfolio_growth = float(current_weights @ asset_growth)
266
+ if not math.isfinite(portfolio_growth) or portfolio_growth <= 0.0:
267
+ raise ValueError(
268
+ f"{identifier}: portfolio value became non-positive on "
269
+ f"daily return row {day_index}"
270
+ )
271
+ capital *= portfolio_growth
272
+ current_weights = current_weights * asset_growth / portfolio_growth
273
+ peak, maximum_drawdown = _update_drawdown(
274
+ capital, peak, maximum_drawdown
275
+ )
276
+
277
+ weekly_net_returns.append(capital / period_start_capital - 1.0)
278
+
279
+ returns = np.asarray(weekly_net_returns, dtype=float)
280
+ volatility = float(returns.std(ddof=0))
281
+ sharpe = (
282
+ float(returns.mean() / volatility * math.sqrt(52.0))
283
+ if volatility > 0.0
284
+ else 0.0
285
+ )
286
  return {
287
  "samples": len(records),
288
  "cumulative_return": round(capital - 1.0, 10),
289
  "annualized_sharpe": round(sharpe, 10),
290
  "max_drawdown": round(maximum_drawdown, 10),
291
  "average_turnover": round(float(np.mean(turnovers)), 10),
292
+ "transaction_cost": cost,
293
  }
294
 
295
 
 
305
  for record in records
306
  }
307
  method = args.baseline
308
+ buy_and_hold = args.baseline == "equal_weight"
309
  else:
310
  weights_by_id = load_predictions(args.predictions.resolve())
 
 
 
 
311
  method = str(args.predictions)
312
+ buy_and_hold = False
313
 
314
+ metrics = evaluate(
315
+ records,
316
+ weights_by_id,
317
+ args.transaction_cost,
318
+ buy_and_hold=buy_and_hold,
319
+ )
320
  print(json.dumps({"method": method, **metrics}, indent=2, allow_nan=False))
321
 
322
 
323
  if __name__ == "__main__":
324
  main()
 
scripts/generate.py CHANGED
@@ -5,7 +5,7 @@ from __future__ import annotations
5
 
6
  import argparse
7
  import json
8
- from datetime import datetime, timedelta, timezone
9
  from pathlib import Path
10
 
11
  import numpy as np
@@ -13,7 +13,12 @@ import pandas as pd
13
 
14
  from common import (
15
  ASSETS,
 
 
16
  COINS,
 
 
 
17
  REBALANCE_DAYS,
18
  STRATEGIES,
19
  TRANSACTION_COST,
@@ -123,9 +128,14 @@ def split_dates(
123
  ) -> list[pd.Timestamp]:
124
  configured_start, configured_end = SPLIT_BOUNDS[split]
125
  history_ready = common_dates.min() + pd.Timedelta(days=61)
126
- start = max(history_ready, configured_start) if configured_start is not None else history_ready
127
- latest_execution = common_dates.max() - pd.Timedelta(days=REBALANCE_DAYS)
128
- end = min(configured_end, latest_execution)
 
 
 
 
 
129
  if start > end:
130
  raise ValueError(f"{split}: no dates available between {start} and {end}")
131
 
@@ -153,11 +163,23 @@ def make_record(
153
 
154
  as_of_timestamp = execution.to_pydatetime() - timedelta(microseconds=1)
155
  exit_date = execution + pd.Timedelta(days=REBALANCE_DAYS)
156
- next_returns = []
157
- for coin in COINS:
158
- entry = scalar_at(frames[coin], execution, "open")
159
- exit_price = scalar_at(frames[coin], exit_date, "open")
160
- next_returns.append(round(exit_price / entry - 1.0, 10))
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  proposals = compute_proposals(history, sentiment, as_of_timestamp)
163
  if [proposal["strategy"] for proposal in proposals] != list(STRATEGIES):
@@ -168,8 +190,10 @@ def make_record(
168
  "split": split,
169
  "as_of": as_of_timestamp.astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),
170
  "execution_at": execution.isoformat().replace("+00:00", "Z"),
 
171
  "assets": list(ASSETS),
172
  "strategy_proposals": proposals,
 
173
  "next_7d_returns": next_returns,
174
  }
175
 
@@ -193,6 +217,14 @@ def main() -> None:
193
  ]
194
  split_records[split] = records
195
 
 
 
 
 
 
 
 
 
196
  output_dir.mkdir(parents=True, exist_ok=True)
197
  for split, records in split_records.items():
198
  write_jsonl(output_dir / f"{split}.jsonl", records)
@@ -202,15 +234,30 @@ def main() -> None:
202
  for coin in COINS
203
  }
204
  source_hashes[sentiment_file.name] = sha256_file(sentiment_file)
 
 
 
 
 
 
 
 
 
 
 
 
205
  manifest = {
206
  "dataset": "QuantInvBench",
207
- "version": "1.0.0",
208
- "generated_at": datetime.now(timezone.utc).isoformat(),
209
  "assets": list(ASSETS),
210
  "strategies": list(STRATEGIES),
211
  "rebalance_days": REBALANCE_DAYS,
 
212
  "transaction_cost": TRANSACTION_COST,
213
- "splits": {split: len(records) for split, records in split_records.items()},
 
 
 
214
  "data_sha256": {
215
  f"{split}.jsonl": sha256_file(output_dir / f"{split}.jsonl")
216
  for split in split_records
 
5
 
6
  import argparse
7
  import json
8
+ from datetime import timedelta, timezone
9
  from pathlib import Path
10
 
11
  import numpy as np
 
13
 
14
  from common import (
15
  ASSETS,
16
+ ATTACK_PROTOCOL_VERSION,
17
+ BENCHMARK_VERSION,
18
  COINS,
19
+ EVALUATION_PROTOCOL,
20
+ EXPECTED_SPLIT_COUNTS,
21
+ EXPECTED_SPLIT_RANGES,
22
  REBALANCE_DAYS,
23
  STRATEGIES,
24
  TRANSACTION_COST,
 
128
  ) -> list[pd.Timestamp]:
129
  configured_start, configured_end = SPLIT_BOUNDS[split]
130
  history_ready = common_dates.min() + pd.Timedelta(days=61)
131
+ start = (
132
+ max(history_ready, configured_start)
133
+ if configured_start is not None
134
+ else history_ready
135
+ )
136
+ latest_source_execution = common_dates.max() - pd.Timedelta(days=REBALANCE_DAYS)
137
+ latest_split_execution = configured_end - pd.Timedelta(days=REBALANCE_DAYS)
138
+ end = min(latest_split_execution, latest_source_execution)
139
  if start > end:
140
  raise ValueError(f"{split}: no dates available between {start} and {end}")
141
 
 
163
 
164
  as_of_timestamp = execution.to_pydatetime() - timedelta(microseconds=1)
165
  exit_date = execution + pd.Timedelta(days=REBALANCE_DAYS)
166
+ daily_returns = []
167
+ for offset in range(REBALANCE_DAYS):
168
+ entry_date = execution + pd.Timedelta(days=offset)
169
+ daily_exit_date = entry_date + pd.Timedelta(days=1)
170
+ daily_returns.append(
171
+ [
172
+ round(
173
+ scalar_at(frames[coin], daily_exit_date, "open")
174
+ / scalar_at(frames[coin], entry_date, "open")
175
+ - 1.0,
176
+ 10,
177
+ )
178
+ for coin in COINS
179
+ ]
180
+ )
181
+ next_returns = np.prod(1.0 + np.asarray(daily_returns), axis=0) - 1.0
182
+ next_returns = [round(float(value), 10) for value in next_returns]
183
 
184
  proposals = compute_proposals(history, sentiment, as_of_timestamp)
185
  if [proposal["strategy"] for proposal in proposals] != list(STRATEGIES):
 
190
  "split": split,
191
  "as_of": as_of_timestamp.astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),
192
  "execution_at": execution.isoformat().replace("+00:00", "Z"),
193
+ "label_end_at": exit_date.isoformat().replace("+00:00", "Z"),
194
  "assets": list(ASSETS),
195
  "strategy_proposals": proposals,
196
+ "next_7d_daily_returns": daily_returns,
197
  "next_7d_returns": next_returns,
198
  }
199
 
 
217
  ]
218
  split_records[split] = records
219
 
220
+ actual_counts = {
221
+ split: len(records) for split, records in split_records.items()
222
+ }
223
+ if actual_counts != EXPECTED_SPLIT_COUNTS:
224
+ raise ValueError(
225
+ f"split counts changed: expected {EXPECTED_SPLIT_COUNTS}, got {actual_counts}"
226
+ )
227
+
228
  output_dir.mkdir(parents=True, exist_ok=True)
229
  for split, records in split_records.items():
230
  write_jsonl(output_dir / f"{split}.jsonl", records)
 
234
  for coin in COINS
235
  }
236
  source_hashes[sentiment_file.name] = sha256_file(sentiment_file)
237
+ split_ranges = {
238
+ split: {
239
+ "execution_start": records[0]["execution_at"],
240
+ "execution_end": records[-1]["execution_at"],
241
+ "label_end": records[-1]["label_end_at"],
242
+ }
243
+ for split, records in split_records.items()
244
+ }
245
+ if split_ranges != EXPECTED_SPLIT_RANGES:
246
+ raise ValueError(
247
+ f"split ranges changed: expected {EXPECTED_SPLIT_RANGES}, got {split_ranges}"
248
+ )
249
  manifest = {
250
  "dataset": "QuantInvBench",
251
+ "version": BENCHMARK_VERSION,
 
252
  "assets": list(ASSETS),
253
  "strategies": list(STRATEGIES),
254
  "rebalance_days": REBALANCE_DAYS,
255
+ "label_horizon_days": REBALANCE_DAYS,
256
  "transaction_cost": TRANSACTION_COST,
257
+ "splits": actual_counts,
258
+ "split_ranges": split_ranges,
259
+ "evaluation_protocol": EVALUATION_PROTOCOL,
260
+ "attack_protocol": ATTACK_PROTOCOL_VERSION,
261
  "data_sha256": {
262
  f"{split}.jsonl": sha256_file(output_dir / f"{split}.jsonl")
263
  for split in split_records
scripts/strategies.py CHANGED
@@ -10,6 +10,7 @@ from typing import Mapping
10
 
11
  import numpy as np
12
  import pandas as pd
 
13
 
14
  from common import COINS, STRATEGIES, usdt_fallback, validated_weights
15
 
@@ -85,6 +86,45 @@ def risk_parity(history: History, lookback: int = 60) -> list[float]:
85
  return _normalize(inverse_volatility, "RiskParity")
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  class SentimentIndex:
89
  """Precomputed FinBERT scores indexed without retaining article text."""
90
 
@@ -193,6 +233,7 @@ def compute_proposals(
193
  "TSMom14": ts_momentum(history, 14, "TSMom14"),
194
  "TSMom60": ts_momentum(history, 60, "TSMom60"),
195
  "RiskParity": risk_parity(history),
 
196
  "NewsSentiment": sentiment.weights(as_of),
197
  "Size": size(history),
198
  "ValueNVT": value_nvt(history),
 
10
 
11
  import numpy as np
12
  import pandas as pd
13
+ from scipy.optimize import minimize
14
 
15
  from common import COINS, STRATEGIES, usdt_fallback, validated_weights
16
 
 
86
  return _normalize(inverse_volatility, "RiskParity")
87
 
88
 
89
+ def min_variance(history: History, lookback: int = 60) -> list[float]:
90
+ return_series = []
91
+ for coin in COINS:
92
+ prices = history[coin]["open"].tail(lookback + 1).to_numpy(dtype=float)
93
+ if len(prices) < 11 or np.any(prices[:-1] <= 0):
94
+ raise ValueError(f"MinVar: insufficient price history for {coin}")
95
+ return_series.append(np.diff(prices) / prices[:-1])
96
+
97
+ common_length = min(len(values) for values in return_series)
98
+ matrix = np.column_stack([values[-common_length:] for values in return_series])
99
+ covariance = np.atleast_2d(np.cov(matrix, rowvar=False))
100
+ if covariance.shape != (len(COINS), len(COINS)) or not np.isfinite(
101
+ covariance
102
+ ).all():
103
+ raise ValueError("MinVar: invalid covariance matrix")
104
+
105
+ # Scaling preserves the optimum while keeping SLSQP's stopping criteria
106
+ # meaningful for daily return covariances, which are typically very small.
107
+ scale = float(np.max(np.abs(covariance)))
108
+ scaled_covariance = covariance / scale if scale > 0 else covariance
109
+ initial = np.full(len(COINS), 1.0 / len(COINS), dtype=float)
110
+ result = minimize(
111
+ fun=lambda weights: float(weights @ scaled_covariance @ weights),
112
+ x0=initial,
113
+ jac=lambda weights: 2.0 * scaled_covariance @ weights,
114
+ method="SLSQP",
115
+ bounds=[(0.0, 1.0)] * len(COINS),
116
+ constraints={
117
+ "type": "eq",
118
+ "fun": lambda weights: float(np.sum(weights) - 1.0),
119
+ "jac": lambda weights: np.ones_like(weights),
120
+ },
121
+ options={"ftol": 1e-12, "maxiter": 1_000, "disp": False},
122
+ )
123
+ if not result.success or not np.isfinite(result.x).all():
124
+ raise ValueError(f"MinVar: optimization failed: {result.message}")
125
+ return _normalize(dict(zip(COINS, result.x.tolist())), "MinVar")
126
+
127
+
128
  class SentimentIndex:
129
  """Precomputed FinBERT scores indexed without retaining article text."""
130
 
 
233
  "TSMom14": ts_momentum(history, 14, "TSMom14"),
234
  "TSMom60": ts_momentum(history, 60, "TSMom60"),
235
  "RiskParity": risk_parity(history),
236
+ "MinVar": min_variance(history),
237
  "NewsSentiment": sentiment.weights(as_of),
238
  "Size": size(history),
239
  "ValueNVT": value_nvt(history),
scripts/validate.py CHANGED
@@ -13,7 +13,20 @@ from pathlib import Path
13
 
14
  import pandas as pd
15
 
16
- from common import ASSETS, REBALANCE_DAYS, STRATEGIES, WEIGHT_TOLERANCE, read_jsonl, sha256_file
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
 
19
  ID_PATTERN = re.compile(r"^quantinv_(train|validation|test)_\d{4}_\d{8}$")
@@ -22,8 +35,10 @@ REQUIRED_FIELDS = {
22
  "split",
23
  "as_of",
24
  "execution_at",
 
25
  "assets",
26
  "strategy_proposals",
 
27
  "next_7d_returns",
28
  }
29
 
@@ -70,7 +85,12 @@ def validate_weights(values: object, label: str, result: Validation) -> None:
70
  )
71
 
72
 
73
- def validate_record(record: dict, split: str, index: int, result: Validation) -> datetime | None:
 
 
 
 
 
74
  label = f"{split}[{index}]"
75
  result.check(set(record) == REQUIRED_FIELDS, f"{label}: fields do not match schema")
76
  result.check(record.get("split") == split, f"{label}: wrong split value")
@@ -81,16 +101,28 @@ def validate_record(record: dict, split: str, index: int, result: Validation) ->
81
  try:
82
  as_of = parse_timestamp(record.get("as_of"), f"{label}.as_of")
83
  execution = parse_timestamp(record.get("execution_at"), f"{label}.execution_at")
 
84
  result.check(as_of < execution, f"{label}: as_of must precede execution_at")
85
  result.check(execution - as_of <= timedelta(seconds=1), f"{label}: unexpected decision gap")
 
 
 
 
 
 
 
86
  except (TypeError, ValueError) as exc:
87
  result.check(False, str(exc))
88
  execution = None
 
89
 
90
  proposals = record.get("strategy_proposals")
91
  result.check(isinstance(proposals, list), f"{label}: strategy_proposals must be a list")
92
  if isinstance(proposals, list):
93
- result.check(len(proposals) == len(STRATEGIES), f"{label}: expected nine strategies")
 
 
 
94
  names = [proposal.get("strategy") for proposal in proposals if isinstance(proposal, dict)]
95
  result.check(names == list(STRATEGIES), f"{label}: strategy roster/order changed")
96
  for proposal_index, proposal in enumerate(proposals):
@@ -102,12 +134,52 @@ def validate_record(record: dict, split: str, index: int, result: Validation) ->
102
 
103
  returns = record.get("next_7d_returns")
104
  result.check(isinstance(returns, list) and len(returns) == len(ASSETS), f"{label}: invalid returns")
 
105
  if isinstance(returns, list) and len(returns) == len(ASSETS):
106
- result.check(
107
- all(isinstance(value, (int, float)) and math.isfinite(float(value)) for value in returns),
108
- f"{label}: returns contain invalid values",
 
 
 
109
  )
110
- return execution
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
 
113
  def main() -> int:
@@ -131,6 +203,18 @@ def main() -> int:
131
  except (OSError, json.JSONDecodeError) as exc:
132
  result.check(False, f"invalid manifest: {exc}")
133
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  seen_ids = set()
135
  split_ranges = {}
136
  all_records = []
@@ -146,33 +230,51 @@ def main() -> int:
146
  continue
147
  all_records.extend(records)
148
  result.check(bool(records), f"{split}: split is empty")
149
- execution_times = []
150
  for index, record in enumerate(records):
151
  result.check(isinstance(record, dict), f"{split}[{index}]: record must be an object")
152
  if not isinstance(record, dict):
153
  continue
154
- execution = validate_record(record, split, index, result)
155
- if execution is not None:
156
- execution_times.append(execution)
157
  identifier = record.get("id")
158
  result.check(identifier not in seen_ids, f"duplicate id: {identifier}")
159
  seen_ids.add(identifier)
160
 
 
161
  result.check(execution_times == sorted(execution_times), f"{split}: records are not sorted")
162
- for left, right in zip(execution_times, execution_times[1:]):
163
- result.check(right - left == timedelta(days=REBALANCE_DAYS), f"{split}: rebalance interval is not seven days")
164
- if execution_times:
165
- split_ranges[split] = (execution_times[0], execution_times[-1])
 
 
 
 
 
 
 
166
 
167
- expected_count = manifest.get("splits", {}).get(split)
168
  result.check(expected_count == len(records), f"{split}: manifest count does not match")
169
  expected_hash = manifest.get("data_sha256", {}).get(path.name)
170
  result.check(expected_hash == sha256_file(path), f"{split}: SHA-256 does not match manifest")
 
 
 
 
 
 
 
 
 
 
171
 
172
  ordered_ranges = [split_ranges.get(split) for split in ("train", "validation", "test")]
173
  if all(ordered_ranges):
174
- result.check(ordered_ranges[0][1] < ordered_ranges[1][0], "train overlaps validation")
175
- result.check(ordered_ranges[1][1] < ordered_ranges[2][0], "validation overlaps test")
176
 
177
  if args.source_data_dir:
178
  from generate import load_daily_data, scalar_at
@@ -182,6 +284,8 @@ def main() -> int:
182
  execution = parse_timestamp(record["execution_at"], record["id"])
183
  execution_date = pd.Timestamp(execution)
184
  exit_date = execution_date + pd.Timedelta(days=REBALANCE_DAYS)
 
 
185
  for asset_index, coin in enumerate(("bitcoin", "ethereum", "tether", "xrp", "bnb")):
186
  entry = scalar_at(frames[coin], execution_date, "open")
187
  exit_price = scalar_at(frames[coin], exit_date, "open")
@@ -191,6 +295,17 @@ def main() -> int:
191
  abs(expected - actual) <= 1e-9,
192
  f"{record['id']}: {ASSETS[asset_index]} next_7d_returns does not match source",
193
  )
 
 
 
 
 
 
 
 
 
 
 
194
 
195
  if result.errors:
196
  for error in result.errors:
 
13
 
14
  import pandas as pd
15
 
16
+ from common import (
17
+ ASSETS,
18
+ ATTACK_PROTOCOL_VERSION,
19
+ BENCHMARK_VERSION,
20
+ EVALUATION_PROTOCOL,
21
+ EXPECTED_SPLIT_COUNTS,
22
+ EXPECTED_SPLIT_RANGES,
23
+ REBALANCE_DAYS,
24
+ STRATEGIES,
25
+ TRANSACTION_COST,
26
+ WEIGHT_TOLERANCE,
27
+ read_jsonl,
28
+ sha256_file,
29
+ )
30
 
31
 
32
  ID_PATTERN = re.compile(r"^quantinv_(train|validation|test)_\d{4}_\d{8}$")
 
35
  "split",
36
  "as_of",
37
  "execution_at",
38
+ "label_end_at",
39
  "assets",
40
  "strategy_proposals",
41
+ "next_7d_daily_returns",
42
  "next_7d_returns",
43
  }
44
 
 
85
  )
86
 
87
 
88
+ def validate_record(
89
+ record: dict,
90
+ split: str,
91
+ index: int,
92
+ result: Validation,
93
+ ) -> tuple[datetime | None, datetime | None]:
94
  label = f"{split}[{index}]"
95
  result.check(set(record) == REQUIRED_FIELDS, f"{label}: fields do not match schema")
96
  result.check(record.get("split") == split, f"{label}: wrong split value")
 
101
  try:
102
  as_of = parse_timestamp(record.get("as_of"), f"{label}.as_of")
103
  execution = parse_timestamp(record.get("execution_at"), f"{label}.execution_at")
104
+ label_end = parse_timestamp(record.get("label_end_at"), f"{label}.label_end_at")
105
  result.check(as_of < execution, f"{label}: as_of must precede execution_at")
106
  result.check(execution - as_of <= timedelta(seconds=1), f"{label}: unexpected decision gap")
107
+ result.check(
108
+ label_end - execution == timedelta(days=REBALANCE_DAYS),
109
+ f"{label}: label horizon is not seven days",
110
+ )
111
+ if isinstance(identifier, str):
112
+ expected_id = f"quantinv_{split}_{index:04d}_{execution:%Y%m%d}"
113
+ result.check(identifier == expected_id, f"{label}: id does not match split/index/date")
114
  except (TypeError, ValueError) as exc:
115
  result.check(False, str(exc))
116
  execution = None
117
+ label_end = None
118
 
119
  proposals = record.get("strategy_proposals")
120
  result.check(isinstance(proposals, list), f"{label}: strategy_proposals must be a list")
121
  if isinstance(proposals, list):
122
+ result.check(
123
+ len(proposals) == len(STRATEGIES),
124
+ f"{label}: expected {len(STRATEGIES)} strategies",
125
+ )
126
  names = [proposal.get("strategy") for proposal in proposals if isinstance(proposal, dict)]
127
  result.check(names == list(STRATEGIES), f"{label}: strategy roster/order changed")
128
  for proposal_index, proposal in enumerate(proposals):
 
134
 
135
  returns = record.get("next_7d_returns")
136
  result.check(isinstance(returns, list) and len(returns) == len(ASSETS), f"{label}: invalid returns")
137
+ endpoint_returns_valid = False
138
  if isinstance(returns, list) and len(returns) == len(ASSETS):
139
+ endpoint_returns_valid = all(
140
+ isinstance(value, (int, float))
141
+ and not isinstance(value, bool)
142
+ and math.isfinite(float(value))
143
+ and float(value) > -1.0
144
+ for value in returns
145
  )
146
+ result.check(endpoint_returns_valid, f"{label}: returns contain invalid values")
147
+
148
+ daily_returns = record.get("next_7d_daily_returns")
149
+ result.check(
150
+ isinstance(daily_returns, list) and len(daily_returns) == REBALANCE_DAYS,
151
+ f"{label}: next_7d_daily_returns must contain seven rows",
152
+ )
153
+ daily_returns_valid = False
154
+ if isinstance(daily_returns, list) and len(daily_returns) == REBALANCE_DAYS:
155
+ rows_valid = []
156
+ for day_index, row in enumerate(daily_returns):
157
+ row_valid = (
158
+ isinstance(row, list)
159
+ and len(row) == len(ASSETS)
160
+ and all(
161
+ isinstance(value, (int, float))
162
+ and not isinstance(value, bool)
163
+ and math.isfinite(float(value))
164
+ and float(value) > -1.0
165
+ for value in row
166
+ )
167
+ )
168
+ result.check(row_valid, f"{label}.next_7d_daily_returns[{day_index}]: invalid row")
169
+ rows_valid.append(row_valid)
170
+ daily_returns_valid = all(rows_valid)
171
+
172
+ if endpoint_returns_valid and daily_returns_valid:
173
+ for asset_index, asset in enumerate(ASSETS):
174
+ compounded = math.prod(
175
+ 1.0 + float(daily_returns[day_index][asset_index])
176
+ for day_index in range(REBALANCE_DAYS)
177
+ ) - 1.0
178
+ result.check(
179
+ abs(compounded - float(returns[asset_index])) <= 1e-8,
180
+ f"{label}: {asset} endpoint return does not compound from daily returns",
181
+ )
182
+ return execution, label_end
183
 
184
 
185
  def main() -> int:
 
203
  except (OSError, json.JSONDecodeError) as exc:
204
  result.check(False, f"invalid manifest: {exc}")
205
 
206
+ result.check(manifest.get("dataset") == "QuantInvBench", "manifest: wrong dataset name")
207
+ result.check(manifest.get("version") == BENCHMARK_VERSION, f"manifest: expected benchmark version {BENCHMARK_VERSION}")
208
+ result.check(manifest.get("assets") == list(ASSETS), "manifest: asset roster/order changed")
209
+ result.check(manifest.get("strategies") == list(STRATEGIES), "manifest: strategy roster/order changed")
210
+ result.check(manifest.get("rebalance_days") == REBALANCE_DAYS, "manifest: wrong rebalance period")
211
+ result.check(manifest.get("label_horizon_days") == REBALANCE_DAYS, "manifest: wrong label horizon")
212
+ result.check(manifest.get("transaction_cost") == TRANSACTION_COST, "manifest: wrong transaction cost")
213
+ result.check(manifest.get("splits") == EXPECTED_SPLIT_COUNTS, "manifest: wrong fixed split counts")
214
+ result.check(manifest.get("split_ranges") == EXPECTED_SPLIT_RANGES, "manifest: wrong fixed split ranges")
215
+ result.check(manifest.get("evaluation_protocol") == EVALUATION_PROTOCOL, "manifest: wrong evaluation protocol")
216
+ result.check(manifest.get("attack_protocol") == ATTACK_PROTOCOL_VERSION, "manifest: wrong attack protocol")
217
+
218
  seen_ids = set()
219
  split_ranges = {}
220
  all_records = []
 
230
  continue
231
  all_records.extend(records)
232
  result.check(bool(records), f"{split}: split is empty")
233
+ periods = []
234
  for index, record in enumerate(records):
235
  result.check(isinstance(record, dict), f"{split}[{index}]: record must be an object")
236
  if not isinstance(record, dict):
237
  continue
238
+ execution, label_end = validate_record(record, split, index, result)
239
+ if execution is not None and label_end is not None:
240
+ periods.append((execution, label_end))
241
  identifier = record.get("id")
242
  result.check(identifier not in seen_ids, f"duplicate id: {identifier}")
243
  seen_ids.add(identifier)
244
 
245
+ execution_times = [execution for execution, _ in periods]
246
  result.check(execution_times == sorted(execution_times), f"{split}: records are not sorted")
247
+ for (left_execution, left_end), (right_execution, _) in zip(periods, periods[1:]):
248
+ result.check(
249
+ right_execution - left_execution == timedelta(days=REBALANCE_DAYS),
250
+ f"{split}: rebalance interval is not seven days",
251
+ )
252
+ result.check(
253
+ left_end == right_execution,
254
+ f"{split}: holding periods are not contiguous",
255
+ )
256
+ if periods:
257
+ split_ranges[split] = (periods[0][0], periods[-1][1])
258
 
259
+ expected_count = EXPECTED_SPLIT_COUNTS[split]
260
  result.check(expected_count == len(records), f"{split}: manifest count does not match")
261
  expected_hash = manifest.get("data_sha256", {}).get(path.name)
262
  result.check(expected_hash == sha256_file(path), f"{split}: SHA-256 does not match manifest")
263
+ if periods:
264
+ expected_range = {
265
+ "execution_start": records[0]["execution_at"],
266
+ "execution_end": records[-1]["execution_at"],
267
+ "label_end": records[-1]["label_end_at"],
268
+ }
269
+ result.check(
270
+ manifest.get("split_ranges", {}).get(split) == expected_range,
271
+ f"{split}: manifest range does not match records",
272
+ )
273
 
274
  ordered_ranges = [split_ranges.get(split) for split in ("train", "validation", "test")]
275
  if all(ordered_ranges):
276
+ result.check(ordered_ranges[0][1] < ordered_ranges[1][0], "train labels overlap validation")
277
+ result.check(ordered_ranges[1][1] < ordered_ranges[2][0], "validation labels overlap test")
278
 
279
  if args.source_data_dir:
280
  from generate import load_daily_data, scalar_at
 
284
  execution = parse_timestamp(record["execution_at"], record["id"])
285
  execution_date = pd.Timestamp(execution)
286
  exit_date = execution_date + pd.Timedelta(days=REBALANCE_DAYS)
287
+ label_end = parse_timestamp(record["label_end_at"], record["id"])
288
+ result.check(pd.Timestamp(label_end) == exit_date, f"{record['id']}: wrong label_end_at")
289
  for asset_index, coin in enumerate(("bitcoin", "ethereum", "tether", "xrp", "bnb")):
290
  entry = scalar_at(frames[coin], execution_date, "open")
291
  exit_price = scalar_at(frames[coin], exit_date, "open")
 
295
  abs(expected - actual) <= 1e-9,
296
  f"{record['id']}: {ASSETS[asset_index]} next_7d_returns does not match source",
297
  )
298
+ for day_index in range(REBALANCE_DAYS):
299
+ day_start = execution_date + pd.Timedelta(days=day_index)
300
+ day_end = day_start + pd.Timedelta(days=1)
301
+ start_price = scalar_at(frames[coin], day_start, "open")
302
+ end_price = scalar_at(frames[coin], day_end, "open")
303
+ expected_daily = end_price / start_price - 1.0
304
+ actual_daily = record["next_7d_daily_returns"][day_index][asset_index]
305
+ result.check(
306
+ abs(expected_daily - actual_daily) <= 1e-9,
307
+ f"{record['id']}: {ASSETS[asset_index]} day {day_index} return does not match source",
308
+ )
309
 
310
  if result.errors:
311
  for error in result.errors:
tests/test_release.py CHANGED
@@ -1,6 +1,7 @@
1
  from __future__ import annotations
2
 
3
  import json
 
4
  import sys
5
  import tempfile
6
  import unittest
@@ -11,15 +12,91 @@ import numpy as np
11
  import pandas as pd
12
 
13
 
14
- SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts"
 
 
15
  sys.path.insert(0, str(SCRIPT_DIR))
16
 
17
- from common import ASSETS, STRATEGIES # noqa: E402
18
- from evaluate import evaluate # noqa: E402
 
 
 
 
 
 
 
 
 
19
  from strategies import SentimentIndex, compute_proposals # noqa: E402
20
 
21
 
22
- class ReleaseTests(unittest.TestCase):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def make_history(self) -> dict[str, pd.DataFrame]:
24
  dates = pd.date_range("2023-01-01", periods=320, tz="UTC")
25
  frames = {}
@@ -59,7 +136,10 @@ class ReleaseTests(unittest.TestCase):
59
  )
60
  return SentimentIndex(path)
61
 
62
- def test_all_strategies_return_valid_weights(self) -> None:
 
 
 
63
  with tempfile.TemporaryDirectory() as temporary_directory:
64
  sentiment = self.make_sentiment(Path(temporary_directory))
65
  proposals = compute_proposals(
@@ -67,23 +147,281 @@ class ReleaseTests(unittest.TestCase):
67
  sentiment,
68
  datetime(2023, 11, 16, tzinfo=timezone.utc),
69
  )
70
- self.assertEqual([proposal["strategy"] for proposal in proposals], list(STRATEGIES))
 
 
 
 
71
  for proposal in proposals:
72
  self.assertEqual(len(proposal["weights"]), len(ASSETS))
73
  self.assertAlmostEqual(sum(proposal["weights"]), 1.0, places=6)
74
- self.assertTrue(all(weight >= 0 for weight in proposal["weights"]))
 
75
 
76
- def test_evaluator_equal_weight(self) -> None:
77
- record = {
78
- "id": "sample",
79
- "next_7d_returns": [0.1, 0.0, 0.0, 0.0, 0.0],
 
 
 
 
 
 
 
 
 
 
 
80
  }
81
- weights = {"sample": [0.2] * 5}
82
- metrics = evaluate([record], weights, transaction_cost=0.001)
83
- self.assertAlmostEqual(metrics["cumulative_return"], 0.02)
84
- self.assertEqual(metrics["max_drawdown"], 0.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
 
87
  if __name__ == "__main__":
88
  unittest.main()
89
-
 
1
  from __future__ import annotations
2
 
3
  import json
4
+ import math
5
  import sys
6
  import tempfile
7
  import unittest
 
12
  import pandas as pd
13
 
14
 
15
+ RELEASE_ROOT = Path(__file__).resolve().parents[1]
16
+ SCRIPT_DIR = RELEASE_ROOT / "scripts"
17
+ DATA_DIR = RELEASE_ROOT / "data"
18
  sys.path.insert(0, str(SCRIPT_DIR))
19
 
20
+ from attacks import MIXED_ROLES, apply_attacks # noqa: E402
21
+ from common import ( # noqa: E402
22
+ ASSETS,
23
+ BENCHMARK_VERSION,
24
+ EXPECTED_SPLIT_COUNTS,
25
+ REBALANCE_DAYS,
26
+ STRATEGIES,
27
+ read_jsonl,
28
+ )
29
+ from evaluate import evaluate, strict_weights # noqa: E402
30
+ from generate import SPLIT_BOUNDS # noqa: E402
31
  from strategies import SentimentIndex, compute_proposals # noqa: E402
32
 
33
 
34
+ EXPECTED_STRATEGIES = (
35
+ "Momentum",
36
+ "MaxSharpe",
37
+ "TSMom14",
38
+ "TSMom60",
39
+ "RiskParity",
40
+ "MinVar",
41
+ "NewsSentiment",
42
+ "Size",
43
+ "ValueNVT",
44
+ "Liquidity",
45
+ )
46
+ EXPECTED_COUNTS = {"train": 297, "validation": 52, "test": 52}
47
+ EXPECTED_MIXED_ROLES = ("reverse", "bias", "drift")
48
+ EXPECTED_VERSION = "2.0.0"
49
+
50
+
51
+ def evaluation_record(identifier: str, daily_returns: list[list[float]]) -> dict:
52
+ return {
53
+ "id": identifier,
54
+ "assets": list(ASSETS),
55
+ "next_7d_daily_returns": daily_returns,
56
+ }
57
+
58
+
59
+ def daily_path(*rows: list[float]) -> list[list[float]]:
60
+ path = [list(row) for row in rows]
61
+ path.extend([[0.0] * len(ASSETS) for _ in range(REBALANCE_DAYS - len(path))])
62
+ return path
63
+
64
+
65
+ def attack_records(rounds: int) -> list[dict]:
66
+ records = []
67
+ for round_index in range(rounds):
68
+ proposals = []
69
+ for strategy_index, strategy in enumerate(STRATEGIES):
70
+ raw = [
71
+ 1.0 + ((strategy_index + asset_index + round_index) % len(ASSETS))
72
+ for asset_index in range(len(ASSETS))
73
+ ]
74
+ total = sum(raw)
75
+ proposals.append(
76
+ {
77
+ "strategy": strategy,
78
+ "weights": [value / total for value in raw],
79
+ }
80
+ )
81
+ records.append(
82
+ {
83
+ "id": f"round_{round_index + 1:04d}",
84
+ "assets": list(ASSETS),
85
+ "strategy_proposals": proposals,
86
+ }
87
+ )
88
+ return records
89
+
90
+
91
+ def proposal_weights(record: dict, strategy: str) -> list[float]:
92
+ return next(
93
+ proposal["weights"]
94
+ for proposal in record["strategy_proposals"]
95
+ if proposal["strategy"] == strategy
96
+ )
97
+
98
+
99
+ class StrategyContractTests(unittest.TestCase):
100
  def make_history(self) -> dict[str, pd.DataFrame]:
101
  dates = pd.date_range("2023-01-01", periods=320, tz="UTC")
102
  frames = {}
 
136
  )
137
  return SentimentIndex(path)
138
 
139
+ def test_fixed_ten_strategy_roster_includes_minvar(self) -> None:
140
+ self.assertEqual(STRATEGIES, EXPECTED_STRATEGIES)
141
+ self.assertEqual(len(STRATEGIES), 10)
142
+
143
  with tempfile.TemporaryDirectory() as temporary_directory:
144
  sentiment = self.make_sentiment(Path(temporary_directory))
145
  proposals = compute_proposals(
 
147
  sentiment,
148
  datetime(2023, 11, 16, tzinfo=timezone.utc),
149
  )
150
+
151
+ self.assertEqual(
152
+ [proposal["strategy"] for proposal in proposals],
153
+ list(EXPECTED_STRATEGIES),
154
+ )
155
  for proposal in proposals:
156
  self.assertEqual(len(proposal["weights"]), len(ASSETS))
157
  self.assertAlmostEqual(sum(proposal["weights"]), 1.0, places=6)
158
+ self.assertTrue(all(weight >= 0.0 for weight in proposal["weights"]))
159
+
160
 
161
+ class ReleaseDataContractTests(unittest.TestCase):
162
+ def test_manifest_declares_frozen_release_contract(self) -> None:
163
+ with (DATA_DIR / "manifest.json").open(encoding="utf-8") as handle:
164
+ manifest = json.load(handle)
165
+
166
+ self.assertEqual(BENCHMARK_VERSION, EXPECTED_VERSION)
167
+ self.assertEqual(EXPECTED_SPLIT_COUNTS, EXPECTED_COUNTS)
168
+ self.assertEqual(manifest["version"], EXPECTED_VERSION)
169
+ self.assertEqual(manifest["splits"], EXPECTED_COUNTS)
170
+ self.assertEqual(manifest["strategies"], list(EXPECTED_STRATEGIES))
171
+
172
+ def test_formal_splits_have_purged_labels_and_compounded_returns(self) -> None:
173
+ records_by_split = {
174
+ split: read_jsonl(DATA_DIR / f"{split}.jsonl")
175
+ for split in EXPECTED_COUNTS
176
  }
177
+ self.assertEqual(
178
+ {split: len(records) for split, records in records_by_split.items()},
179
+ EXPECTED_COUNTS,
180
+ )
181
+
182
+ for split, records in records_by_split.items():
183
+ configured_start, configured_end = SPLIT_BOUNDS[split]
184
+ for record in records:
185
+ with self.subTest(split=split, identifier=record.get("id")):
186
+ self.assertEqual(record["split"], split)
187
+ self.assertEqual(record["assets"], list(ASSETS))
188
+ self.assertEqual(
189
+ [
190
+ proposal["strategy"]
191
+ for proposal in record["strategy_proposals"]
192
+ ],
193
+ list(EXPECTED_STRATEGIES),
194
+ )
195
+
196
+ execution = pd.Timestamp(record["execution_at"])
197
+ label_end = pd.Timestamp(record["label_end_at"])
198
+ self.assertEqual(
199
+ label_end - execution,
200
+ pd.Timedelta(days=REBALANCE_DAYS),
201
+ )
202
+ if configured_start is not None:
203
+ self.assertGreaterEqual(execution, configured_start)
204
+ self.assertLessEqual(label_end, configured_end)
205
+
206
+ daily_returns = np.asarray(
207
+ record["next_7d_daily_returns"], dtype=float
208
+ )
209
+ self.assertEqual(
210
+ daily_returns.shape,
211
+ (REBALANCE_DAYS, len(ASSETS)),
212
+ )
213
+ self.assertTrue(np.isfinite(daily_returns).all())
214
+ compounded = np.prod(1.0 + daily_returns, axis=0) - 1.0
215
+ np.testing.assert_allclose(
216
+ record["next_7d_returns"],
217
+ compounded,
218
+ rtol=0.0,
219
+ atol=1e-9,
220
+ )
221
+
222
+ split_order = ("train", "validation", "test")
223
+ for previous_split, next_split in zip(split_order, split_order[1:]):
224
+ previous_label_end = max(
225
+ pd.Timestamp(record["label_end_at"])
226
+ for record in records_by_split[previous_split]
227
+ )
228
+ next_execution = min(
229
+ pd.Timestamp(record["execution_at"])
230
+ for record in records_by_split[next_split]
231
+ )
232
+ self.assertLess(previous_label_end, next_execution)
233
+
234
+ test_records = records_by_split["test"]
235
+ self.assertEqual(test_records[0]["execution_at"], "2025-03-16T00:00:00Z")
236
+ self.assertEqual(test_records[-1]["execution_at"], "2026-03-08T00:00:00Z")
237
+ self.assertEqual(test_records[-1]["label_end_at"], "2026-03-15T00:00:00Z")
238
+
239
+
240
+ class EvaluationContractTests(unittest.TestCase):
241
+ def test_equal_weight_buy_and_hold_never_rebalances(self) -> None:
242
+ records = [
243
+ evaluation_record("week_1", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
244
+ evaluation_record("week_2", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
245
+ ]
246
+ equal_targets = {record["id"]: [0.2] * len(ASSETS) for record in records}
247
+
248
+ held = evaluate(records, equal_targets, 0.0, buy_and_hold=True)
249
+ rebalanced = evaluate(records, equal_targets, 0.0)
250
+
251
+ self.assertAlmostEqual(held["cumulative_return"], 0.6)
252
+ self.assertAlmostEqual(held["average_turnover"], 0.0)
253
+ self.assertAlmostEqual(rebalanced["cumulative_return"], 0.44)
254
+ self.assertAlmostEqual(rebalanced["average_turnover"], 1.0 / 15.0)
255
+
256
+ def test_rebalance_turnover_uses_return_drifted_holdings(self) -> None:
257
+ records = [
258
+ evaluation_record("week_1", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
259
+ evaluation_record("week_2", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
260
+ ]
261
+ equal_targets = {record["id"]: [0.2] * len(ASSETS) for record in records}
262
+
263
+ metrics = evaluate(records, equal_targets, 0.01)
264
+
265
+ second_turnover = 2.0 / 15.0
266
+ expected_capital = 1.2 * (1.0 - 0.01 * second_turnover) * 1.2
267
+ self.assertAlmostEqual(metrics["average_turnover"], second_turnover / 2.0)
268
+ self.assertAlmostEqual(metrics["cumulative_return"], expected_capital - 1.0)
269
+
270
+ def test_max_drawdown_uses_daily_nav(self) -> None:
271
+ records = [
272
+ evaluation_record(
273
+ "round_trip",
274
+ daily_path([1.0] * len(ASSETS), [-0.5] * len(ASSETS)),
275
+ )
276
+ ]
277
+ targets = {"round_trip": [0.2] * len(ASSETS)}
278
+
279
+ metrics = evaluate(records, targets, 0.0)
280
+
281
+ self.assertAlmostEqual(metrics["cumulative_return"], 0.0)
282
+ self.assertAlmostEqual(metrics["max_drawdown"], 0.5)
283
+
284
+ def test_sharpe_uses_weekly_returns(self) -> None:
285
+ records = [
286
+ evaluation_record("up_week", daily_path([0.1] * len(ASSETS))),
287
+ evaluation_record("flat_week", daily_path([0.0] * len(ASSETS))),
288
+ ]
289
+ targets = {record["id"]: [0.2] * len(ASSETS) for record in records}
290
+
291
+ metrics = evaluate(records, targets, 0.0)
292
+
293
+ self.assertAlmostEqual(metrics["annualized_sharpe"], math.sqrt(52.0))
294
+
295
+ def test_submitted_weights_are_not_coerced_or_normalized(self) -> None:
296
+ invalid = {
297
+ "boolean": [True, 0.2, 0.2, 0.2, 0.2],
298
+ "string": ["0.2", 0.2, 0.2, 0.2, 0.2],
299
+ "negative": [-0.1, 0.275, 0.275, 0.275, 0.275],
300
+ "not_normalized": [0.1] * len(ASSETS),
301
+ }
302
+ for label, weights in invalid.items():
303
+ with self.subTest(label=label):
304
+ with self.assertRaises(ValueError):
305
+ strict_weights(weights, label=label)
306
+
307
+ self.assertEqual(
308
+ strict_weights([0.2] * len(ASSETS), label="valid"),
309
+ [0.2] * len(ASSETS),
310
+ )
311
+
312
+
313
+ class AttackContractTests(unittest.TestCase):
314
+ def test_reverse_and_bias_match_frozen_formulas(self) -> None:
315
+ clean = attack_records(1)
316
+ malicious_id = STRATEGIES[0]
317
+ honest = [
318
+ proposal["weights"]
319
+ for proposal in clean[0]["strategy_proposals"]
320
+ if proposal["strategy"] != malicious_id
321
+ ]
322
+ honest_mean = np.mean(np.asarray(honest, dtype=float), axis=0)
323
+
324
+ reverse = apply_attacks(
325
+ clean,
326
+ attack="reverse",
327
+ f=1,
328
+ seed=7,
329
+ malicious_ids=[malicious_id],
330
+ )
331
+ bias = apply_attacks(
332
+ clean,
333
+ attack="bias",
334
+ f=1,
335
+ seed=7,
336
+ malicious_ids=[malicious_id],
337
+ )
338
+
339
+ np.testing.assert_allclose(
340
+ proposal_weights(reverse.records[0], malicious_id),
341
+ (1.0 - honest_mean) / (len(ASSETS) - 1),
342
+ rtol=0.0,
343
+ atol=1e-9,
344
+ )
345
+ expected_bias = 0.9 * honest_mean
346
+ expected_bias[ASSETS.index("BTC")] += 0.1
347
+ np.testing.assert_allclose(
348
+ proposal_weights(bias.records[0], malicious_id),
349
+ expected_bias,
350
+ rtol=0.0,
351
+ atol=1e-9,
352
+ )
353
+
354
+ def test_drift_has_twenty_round_warmup_then_frozen_target(self) -> None:
355
+ clean = attack_records(21)
356
+ malicious_id = STRATEGIES[0]
357
+ attacked = apply_attacks(
358
+ clean,
359
+ attack="drift",
360
+ f=1,
361
+ seed=11,
362
+ malicious_ids=[malicious_id],
363
+ )
364
+
365
+ for round_index in range(20):
366
+ self.assertEqual(
367
+ proposal_weights(attacked.records[round_index], malicious_id),
368
+ proposal_weights(clean[round_index], malicious_id),
369
+ )
370
+
371
+ clean_round_21 = np.asarray(
372
+ proposal_weights(clean[20], malicious_id), dtype=float
373
+ )
374
+ target = np.asarray(
375
+ attacked.audit["drift_targets"][malicious_id], dtype=float
376
+ )
377
+ expected_round_21 = 0.98 * clean_round_21 + 0.02 * target
378
+ np.testing.assert_allclose(
379
+ proposal_weights(attacked.records[20], malicious_id),
380
+ expected_round_21,
381
+ rtol=0.0,
382
+ atol=1e-9,
383
+ )
384
+
385
+ def test_mixed_attack_is_deterministic_static_and_label_free(self) -> None:
386
+ clean = attack_records(21)
387
+ first = apply_attacks(clean, attack="mixed", f=3, seed=17)
388
+ second = apply_attacks(clean, attack="mixed", f=3, seed=17)
389
+ self.assertEqual(first, second)
390
+
391
+ explicit_ids = list(STRATEGIES[:3])
392
+ mixed = apply_attacks(
393
+ clean,
394
+ attack="mixed",
395
+ f=3,
396
+ seed=17,
397
+ malicious_ids=explicit_ids,
398
+ )
399
+ self.assertEqual(mixed.audit["malicious_ids"], explicit_ids)
400
+ self.assertEqual(MIXED_ROLES, EXPECTED_MIXED_ROLES)
401
+ self.assertEqual(
402
+ mixed.audit["attack_roles"],
403
+ dict(zip(explicit_ids, EXPECTED_MIXED_ROLES)),
404
+ )
405
+
406
+ honest_ids = set(STRATEGIES) - set(explicit_ids)
407
+ audit_fields = {"attack", "attack_role", "attack_roles", "malicious_ids"}
408
+ for clean_record, attacked_record in zip(clean, mixed.records):
409
+ self.assertTrue(audit_fields.isdisjoint(attacked_record))
410
+ self.assertEqual(
411
+ [
412
+ proposal["strategy"]
413
+ for proposal in attacked_record["strategy_proposals"]
414
+ ],
415
+ list(STRATEGIES),
416
+ )
417
+ for strategy in honest_ids:
418
+ self.assertEqual(
419
+ proposal_weights(attacked_record, strategy),
420
+ proposal_weights(clean_record, strategy),
421
+ )
422
+ for proposal in attacked_record["strategy_proposals"]:
423
+ self.assertTrue(audit_fields.isdisjoint(proposal))
424
 
425
 
426
  if __name__ == "__main__":
427
  unittest.main()