Quantitative Trading Strategy Using Quantstrat Package in R: A Step by Step Guide

In this post, we will be building a trading strategy 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 you the list of packages along with the base installation required. There are 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 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,

  • Adding indicators
  • Adding signals
  • Adding rules

A helicopter view towards the output of the strategy is given in the diagram below.

Thus our hypothesis that market is mean reverting is supported. Since this is back-testing we have room for refining the trading parameters that would improve our average returns and the profits realized. This can be done by setting different threshold levels, more strict entry rules, stop loss etc. One could choose more data for back-testing, use Bayseian approach for threshold set up, take volatility into account.

Once you are confident about the trading strategy backed by the back-testing results you could step into live trading. Production environment is a big topic in itself and it’s out of scope in the article’s context. To explain in brief this would involve writing the strategy on a trading platform.

As mentioned earlier, we would be building the model using quantstrat package. Quantstrat provides a generic infrastructure to model and backtest signal-based quantitative strategies. It is a high-level abstraction layer (built on xts, FinancialInstrument, blotter, etc.) that allows you to build and test strategies in very few lines of code.

The key features of quantstrat are,

  • Supports strategies which include indicators, signals, and rules
  • Allows strategies to be applied to multi-asset portfolios
  • Supports market, limit, stoplimit, and stoptrailing order types
  • Supports order sizing and parameter optimization

In this post we build a strategy that includes indicators, signals, and rules.

For a generic signal based model following are the objects one should consider,

  • Instruments- Contain market data
  • Indicators- Quantitative values derived from market data
  • Signals- Result of interaction between market data and indicators
  • Rules- Generate orders using market data, indicators and signals.

Without much ado let’s discuss the coding part. We prefer R studio for coding and insist you use the same. You need to have certain packages installed before programming the strategy.

The following set of commands installs the necessary packages.

Once you have installed the packages you import them for further usage.

Read the data from csv file and convert it into xts object.

We initialize the portfolio with the stock, currency, initial equity and the strategy type.

Add position limit if you wish to trade more than once on the same side.

Create the strategy object.

We build a function that computes the thresholds are which we want to trade. If price moves by thresh1 we update threshold to new price. New bands for trading are Threshold+/-Thresh2. Output is an xts object though we use reclass function to ensure.

Add the indicator, signal and the trading rule.

Run the strategy and have a look at the order book.

Update the portfolio and view the trade statistics

Here is the complete code

Next Step

Once you are familiar with these basics you could take a look at how to start using quantimod package in R. Or in case you’re good at C++, take a look at an example strategy coded in C++.

If you’re a retail trader or a tech professional looking to start your own automated trading desk, start learning algo trading today! Begin with basic concepts like automated trading architecture, market microstructure, strategy backtesting system and order management system.

Leave a Reply

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