Spaces:
Sleeping
Sleeping
Download engine/simulator.py from BharathPESU/meta: direct link, hf CLI and curl.
- Browser
- Download file 4.63 kB
-
https://huggingface.co/spaces/BharathPESU/meta/resolve/main/engine/simulator.py
- Command line
-
hf download hf://spaces/BharathPESU/meta/engine/simulator.py
-
curl -L -o simulator.py https://huggingface.co/spaces/BharathPESU/meta/resolve/main/engine/simulator.py
4.63 kB
| """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) | |