Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
Fix mypy errors: replace dict[str, object] with typed Trade dataclass
Camo67 committed
Oct 12, 2026 at 12:07 UTC
cd2383fa1a29f3b4984104d7a76fb8a7baac2440
2 files changed
+41
-33
src/open_alice/cli.py
+5
-5
@@ -102,16 +102,16 @@ def _run_paper(args: argparse.Namespace) -> None:
102
print(f" Total Trades: {len(portfolio.trades):>10d}")
103
104
if portfolio.trades:
105
- total_pnl = sum(float(t.get("pnl", 0)) for t in portfolio.trades)
105
+ total_pnl = sum(t.pnl or 0.0 for t in portfolio.trades)
106
print(f" Total P&L: ${total_pnl:>10,.2f}")
107
108
print("\n --- Trade Log ---")
109
for t in portfolio.trades[:20]:
110
- pnl_str = f" P&L: ${float(t['pnl']):,.2f}" if "pnl" in t else ""
110
+ pnl_str = f" P&L: ${t.pnl:,.2f}" if t.pnl is not None else ""
111
print(
112
- f" {str(t['time'])} | {str(t['action']):>4} | "
113
- f"{str(t.get('symbol', '')):>6} | {int(t.get('shares', 0)):>6} @ "
114
- f"${float(t.get('price', 0)):>8.2f}{pnl_str}"
112
+ f" {t.time.strftime('%Y-%m-%d %H:%M')} | {t.action:>4} | "
113
+ f"{t.symbol:>6} | {t.shares:>6} @ "
114
+ f"${t.price:>8.2f}{pnl_str}"
115
)
116
117
if len(portfolio.trades) > 20:
src/open_alice/engine/paper.py
+36
-28
@@ -18,11 +18,21 @@ class PaperPosition:
18
entry_time: datetime
19
20
21
+@dataclass
22
+class Trade:
23
+ time: datetime
24
+ action: str
25
+ symbol: str
26
+ shares: int
27
+ price: float
28
+ pnl: float | None = None
29
+
30
+
31
@dataclass
32
class PaperPortfolio:
33
cash: float
34
positions: dict[str, PaperPosition] = field(default_factory=dict)
25
- trades: list[dict[str, object]] = field(default_factory=list)
35
+ trades: list[Trade] = field(default_factory=list)
36
37
@property
38
def equity(self) -> float:
@@ -31,19 +41,19 @@ class PaperPortfolio:
41
total += pos.shares * pos.entry_price
42
return total
43
34
- def buy(self, symbol: str, price: int, shares: int) -> None:
44
+ def buy(self, symbol: str, price: float, shares: int) -> None:
45
cost = shares * price
46
if cost > self.cash:
47
return
48
self.cash -= cost
49
self.positions[symbol] = PaperPosition(symbol, shares, price, datetime.now())
40
- self.trades.append({
41
- "time": datetime.now(),
42
- "action": "BUY",
43
- "symbol": symbol,
44
- "shares": shares,
45
- "price": price,
46
- })
50
+ self.trades.append(Trade(
51
+ time=datetime.now(),
52
+ action="BUY",
53
+ symbol=symbol,
54
+ shares=shares,
55
+ price=price,
56
+ ))
57
58
def sell(self, symbol: str, price: float) -> None:
59
if symbol not in self.positions:
@@ -52,14 +62,14 @@ class PaperPortfolio:
62
proceeds = pos.shares * price
63
self.cash += proceeds
64
pnl = proceeds - (pos.shares * pos.entry_price)
55
- self.trades.append({
56
- "time": datetime.now(),
57
- "action": "SELL",
58
- "symbol": symbol,
59
- "shares": pos.shares,
60
- "price": price,
61
- "pnl": pnl,
62
- })
65
+ self.trades.append(Trade(
66
+ time=datetime.now(),
67
+ action="SELL",
68
+ symbol=symbol,
69
+ shares=pos.shares,
70
+ price=price,
71
+ pnl=pnl,
72
+ ))
73
74
75
def run_paper(
@@ -73,7 +83,8 @@ def run_paper(
83
84
Args:
85
df: OHLCV DataFrame.
76
- strategy: Strategy with generate_signals method.
86
+ strategy: Strategy implementing the Strategy protocol.
87
+ symbol: Trading symbol.
88
initial_capital: Starting cash.
89
risk_per_trade: Fraction of equity risked per trade.
90
@@ -88,22 +99,19 @@ def run_paper(
99
prev = signals.iloc[i - 1]
100
101
if row["Signal"] == 1 and prev["Signal"] != 1:
91
- # Buy signal
102
risk_amount = portfolio.equity * risk_per_trade
103
stop_distance = row["Close"] * 0.05
104
if stop_distance > 0:
105
shares = int(risk_amount / stop_distance)
106
if shares > 0:
97
- portfolio.buy(symbol, row["Close"], shares)
107
+ portfolio.buy(symbol, float(row["Close"]), shares)
108
109
elif row["Signal"] == -1 and prev["Signal"] != -1:
100
- # Sell signal
101
- for symbol in list(portfolio.positions.keys()):
102
- portfolio.sell(symbol, row["Close"])
103
-
104
- # Close all positions at the end
105
- final_price = signals["Close"].iloc[-1]
106
- for symbol in list(portfolio.positions.keys()):
107
- portfolio.sell(symbol, final_price)
110
+ for sym in list(portfolio.positions.keys()):
111
+ portfolio.sell(sym, float(row["Close"]))
112
+
113
+ final_price = float(signals["Close"].iloc[-1])
114
+ for sym in list(portfolio.positions.keys()):
115
+ portfolio.sell(sym, final_price)
116
117
return portfolio