### Amibroker AFL- Mean Reversion Strategy

This article shows a step-wise example about how to design a mean reversion strategy for Bank Nifty.

Contents

## Step 1: The Trading Idea

We pick the idea from a previous article:

So here is your second trading strategy! Buy in a uptrend when prices are extended downwards (oversold) and returning to the mean.

## Step 2: Selecting Technical Indicators

The trading idea requires quantifying key concepts: uptrend and mean reversion. There can be a million methods to quantify, and similarly, each method has different impact on the profitability of strategy. As a start:

Chart Time Frame: 15 minutes

Uptrend: defined when EMA(20) is above EMA(200). This is because most people use Moving Average Crossover for analysis/trading. 20 periods EMA is used for short-term trend, while 200 period EMA is used for long-term trend. Downtrend is defined as opposite of uptrend.

Mean Reversion: We can use Bollinger Bands to identify mean reversion opportunity. Bollinger Bands are one of the most common technical indicators and use 2 Standard Deviations to contain 95% price movement within the bands. The common parameters are used for Bollinger Band- 15 periods and 2 standard deviations. When price go beyond the bands and retrace back inside the bands, we use it as a confirmation to generate Buy/Sell signals.

StopLoss: Lowest value of the last five closing candles when Buy is triggered.

## Step 3: Defining Clear Strategy Rules

Buy: when prices are in uptrend and crossing above lower Bollinger Band

Sell: when prices cross below lower Bollinger band or stop loss condition is met

## Step 4: AFL Coding Guide

Once the logic is clear, we code the AFL in same manner. Since AFL is an array based language, it is best practice to code the Buy/Sell conditions in a loop. To find out the profits in number of points, we use the function SetPositionSize(1,spsShares);

## Step 5: The Backtest

Thankfully and intuitively, the strategy gives a profit of Rs. 3,90,318 on Bank Nifty one lot (first month futures).  It however has a high percentage of losing trades (70%) because a large number of trades are stopped at initial small stop loss.  Related Article: Basics in Strategy Backtesting

• All trades executed at Close price of the bar on which signal is triggered
• Brokerage: 0.01% of Trade Value
• Time Frame: 15 minute
• Data History: 01-01-2014 to 31-12-2015 (two years)
• Strategy Optimization: None

## Step 6: Further Improvement

We leave it to the readers to suggest any improvement  in Step 2 and Step 3 which can increase the profitability. Particularly by modifying the stop loss condition, we can drastically improve the percentage of profitable trades.