0bps

Strategy vault / Mean reversion

Quantitative Strategy Combining Mean Reversion and Trend Following

This article explains in detail a quantitative trading strategy that combines both mean reversion and trend following techniques. It aims to trade counter-trend during trending markets and ride the momentum during…

Author
ChaoZhang
Complexity
Starter · 56 lines
Parameters
5
Backtest bar
1d · swing
Tested on
BTC/USDT · futures

This article explains in detail a quantitative trading strategy that combines both mean reversion and trend following techniques. It aims to trade counter-trend during trending markets and ride the momentum during trending markets.

I. Strategy Logic

The strategy mainly uses Simple Moving Average and RSI indicator to generate trading signals:

  1. When price is below 200-period SMA, it judges the current market as downtrend.

  2. When RSI is below 20, it takes counter-trend mean reversion trades.

  3. When price is above 200-period SMA, it judges the current market as uptrend.

  4. When price crosses above SMA, it takes trend-following trades.

  5. Exits are triggered when RSI exceeds 80 or price drops below SMA by a certain percentage.

  6. Position sizing for mean reversion and trend following can be adjusted separately.

The strategy combines mean reversion and trend following techniques and applies them in different market stages.

II. Advantages of the Strategy

The main advantages are:

  1. Combining two techniques improves strategy adaptiveness.

  2. It can find trading opportunities in trending and ranging markets.

  3. Risks can be controlled by adjusting position sizing.

  4. Simple parameter settings make it easy to implement.

III. Potential Risks

However, the risks are:

  1. Indicators like SMA and RSI are susceptible to false breakouts.

  2. Switching between two modes may lag.

  3. Certain drawdowns need to be endured for long term gains.

IV. Summary

In summary, this article has explained a quantitative strategy utilizing mean reversion and trend following techniques. It can trade in different market stages to improve adaptiveness. But risks like indicator failure and delayed mode switching need to be managed. Overall, it provides a flexible approach to combine different techniques.

Parameters

NameDefaultWhat it controls
v_input_1timestamp(1 Feb 2000 12:00)Starting Date
v_input_bool_1trueenableMeanReversion
v_input_bool_2trueenableTrendfollowing
v_input_float_1truetrendPositionFactor
v_input_float_20.5meanReversionPositionFactor

Source Pine Script

/*backtest
start: 2022-09-07 00:00:00
end: 2023-04-05 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © I11L

//@version=5
strategy("Mean Reversion and Trendfollowing", overlay=true, pyramiding=1, default_qty_value=100000, initial_capital=100000, default_qty_type=strategy.cash, process_orders_on_close=false, calc_on_every_tick=false)

// Input for the starting date
start_date = input(timestamp("1 Feb 2000 12:00"), title="Starting Date")
enableMeanReversion = input.bool(true)
enableTrendfollowing = input.bool(true)
trendPositionFactor = input.float(1)
meanReversionPositionFactor = input.float(0.5)

// Convert the input string to a timestamp
start_ts = timestamp(year(start_date), month(start_date), dayofmonth(start_date), 0, 0)

// Check if the current bar's time is greater than or equal to the start timestamp
start_condition = time >= start_ts

var tradeOrigin = ""

sma200 = ta.sma(close,200)
rsi2 = ta.rsi(close,2)

isMeanReversionMode = close < sma200 or not(enableTrendfollowing)
isTrendfollowingMode = close > sma200 or not(enableMeanReversion)

isRsiBuy = rsi2 < 20 and enableMeanReversion
isRsiClose = rsi2 > 80 and enableMeanReversion

isSmaBuy = close > sma200 and enableTrendfollowing
isSmaClose = close < sma200 * 0.95 and enableTrendfollowing

isBuy = (isMeanReversionMode and isRsiBuy) or (isTrendfollowingMode and isSmaBuy)

positionSizeFactor = isSmaBuy ? trendPositionFactor : meanReversionPositionFactor

// Only execute the strategy after the starting date
if (start_condition)
    if (isBuy and strategy.opentrades == 0)
        tradeOrigin := isSmaBuy ? "SMA" : "RSI"
        strategy.entry("My Long Entry Id", strategy.long, qty=(strategy.equity / close) * positionSizeFactor, comment=str.tostring(positionSizeFactor))
    isClose = tradeOrigin == "SMA" ? isSmaClose : isRsiClose
    if (isClose)
        strategy.exit("Exit", limit = close)

plot(sma200)
plot(sma200 * 0.95, color=color.orange)

Published by ChaoZhang on the FMZ strategy square · last modified 2023-09-14. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.

Build this with AgenKit

A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.

in Claude Code, Cursor, Codex & 4 more
/agenkit build a production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/Quantitative-Strategy-Combining-Mean-Reversion-and-Trend-Following.md
  1. npx agenkit install engineering-kit in your project
  2. Paste the command into your agent and approve each phase
  3. Get tests, backtest, risk controls and a paper-trading switch

Understand it first

Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.

Related specs

esc

Try , , or .

↑↓ move↵ open