File size: 4,626 Bytes
9d82314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Intraday trade simulator. Pure functions: no I/O.

Rules (see docs/STRATEGY.md sections 6-8):
- Entry at the open of the first bar at or after entry_time on entry_date.
- Stop is stop_loss_pct from the entry fill. Gap-through fills at the bar open.
- Forced exit at the close of the last bar at or before square_off_time.
- Slippage is applied against the trader on each fill.
- Gross P&L uses raw prices with no costs. Net P&L uses slipped prices minus fees.
- Max positions is applied per entry date. All entries share entry_time and all
  positions close by square-off, so this is exact for intraday trading.
"""
from __future__ import annotations

from collections import Counter
from datetime import date
from typing import Any

import pandas as pd

from engine.config import BacktestConfig
from engine.costs import round_trip_cost
from engine.sizing import position_quantity

TRADE_COLUMNS = [
    "symbol", "side", "entry_date", "entry_time", "entry_price",
    "exit_time", "exit_price", "exit_reason", "qty",
    "gross_pnl", "fees", "net_pnl", "surprise",
]


def _session_bars(bars: pd.DataFrame, day: date, cfg: BacktestConfig) -> pd.DataFrame | None:
    day_bars = bars[bars.index.date == day]
    if day_bars.empty:
        return None
    start_times = day_bars.index.time
    end_times = (day_bars.index + pd.Timedelta(cfg.bar_interval)).time
    sess = day_bars[(start_times >= cfg.entry_time) & (end_times <= cfg.square_off_time)]
    return sess if not sess.empty else None


def simulate_trade(signal: dict[str, Any], bars: pd.DataFrame, cfg: BacktestConfig) -> dict[str, Any] | None:
    """Simulate one signal on one day. Returns a trade record, or None if not tradeable."""
    sess = _session_bars(bars, signal["entry_date"], cfg)
    if sess is None:
        return None

    is_long = signal["side"] == "long"
    sign = 1 if is_long else -1
    slip = cfg.costs.slippage_pct

    raw_entry = float(sess.iloc[0].open)
    entry_px = raw_entry * (1 + slip) if is_long else raw_entry * (1 - slip)
    qty = position_quantity(cfg.capital, entry_px, cfg)
    if qty <= 0:
        return None

    stop_px = entry_px * (1 - cfg.stop_loss_pct) if is_long else entry_px * (1 + cfg.stop_loss_pct)

    exit_ts = sess.index[-1]
    raw_exit = float(sess.iloc[-1].close)
    reason = "square_off"
    for ts, bar in sess.iterrows():
        if is_long and bar.low <= stop_px:
            raw_exit = min(float(bar.open), stop_px)
            exit_ts, reason = ts, "stop"
            break
        if not is_long and bar.high >= stop_px:
            raw_exit = max(float(bar.open), stop_px)
            exit_ts, reason = ts, "stop"
            break

    exit_px = raw_exit * (1 - slip) if is_long else raw_exit * (1 + slip)

    gross = sign * (raw_exit - raw_entry) * qty
    slipped = sign * (exit_px - entry_px) * qty
    buy_value = qty * (entry_px if is_long else exit_px)
    sell_value = qty * (exit_px if is_long else entry_px)
    fees = round_trip_cost(buy_value, sell_value, cfg.costs)

    return {
        "symbol": signal["symbol"],
        "side": signal["side"],
        "entry_date": signal["entry_date"],
        "entry_time": sess.index[0].time(),
        "entry_price": entry_px,
        "exit_time": exit_ts.time(),
        "exit_price": exit_px,
        "exit_reason": reason,
        "qty": qty,
        "gross_pnl": gross,
        "fees": fees,
        "net_pnl": slipped - fees,
        "surprise": signal.get("surprise"),
    }


def run_backtest(
    signals: pd.DataFrame,
    bars_by_symbol: dict[str, pd.DataFrame],
    cfg: BacktestConfig,
) -> pd.DataFrame:
    """Run all signals. Signals need columns: symbol, entry_date, side, announced_at, surprise."""
    if signals.empty:
        return pd.DataFrame(columns=TRADE_COLUMNS)

    trades: list[dict[str, Any]] = []
    per_day: Counter[date] = Counter()
    seen: set[tuple[str, date]] = set()

    ordered = signals.sort_values(["entry_date", "announced_at"])
    for sig in ordered.to_dict("records"):
        side_enabled = cfg.enable_long if sig["side"] == "long" else cfg.enable_short
        if not side_enabled:
            continue
        key = (sig["symbol"], sig["entry_date"])
        if key in seen or per_day[sig["entry_date"]] >= cfg.max_positions:
            continue
        bars = bars_by_symbol.get(sig["symbol"])
        if bars is None:
            continue
        trade = simulate_trade(sig, bars, cfg)
        if trade is None:
            continue
        seen.add(key)
        per_day[sig["entry_date"]] += 1
        trades.append(trade)

    return pd.DataFrame(trades, columns=TRADE_COLUMNS)