Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
| 1 | """Pure helpers that turn strategy output into dashboard JSON payloads.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | from typing import Any |
| 6 | |
| 7 | import pandas as pd |
| 8 | |
| 9 | from open_alice.engine import run_backtest |
| 10 | from open_alice.strategies import ( |
| 11 | BollingerStrategy, |
| 12 | MacdStrategy, |
| 13 | RsiStrategy, |
| 14 | SmaCrossover, |
| 15 | Strategy, |
| 16 | ) |
| 17 | |
| 18 | _OVERLAY_COLUMNS: dict[str, list[str]] = { |
| 19 | "sma_crossover": ["SMA_fast", "SMA_slow"], |
| 20 | "rsi": ["RSI"], |
| 21 | "macd": ["MACD", "MACD_Signal"], |
| 22 | "bollinger": ["BB_Upper", "BB_Mid", "BB_Lower"], |
| 23 | } |
| 24 | |
| 25 | |
| 26 | def build_strategy(name: str, fast: int = 20, slow: int = 50) -> Strategy: |
| 27 | """Build a strategy instance by name.""" |
| 28 | if name == "sma_crossover": |
| 29 | return SmaCrossover(fast=fast, slow=slow) |
| 30 | factories: dict[str, type[Strategy]] = { |
| 31 | "rsi": RsiStrategy, |
| 32 | "macd": MacdStrategy, |
| 33 | "bollinger": BollingerStrategy, |
| 34 | } |
| 35 | return factories[name]() |
| 36 | |
| 37 | |
| 38 | def chart_payload( |
| 39 | df: pd.DataFrame, |
| 40 | strategy_name: str, |
| 41 | fast: int = 20, |
| 42 | slow: int = 50, |
| 43 | max_points: int = 300, |
| 44 | ) -> dict[str, Any]: |
| 45 | """Run a strategy + backtest and return a JSON-serializable chart payload. |
| 46 | |
| 47 | Args: |
| 48 | df: OHLCV DataFrame with a Returns column (see data.add_returns). |
| 49 | strategy_name: One of sma_crossover, rsi, macd, bollinger. |
| 50 | fast: Fast SMA period (sma_crossover only). |
| 51 | slow: Slow SMA period (sma_crossover only). |
| 52 | max_points: Downsample to at most this many chart points. |
| 53 | |
| 54 | Returns: |
| 55 | Dict with labels, close, overlays, markers, equity and metrics. |
| 56 | """ |
| 57 | strategy = build_strategy(strategy_name, fast=fast, slow=slow) |
| 58 | framed = strategy.generate_signals(df) |
| 59 | if len(framed) > max_points: |
| 60 | step = len(framed) // max_points + 1 |
| 61 | framed = framed.iloc[::step] |
| 62 | |
| 63 | result = run_backtest(framed) |
| 64 | |
| 65 | labels = [_label(ts) for ts in framed.index] |
| 66 | payload: dict[str, Any] = { |
| 67 | "labels": labels, |
| 68 | "close": [float(v) for v in framed["Close"].tolist()], |
| 69 | "overlays": { |
| 70 | col: [None if pd.isna(v) else float(v) for v in framed[col].tolist()] |
| 71 | for col in _OVERLAY_COLUMNS[strategy_name] |
| 72 | if col in framed.columns |
| 73 | }, |
| 74 | "markers": _signal_markers(framed), |
| 75 | "equity": { |
| 76 | "labels": labels, |
| 77 | "values": [float(v) for v in result.equity_curve.tolist()], |
| 78 | }, |
| 79 | "metrics": { |
| 80 | "total_return": result.total_return, |
| 81 | "sharpe_ratio": result.sharpe_ratio, |
| 82 | "max_drawdown": result.max_drawdown, |
| 83 | "num_trades": result.num_trades, |
| 84 | "win_rate": result.win_rate, |
| 85 | }, |
| 86 | } |
| 87 | return payload |
| 88 | |
| 89 | |
| 90 | def _label(ts: Any) -> str: |
| 91 | if hasattr(ts, "isoformat"): |
| 92 | return str(ts.isoformat()) |
| 93 | return str(ts) |
| 94 | |
| 95 | |
| 96 | def _signal_markers(framed: pd.DataFrame) -> list[dict[str, Any]]: |
| 97 | """Extract fresh buy/sell markers from Signal/Position columns.""" |
| 98 | if "Signal" not in framed.columns: |
| 99 | return [] |
| 100 | sig = framed["Signal"] |
| 101 | prev = sig.shift(1).fillna(0) |
| 102 | markers: list[dict[str, Any]] = [] |
| 103 | for ts, row in framed[(sig == 1) & (prev != 1)].iterrows(): |
| 104 | markers.append({"t": _label(ts), "price": float(row["Close"]), "side": "buy"}) |
| 105 | for ts, row in framed[(sig == -1) & (prev != -1)].iterrows(): |
| 106 | markers.append({"t": _label(ts), "price": float(row["Close"]), "side": "sell"}) |
| 107 | return markers |