Building a High-Performance Mean Reversion Bot in Python with VectorBT


Mean reversion strategies rest on a core mathematical principle: extreme price extensions from a statistical moving average tend to snap back toward the mean over a predictable lookback window.

In this guide, we break down how to implement a production-ready mean reversion backtest using Python and VectorBT, one of the fastest vector-based backtesting engines in quantitative finance.

1. Strategy Mathematical Rules

We utilize a 20-period Bollinger Band alongside a 14-period Relative Strength Index (RSI) filter:

  • Entry Condition (Long): Close crosses below the Lower Bollinger Band ($2\sigma$) AND $RSI < 30$.
  • Exit Condition (Close): Close touches the Middle Band (20 SMA) OR Stop Loss of 2% is hit.
  • Slippage & Fees: 0.05% per execution modeled on liquid equities.

2. Python Implementation

Here is the clean vectorized logic using vectorbt and yfinance:

import vectorbt as vbt
import numpy as np

# Download historical market data
price = vbt.YFData.download("SPY", start="2022-01-01").get("Close")

# Compute Bollinger Bands and RSI
bb = vbt.BBANDS.run(price, window=20, alpha=2)
rsi = vbt.RSI.run(price, window=14)

# Define Entry & Exit Signals
entries = (price < bb.lower) & (rsi.rsi < 30)
exits = price >= bb.middle

# Execute Portfolio Backtest
portfolio = vbt.Portfolio.from_signals(
    price,
    entries=entries,
    exits=exits,
    fees=0.0005,
    slippage=0.0005,
    freq="1D"
)

print(portfolio.stats())

3. Backtest Metrics & Caveats

When evaluating any mean reversion framework, pay close attention to:

  1. Max Drawdown (MDD): Strong trend days can produce significant drawdowns if strict stop-losses are omitted.
  2. Sharpe & Sortino Ratios: A healthy intraday or daily mean reversion system should produce a Sharpe ratio $> 1.4$.
  3. Execution Latency: If deploying intraday, consider using WebSocket feeds rather than REST API polling to minimize slippage.

Disclaimer: This post is for technical and educational purposes only and does not constitute financial advice.

SEBI MANDATORY REGULATORY DISCLAIMER

Important Notice & Educational Purpose: XAlgoPro (xalgopro.com) and its authors/contributors are NOT SEBI registered Research Analysts (RA) or Investment Advisers (IA) under the SEBI (Research Analysts) Regulations, 2014, or SEBI (Investment Advisers) Regulations, 2013.

All content, algorithmic logic, indicators, Pine Script codes, Python scripts, statistical models, mathematical formulas, and backtest results presented on this platform are published strictly for educational, academic, and technological research purposes only. Nothing on this website constitutes investment advice, financial guidance, an offer, recommendation, or solicitation to buy or sell any security, derivative, contract, or financial instrument on the National Stock Exchange (NSE), Bombay Stock Exchange (BSE), or any other global exchange.

SEBI Statutory Risk Disclosure on Derivatives (F&O):As per SEBI study on Intraday & Derivatives trading, 9 out of 10 individual traders in the Equity Futures and Options (F&O) segment incurred net losses, with an average loss of over ₹50,000 per trader. Over and above net trading losses, loss-makers expended an additional 15% to 50% in transaction fees, brokerage, and statutory taxes (STT, GST, Stamp Duty). Trading options and futures involves substantial financial risk, leverage, and potential loss of entire invested capital.

Past algorithmic backtest performance or hypothetical simulations do not guarantee or represent future live trading results. Readers and users must perform their own independent due diligence, test thoroughly in simulated/paper trading environments, and consult an authorized SEBI Registered Financial Advisor before risking actual capital in Indian equity or derivatives markets. You are solely responsible for all trading decisions, capital allocations, and monetary risks undertaken.