137 lines
5.3 KiB
Python
Executable File
137 lines
5.3 KiB
Python
Executable File
"""Replay strategies over historical Kraken candles.
|
|
|
|
python -m kraken_trader.backtest [--config config/strategies.yaml] [--only id1,id2] [--warmup 200]
|
|
|
|
Uses the same StrategyRunner and PaperBroker as live paper trading, so fills, fees,
|
|
slippage, lot sizes and minimum order sizes match. Kraken's OHLC endpoint returns at
|
|
most 720 candles, so daily strategies get ~2 years and hourly ones only ~30 days.
|
|
Disabled strategies are included, so you can test candidates before enabling them.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import math
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
|
|
from .broker import PaperBroker
|
|
from .config import AppConfig, Settings, StrategyConfig, load_config
|
|
from .engine import StrategyRunner
|
|
from .kraken import KrakenClient
|
|
from .stats import max_drawdown
|
|
from .storage import Store
|
|
from .strategies import get_strategy_class
|
|
from .strategies.indicators import periods_per_year
|
|
|
|
|
|
@dataclass
|
|
class Result:
|
|
id: str
|
|
type: str
|
|
start: datetime
|
|
end: datetime
|
|
total_return: float
|
|
cagr: float
|
|
max_drawdown: float
|
|
sharpe: float | None
|
|
exposure: float
|
|
trades: int
|
|
fees: float
|
|
|
|
|
|
async def run_one(
|
|
cfg: StrategyConfig, app_cfg: AppConfig, history: dict[str, pd.DataFrame], client, warmup: int
|
|
) -> Result:
|
|
strategy = get_strategy_class(cfg.type)(cfg.pairs, cfg.interval, cfg.params)
|
|
store = Store(Path(":memory:"))
|
|
broker = PaperBroker(app_cfg.fee_rate, app_cfg.slippage)
|
|
runner = StrategyRunner(cfg, strategy, broker, client, store, app_cfg)
|
|
|
|
timeline = sorted(set().union(*(df.index for df in history.values())))[warmup:]
|
|
if not timeline:
|
|
raise ValueError(f"{cfg.id}: not enough history for warmup={warmup}")
|
|
equity, exposure = [], []
|
|
for t in timeline:
|
|
candles = {p: df.loc[:t] for p, df in history.items()}
|
|
prices = {p: float(df["close"].iloc[-1]) for p, df in candles.items() if not df.empty}
|
|
await runner.step(t + timedelta(minutes=cfg.interval), candles, prices)
|
|
value = runner.portfolio.equity(prices)
|
|
equity.append(value)
|
|
exposure.append(1 - runner.portfolio.cash / value if value else 0)
|
|
|
|
curve = pd.Series([cfg.starting_capital, *equity])
|
|
returns = curve.pct_change().dropna()
|
|
ppy = periods_per_year(cfg.interval)
|
|
trades = store.trades(cfg.id)
|
|
return Result(
|
|
id=cfg.id,
|
|
type=cfg.type,
|
|
start=timeline[0].to_pydatetime(),
|
|
end=timeline[-1].to_pydatetime(),
|
|
total_return=curve.iloc[-1] / curve.iloc[0] - 1,
|
|
cagr=(curve.iloc[-1] / curve.iloc[0]) ** (ppy / len(returns)) - 1,
|
|
max_drawdown=max_drawdown(curve),
|
|
sharpe=float(returns.mean() / returns.std() * math.sqrt(ppy)) if returns.std() > 0 else None,
|
|
exposure=sum(exposure) / len(exposure),
|
|
trades=len(trades),
|
|
fees=sum(t["fee"] for t in trades),
|
|
)
|
|
|
|
|
|
async def backtest(app_cfg: AppConfig, only: set[str] | None, warmup: int) -> list[Result]:
|
|
client = KrakenClient()
|
|
try:
|
|
await client.load_metadata()
|
|
configs = []
|
|
for cfg in app_cfg.strategies:
|
|
if only and cfg.id not in only:
|
|
continue
|
|
pairs = [client.pair(p).altname for p in cfg.pairs]
|
|
configs.append(cfg.model_copy(update={"pairs": pairs, "mode": "paper"}))
|
|
|
|
cache: dict[tuple[str, int], pd.DataFrame] = {}
|
|
for cfg in configs:
|
|
for pair in cfg.pairs:
|
|
if (pair, cfg.interval) not in cache:
|
|
cache[(pair, cfg.interval)] = await client.ohlc(pair, cfg.interval)
|
|
|
|
results = []
|
|
for cfg in configs:
|
|
history = {p: cache[(p, cfg.interval)] for p in cfg.pairs}
|
|
results.append(await run_one(cfg, app_cfg, history, client, warmup))
|
|
return results
|
|
finally:
|
|
await client.close()
|
|
|
|
|
|
def print_results(results: list[Result]) -> None:
|
|
header = f"{'strategy':<28}{'type':<26}{'period':<25}{'return':>9}{'CAGR':>9}{'maxDD':>8}{'sharpe':>8}{'expo':>6}{'trades':>7}{'fees':>9}"
|
|
print(header)
|
|
print("-" * len(header))
|
|
for r in sorted(results, key=lambda r: r.sharpe if r.sharpe is not None else -99, reverse=True):
|
|
sharpe = f"{r.sharpe:8.2f}" if r.sharpe is not None else f"{'—':>8}"
|
|
period = f"{r.start:%Y-%m-%d}..{r.end:%Y-%m-%d}"
|
|
print(
|
|
f"{r.id:<28}{r.type:<26}{period:<25}{r.total_return:>9.1%}{r.cagr:>9.1%}"
|
|
f"{r.max_drawdown:>8.1%}{sharpe}{r.exposure:>6.0%}{r.trades:>7}{r.fees:>9.2f}"
|
|
)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("--config", type=Path, default=Settings().config_path)
|
|
parser.add_argument("--only", help="comma-separated strategy ids")
|
|
parser.add_argument("--warmup", type=int, default=200, help="candles reserved for indicator warm-up")
|
|
args = parser.parse_args()
|
|
only = set(args.only.split(",")) if args.only else None
|
|
print_results(asyncio.run(backtest(load_config(args.config), only, args.warmup)))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|