Files
kraken-bot/tests/test_strategies.py
2026-10-21 20:47:59 -04:00

94 lines
3.8 KiB
Python
Executable File

import asyncio
import numpy as np
import pandas as pd
import pytest
from kraken_trader.backtest import run_one
from kraken_trader.config import AppConfig, StrategyConfig
from kraken_trader.kraken import PairInfo
from kraken_trader.strategies import Context, get_strategy_class
from kraken_trader.strategies import indicators as ind
PAIRS = ["XBTUSD", "ETHUSD", "SOLUSD", "XRPUSD"]
NEW_TYPES = [
"time_series_momentum",
"donchian_breakout",
"cross_sectional_momentum",
"trend_risk_parity",
"adaptive_regime",
"squeeze_breakout",
"btc_regime_rotation",
]
class FakeClient:
def pair(self, name):
return PairInfo(name, name, name[:3], "ZUSD", 8, 2, 0.0, 0.0)
def make_history(drifts, n=500, seed=1):
"""Random walks per pair: list of (drift per candle) segments applied in sequence."""
rng = np.random.default_rng(seed)
idx = pd.date_range("2024-01-01", periods=n, freq="1D", tz="UTC")
history = {}
for i, pair in enumerate(PAIRS):
drift = np.concatenate([np.full(n // len(drifts), d * (1 + 0.2 * i)) for d in drifts])
drift = np.pad(drift, (0, n - len(drift)), mode="edge")
close = 100 * np.exp(np.cumsum(drift + rng.normal(0, 0.03, n)))
history[pair] = pd.DataFrame(
{"open": close, "high": close * 1.01, "low": close * 0.99, "close": close,
"vwap": close, "volume": 1.0},
index=idx,
)
return history
@pytest.mark.parametrize("strategy_type", NEW_TYPES)
def test_strategy_backtests_cleanly(strategy_type):
cfg = StrategyConfig(id="t", type=strategy_type, starting_capital=1000, pairs=PAIRS, interval=1440)
result = asyncio.run(run_one(cfg, AppConfig(), make_history([0.004, -0.004]), FakeClient(), 210))
assert result.trades > 0
assert -1 < result.total_return < 10
assert 0 <= result.exposure <= 1.0001
@pytest.mark.parametrize("strategy_type", NEW_TYPES)
def test_strategy_ends_in_cash_after_long_crash(strategy_type):
history = make_history([0.004, -0.01], n=500)
for df in history.values():
df.iloc[-1] = df.iloc[-1] * 0.8 # capitulation candle: fresh low for every pair
cfg = StrategyConfig(id="t", type=strategy_type, starting_capital=1000, pairs=PAIRS, interval=1440)
strategy = get_strategy_class(strategy_type)(PAIRS, 1440, {})
# Hold everything, then ask the strategy what to do at the bottom of the crash.
weights = {p: 1 / len(PAIRS) for p in PAIRS}
ctx = Context(now=history[PAIRS[0]].index[-1], candles=history,
prices={p: df["close"].iloc[-1] for p, df in history.items()},
weights=weights, cash=0, equity=1000)
targets = strategy.decide(ctx)
if strategy_type in ("cross_sectional_momentum", "trend_risk_parity") and not targets:
pytest.skip("not a rebalance candle")
assert all(targets.get(p, 1) == 0 for p in PAIRS), targets
def test_banded_skips_small_changes():
assert ind.banded({"A": 0.52, "B": 0.0, "C": 0.3}, {"A": 0.5, "B": 0.0, "C": 0.1}, 0.05) == {"C": 0.3}
assert ind.banded({"A": 0.0}, {"A": 0.01}, 0.05) == {"A": 0.0}
def test_select_with_buffer_keeps_incumbents():
scores = {"A": 0.5, "B": 0.4, "C": 0.3, "D": 0.2, "E": -0.1}
assert ind.select_with_buffer(scores, {}, 2, 2) == ["A", "B"]
assert ind.select_with_buffer(scores, {"D": 0.5}, 2, 2) == ["D", "A"]
assert ind.select_with_buffer(scores, {"E": 0.5}, 2, 2) == ["A", "B"]
def test_efficiency_ratio():
assert ind.efficiency_ratio(pd.Series(range(30), dtype=float), 20) == pytest.approx(1.0)
assert ind.efficiency_ratio(pd.Series([1.0, 2.0] * 15), 20) == pytest.approx(0.0)
def test_rotation_requires_market_pair():
with pytest.raises(ValueError):
get_strategy_class("btc_regime_rotation")(["ETHUSD"], 1440, {})