Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro

fix/nan-prices-cli-demo-mode
py 39 lines 1.26 KB
Raw
1 """Simple Moving Average Crossover strategy."""
2
3 from __future__ import annotations
4
5 import pandas as pd
6
7
8 class SmaCrossover:
9 """Generate buy/sell signals based on SMA crossover.
10
11 Buy when the fast SMA crosses above the slow SMA.
12 Sell when the fast SMA crosses below the slow SMA.
13 """
14
15 def __init__(self, fast: int = 20, slow: int = 50) -> None:
16 if fast >= slow:
17 raise ValueError("fast period must be less than slow period")
18 self.fast = fast
19 self.slow = slow
20
21 def generate_signals(self, df: pd.DataFrame) -> pd.DataFrame:
22 """Add signal columns to the DataFrame.
23
24 Returns:
25 DataFrame with added columns:
26 SMA_fast, SMA_slow, Signal (1=buy, -1=sell, 0=hold), Position.
27 """
28 out = df.copy()
29 out["SMA_fast"] = out["Close"].rolling(self.fast).mean()
30 out["SMA_slow"] = out["Close"].rolling(self.slow).mean()
31
32 out["Signal"] = 0
33 out.loc[out["SMA_fast"] > out["SMA_slow"], "Signal"] = 1
34 out.loc[out["SMA_fast"] < out["SMA_slow"], "Signal"] = -1
35
36 # Position: forward-fill the signal (stay in position until signal changes)
37 out["Position"] = out["Signal"].replace(0, pd.NA).ffill().fillna(0).astype(int)
38
39 return out