File size: 6,889 Bytes
0d02553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
"""Event-driven backtester with fees, slippage, stops and no lookahead.

Signals are computed on candle i's close and filled at candle i+1's open.
Stops are checked against each candle's low and filled at the stop price
(minus slippage), which is realistic for spot markets without gaps.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Optional

import numpy as np
import pandas as pd

from .portfolio import Ledger, Trade
from .risk import RiskLimits, RiskManager
from .strategies import Strategy


@dataclass
class BacktestResult:
    strategy: str
    symbol: str
    timeframe: str
    start: str
    end: str
    initial: float
    final: float
    total_return_pct: float
    buy_hold_return_pct: float
    cagr_pct: float
    max_drawdown_pct: float
    sharpe: float
    trades: int
    win_rate_pct: float
    profit_factor: float
    exposure_pct: float
    fees_paid: float
    halted: Optional[str]
    equity_curve: list[float] = field(default_factory=list)
    trade_log: list[dict] = field(default_factory=list)

    def summary(self) -> dict[str, Any]:
        d = self.__dict__.copy()
        d.pop("equity_curve")
        d.pop("trade_log")
        return d


def _metrics(equity: pd.Series, candles_per_year: float) -> tuple[float, float, float]:
    rets = equity.pct_change().dropna()
    if len(rets) < 2 or rets.std(ddof=0) == 0:
        sharpe = 0.0
    else:
        sharpe = float(rets.mean() / rets.std(ddof=0) * np.sqrt(candles_per_year))
    peak = equity.cummax()
    dd = float(((equity / peak) - 1).min())
    years = len(equity) / candles_per_year
    cagr = float((equity.iloc[-1] / equity.iloc[0]) ** (1 / years) - 1) if years > 0 else 0.0
    return sharpe, dd, cagr


def run_backtest(
    strategy: Strategy,
    candles: pd.DataFrame,
    symbol: str = "BTC/USDT",
    timeframe: str = "1h",
    initial: float = 1000.0,
    fee_pct: float = 0.001,
    slippage_pct: float = 0.0005,
    limits: RiskLimits | None = None,
    window: int = 400,
) -> BacktestResult:
    from .data import timeframe_seconds

    candles = candles.reset_index(drop=True)
    tf_s = timeframe_seconds(timeframe)
    candles_per_year = 365 * 86400 / tf_s
    rm = RiskManager(limits)
    ledger = Ledger(quote=initial)
    pos = ledger.position(symbol)
    if hasattr(strategy, "reset"):
        strategy.reset()

    equity_curve: list[float] = []
    fees_paid = 0.0
    pending = None  # signal to fill at this candle's open
    warm = strategy.warmup()
    in_market_bars = 0

    for i in range(len(candles)):
        row = candles.iloc[i]
        o, h, l, c, ts = float(row.open), float(row.high), float(row.low), float(row.close), row.timestamp
        ts_py = ts.to_pydatetime()

        # 1) fill pending signal at open
        if pending is not None:
            sig = pending
            pending = None
            eq = ledger.equity({symbol: o})
            exposure = pos.value(o)
            if sig.action == "buy":
                quote_amt = rm.position_size_quote(eq, exposure, sig.fraction)
                quote_amt = min(quote_amt, ledger.quote)
                ok, why = rm.approve("buy", quote_amt, eq, exposure)
                if ok and quote_amt > 0:
                    px = o * (1 + slippage_pct)
                    fee = quote_amt * fee_pct
                    qty = (quote_amt - fee) / px
                    ledger.quote -= quote_amt
                    pos.add(qty, px, ts_py)
                    pos.stop = rm.stop_price(pos.avg_entry, sig.stop)
                    fees_paid += fee
                    ledger.trades.append(Trade(ts_py, symbol, "buy", qty, px, fee, sig.reason, bot=strategy.name))
            elif sig.action == "sell" and pos.open:
                qty = pos.qty * min(1.0, sig.fraction)
                px = o * (1 - slippage_pct)
                gross = qty * px
                fee = gross * fee_pct
                pnl = (px - pos.avg_entry) * qty - fee
                ok, _ = rm.approve("sell", gross, eq, exposure)
                if ok:
                    ledger.quote += gross - fee
                    pos.reduce(qty)
                    fees_paid += fee
                    ledger.trades.append(Trade(ts_py, symbol, "sell", qty, px, fee, sig.reason, pnl=pnl, bot=strategy.name))

        # 2) stop-loss check intra-candle
        if pos.open and pos.stop is not None and l <= pos.stop:
            px = pos.stop * (1 - slippage_pct)
            qty = pos.qty
            gross = qty * px
            fee = gross * fee_pct
            pnl = (px - pos.avg_entry) * qty - fee
            ledger.quote += gross - fee
            pos.reduce(qty)
            fees_paid += fee
            ledger.trades.append(Trade(ts_py, symbol, "sell", qty, px, fee, "stop-loss", pnl=pnl, bot=strategy.name))
            if hasattr(strategy, "reset"):
                strategy.reset()

        # 3) mark to market at close, update risk state
        eq = ledger.equity({symbol: c})
        equity_curve.append(eq)
        rm.observe(eq, ts_py)
        if pos.open:
            in_market_bars += 1

        # 4) compute next signal on this close
        if i + 1 >= warm and not rm.halted:
            start = max(0, i + 1 - window)
            view = candles.iloc[start : i + 1]
            sig = strategy.evaluate(view, pos.open, pos.avg_entry if pos.open else None)
            if sig.action != "hold":
                pending = sig

    equity = pd.Series(equity_curve)
    sharpe, dd, cagr = _metrics(equity, candles_per_year)
    sells = [t for t in ledger.trades if t.side == "sell"]
    wins = [t for t in sells if t.pnl > 0]
    gross_win = sum(t.pnl for t in wins)
    gross_loss = -sum(t.pnl for t in sells if t.pnl <= 0)
    pf = gross_win / gross_loss if gross_loss > 0 else (float("inf") if gross_win > 0 else 0.0)
    final = float(equity.iloc[-1])
    bh = float(candles.close.iloc[-1] / candles.close.iloc[0] - 1) * 100

    return BacktestResult(
        strategy=strategy.name,
        symbol=symbol,
        timeframe=timeframe,
        start=str(candles.timestamp.iloc[0]),
        end=str(candles.timestamp.iloc[-1]),
        initial=initial,
        final=round(final, 2),
        total_return_pct=round((final / initial - 1) * 100, 2),
        buy_hold_return_pct=round(bh, 2),
        cagr_pct=round(cagr * 100, 2),
        max_drawdown_pct=round(dd * 100, 2),
        sharpe=round(sharpe, 2),
        trades=len(ledger.trades),
        win_rate_pct=round(100 * len(wins) / len(sells), 1) if sells else 0.0,
        profit_factor=round(pf, 2) if pf != float("inf") else 99.0,
        exposure_pct=round(100 * in_market_bars / max(1, len(candles)), 1),
        fees_paid=round(fees_paid, 2),
        halted=rm.state.halted_reason,
        equity_curve=[round(x, 2) for x in equity_curve],
        trade_log=[t.to_dict() for t in ledger.trades],
    )