Strategy Backtester
Goal: Backtest a trading strategy on historical OHLCV data and produce a markdown report plus structured metrics (Sharpe, return, drawdown, win rate) and trade list for pipeline or human use.
Description
Backtests trading strategies on historical data and calculates performance metrics (Sharpe, drawdown, win rate, etc.).
Usage
- •"Backtest [strategy] on [symbol] from [start] to [end]"
- •"Test momentum strategy on SPY 2020-2023"
- •"Compare strategy A vs strategy B"
- •"Run backtest with [parameters]"
When run by pipeline, also output a JSON object with trades (array), metrics (sharpe_ratio, total_return, max_drawdown, win_rate), and trade_count.
Pipeline Contract (tdlc-backtest.lobster)
Inputs (from pipeline or user; bin wrapper passes --strategy, --symbol, --start, --end):
- •
strategy(string): e.g. "momentum", "mean-reversion", "breakout". - •
symbol(string): e.g. "SPY", "AAPL". - •
start_date,end_date(strings): YYYY-MM-DD. - •
parameters(object, optional): Strategy-specific (e.g. lookback days, thresholds). Defaults in Implementation.
Output: Markdown report (see Output Format below) plus, when by pipeline, a clearly delimited JSON block (e.g. json ... ) with: trades (array of { date, side, price, size, pnl }), metrics (sharpe_ratio, total_return, max_drawdown, win_rate; numeric types, not strings), trade_count (number).
Implementation
Execute in order. Do not run the Lobster tool or any pipeline. Use Python if available (pandas, yfinance); otherwise use bash + curl for data and compute metrics in a small script or inline.
Step 1: Fetch Historical Price Data
- •Prefer TimescaleDB/workspace data if available: if the workspace has TimescaleDB or a data client, query OHLCV for
symbolfromstart_datetoend_date. - •Else use yfinance: e.g.
python -c "import yfinance as yf; d=yf.download('SPY', start='...', end='...'); print(d)"or run a small script that saves OHLCV to a DataFrame or CSV. - •Require columns: date (index or column), Open, High, Low, Close, Volume (Volume optional). Normalize column names to lowercase.
Step 2: Apply Strategy Logic
- •Momentum: Default lookback 20 days. Signal = (Close - Close.shift(lookback)) / Close.shift(lookback). Buy when > entry threshold (e.g. 0.02), sell when < exit threshold (e.g. -0.01).
- •Mean-reversion: Default lookback 20, entry when price < SMA - k*std, exit when price > SMA.
- •Breakout: Entry when Close > max(High, lookback), exit when Close < min(Low, lookback).
- •Use
parametersto override defaults. Output a series of signals (1 = long, -1 = short, 0 = flat) aligned with dates.
Step 3: Simulate Trades
- •Initial capital (e.g. 100000). Position size: fixed fractional (e.g. 100% on signal change) or fixed amount per trade. Apply slippage (e.g. 0.1%) and fee (e.g. 0.1%) per trade. Record each trade: date, side, price, size, pnl. Append to
tradeslist. Computetrade_count = len(trades).
Step 4: Calculate Metrics
- •From equity curve (cumulative PnL or portfolio value over time): total_return (%), annualized return, volatility (annualized). Sharpe = (annualized return - risk_free) / volatility (risk_free ≈ 0). Sortino uses downside deviation. Max drawdown = max(peak - trough) / peak. Win rate = winning trades / total trades. Set
metrics.sharpe_ratio,total_return,max_drawdown,win_rate(and optional sortino_ratio, calmar_ratio). Ensure metrics are numbers, not strings, for pipeline consumption.
Step 5: Report and Optional Chart
- •Write markdown report: Strategy, Symbol, Period, Performance Metrics, Trade Statistics, Strategy Parameters. Optionally generate equity curve (matplotlib to PNG or ASCII art) and reference path in report.
- •When invoked by pipeline: after the markdown report, include a clearly delimited JSON block (e.g.
json ...) with keystrades,metrics,trade_countso the pipeline or a future wrapper can parse the result.
Metrics Calculated
- •Total Return %
- •Sharpe Ratio
- •Sortino Ratio
- •Max Drawdown
- •Win Rate
- •Avg Win / Avg Loss
- •Number of Trades
- •Avg Hold Time
Output Format
Backtest Results: Momentum Strategy on SPY (2020-01-01 to 2023-12-31) Performance Metrics: - Total Return: +45.3% - Sharpe Ratio: 1.82 - Sortino Ratio: 2.41 - Max Drawdown: -12.4% - Calmar Ratio: 3.65 Trade Statistics: - Total Trades: 127 - Win Rate: 58% - Avg Win: +2.3% - Avg Loss: -1.1% - Avg Hold Time: 8 days [Equity Curve Chart - shows growth over time] [Drawdown Chart - shows peak-to-trough declines] Strategy Parameters: - Lookback Period: 20 days - Entry Threshold: 0.5 - Exit Threshold: -0.3