How to Design Quant Trading Strategies Using R?

This blog covers in brief the concept of strategy back-testing using R. Before dwelling into the trading jargons using R let us spend some time understanding what R is. R is an open source. There are more than 4000 add-on packages,18000 plus members of LinkedIn’s group and close to 80 R Meetup groups currently in existence. It is a perfect tool, for statistical analysis, especially for data analysis. The concise setup of Comprehensive R Archive Network knows as CRAN provides a list of packages along with the base installation required. There are a lot of packages available depending upon the analysis needs to be done. To implement the trading strategy, we will use the package called quantstrat.

Four Step Process of Any Basic Trading Strategy

1. Hypothesis formation
2. Testing
3. Refining
4. Production

Our hypothesis is formulated as “market is mean reverting”. Mean reversion is a theory that suggests that the prices eventually move back to their average value. The second step involves testing the hypothesis for which we formulate a strategy on our hypothesis and compute indicators, signals and performance metrics. The testing phase can be broken down into three steps, getting the data, writing the strategy and analyzing the output. In this example we consider NIFTY-Bees. It is an exchange traded fund managed by Goldman Sachs. NSE has huge volume for the instrument hence we consider this. The image below shows the Open-High-Low-Close price of the same.

We plot the Bollinger band for the closing price.

We set a threshold level to compare the fluctuations in the price. If the price increases/decreases, we update the threshold column. The closing price is compared with the upper band and with the lower band. When the upper band is crossed, it is a signal for sell. Similarly, when the lower band is crossed, it is a buy signal. The coding section can be summarized as follows:-