@devries-cameron20 / open-alice / commits / 173e9b0
Fork 0

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

Initial commit: Alice trading bot with SMA, RSI, MACD, Bollinger strategies, backtesting, paper trading, Docker, and CI

Camo67 committed Oct 12, 2026 at 11:57 UTC 173e9b02771096969efbea5fcc622f18d977e26f
30 files changed +966
.dockerignore new
+14
@@ -0,0 +1,14 @@
1 +.git
2 +.github
3 +__pycache__
4 +*.pyc
5 +.pytest_cache
6 +.mypy_cache
7 +.ruff_cache
8 +htmlcov
9 +.env
10 +.venv
11 +venv
12 +*.egg-info
13 +dist
14 +build
.github/workflows/ci.yml new
+43
@@ -0,0 +1,43 @@
1 +name: CI
2 +
3 +on:
4 + push:
5 + branches: [main, master]
6 + pull_request:
7 + branches: [main, master]
8 +
9 +jobs:
10 + lint-and-test:
11 + runs-on: ubuntu-latest
12 + strategy:
13 + matrix:
14 + python-version: ["3.11", "3.12"]
15 +
16 + steps:
17 + - uses: actions/checkout@v4
18 +
19 + - name: Set up Python ${{ matrix.python-version }}
20 + uses: actions/setup-python@v5
21 + with:
22 + python-version: ${{ matrix.python-version }}
23 +
24 + - name: Install dependencies
25 + run: |
26 + python -m pip install --upgrade pip
27 + pip install -e ".[dev]"
28 +
29 + - name: Lint with ruff
30 + run: ruff check src tests
31 +
32 + - name: Type check with mypy
33 + run: mypy src
34 +
35 + - name: Test with pytest
36 + run: pytest tests/ -v --tb=short --color=yes
37 +
38 + - name: Upload coverage
39 + if: matrix.python-version == '3.12'
40 + uses: actions/upload-artifact@v4
41 + with:
42 + name: coverage-report
43 + path: htmlcov/
.gitignore new
+15
@@ -0,0 +1,15 @@
1 +__pycache__/
2 +*.py[cod]
3 +*.egg-info/
4 +.eggs/
5 +build/
6 +dist/
7 +.pytest_cache/
8 +.mypy_cache/
9 +.ruff_cache/
10 +htmlcov/
11 +.coverage
12 +.env
13 +.venv/
14 +venv/
15 +*.log
Dockerfile new
+12
@@ -0,0 +1,12 @@
1 +FROM python:3.12-slim
2 +
3 +WORKDIR /app
4 +
5 +COPY pyproject.toml requirements.txt README.md ./
6 +COPY src/ ./src/
7 +COPY tests/ ./tests/
8 +
9 +RUN pip install --no-cache-dir -e ".[dev]"]
10 +
11 +ENTRYPOINT ["alice"]
12 +CMD ["--help"]
README.md new
+44
@@ -0,0 +1,44 @@
1 +# open-alice
2 +
3 +> Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro.
4 +
5 +## Features
6 +
7 +- **Multi-asset support** — equities, crypto, commodities, forex
8 +- **Strategy engine** — pluggable strategies with backtesting
9 +- **Risk management** — position sizing, stop-loss, take-profit
10 +- **Paper trading** — test without real money
11 +- **CLI interface** — simple command-line controls
12 +
13 +## Quick Start
14 +
15 +```bash
16 +# Install
17 +pip install -e .
18 +
19 +# Run paper trading
20 +alice paper --strategy sma_crossover --symbol AAPL
21 +
22 +# Backtest
23 +alice backtest --strategy sma_crossover --symbol AAPL --start 2024-01-01 --end 2025-01-01
24 +```
25 +
26 +## Project Structure
27 +
28 +```
29 +open-alice/
30 +├── src/
31 +│ └── open_alice/
32 +│ ├── __init__.py
33 +│ ├── __main__.py
34 +│ ├── cli.py # CLI entry point
35 +│ ├── data.py # Market data fetching
36 +│ ├── strategies/ # Trading strategies
37 +│ ├── engine/ # Backtesting & execution engine
38 +│ └── risk/ # Risk management
39 +└── tests/
40 +```
41 +
42 +## License
43 +
44 +AGPL-3.0
docker-compose.yml new
+10
@@ -0,0 +1,10 @@
1 +services:
2 + alice:
3 + build: .
4 + volumes:
5 + - ./data:/app/data
6 + command: ["backtest", "--symbol", "AAPL", "--period", "1y"]
7 +
8 + test:
9 + build: .
10 + command: ["pytest", "tests/", "-v", "--tb=short"]
pyproject.toml new
+32
@@ -0,0 +1,32 @@
1 +[build-system]
2 +requires = ["hatchling"]
3 +build-backend = "hatchling.build"
4 +
5 +[project]
6 +name = "open-alice"
7 +version = "0.1.0"
8 +description = "Alice — an open-source AI trading bot"
9 +requires-python = ">=3.11"
10 +dependencies = [
11 + "pandas>=2.0",
12 + "numpy>=1.26",
13 + "yfinance>=0.2.31",
14 +]
15 +
16 +[project.optional-dependencies]
17 +dev = [
18 + "pytest>=8.0",
19 + "ruff>=0.1.0",
20 + "mypy>=1.8",
21 +]
22 +
23 +[tool.ruff]
24 +line-length = 100
25 +target-version = "py311"
26 +
27 +[tool.ruff.lint]
28 +select = ["E", "F", "I", "N", "UP", "B", "SIM"]
29 +
30 +[tool.mypy]
31 +python_version = "3.11"
32 +strict = true
requirements.txt new
+3
@@ -0,0 +1,3 @@
1 +pandas>=2.0
2 +numpy>=1.26
3 +yfinance>=0.2.31
src/open_alice/__init__.py new
+3
@@ -0,0 +1,3 @@
1 +"""Alice — an open-source AI trading bot."""
2 +
3 +__version__ = "0.1.0"
src/open_alice/__main__.py new
+6
@@ -0,0 +1,6 @@
1 +"""CLI entry point for open-alice."""
2 +
3 +from open_alice.cli import main
4 +
5 +if __name__ == "__main__":
6 + main()
src/open_alice/cli.py new
+112
@@ -0,0 +1,112 @@
1 +"""CLI interface for open-alice."""
2 +
3 +from __future__ import annotations
4 +
5 +import argparse
6 +import sys
7 +
8 +from open_alice.data import add_returns, fetch_ohlcv
9 +from open_alice.engine import run_backtest, run_paper
10 +from open_alice.strategies import BollingerStrategy, MacdStrategy, RsiStrategy, SmaCrossover
11 +
12 +STRATEGIES = {
13 + "sma_crossover": SmaCrossover,
14 + "rsi": RsiStrategy,
15 + "macd": MacdStrategy,
16 + "bollinger": BollingerStrategy,
17 +}
18 +
19 +
20 +def main() -> None:
21 + parser = argparse.ArgumentParser(
22 + prog="alice",
23 + description="Alice — an open-source AI trading bot",
24 + )
25 + subparsers = parser.add_subparsers(dest="command", required=True)
26 +
27 + # Backtest command
28 + bt = subparsers.add_parser("backtest", help="Run a backtest")
29 + bt.add_argument("--symbol", default="AAPL", help="Ticker symbol")
30 + bt.add_argument("--strategy", default="sma_crossover", choices=STRATEGIES.keys())
31 + bt.add_argument("--period", default="1y", help="Data period")
32 + bt.add_argument("--capital", type=float, default=100_000, help="Initial capital")
33 + bt.add_argument("--fast", type=int, default=20, help="Fast SMA period")
34 + bt.add_argument("--slow", type=int, default=50, help="Slow SMA period")
35 +
36 + # Paper trading command
37 + paper = subparsers.add_parser("paper", help="Run paper trading simulation")
38 + paper.add_argument("--symbol", default="AAPL", help="Ticker symbol")
39 + paper.add_argument("--strategy", default="sma_crossover", choices=STRATEGIES.keys())
40 + paper.add_argument("--period", default="1y", help="Data period")
41 + paper.add_argument("--capital", type=float, default=100_000, help="Initial capital")
42 + paper.add_argument("--risk", type=float, default=0.02, help="Risk per trade")
43 +
44 + args = parser.parse_args()
45 +
46 + if args.command == "backtest":
47 + _run_backtest(args)
48 + elif args.command == "paper":
49 + _run_paper(args)
50 +
51 +
52 +def _build_strategy(name: str, args: argparse.Namespace):
53 + if name == "sma_crossover":
54 + return SmaCrossover(fast=args.fast, slow=args.slow)
55 + return STRATEGIES[name]()
56 +
57 +
58 +def _run_backtest(args: argparse.Namespace) -> None:
59 + print(f"\n{'='*60}")
60 + print(f" Alice Backtest — {args.symbol}")
61 + print(f" Strategy: {args.strategy} | Period: {args.period} | Capital: ${args.capital:,.0f}")
62 + print(f"{'='*60}\n")
63 +
64 + df = fetch_ohlcv(args.symbol, period=args.period)
65 + df = add_returns(df)
66 +
67 + strategy = _build_strategy(args.strategy, args)
68 + df = strategy.generate_signals(df)
69 +
70 + result = run_backtest(df, initial_capital=args.capital)
71 +
72 + print(f" Total Return: {result.total_return:>10.2%}")
73 + print(f" Sharpe Ratio: {result.sharpe_ratio:>10.2f}")
74 + print(f" Max Drawdown: {result.max_drawdown:>10.2%}")
75 + print(f" Num Trades: {result.num_trades:>10d}")
76 + print(f" Win Rate: {result.win_rate:>10.2%}")
77 + print(f"\n{'='*60}\n")
78 +
79 +
80 +def _run_paper(args: argparse.Namespace) -> None:
81 + print(f"\n{'='*60}")
82 + print(f" Alice Paper Trading — {args.symbol}")
83 + print(f" Strategy: {args.strategy} | Period: {args.period} | Capital: ${args.capital:,.0f}")
84 + print(f"{'='*60}\n")
85 +
86 + df = fetch_ohlcv(args.symbol, period=args.period)
87 + df = add_returns(df)
88 +
89 + strategy = _build_strategy(args.strategy, args)
90 + portfolio = run_paper(df, strategy, initial_capital=args.capital, risk_per_trade=args.risk)
91 +
92 + print(f" Final Equity: ${portfolio.equity:>10,.2f}")
93 + print(f" Cash Remaining: ${portfolio.cash:>10,.2f}")
94 + print(f" Total Trades: {len(portfolio.trades):>10d}")
95 +
96 + if portfolio.trades:
97 + total_pnl = sum(t.get("pnl", 0) for t in portfolio.trades)
98 + print(f" Total P&L: ${total_pnl:>10,.2f}")
99 +
100 + print(f"\n --- Trade Log ---")
101 + for t in portfolio.trades[:20]:
102 + pnl_str = f" P&L: ${t['pnl']:,.2f}" if "pnl" in t else ""
103 + print(f" {t['time'].strftime('%Y-%m-%d %H:%M')} | {t['action']:>4} | {t.get('symbol', ''):>6} | {t.get('shares', 0):>6} @ ${t.get('price', 0):>8.2f}{pnl_str}")
104 +
105 + if len(portfolio.trades) > 20:
106 + print(f" ... and {len(portfolio.trades) - 20} more trades")
107 +
108 + print(f"\n{'='*60}\n")
109 +
110 +
111 +if __name__ == "__main__":
112 + sys.exit(main())
src/open_alice/data.py new
+36
@@ -0,0 +1,36 @@
1 +"""Market data fetching and caching."""
2 +
3 +from __future__ import annotations
4 +
5 +import pandas as pd
6 +import yfinance as yf
7 +
8 +
9 +def fetch_ohlcv(
10 + symbol: str,
11 + period: str = "1y",
12 + interval: str = "1d",
13 +) -> pd.DataFrame:
14 + """Fetch OHLCV data for a symbol via yfinance.
15 +
16 + Args:
17 + symbol: Ticker symbol (e.g. "AAPL", "BTC-USD").
18 + period: Data period ("1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max").
19 + interval: Bar interval ("1m", "5m", "15m", "1h", "1d", "1wk", "1mo").
20 +
21 + Returns:
22 + DataFrame with columns: Open, High, Low, Close, Volume.
23 + """
24 + ticker = yf.Ticker(symbol)
25 + df = ticker.history(period=period, interval=interval, auto_adjust=True)
26 + if df.empty:
27 + raise ValueError(f"No data returned for symbol: {symbol}")
28 + df.index = pd.DatetimeIndex(df.index).tz_localize(None)
29 + return df
30 +
31 +
32 +def add_returns(df: pd.DataFrame) -> pd.DataFrame:
33 + """Add a simple daily returns column."""
34 + df = df.copy()
35 + df["Return"] = df["Close"].pct_change()
36 + return df
src/open_alice/engine/__init__.py new
+6
@@ -0,0 +1,6 @@
1 +"""Backtesting and execution engine."""
2 +
3 +from open_alice.engine.backtest import BacktestResult, run_backtest
4 +from open_alice.engine.paper import PaperPortfolio, run_paper
5 +
6 +__all__ = ["BacktestResult", "run_backtest", "PaperPortfolio", "run_paper"]
src/open_alice/engine/backtest.py new
+80
@@ -0,0 +1,80 @@
1 +"""Backtesting engine."""
2 +
3 +from __future__ import annotations
4 +
5 +from dataclasses import dataclass
6 +
7 +import pandas as pd
8 +
9 +
10 +@dataclass
11 +class BacktestResult:
12 + """Results from a backtest run."""
13 +
14 + equity_curve: pd.Series
15 + returns: pd.Series
16 + total_return: float
17 + sharpe_ratio: float
18 + max_drawdown: float
19 + num_trades: int
20 + win_rate: float
21 +
22 +
23 +def run_backtest(
24 + df: pd.DataFrame,
25 + initial_capital: float = 100_000.0,
26 + commission: float = 0.001,
27 +) -> BacktestResult:
28 + """Run a simple backtest on a DataFrame with Signal and Position columns.
29 +
30 + Args:
31 + df: DataFrame with Close, Signal, and Position columns.
32 + initial_capital: Starting capital.
33 + commission: Per-trade commission as a fraction (0.001 = 0.1%).
34 +
35 + Returns:
36 + BacktestResult with performance metrics.
37 + """
38 + out = df.copy()
39 +
40 + # Strategy returns: position * daily return
41 + out["Strategy_Return"] = out["Position"].shift(1).fillna(0) * out["Return"]
42 +
43 + # Apply commission on position changes
44 + out["Position_Change"] = out["Position"].diff().abs().fillna(0)
45 + out["Strategy_Return"] = out["Strategy_Return"] - out["Position_Change"] * commission
46 +
47 + # Equity curve
48 + out["Equity"] = initial_capital * (1 + out["Strategy_Return"].fillna(0)).cumprod()
49 +
50 + equity = out["Equity"]
51 + returns = out["Strategy_Return"].fillna(0)
52 +
53 + # Metrics
54 + total_return = float(equity.iloc[-1] / initial_capital - 1)
55 +
56 + # Sharpe ratio (annualized, assuming 252 trading days)
57 + mean_return = returns.mean()
58 + std_return = returns.std()
59 + sharpe = float((mean_return / std_return) * (252**0.5)) if std_return > 0 else 0.0
60 +
61 + # Max drawdown
62 + rolling_max = equity.cummax()
63 + drawdown = (equity - rolling_max) / rolling_max
64 + max_drawdown = float(drawdown.min())
65 +
66 + # Trade count and win rate
67 + num_trades = int((out["Position_Change"] > 0).sum())
68 + winning_trades = int((returns > 0).sum())
69 + total_trades_with_return = int((returns != 0).sum())
70 + win_rate = winning_trades / total_trades_with_return if total_trades_with_return > 0 else 0.0
71 +
72 + return BacktestResult(
73 + equity_curve=equity,
74 + returns=returns,
75 + total_return=total_return,
76 + sharpe_ratio=sharpe,
77 + max_drawdown=max_drawdown,
78 + num_trades=num_trades,
79 + win_rate=win_rate,
80 + )
src/open_alice/engine/paper.py new
+106
@@ -0,0 +1,106 @@
1 +"""Paper trading engine."""
2 +
3 +from __future__ import annotations
4 +
5 +from dataclasses import dataclass, field
6 +from datetime import datetime
7 +
8 +import pandas as pd
9 +
10 +
11 +@dataclass
12 +class PaperPosition:
13 + symbol: str
14 + shares: int
15 + entry_price: float
16 + entry_time: datetime
17 +
18 +
19 +@dataclass
20 +class PaperPortfolio:
21 + cash: float
22 + positions: dict[str, PaperPosition] = field(default_factory=dict)
23 + trades: list[dict] = field(default_factory=list)
24 +
25 + @property
26 + def equity(self) -> float:
27 + total = self.cash
28 + for pos in self.positions.values():
29 + total += pos.shares * pos.entry_price
30 + return total
31 +
32 + def buy(self, symbol: str, price: int, shares: int) -> None:
33 + cost = shares * price
34 + if cost > self.cash:
35 + return
36 + self.cash -= cost
37 + self.positions[symbol] = PaperPosition(symbol, shares, price, datetime.now())
38 + self.trades.append({
39 + "time": datetime.now(),
40 + "action": "BUY",
41 + "symbol": symbol,
42 + "shares": shares,
43 + "price": price,
44 + })
45 +
46 + def sell(self, symbol: str, price: float) -> None:
47 + if symbol not in self.positions:
48 + return
49 + pos = self.positions.pop(symbol)
50 + proceeds = pos.shares * price
51 + self.cash += proceeds
52 + pnl = proceeds - (pos.shares * pos.entry_price)
53 + self.trades.append({
54 + "time": datetime.now(),
55 + "action": "SELL",
56 + "symbol": symbol,
57 + "shares": pos.shares,
58 + "price": price,
59 + "pnl": pnl,
60 + })
61 +
62 +
63 +def run_paper(
64 + df: pd.DataFrame,
65 + strategy,
66 + initial_capital: float = 100_000.0,
67 + risk_per_trade: float = 0.02,
68 +) -> PaperPortfolio:
69 + """Run a paper trading simulation.
70 +
71 + Args:
72 + df: OHLCV DataFrame.
73 + strategy: Strategy with generate_signals method.
74 + initial_capital: Starting cash.
75 + risk_per_trade: Fraction of equity risked per trade.
76 +
77 + Returns:
78 + PaperPortfolio with final state and trade log.
79 + """
80 + portfolio = PaperPortfolio(cash=initial_capital)
81 + signals = strategy.generate_signals(df)
82 +
83 + for i in range(1, len(signals)):
84 + row = signals.iloc[i]
85 + prev = signals.iloc[i - 1]
86 +
87 + if row["Signal"] == 1 and prev["Signal"] != 1:
88 + # Buy signal
89 + risk_amount = portfolio.equity * risk_per_trade
90 + stop_distance = row["Close"] * 0.05
91 + if stop_distance > 0:
92 + shares = int(risk_amount / stop_distance)
93 + if shares > 0:
94 + portfolio.buy(row["Close"], shares)
95 +
96 + elif row["Signal"] == -1 and prev["Signal"] != -1:
97 + # Sell signal
98 + for symbol in list(portfolio.positions.keys()):
99 + portfolio.sell(symbol, row["Close"])
100 +
101 + # Close all positions at the end
102 + final_price = signals["Close"].iloc[-1]
103 + for symbol in list(portfolio.positions.keys()):
104 + portfolio.sell(symbol, final_price)
105 +
106 + return portfolio
src/open_alice/risk/__init__.py new
+5
@@ -0,0 +1,5 @@
1 +"""Risk management."""
2 +
3 +from open_alice.risk.position_sizing import PositionSizer
4 +
5 +__all__ = ["PositionSizer"]
src/open_alice/risk/position_sizing.py new
+60
@@ -0,0 +1,60 @@
1 +"""Position sizing and risk management."""
2 +
3 +from __future__ import annotations
4 +
5 +
6 +class PositionSizer:
7 + """Fixed-fractional position sizing.
8 +
9 + Risks a fixed fraction of capital per trade, with optional
10 + stop-loss and take-profit levels.
11 + """
12 +
13 + def __init__(
14 + self,
15 + risk_per_trade: float = 0.02,
16 + stop_loss_pct: float = 0.05,
17 + take_profit_pct: float = 0.10,
18 + ) -> None:
19 + if not 0 < risk_per_trade <= 1:
20 + raise ValueError("risk_per_trade must be between 0 and 1")
21 + self.risk_per_trade = risk_per_trade
22 + self.stop_loss_pct = stop_loss_pct
23 + self.take_profit_pct = take_profit_pct
24 +
25 + def calculate_size(self, capital: float, entry_price: float, stop_price: float) -> int:
26 + """Calculate position size based on risk.
27 +
28 + Args:
29 + capital: Current capital.
30 + entry_price: Entry price per share.
31 + stop_price: Stop-loss price per share.
32 +
33 + Returns:
34 + Number of shares to trade (integer, floored).
35 + """
36 + risk_amount = capital * self.risk_per_trade
37 + risk_per_share = abs(entry_price - stop_price)
38 + if risk_per_share == 0:
39 + return 0
40 + return int(risk_amount / risk_per_share)
41 +
42 + def should_exit(self, entry_price: float, current_price: float, position: int) -> bool:
43 + """Check if stop-loss or take-profit has been hit.
44 +
45 + Args:
46 + entry_price: Original entry price.
47 + current_price: Current market price.
48 + position: Current position (positive=long, negative=short).
49 +
50 + Returns:
51 + True if the position should be closed.
52 + """
53 + if position == 0:
54 + return False
55 +
56 + pnl_pct = (current_price - entry_price) / entry_price
57 + if position > 0:
58 + return pnl_pct <= -self.stop_loss_pct or pnl_pct >= self.take_profit_pct
59 + else:
60 + return pnl_pct >= self.stop_loss_pct or pnl_pct <= -self.take_profit_pct
src/open_alice/strategies/__init__.py new
+8
@@ -0,0 +1,8 @@
1 +"""Trading strategies."""
2 +
3 +from open_alice.strategies.bollinger import BollingerStrategy
4 +from open_alice.strategies.macd import MacdStrategy
5 +from open_alice.strategies.rsi import RsiStrategy
6 +from open_alice.strategies.sma_crossover import SmaCrossover
7 +
8 +__all__ = ["SmaCrossover", "RsiStrategy", "MacdStrategy", "BollingerStrategy"]
src/open_alice/strategies/bollinger.py new
+28
@@ -0,0 +1,28 @@
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
src/open_alice/strategies/macd.py new
+31
@@ -0,0 +1,31 @@
1 +"""MACD (Moving Average Convergence Divergence) strategy."""
2 +
3 +from __future__ import annotations
4 +
5 +import pandas as pd
6 +
7 +
8 +class MacdStrategy:
9 + """Buy when MACD line crosses above signal line, sell when it crosses below."""
10 +
11 + def __init__(self, fast: int = 12, slow: int = 26, signal: int = 9) -> None:
12 + self.fast = fast
13 + self.slow = slow
14 + self.signal = signal
15 +
16 + def generate_signals(self, df: pd.DataFrame) -> pd.DataFrame:
17 + out = df.copy()
18 +
19 + ema_fast = out["Close"].ewm(span=self.fast, adjust=False).mean()
20 + ema_slow = out["Close"].ewm(span=self.slow, adjust=False).mean()
21 +
22 + out["MACD"] = ema_fast - ema_slow
23 + out["MACD_Signal"] = out["MACD"].ewm(span=self.signal, adjust=False).mean()
24 + out["MACD_Hist"] = out["MACD"] - out["MACD_Signal"]
25 +
26 + out["Signal"] = 0
27 + out.loc[out["MACD"] > out["MACD_Signal"], "Signal"] = 1
28 + out.loc[out["MACD"] < out["MACD_Signal"], "Signal"] = -1
29 +
30 + out["Position"] = out["Signal"].replace(0, pd.NA).ffill().fillna(0).astype(int)
31 + return out
src/open_alice/strategies/rsi.py new
+38
@@ -0,0 +1,38 @@
1 +"""RSI (Relative Strength Index) mean-reversion strategy."""
2 +
3 +from __future__ import annotations
4 +
5 +import numpy as np
6 +import pandas as pd
7 +
8 +
9 +class RsiStrategy:
10 + """Buy when RSI oversold, sell when RSI overbought."""
11 +
12 + def __init__(self, period: int = 14, oversold: float = 30, overbought: float = 70) -> None:
13 + self.period = period
14 + self.oversold = oversold
15 + self.overbought = overbought
16 +
17 + @staticmethod
18 + def _rsi(prices: pd.Series, period: int) -> pd.Series:
19 + delta = prices.diff()
20 + gain = delta.clip(lower=0)
21 + loss = -delta.clip(upper=0)
22 +
23 + avg_gain = gain.ewm(alpha=1 / period, min_periods=period).mean()
24 + avg_loss = loss.ewm(alpha=1 / period, min_periods=period).mean()
25 +
26 + rs = avg_gain / avg_loss
27 + return 100 - (100 / (1 + rs))
28 +
29 + def generate_signals(self, df: pd.DataFrame) -> pd.DataFrame:
30 + out = df.copy()
31 + out["RSI"] = self._rsi(out["Close"], self.period)
32 +
33 + out["Signal"] = 0
34 + out.loc[out["RSI"] < self.oversold, "Signal"] = 1
35 + out.loc[out["RSI"] > self.overbought, "Signal"] = -1
36 +
37 + out["Position"] = out["Signal"].replace(0, pd.NA).ffill().fillna(0).astype(int)
38 + return out
src/open_alice/strategies/sma_crossover.py new
+39
@@ -0,0 +1,39 @@
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
tests/__init__.py
tests/test_backtest.py new
+37
@@ -0,0 +1,37 @@
1 +"""Tests for the backtesting engine."""
2 +
3 +import pandas as pd
4 +import pytest
5 +
6 +from open_alice.engine.backtest import run_backtest
7 +
8 +
9 +@pytest.fixture
10 +def sample_ohlcv() -> pd.DataFrame:
11 + dates = pd.date_range("2024-01-01", periods=100, freq="D")
12 + prices = pd.Series(range(100, 200), dtype=float)
13 + returns = prices.pct_change()
14 + return pd.DataFrame(
15 + {
16 + "Close": prices,
17 + "Return": returns,
18 + "Signal": [1] * 50 + [-1] * 50,
19 + "Position": [1] * 50 + [-1] * 50,
20 + },
21 + index=dates,
22 + )
23 +
24 +
25 +def test_backtest_returns_result(sample_ohlcv: pd.DataFrame) -> None:
26 + result = run_backtest(sample_ohlcv)
27 + assert result.total_return is not None
28 + assert result.sharpe_ratio is not None
29 + assert result.max_drawdown is not None
30 + assert result.num_trades is not None
31 + assert result.win_rate is not None
32 +
33 +
34 +def test_backtest_equity_curve(sample_ohlcv: pd.DataFrame) -> None:
35 + result = run_backtest(sample_ohlcv, initial_capital=100_000)
36 + assert len(result.equity_curve) == 100
37 + assert result.equity_curve.iloc[0] == pytest.approx(100_000)
tests/test_bollinger.py new
+30
@@ -0,0 +1,30 @@
1 +"""Tests for Bollinger Bands strategy."""
2 +
3 +import pandas as pd
4 +import pytest
5 +
6 +from open_alice.strategies.bollinger import BollingerStrategy
7 +
8 +
9 +@pytest.fixture
10 +def sample_data() -> pd.DataFrame:
11 + dates = pd.date_range("2024-01-01", periods=100, freq="D")
12 + prices = pd.Series(range(100, 200), dtype=float)
13 + return pd.DataFrame({"Close": prices}, index=dates)
14 +
15 +
16 +def test_bollinger_columns(sample_data: pd.DataFrame) -> None:
17 + strat = BollingerStrategy(period=20)
18 + result = strat.generate_signals(sample_data)
19 + assert "BB_Mid" in result.columns
20 + assert "BB_Upper" in result.columns
21 + assert "BB_Lower" in result.columns
22 + assert "Signal" in result.columns
23 + assert "Position" in result.columns
24 +
25 +
26 +def test_bollinger_upper_above_lower(sample_data: pd.DataFrame) -> None:
27 + strat = BollingerStrategy(period=20)
28 + result = strat.generate_signals(sample_data)
29 + valid = result.dropna(subset=["BB_Upper", "BB_Lower"])
30 + assert (valid["BB_Upper"] >= valid["BB_Lower"]).all()
tests/test_macd.py new
+23
@@ -0,0 +1,23 @@
1 +"""Tests for MACD strategy."""
2 +
3 +import pandas as pd
4 +import pytest
5 +
6 +from open_alice.strategies.macd import MacdStrategy
7 +
8 +
9 +@pytest.fixture
10 +def sample_data() -> pd.DataFrame:
11 + dates = pd.date_range("2024-01-01", periods=100, freq="D")
12 + prices = pd.Series(range(100, 200), dtype=float)
13 + return pd.DataFrame({"Close": prices}, index=dates)
14 +
15 +
16 +def test_macd_columns(sample_data: pd.DataFrame) -> None:
17 + strat = MacdStrategy()
18 + result = strat.generate_signals(sample_data)
19 + assert "MACD" in result.columns
20 + assert "MACD_Signal" in result.columns
21 + assert "MACD_Hist" in result.columns
22 + assert "Signal" in result.columns
23 + assert "Position" in result.columns
tests/test_paper.py new
+43
@@ -0,0 +1,43 @@
1 +"""Tests for paper trading engine."""
2 +
3 +import pandas as pd
4 +import pytest
5 +
6 +from open_alice.engine.paper import PaperPortfolio, run_paper
7 +from open_alice.strategies.sma_crossover import SmaCrossover
8 +
9 +
10 +@pytest.fixture
11 +def sample_ohlcv() -> pd.DataFrame:
12 + dates = pd.date_range("2024-01-01", periods=100, freq="D")
13 + prices = pd.Series(range(100, 200), dtype=float)
14 + returns = prices.pct_change()
15 + return pd.DataFrame(
16 + {"Close": prices, "Return": returns, "Signal": 1, "Position": 1},
17 + index=dates,
18 + )
19 +
20 +
21 +def test_paper_portfolio_buy_sell() -> None:
22 + portfolio = PaperPortfolio(cash=100_000)
23 + portfolio.buy("TEST", 100.0, 10)
24 + assert portfolio.cash == 90_000
25 + assert "TEST" in portfolio.positions
26 +
27 + portfolio.sell("TEST", 110.0)
28 + assert portfolio.cash == 101_000
29 + assert "TEST" not in portfolio.positions
30 +
31 +
32 +def test_paper_portfolio_insufficient_funds() -> None:
33 + portfolio = PaperPortfolio(cash=100)
34 + portfolio.buy("TEST", 100.0, 10)
35 + assert portfolio.cash == 100
36 + assert "TEST" not in portfolio.positions
37 +
38 +
39 +def test_run_paper(sample_ohlcv: pd.DataFrame) -> None:
40 + strategy = SmaCrossover(fast=5, slow=10)
41 + portfolio = run_paper(sample_ohlcv, strategy, initial_capital=100_000)
42 + assert portfolio.equity > 0
43 + assert isinstance(portfolio.trades, list)
tests/test_position_sizing.py new
+41
@@ -0,0 +1,41 @@
1 +"""Tests for position sizing and risk management."""
2 +
3 +import pytest
4 +
5 +from open_alice.risk.position_sizing import PositionSizer
6 +
7 +
8 +def test_calculate_size_basic() -> None:
9 + sizer = PositionSizer(risk_per_trade=0.02)
10 + # $100k capital, risk 2% = $2000, risk $5/share => 400 shares
11 + size = sizer.calculate_size(capital=100_000, entry_price=100, stop_price=95)
12 + assert size == 400
13 +
14 +
15 +def test_calculate_size_zero_risk_per_share() -> None:
16 + sizer = PositionSizer(risk_per_trade=0.02)
17 + size = sizer.calculate_size(capital=100_000, entry_price=100, stop_price=100)
18 + assert size == 0
19 +
20 +
21 +def test_should_exit_stop_loss() -> None:
22 + sizer = PositionSizer(stop_loss_pct=0.05)
23 + # Long position, price dropped 6% — should exit
24 + assert sizer.should_exit(entry_price=100, current_price=94, position=1) is True
25 +
26 +
27 +def test_should_exit_take_profit() -> None:
28 + sizer = PositionSizer(take_profit_pct=0.10)
29 + # Long position, price rose 12% — should exit
30 + assert sizer.should_exit(entry_price=100, current_price=112, position=1) is True
31 +
32 +
33 +def test_should_not_exit() -> None:
34 + sizer = PositionSizer(stop_loss_pct=0.05, take_profit_pct=0.10)
35 + # Long position, price moved 2% — within bounds
36 + assert sizer.should_exit(entry_price=100, current_price=102, position=1) is False
37 +
38 +
39 +def test_invalid_risk_per_trade() -> None:
40 + with pytest.raises(ValueError):
41 + PositionSizer(risk_per_trade=1.5)
tests/test_rsi.py new
+27
@@ -0,0 +1,27 @@
1 +"""Tests for RSI strategy."""
2 +
3 +import pandas as pd
4 +import pytest
5 +
6 +from open_alice.strategies.rsi import RsiStrategy
7 +
8 +
9 +@pytest.fixture
10 +def sample_data() -> pd.DataFrame:
11 + dates = pd.date_range("2024-01-01", periods=100, freq="D")
12 + prices = pd.Series(range(100, 200), dtype=float)
13 + return pd.DataFrame({"Close": prices}, index=dates)
14 +
15 +
16 +def test_rsi_columns(sample_data: pd.DataFrame) -> None:
17 + strat = RsiStrategy(period=14)
18 + result = strat.generate_signals(sample_data)
19 + assert "RSI" in result.columns
20 + assert "Signal" in result.columns
21 + assert "Position" in result.columns
22 +
23 +
24 +def test_rsi_bounds(sample_data: pd.DataFrame) -> None:
25 + strat = RsiStrategy(period=14)
26 + result = strat.generate_signals(sample_data)
27 + assert result["RSI"].dropna().between(0, 100).all()
tests/test_sma_crossover.py new
+34
@@ -0,0 +1,34 @@
1 +"""Tests for SMA Crossover strategy."""
2 +
3 +import pandas as pd
4 +import pytest
5 +
6 +from open_alice.strategies.sma_crossover import SmaCrossover
7 +
8 +
9 +@pytest.fixture
10 +def sample_data() -> pd.DataFrame:
11 + dates = pd.date_range("2024-01-01", periods=100, freq="D")
12 + prices = pd.Series(range(100, 200), dtype=float)
13 + return pd.DataFrame({"Close": prices}, index=dates)
14 +
15 +
16 +def test_generate_signals_columns(sample_data: pd.DataFrame) -> None:
17 + strat = SmaCrossover(fast=5, slow=10)
18 + result = strat.generate_signals(sample_data)
19 + assert "SMA_fast" in result.columns
20 + assert "SMA_slow" in result.columns
21 + assert "Signal" in result.columns
22 + assert "Position" in result.columns
23 +
24 +
25 +def test_invalid_periods() -> None:
26 + with pytest.raises(ValueError):
27 + SmaCrossover(fast=50, slow=20)
28 +
29 +
30 +def test_uptrend_generates_buy_signal(sample_data: pd.DataFrame) -> None:
31 + strat = SmaCrossover(fast=5, slow=10)
32 + result = strat.generate_signals(sample_data)
33 + # In a strong uptrend, fast SMA should be above slow SMA
34 + assert result["Signal"].iloc[-1] == 1