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32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
from __future__ import annotations

import json
import math
import sys
import tempfile
import unittest
from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import pandas as pd


RELEASE_ROOT = Path(__file__).resolve().parents[1]
SCRIPT_DIR = RELEASE_ROOT / "scripts"
DATA_DIR = RELEASE_ROOT / "data"
sys.path.insert(0, str(SCRIPT_DIR))

from attacks import MIXED_ROLES, apply_attacks  # noqa: E402
from common import (  # noqa: E402
    ASSETS,
    BENCHMARK_VERSION,
    EXPECTED_SPLIT_COUNTS,
    REBALANCE_DAYS,
    STRATEGIES,
    read_jsonl,
)
from evaluate import evaluate, strict_weights  # noqa: E402
from generate import SPLIT_BOUNDS  # noqa: E402
from strategies import SentimentIndex, compute_proposals  # noqa: E402


EXPECTED_STRATEGIES = (
    "Momentum",
    "MaxSharpe",
    "TSMom14",
    "TSMom60",
    "RiskParity",
    "MinVar",
    "NewsSentiment",
    "Size",
    "ValueNVT",
    "Liquidity",
)
EXPECTED_COUNTS = {"train": 297, "validation": 52, "test": 52}
EXPECTED_MIXED_ROLES = ("reverse", "bias", "drift")
EXPECTED_VERSION = "2.0.0"


def evaluation_record(identifier: str, daily_returns: list[list[float]]) -> dict:
    return {
        "id": identifier,
        "assets": list(ASSETS),
        "next_7d_daily_returns": daily_returns,
    }


def daily_path(*rows: list[float]) -> list[list[float]]:
    path = [list(row) for row in rows]
    path.extend([[0.0] * len(ASSETS) for _ in range(REBALANCE_DAYS - len(path))])
    return path


def attack_records(rounds: int) -> list[dict]:
    records = []
    for round_index in range(rounds):
        proposals = []
        for strategy_index, strategy in enumerate(STRATEGIES):
            raw = [
                1.0 + ((strategy_index + asset_index + round_index) % len(ASSETS))
                for asset_index in range(len(ASSETS))
            ]
            total = sum(raw)
            proposals.append(
                {
                    "strategy": strategy,
                    "weights": [value / total for value in raw],
                }
            )
        records.append(
            {
                "id": f"round_{round_index + 1:04d}",
                "assets": list(ASSETS),
                "strategy_proposals": proposals,
            }
        )
    return records


def proposal_weights(record: dict, strategy: str) -> list[float]:
    return next(
        proposal["weights"]
        for proposal in record["strategy_proposals"]
        if proposal["strategy"] == strategy
    )


class StrategyContractTests(unittest.TestCase):
    def make_history(self) -> dict[str, pd.DataFrame]:
        dates = pd.date_range("2023-01-01", periods=320, tz="UTC")
        frames = {}
        for index, coin in enumerate(("bitcoin", "ethereum", "tether", "xrp", "bnb")):
            trend = 1.0 + 0.0005 * (index + 1)
            close = (100.0 + index) * np.power(trend, np.arange(len(dates)))
            if coin == "tether":
                close = 1.0 + np.sin(np.arange(len(dates)) / 15.0) * 0.0001
            frames[coin] = pd.DataFrame(
                {
                    "open": close,
                    "high": close * 1.001,
                    "low": close * 0.999,
                    "close": close,
                    "volume": np.full(len(dates), 1_000_000.0 * (index + 1)),
                    "quote_volume": close * 1_000_000.0 * (index + 1),
                },
                index=dates,
            )
        return frames

    def make_sentiment(self, directory: Path) -> SentimentIndex:
        path = directory / "sentiment.json"
        path.write_text(
            json.dumps(
                {
                    "articles": [
                        {
                            "timestamp": "2023-11-15T12:00:00Z",
                            "sentiment": 0.8,
                            "coins": ["bitcoin"],
                        }
                    ]
                }
            ),
            encoding="utf-8",
        )
        return SentimentIndex(path)

    def test_fixed_ten_strategy_roster_includes_minvar(self) -> None:
        self.assertEqual(STRATEGIES, EXPECTED_STRATEGIES)
        self.assertEqual(len(STRATEGIES), 10)

        with tempfile.TemporaryDirectory() as temporary_directory:
            sentiment = self.make_sentiment(Path(temporary_directory))
            proposals = compute_proposals(
                self.make_history(),
                sentiment,
                datetime(2023, 11, 16, tzinfo=timezone.utc),
            )

        self.assertEqual(
            [proposal["strategy"] for proposal in proposals],
            list(EXPECTED_STRATEGIES),
        )
        for proposal in proposals:
            self.assertEqual(len(proposal["weights"]), len(ASSETS))
            self.assertAlmostEqual(sum(proposal["weights"]), 1.0, places=6)
            self.assertTrue(all(weight >= 0.0 for weight in proposal["weights"]))


class ReleaseDataContractTests(unittest.TestCase):
    def test_manifest_declares_frozen_release_contract(self) -> None:
        with (DATA_DIR / "manifest.json").open(encoding="utf-8") as handle:
            manifest = json.load(handle)

        self.assertEqual(BENCHMARK_VERSION, EXPECTED_VERSION)
        self.assertEqual(EXPECTED_SPLIT_COUNTS, EXPECTED_COUNTS)
        self.assertEqual(manifest["version"], EXPECTED_VERSION)
        self.assertEqual(manifest["splits"], EXPECTED_COUNTS)
        self.assertEqual(manifest["strategies"], list(EXPECTED_STRATEGIES))

    def test_formal_splits_have_purged_labels_and_compounded_returns(self) -> None:
        records_by_split = {
            split: read_jsonl(DATA_DIR / f"{split}.jsonl")
            for split in EXPECTED_COUNTS
        }
        self.assertEqual(
            {split: len(records) for split, records in records_by_split.items()},
            EXPECTED_COUNTS,
        )

        for split, records in records_by_split.items():
            configured_start, configured_end = SPLIT_BOUNDS[split]
            for record in records:
                with self.subTest(split=split, identifier=record.get("id")):
                    self.assertEqual(record["split"], split)
                    self.assertEqual(record["assets"], list(ASSETS))
                    self.assertEqual(
                        [
                            proposal["strategy"]
                            for proposal in record["strategy_proposals"]
                        ],
                        list(EXPECTED_STRATEGIES),
                    )

                    execution = pd.Timestamp(record["execution_at"])
                    label_end = pd.Timestamp(record["label_end_at"])
                    self.assertEqual(
                        label_end - execution,
                        pd.Timedelta(days=REBALANCE_DAYS),
                    )
                    if configured_start is not None:
                        self.assertGreaterEqual(execution, configured_start)
                    self.assertLessEqual(label_end, configured_end)

                    daily_returns = np.asarray(
                        record["next_7d_daily_returns"], dtype=float
                    )
                    self.assertEqual(
                        daily_returns.shape,
                        (REBALANCE_DAYS, len(ASSETS)),
                    )
                    self.assertTrue(np.isfinite(daily_returns).all())
                    compounded = np.prod(1.0 + daily_returns, axis=0) - 1.0
                    np.testing.assert_allclose(
                        record["next_7d_returns"],
                        compounded,
                        rtol=0.0,
                        atol=1e-9,
                    )

        split_order = ("train", "validation", "test")
        for previous_split, next_split in zip(split_order, split_order[1:]):
            previous_label_end = max(
                pd.Timestamp(record["label_end_at"])
                for record in records_by_split[previous_split]
            )
            next_execution = min(
                pd.Timestamp(record["execution_at"])
                for record in records_by_split[next_split]
            )
            self.assertLess(previous_label_end, next_execution)

        test_records = records_by_split["test"]
        self.assertEqual(test_records[0]["execution_at"], "2025-03-16T00:00:00Z")
        self.assertEqual(test_records[-1]["execution_at"], "2026-03-08T00:00:00Z")
        self.assertEqual(test_records[-1]["label_end_at"], "2026-03-15T00:00:00Z")


class EvaluationContractTests(unittest.TestCase):
    def test_equal_weight_buy_and_hold_never_rebalances(self) -> None:
        records = [
            evaluation_record("week_1", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
            evaluation_record("week_2", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
        ]
        equal_targets = {record["id"]: [0.2] * len(ASSETS) for record in records}

        held = evaluate(records, equal_targets, 0.0, buy_and_hold=True)
        rebalanced = evaluate(records, equal_targets, 0.0)

        self.assertAlmostEqual(held["cumulative_return"], 0.6)
        self.assertAlmostEqual(held["average_turnover"], 0.0)
        self.assertAlmostEqual(rebalanced["cumulative_return"], 0.44)
        self.assertAlmostEqual(rebalanced["average_turnover"], 1.0 / 15.0)

    def test_rebalance_turnover_uses_return_drifted_holdings(self) -> None:
        records = [
            evaluation_record("week_1", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
            evaluation_record("week_2", daily_path([1.0, 0.0, 0.0, 0.0, 0.0])),
        ]
        equal_targets = {record["id"]: [0.2] * len(ASSETS) for record in records}

        metrics = evaluate(records, equal_targets, 0.01)

        second_turnover = 2.0 / 15.0
        expected_capital = 1.2 * (1.0 - 0.01 * second_turnover) * 1.2
        self.assertAlmostEqual(metrics["average_turnover"], second_turnover / 2.0)
        self.assertAlmostEqual(metrics["cumulative_return"], expected_capital - 1.0)

    def test_max_drawdown_uses_daily_nav(self) -> None:
        records = [
            evaluation_record(
                "round_trip",
                daily_path([1.0] * len(ASSETS), [-0.5] * len(ASSETS)),
            )
        ]
        targets = {"round_trip": [0.2] * len(ASSETS)}

        metrics = evaluate(records, targets, 0.0)

        self.assertAlmostEqual(metrics["cumulative_return"], 0.0)
        self.assertAlmostEqual(metrics["max_drawdown"], 0.5)

    def test_sharpe_uses_weekly_returns(self) -> None:
        records = [
            evaluation_record("up_week", daily_path([0.1] * len(ASSETS))),
            evaluation_record("flat_week", daily_path([0.0] * len(ASSETS))),
        ]
        targets = {record["id"]: [0.2] * len(ASSETS) for record in records}

        metrics = evaluate(records, targets, 0.0)

        self.assertAlmostEqual(metrics["annualized_sharpe"], math.sqrt(52.0))

    def test_submitted_weights_are_not_coerced_or_normalized(self) -> None:
        invalid = {
            "boolean": [True, 0.2, 0.2, 0.2, 0.2],
            "string": ["0.2", 0.2, 0.2, 0.2, 0.2],
            "negative": [-0.1, 0.275, 0.275, 0.275, 0.275],
            "not_normalized": [0.1] * len(ASSETS),
        }
        for label, weights in invalid.items():
            with self.subTest(label=label):
                with self.assertRaises(ValueError):
                    strict_weights(weights, label=label)

        self.assertEqual(
            strict_weights([0.2] * len(ASSETS), label="valid"),
            [0.2] * len(ASSETS),
        )


class AttackContractTests(unittest.TestCase):
    def test_reverse_and_bias_match_frozen_formulas(self) -> None:
        clean = attack_records(1)
        malicious_id = STRATEGIES[0]
        honest = [
            proposal["weights"]
            for proposal in clean[0]["strategy_proposals"]
            if proposal["strategy"] != malicious_id
        ]
        honest_mean = np.mean(np.asarray(honest, dtype=float), axis=0)

        reverse = apply_attacks(
            clean,
            attack="reverse",
            f=1,
            seed=7,
            malicious_ids=[malicious_id],
        )
        bias = apply_attacks(
            clean,
            attack="bias",
            f=1,
            seed=7,
            malicious_ids=[malicious_id],
        )

        np.testing.assert_allclose(
            proposal_weights(reverse.records[0], malicious_id),
            (1.0 - honest_mean) / (len(ASSETS) - 1),
            rtol=0.0,
            atol=1e-9,
        )
        expected_bias = 0.9 * honest_mean
        expected_bias[ASSETS.index("BTC")] += 0.1
        np.testing.assert_allclose(
            proposal_weights(bias.records[0], malicious_id),
            expected_bias,
            rtol=0.0,
            atol=1e-9,
        )

    def test_drift_has_twenty_round_warmup_then_frozen_target(self) -> None:
        clean = attack_records(21)
        malicious_id = STRATEGIES[0]
        attacked = apply_attacks(
            clean,
            attack="drift",
            f=1,
            seed=11,
            malicious_ids=[malicious_id],
        )

        for round_index in range(20):
            self.assertEqual(
                proposal_weights(attacked.records[round_index], malicious_id),
                proposal_weights(clean[round_index], malicious_id),
            )

        clean_round_21 = np.asarray(
            proposal_weights(clean[20], malicious_id), dtype=float
        )
        target = np.asarray(
            attacked.audit["drift_targets"][malicious_id], dtype=float
        )
        expected_round_21 = 0.98 * clean_round_21 + 0.02 * target
        np.testing.assert_allclose(
            proposal_weights(attacked.records[20], malicious_id),
            expected_round_21,
            rtol=0.0,
            atol=1e-9,
        )

    def test_mixed_attack_is_deterministic_static_and_label_free(self) -> None:
        clean = attack_records(21)
        first = apply_attacks(clean, attack="mixed", f=3, seed=17)
        second = apply_attacks(clean, attack="mixed", f=3, seed=17)
        self.assertEqual(first, second)

        explicit_ids = list(STRATEGIES[:3])
        mixed = apply_attacks(
            clean,
            attack="mixed",
            f=3,
            seed=17,
            malicious_ids=explicit_ids,
        )
        self.assertEqual(mixed.audit["malicious_ids"], explicit_ids)
        self.assertEqual(MIXED_ROLES, EXPECTED_MIXED_ROLES)
        self.assertEqual(
            mixed.audit["attack_roles"],
            dict(zip(explicit_ids, EXPECTED_MIXED_ROLES)),
        )

        honest_ids = set(STRATEGIES) - set(explicit_ids)
        audit_fields = {"attack", "attack_role", "attack_roles", "malicious_ids"}
        for clean_record, attacked_record in zip(clean, mixed.records):
            self.assertTrue(audit_fields.isdisjoint(attacked_record))
            self.assertEqual(
                [
                    proposal["strategy"]
                    for proposal in attacked_record["strategy_proposals"]
                ],
                list(STRATEGIES),
            )
            for strategy in honest_ids:
                self.assertEqual(
                    proposal_weights(attacked_record, strategy),
                    proposal_weights(clean_record, strategy),
                )
            for proposal in attacked_record["strategy_proposals"]:
                self.assertTrue(audit_fields.isdisjoint(proposal))


if __name__ == "__main__":
    unittest.main()