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()