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

fix/nan-prices-cli-demo-mode
py 28 lines 915 Bytes
Raw
1 """Bollinger Bands mean-reversion strategy."""
2
3 from __future__ import annotations
4
5 import pandas as pd
6
7
8 class BollingerStrategy:
9 """Buy at lower band, sell at upper band."""
10
11 def __init__(self, period: int = 20, num_std: float = 2.0) -> None:
12 self.period = period
13 self.num_std = num_std
14
15 def generate_signals(self, df: pd.DataFrame) -> pd.DataFrame:
16 out = df.copy()
17
18 out["BB_Mid"] = out["Close"].rolling(self.period).mean()
19 bb_std = out["Close"].rolling(self.period).std()
20 out["BB_Upper"] = out["BB_Mid"] + self.num_std * bb_std
21 out["BB_Lower"] = out["BB_Mid"] - self.num_std * bb_std
22
23 out["Signal"] = 0
24 out.loc[out["Close"] < out["BB_Lower"], "Signal"] = 1
25 out.loc[out["Close"] > out["BB_Upper"], "Signal"] = -1
26
27 out["Position"] = out["Signal"].replace(0, pd.NA).ffill().fillna(0).astype(int)
28 return out