from __future__ import annotations import json import sys import tempfile import unittest from datetime import datetime, timezone from pathlib import Path import numpy as np import pandas as pd SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts" sys.path.insert(0, str(SCRIPT_DIR)) from common import ASSETS, STRATEGIES # noqa: E402 from evaluate import evaluate # noqa: E402 from strategies import SentimentIndex, compute_proposals # noqa: E402 class ReleaseTests(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_all_strategies_return_valid_weights(self) -> None: 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(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 for weight in proposal["weights"])) def test_evaluator_equal_weight(self) -> None: record = { "id": "sample", "next_7d_returns": [0.1, 0.0, 0.0, 0.0, 0.0], } weights = {"sample": [0.2] * 5} metrics = evaluate([record], weights, transaction_cost=0.001) self.assertAlmostEqual(metrics["cumulative_return"], 0.02) self.assertEqual(metrics["max_drawdown"], 0.0) if __name__ == "__main__": unittest.main()