Backtest a Mean-Reversion Trading System
Arrays & HashingAuto-graded · 13 test casesLast 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:
-
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. -
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.
-
Position Sizing: Each trade risks 0.1% of current cash, sized by the stop distance. The maximum position value is capped by available cash.
-
Transaction Costs: Each fill incurs 0.01% fee and 0.02% slippage, applied to the trade price.
-
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.
-
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)
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is implementing a realistic backtest that avoids look-ahead bias, models transaction costs accurately, and validates results statistically.
Strategy mechanics: Calculate a rolling z-score over the most recent 20 closing prices. When price deviates more than 2 standard deviations from the mean (z <= -2 or z >= 2), open a position betting on reversion. Exit when price returns near the mean (|z| <= 0.1), or when a stop-loss triggers (1% adverse move), or after 60 bars.
Execution timing: Generate signals at each bar's close but execute at the next bar's open. This prevents using future information. Track a pending order that fills at the subsequent open price.
Position sizing: Risk a fixed fraction (0.1%) of available cash per trade, scaled by the stop distance. Cap the position so it doesn't exceed available capital.
Cost model: Apply fees (0.01%) and slippage (0.02%) to every fill, increasing the effective buy price and decreasing the effective sell price.
Performance measurement: Track equity at every bar. Compute bar-to-bar returns to measure volatility and Sharpe ratio, annualized using 98,280 bars per year (390 minutes/day × 252 days). Drawdown is the peak-to-trough decline as a fraction of peak equity. Win rate and average trade come from the list of completed round-trip trades.
Train/test split: Use the first 70% of bars for training metrics, the remaining 30% for test metrics. Report all three: overall, train, and test.
Bootstrap validation: Resample the test trades 1,000 times with replacement using a linear congruential generator seeded at 24681357. Count how many bootstrap means equal or exceed the observed mean. The p-value is (count + 1) / 1001, representing the probability of observing such performance by chance.
Why it works: Mean reversion exploits temporary price dislocations. The z-score quantifies how extreme the deviation is. Position sizing limits risk per trade. The bootstrap test accounts for sample variability and guards against overfitting.
Time complexity: O(n · w) where n is the number of bars and w is the lookback window (20). Each bar recomputes the rolling mean and standard deviation.
Space complexity: O(n) to store the equity curve and closing prices.
import math
from typing import List, Dict
def backtest_mean_reversion(bars: List[List[float]]) -> Dict[str, object]:
initial_capital = 100000.0
fee_rate = 0.0001
slippage_rate = 0.0002
lookback_window = 20
stop_loss_pct = 0.01
risk_per_trade = 0.001
max_hold_bars = 60
annual_factor = 390.0 * 252.0
def compute_metrics(data):
if not data:
return {"pnl": 0.0, "win_rate": 0.0, "average_trade": 0.0,
"max_drawdown": 0.0, "volatility": 0.0, "sharpe": 0.0,
"turnover": 0.0, "trades": 0}
cash = initial_capital
position_qty = 0.0
entry_effective_price = 0.0
entry_raw_price = 0.0
entry_bar_index = 0
pending_order = None
completed_trades = []
equity_curve = []
total_turnover = 0.0
close_prices = []
def apply_costs(price, is_buy):
multiplier = 1.0 + fee_rate + slippage_rate if is_buy else 1.0 - fee_rate - slippage_rate
return price * multiplier
def exit_position(exit_price):
nonlocal cash, position_qty, total_turnover
if position_qty == 0.0:
return
is_buy = position_qty < 0.0
effective_price = apply_costs(exit_price, is_buy)
trade_notional = abs(position_qty * effective_price)
total_turnover += trade_notional
if position_qty > 0.0:
cash += position_qty * effective_price
trade_pnl = position_qty * (effective_price - entry_effective_price)
else:
cash -= (-position_qty) * effective_price
trade_pnl = (-position_qty) * (entry_effective_price - effective_price)
completed_trades.append(trade_pnl)
position_qty = 0.0
for bar_idx, bar in enumerate(data):
open_px, high_px, low_px, close_px, vol = map(float, bar[:5])
if open_px <= 0.0 or close_px <= 0.0:
equity_curve.append(cash + position_qty * max(close_px, 0.0))
continue
close_prices.append(close_px)
if pending_order == "entry_long" and position_qty == 0.0:
stop_distance = open_px * stop_loss_pct
risk_capital = max(cash, 0.0) * risk_per_trade
shares = min(risk_capital / stop_distance, max(cash, 0.0) / open_px) if stop_distance > 0.0 else 0.0
entry_effective_price = apply_costs(open_px, True)
if shares > 0.0:
position_qty = shares
cash -= shares * entry_effective_price
total_turnover += shares * entry_effective_price
entry_raw_price = open_px
entry_bar_index = bar_idx
elif pending_order == "entry_short" and position_qty == 0.0:
stop_distance = open_px * stop_loss_pct
risk_capital = max(cash, 0.0) * risk_per_trade
shares = min(risk_capital / stop_distance, max(cash, 0.0) / open_px) if stop_distance > 0.0 else 0.0
entry_effective_price = apply_costs(open_px, False)
if shares > 0.0:
position_qty = -shares
cash += shares * entry_effective_price
total_turnover += shares * entry_effective_price
entry_raw_price = open_px
entry_bar_index = bar_idx
elif pending_order == "exit" and position_qty != 0.0:
exit_position(open_px)
pending_order = None
if len(close_prices) >= lookback_window:
window = close_prices[-lookback_window:]
mean_price = sum(window) / lookback_window
variance = sum((x - mean_price) ** 2 for x in window) / lookback_window
std_dev = math.sqrt(variance)
z_score = (close_px - mean_price) / std_dev if std_dev > 0.0 else 0.0
if position_qty == 0.0:
if z_score <= -2.0:
pending_order = "entry_long"
elif z_score >= 2.0:
pending_order = "entry_short"
else:
stop_triggered = ((position_qty > 0.0 and close_px <= entry_raw_price * (1.0 - stop_loss_pct)) or
(position_qty < 0.0 and close_px >= entry_raw_price * (1.0 + stop_loss_pct)))
time_stop = bar_idx - entry_bar_index + 1 >= max_hold_bars
mean_revert = abs(z_score) <= 0.1
if mean_revert or stop_triggered or time_stop:
pending_order = "exit"
equity_curve.append(cash + position_qty * close_px)
if position_qty != 0.0:
exit_position(float(data[-1][3]))
equity_curve[-1] = cash
bar_returns = [(equity_curve[i] / equity_curve[i - 1] - 1.0) if equity_curve[i - 1] > 0.0 else 0.0
for i in range(1, len(equity_curve))]
peak_equity = initial_capital
max_dd = 0.0
for equity_val in equity_curve:
peak_equity = max(peak_equity, equity_val)
if peak_equity > 0.0:
drawdown = (peak_equity - equity_val) / peak_equity
max_dd = max(max_dd, drawdown)
if bar_returns:
mean_return = sum(bar_returns) / len(bar_returns)
return_variance = sum((r - mean_return) ** 2 for r in bar_returns) / len(bar_returns)
volatility = math.sqrt(return_variance * annual_factor)
sharpe = mean_return / math.sqrt(return_variance) * math.sqrt(annual_factor) if return_variance > 0.0 else 0.0
else:
volatility = sharpe = 0.0
winning_trades = sum(1 for t in completed_trades if t > 0.0)
return {
"pnl": equity_curve[-1] - initial_capital,
"win_rate": winning_trades / len(completed_trades) if completed_trades else 0.0,
"average_trade": sum(completed_trades) / len(completed_trades) if completed_trades else 0.0,
"max_drawdown": max_dd,
"volatility": volatility,
"sharpe": sharpe,
"turnover": total_turnover / initial_capital,
"trades": len(completed_trades),
"_trade_list": completed_trades
}
def strip_internal(result):
return {k: v for k, v in result.items() if not k.startswith("_")}
num_bars = len(bars)
if num_bars == 0:
empty_result = strip_internal(compute_metrics([]))
return {
"overall": empty_result,
"train": empty_result,
"test": empty_result,
"bootstrap_p_value": 1.0
}
split_index = max(1, int(num_bars * 0.7))
overall_metrics = compute_metrics(bars)
train_metrics = compute_metrics(bars[:split_index])
test_metrics = compute_metrics(bars[split_index:])
test_trade_list = test_metrics.get("_trade_list", [])
if not test_trade_list:
p_value = 1.0
else:
observed_mean = sum(test_trade_list) / len(test_trade_list)
rng_state = 24681357
extreme_count = 0
for _ in range(1000):
bootstrap_sum = 0.0
for _ in test_trade_list:
rng_state = (1103515245 * rng_state + 12345) % 2147483648
sample_idx = rng_state % len(test_trade_list)
bootstrap_sum += test_trade_list[sample_idx]
bootstrap_mean = bootstrap_sum / len(test_trade_list)
if bootstrap_mean >= observed_mean:
extreme_count += 1
p_value = (extreme_count + 1.0) / 1001.0
return {
"overall": strip_internal(overall_metrics),
"train": strip_internal(train_metrics),
"test": strip_internal(test_metrics),
"bootstrap_p_value": p_value
}