Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
| 1 | """Paper trading engine.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import math |
| 6 | from dataclasses import dataclass, field |
| 7 | from datetime import datetime |
| 8 | |
| 9 | import pandas as pd |
| 10 | |
| 11 | from open_alice.strategies.base import Strategy |
| 12 | |
| 13 | |
| 14 | @dataclass |
| 15 | class PaperPosition: |
| 16 | symbol: str |
| 17 | shares: int |
| 18 | entry_price: float |
| 19 | entry_time: datetime |
| 20 | |
| 21 | |
| 22 | @dataclass |
| 23 | class Trade: |
| 24 | time: datetime |
| 25 | action: str |
| 26 | symbol: str |
| 27 | shares: int |
| 28 | price: float |
| 29 | pnl: float | None = None |
| 30 | |
| 31 | |
| 32 | @dataclass |
| 33 | class PaperPortfolio: |
| 34 | cash: float |
| 35 | positions: dict[str, PaperPosition] = field(default_factory=dict) |
| 36 | trades: list[Trade] = field(default_factory=list) |
| 37 | |
| 38 | @property |
| 39 | def equity(self) -> float: |
| 40 | total = self.cash |
| 41 | for pos in self.positions.values(): |
| 42 | total += pos.shares * pos.entry_price |
| 43 | return total |
| 44 | |
| 45 | def buy(self, symbol: str, price: float, shares: int) -> None: |
| 46 | cost = shares * price |
| 47 | if cost > self.cash: |
| 48 | return |
| 49 | self.cash -= cost |
| 50 | self.positions[symbol] = PaperPosition(symbol, shares, price, datetime.now()) |
| 51 | self.trades.append(Trade( |
| 52 | time=datetime.now(), |
| 53 | action="BUY", |
| 54 | symbol=symbol, |
| 55 | shares=shares, |
| 56 | price=price, |
| 57 | )) |
| 58 | |
| 59 | def sell(self, symbol: str, price: float) -> None: |
| 60 | if symbol not in self.positions: |
| 61 | return |
| 62 | pos = self.positions.pop(symbol) |
| 63 | proceeds = pos.shares * price |
| 64 | self.cash += proceeds |
| 65 | pnl = proceeds - (pos.shares * pos.entry_price) |
| 66 | self.trades.append(Trade( |
| 67 | time=datetime.now(), |
| 68 | action="SELL", |
| 69 | symbol=symbol, |
| 70 | shares=pos.shares, |
| 71 | price=price, |
| 72 | pnl=pnl, |
| 73 | )) |
| 74 | |
| 75 | |
| 76 | def run_paper( |
| 77 | df: pd.DataFrame, |
| 78 | strategy: Strategy, |
| 79 | symbol: str, |
| 80 | initial_capital: float = 100_000.0, |
| 81 | risk_per_trade: float = 0.02, |
| 82 | ) -> PaperPortfolio: |
| 83 | """Run a paper trading simulation. |
| 84 | |
| 85 | Args: |
| 86 | df: OHLCV DataFrame. |
| 87 | strategy: Strategy implementing the Strategy protocol. |
| 88 | symbol: Trading symbol. |
| 89 | initial_capital: Starting cash. |
| 90 | risk_per_trade: Fraction of equity risked per trade. |
| 91 | |
| 92 | Returns: |
| 93 | PaperPortfolio with final state and trade log. |
| 94 | """ |
| 95 | portfolio = PaperPortfolio(cash=initial_capital) |
| 96 | signals = strategy.generate_signals(df) |
| 97 | |
| 98 | for i in range(1, len(signals)): |
| 99 | row = signals.iloc[i] |
| 100 | prev = signals.iloc[i - 1] |
| 101 | |
| 102 | price = float(row["Close"]) |
| 103 | if not math.isfinite(price) or price <= 0: |
| 104 | continue |
| 105 | |
| 106 | if row["Signal"] == 1 and prev["Signal"] != 1: |
| 107 | risk_amount = portfolio.equity * risk_per_trade |
| 108 | stop_distance = price * 0.05 |
| 109 | if stop_distance > 0: |
| 110 | shares = int(risk_amount / stop_distance) |
| 111 | if shares > 0: |
| 112 | portfolio.buy(symbol, price, shares) |
| 113 | |
| 114 | elif row["Signal"] == -1 and prev["Signal"] != -1: |
| 115 | for sym in list(portfolio.positions.keys()): |
| 116 | portfolio.sell(sym, price) |
| 117 | |
| 118 | valid_closes = [ |
| 119 | float(p) |
| 120 | for p in signals["Close"] |
| 121 | if math.isfinite(float(p)) and float(p) > 0 |
| 122 | ] |
| 123 | if valid_closes: |
| 124 | final_price = valid_closes[-1] |
| 125 | for sym in list(portfolio.positions.keys()): |
| 126 | portfolio.sell(sym, final_price) |
| 127 | |
| 128 | return portfolio |