Linear Regression Trading System: Amibroker AFL Code

Quantitative Finance offers plethora of indicators and tools to predict future price movements of Stocks, commodities or any other traded instruments. Linear Regression is one of them through which price direction is speculated using statistical techniques. It has found it’s application in multiple proven trading systems used by hedge funds and large institutional investors. In this post, we will explore Linear regression trading system which is based on the principle of Mean reversion. We shall also understand the definition of linear regression and linear regression channel in simple terms.

Read our article on AFL tutorial here.

Linear Regression line and Linear Regression channel

Linear Regression line is the straight line drawn through the price points in a chart, which most effectively covers all the prices for a given period. It is a kind of ‘best fit’ line which shows the fair value of trading instrument. Any deviation from the linear regression line is considered to be the deviation of price from it’s supposed to be fair value. It is like a trend line and gives an idea of ongoing price trend in the chart.

Linear Regression channel contains two extra lines above and below the standard linear regression line. These extra lines are formed by calculating 1 or 2 standard deviations of linear regression line. If 1 standard deviation is used then linear regression channel covers 68% of prices for a given period, while if 2 standard deviations are used then it covers 95% of prices. Hence linear regression channel can effectively determine overbought and oversold areas, which makes it a perfect tool to develop mean reversion strategies.

Below is the simple illustration for Linear regression channel.

Linear Regression Channel

Image Source: http://forextraininggroup.com/simple-yet-powerful-price-channel-techniques/#

Linear Regression Trading System – AFL Overview

Parameter Value
Preferred Time-frame
 Hourly
Indicators Used  Linear Regression, Standard Deviation
Buy Condition
  • First candle closes below the lower band of linear regression channel.
  • Second candle closes above the lower band.
  • Third candle closes above the second candle.
Short Condition
  • First candle closes above the upper band of linear regression channel.
  • Second candle closes below the upper band.
  • Third candle closes below the second candle.
Sell Condition
  • Same as Short
  • Stop Loss Hit
  • Target met
  • End of Trading day
Cover Condition
  • Same as Buy
  • Stop Loss Hit
  • Target met
  • End of Trading day
Stop Loss  0.5%
Targets  0.5%
Position Size  100% of Equity
Initial Equity  200000
Brokerage  100 per order
Margin  10%

Linear Regression Trading System– AFL Code

This AFL code was originally published at Marketcalls.in. We have modified it to make it suitable for intraday trading and added various backtesting conditions.

//------------------------------------------------------
//
//  Formula Name:    Linear Regression
//  Author/Uploader: Marketcalls/Trading Tuitions
//  E-mail:          support@tradingtuitions.com
//  Website:         www.tradingtuitions.com
//------------------------------------------------------

_SECTION_BEGIN("Linear Regression");

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(100,spsPercentOfEquity);
SetOption( "AllowPositionShrinking", True );
BuyPrice=Open;
SellPrice=Open;
ShortPrice=Open;
CoverPrice=Open;

SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C ));
Plot( Close, "Price", colorWhite, styleCandle );

P = ParamField("Price field",-1);
Periods = Param("Periods", 20, 2, 300, 1, 10 );
Plot( LinearReg( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") ); 
_SECTION_END();

NewDay = (Day()!= Ref(Day(), -1)) OR BarIndex() == 0;  
//Plot(NewDay,"",colorlightGrey,styleHistogram|styleDots|styleNoLabel|styleOwnScale);

FirstTradeTime=093000;
SquareOffTime = 151500;

LR = LinearReg(C,20);
SD = StDev(C,20);
up = LR + 2*SD;
down = LR - 2*SD;

Plot(up,"UP",colorRed);
Plot(down,"DOWN",colorGreen);


Buy = Ref(C,-2) < Ref(down,-2) AND Ref(C,-1)>Ref(down,-1) AND C>Ref(C,-1) AND TimeNum()>= FirstTradeTime AND TimeNum()<SquareOffTime;
Short = Ref(C,-2) > Ref(up,-2) AND Ref(C,-1)<Ref(up,-1) AND C<Ref(C,-1) AND TimeNum()  >= FirstTradeTime and TimeNum()<SquareOffTime;
Sell=Short OR TimeNum() >= SquareOffTime;
Cover=Buy OR TimeNum() >= SquareOffTime;

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

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

StopLoss=Optimize("stop",0.5,0.5,3,0.5);
ApplyStop(Type=0,Mode=1,Amount=StopLoss);

Target=Optimize("Target",0.5,0.5,5,0.5);
ApplyStop(Type=1,Mode=1,Amount=Target);

printf("\nBuy : " + Buy );  
printf("\nSell : " + Sell );  
printf("\nShort : " + Short );  
printf("\nCover : " + Cover ); 

/* 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

Linear Regression Trading System

Also Read: Donchian Channel Trend following system

Linear Regression Trading System- Backtest Report

Linear Regression Trading system does not offer huge returns as it it based on mean reversion, but it is quite consistent owing to low drawdown value. It is suitable for intraday scalping.

Parameter Value
Nifty
Initial Capital 200000
Final Capital 736893.90
Scrip Name NSE Nifty
Backtest Period 26-Feb-2008 to 30-Jun-2017
Timeframe Hourly
Net Profit % 268.45%
Annual Return % 14.71%
Number of Trades 136
Winning Trade % 55.88%
Average holding Period 3.05 periods
Max consecutive losses 4
Max system % drawdown -13.37%
Max Trade % drawdown -13.86%

Download the detailed backtest report here.

Equity Curve

The equity curve is smooth and stable.

Linear Regression- Equity Curve

Profit Table

Linear Regression-Profit Table

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

Leave a Reply

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