KatInterview

Backtest a Mean-Reversion Trading System

Arrays & HashingAuto-graded · 13 test cases
HardAuto-gradedArrays & Hashingbacktestingtime-seriesfinance

Last updated

Tests ability to implement a complete trading backtest with entry/exit logic, transaction costs, performance metrics, train/test splits, and statistical validation.

You are building a backtesting engine for a simple mean-reversion trading strategy on minute-level price data.

Given a list of OHLCV bars (open, high, low, close, volume), implement a backtest that:

  1. Strategy Logic: Uses a rolling 20-bar window to compute the mean and standard deviation of closing prices. The z-score is (close - mean) / std. When |z| >= 2.0, signal a trade in the opposite direction (buy when z <= -2.0, sell when z >= 2.0). Exit when |z| <= 0.1, or when a stop-loss is hit (1% adverse move from entry), or after holding for 60 bars.

  2. Execution Model: Signals are generated at bar close. Orders fill at the next bar's open price. No position is held across the end of the data.

  3. Position Sizing: Each trade risks 0.1% of current cash, sized by the stop distance. The maximum position value is capped by available cash.

  4. Transaction Costs: Each fill incurs 0.01% fee and 0.02% slippage, applied to the trade price.

  5. Performance Metrics: Compute PnL (final equity minus initial capital of $100,000), win rate (fraction of profitable trades), average trade P&L, max drawdown (as a fraction of peak equity), annualized volatility (using bar-to-bar returns and 98,280 bars per year), annualized Sharpe ratio, total turnover (sum of trade notional divided by initial capital), and trade count.

  6. Validation: Split the data 70/30 into train and test sets. Report metrics for overall, train, and test periods separately. Run a bootstrap test on the test-set trades: resample the test trades 1,000 times with replacement (using a fixed seed for reproducibility) and compute the p-value as the fraction of bootstrap samples with mean trade P&L >= observed mean.

Return a dictionary with keys "overall", "train", "test" (each containing the metrics), and "bootstrap_p_value".

Input:

  • bars: a list of lists, where each inner list is [open, high, low, close, volume] as floats, in chronological order.

Output:

  • A dictionary with four keys:
    • "overall", "train", "test": each a dict containing "pnl", "win_rate", "average_trade", "max_drawdown", "volatility", "sharpe", "turnover", "trades" (integer count).
    • "bootstrap_p_value": float.

Constraints:

  • 0 ≤ len(bars) ≤ 100,000
  • All price and volume values are non-negative floats
  • Bars may have zero or invalid prices; handle them gracefully (skip trading logic but track equity)
  • Use the LCG seed 24681357 for bootstrap resampling: state = (1103515245 * state + 12345) % 2^31
  • Return 0 or 0.0 for metrics when no trades occur
  • Return p-value = 1.0 when there are no test trades

Examples

Example 1

Input: backtest_mean_reversion([[100, 100, 100, 100, 100], [100, 100, 100, 100, 100], [100, 100, 100, 100, 100], [100, 100, 100, 100, 100], [100, 100, 100, 100, 100]])

Output: {'overall': {'pnl': 0, 'win_rate': 0, 'average_trade': 0, 'max_drawdown': 0, 'volatility': 0, 'sharpe': 0, 'turnover': 0, 'trades': 0}, 'train': {'pnl': 0, 'win_rate': 0, 'average_trade': 0, 'max_drawdown': 0, 'volatility': 0, 'sharpe': 0, 'turnover': 0, 'trades': 0}, 'test': {'pnl': 0, 'win_rate': 0, 'average_trade': 0, 'max_drawdown': 0, 'volatility': 0, 'sharpe': 0, 'turnover': 0, 'trades': 0}, 'bootstrap_p_value': 1}

Example 2

Input: backtest_mean_reversion([[100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100], [100, 101, 99, 100, 100]])

Output: {'overall': {'pnl': 0, 'win_rate': 0, 'average_trade': 0, 'max_drawdown': 0, 'volatility': 0, 'sharpe': 0, 'turnover': 0, 'trades': 0}, 'train': {'pnl': 0, 'win_rate': 0, 'average_trade': 0, 'max_drawdown': 0, 'volatility': 0, 'sharpe': 0, 'turnover': 0, 'trades': 0}, 'test': {'pnl': 0, 'win_rate': 0, 'average_trade': 0, 'max_drawdown': 0, 'volatility': 0, 'sharpe': 0, 'turnover': 0, 'trades': 0}, 'bootstrap_p_value': 1}

Hints

Hint 1

Track cash and position separately; equity at each bar is cash plus position value at the current close price

Hint 2

Generate the trade signal at bar i but execute at bar i+1's open to avoid look-ahead bias

Hint 3

For the bootstrap p-value, count how many resampled means are at least as large as the observed mean, then divide by (number of samples + 1)