AFL of the week: Mean Reversion Trading System

All the AFL’s posted in this section till now are Trend following. Recently, we experimented on a Mean Reversion Trading System and got surprised with its accuracy and returns. In this post,we would go through this system and its backtest report on NSE Nifty. First, let’s find out what Mean Reversion system actually is.

Mean Reversion Trading System: Definition and Overview

Mean Reversion systems assume that Stock prices oscillate in a Fixed range bounded by an upper and lower price bands. The price always tends to return to a median level in due course of time. In order to trade such system, Buy order is placed at the lower end of range and Sell order is placed at the higher end of range. Any breakout of this range with good volumes may lead to strong trends and trade should be avoided during that time. Strict stoploss is imperative in order to trade Mean Reversion systems. There are many indicators which can be handy for developing Mean Reversion Trading systems. Examples are Bollinger Bands, Donchian  channels, RSI, CCI etc.

In the next section,  we’ll go through an AFL and backtest report for Mean Reversion Trading System based on Bollinger Bands. Read our article on AFL tutorial here.

AFL Overview

Paramter Value
Preferred Timeframe Intraday 5 minute
Indicators Used Bollinger Band, ADX
Buy Condition
  • Current close is greater than Bollinger Band bottom and previous close is less than Bollinger Band bottom.
  • ADX is less than 35 which indicates ranging market
Short Condition
  • Current close is less than Bollinger Band top and previous close is greater than Bollinger Band top.
  • ADX is less than 35 which indicates ranging market.
Sell Condition
  • Stop Loss hit
  • Target Met
  • Close is less than Bollinger Band bottom.
  • Short Condition met
Cover Condition
  • Stop Loss hit
  • Target Met
  • Close is greater than Bollinger Band top.
  • Buy Condition met
Stop Loss 0.5%
Targets 1%
Position Size 150 (fixed)
Initial Equity 200000
Brokerage 100 per order
Margin 10%

AFL Code

//------------------------------------------------------
//
//  Formula Name:    Mean Reversion Trading System
//  Author/Uploader: Trading Tuitions
//  E-mail:          support@tradingtuitions.com
//  Website:         www.tradingtuitions.com
//------------------------------------------------------

_SECTION_BEGIN("Mean Reversion Trading System");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));

SetTradeDelays( 1, 1, 1, 1 );
SetOption( "InitialEquity", 200000);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",100);
SetOption("AccountMargin",10);
SetOption("RefreshWhenCompleted",True);
SetPositionSize(150,spsShares);
SetOption( "AllowPositionShrinking", True );

BuyPrice=Open;
SellPrice=Open;
ShortPrice=Open;
CoverPrice=Open;

Periods =optimize("Periods",110,10,200,20);
Width =optimize("width",2,1,10,1);
MAPeriods = 200;
BBColor = colorOrange;
Style = 0;
bTop=BBandTop( Close, Periods, Width );
bBottom=BBandBot( Close, Periods, Width );
ADXPeriods=optimize("ADXPeriods",10,2,20,1);


BuyCondition=IIf(Ref(C,-1)<bBottom AND close>bBottom AND ADX(ADXPeriods)<35,1,0);
ShortCondition=IIf(Ref(C,-1)>bTop AND close<bTop AND ADX(ADXPeriods)<35,1,0);


Buy = IIf(Ref(C,-1)<bBottom AND close>bBottom AND ADX(ADXPeriods)<35,1,0);
Short = IIf(Ref(C,-1)>bTop AND close<bTop AND ADX(ADXPeriods)<35,1,0);


BarsSinceBuy=BarsSince(BuyCondition);
BarsSinceShort=BarsSince(ShortCondition);

LastBuyPrice=ValueWhen(Buy AND BarsSinceBuy<BarsSinceShort,BuyPrice);
LastShortPrice=ValueWhen(Short AND BarsSinceShort<BarsSinceBuy,ShortPrice);

StopLoss=optimize("SL",0.5,0.2,1,0.2);
Target=optimize("Target",1,0.5,5,0.5);

BuySL=BarsSinceBuy<BarsSinceShort AND Close<=LastBuyPrice-LastBuyPrice*(Stoploss/100);
ShortSL=BarsSinceShort<BarsSinceBuy AND Close>=LastShortPrice+LastBuyPrice*(Stoploss/100);
BuyTarget=BarsSinceBuy<BarsSinceShort AND Close>=LastBuyPrice+LastBuyPrice*(Target/100);
ShortSL=BarsSinceShort<BarsSinceBuy AND Close<=LastShortPrice-LastBuyPrice*(Target/100);

Sell=Short OR Close<bBottom OR BuySL OR BuyTarget;
Cover=Buy OR Close>bTop OR ShortSL OR BuyTarget;



Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
Short=ExRem(Short,Cover);
Cover=ExRem(Cover,Short);



ApplyStop(Type=0,Mode=1,Amount=StopLoss);
ApplyStop(Type=1,Mode=1,Amount=Target);

printf("\nBuy : " + Buy );
printf("\nShort : " + Short );
printf("\nCover : " + Cover );
printf("\nSell : " + Sell );
printf("\nBuyPrice : " + BuyPrice );
printf("\nShortPrice : " + ShortPrice );
printf("\nLastBuyPrice : "+ LastBuyPrice);
printf("\nLastShortPrice : "+ LastShortPrice);
printf("\nBuyCondition : "+ BuyCondition);
printf("\nShortCondition : "+ ShortCondition);
printf("\nBuySL : "+BuySL); 
printf("\nShortSL : "+ShortSL);
 
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
Plot( bTop, "BBTop" + _PARAM_VALUES(), BBColor , Style ); 
Plot( bBottom, "BBBot" + _PARAM_VALUES(), BBColor , Style ); 


/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

_SECTION_END();	

AFL Screenshot

Mean Reversion

Backtest Report

 Paramter Value
  Fixed Position Size
Initial Capital  200000
Final Capital 378919.40
Scrip Name NSE Nifty
Backtest Period 14-Jan-2015 to 29-04-2016
Timeframe 5 Minutes
Net Profit % 89.46%
Annual Return % 61.91%
Number of Trades 114
Winning Trade % 32.46%
Average holding Period 25.17 periods
Max consecutive losses 9
Max system % drawdown -10.78%
Max Trade % drawdown -7.95%

This is the best drawdown figures we were able to achieve in the recent past.Download the detailed backtest report here.

Equity Curve

This strategy has a very smooth and linear equity curve with minimum drawdowns. Check it out.

EquityCurve_MeanReversion

Additional Amibroker settings for backtesting

Goto Symbol–>Information, and specify the lot size and margin requirement. The below screenshot shows lot size of 75 and margin requirement of 10% for NSE Nifty:

Symbol Info_Nifty

Disclaimer:

All the AFL’s posted in this section are for learning purpose. Trading Tuitions does not necessarily own these AFL’s and we don’t have any intellectual property rights on them. We might copy useful AFL’s from public forums and post it in this section in a presentable format. The intent is not to copy anybody’s work but to share knowledge. If you find any misleading or non-reproducible content then please inform us at support@tradingtuitions.com

13 Comments

  1. If we backtest previous periods, I saw some great loss up to 68%, Can you show us how to backtest if possible ?
    Thanks.

    • Hi Harsha,

      Can you please let me know in which period you backtested this system and what is the source of your data?

      • I checked for 2013-14 .. I took the data from the open source. I think it is very similar to the data you provided in your website.. Please check for atleast 3-4 years ..

  2. Dear Sir,
    I have an AFL with exploration function, when I explore it to my NSE futures watch-list, I get both current and past signals for every symbol. I would like to know how to get only the current (or the most recent) signals of every symbols in my watch-list. Kindly advise me what AFL command I should apply.

    Thank you very much.

  3. Dear sir I want to generate 50% return annually with 20% risk. Will this be an ideal strategy to work for long term. Please let me know. Thanks in advance

    • Hi Ramendra,

      I would not recommend Mean-Reversion strategy for long term. Check out for Trend following strategies instead.

      • Thanks a lot sir for your prompt reply. Will you please suggest a strategy as per my requirement. That will be very beneficial for the investor who want to trade in future markets.

  4. The site is very interesting, informative and educative.
    Shall appreciate your guidiance, AND steps to b followed to integrate the AFLS, in AMI BROKER.

    THX N RGDS

  5. Hello,
    which lookback periods have you taken finally for the ADX and the Bollinger Bands, which produce the – truly amazing – results in you backtest report?
    Best regards, Mike

Leave a Reply

Your email address will not be published. Required fields are marked *