Quantitative Trading Strategy Using R: A Step by Step Guide (2024)

[This article was first published on R programming, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Quantitative Trading Strategy Using R: A Step by Step Guide (1)

In this post we will discuss about 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 signal for sell.

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.

install.packages("quantstrat", repos="http://R-Forge.R-project.org")install.packages("blotter", repos="http://R-Forge.R-project.org")install.packages("FinancialInstrument", repos="http://R-Forge.R-project.org")

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

require(quantstrat)

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

ym_xts <- as.xts(read.zoo("Path//Data.csv",sep = "," , header=TRUE,format = "%m/%d/%Y %H:%M", tz=""))NSEI<-ym_xts

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

stock.str='NSEI' # stock we trying it oncurrency('INR')stock(stock.str,currency='INR',multiplier=1)initEq=1000initDate = index(NSEI[1])#should always be before/start of data#Declare mandatory names to be usedportfolio.st='MeanRev'account.st='MeanRev'initPortf(portfolio.st,symbols=stock.str, initDate=initDate)initAcct(account.st,portfolios='MeanRev', initDate=initDate)initOrders(portfolio=portfolio.st,initDate=initDate)

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

addPosLimit(portfolio.st, stock.str, initDate, 1, 1 )

Create the strategy object.

stratMR <- strategy("MeanRev", store = TRUE)

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.

THTFunc<-function(CompTh=NSEI,Thresh=6, Thresh2=3){numRow<- nrow(CompTh)xa<-coredata(CompTh)[,4]xb<-xatht<-xa[1]for(i in 2:numRow){ if(xa[i]>(tht+Thresh)){ tht<-xa[i]} if(xa[i]<(tht-Thresh)){ tht<-xa[i]} xb[i]<-tht}up <- xb + Thresh2dn<- xb-Thresh2res <- cbind(xb, dn,up)colnames(res) <- c("THT", "DOWN", "UP")reclass(res,CompTh)}

Add the indicator, signal and the trading rule.

stratMR <- add.indicator(strategy = stratMR, name = "THTFunc", arguments = list(CompTh=quote(mktdata), Thresh=0.5, Thresh2=0.3), label='THTT')stratMR<-add.signal(stratMR,name="sigCrossover",arguments= list(columns=c("Close","UP"),relationship="gt"),label="Cl.gt.UpperBand")stratMR<-add.signal(stratMR,name="sigCrossover",arguments= list(columns=c("Close","DOWN"),relationship="lt"),label="Cl.lt.LowerBand")stratMR <- add.rule(stratMR,name='ruleSignal', arguments = list(sigcol="Cl.gt.UpperBand",sigval=TRUE, prefer = 'close', orderqty=-1, ordertype='market', orderside=NULL, threshold=NULL,osFUN=osMaxPos),type='enter')stratMR <- add.rule(stratMR,name='ruleSignal', arguments = list(sigcol="Cl.lt.LowerBand",sigval=TRUE, prefer = 'close', orderqty= 1, ordertype='market', orderside=NULL, threshold=NULL,osFUN=osMaxPos),type='enter')start_t<-Sys.time()

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

out<-try(applyStrategy(strategy=stratMR , portfolios='MeanRev') )# look at the order bookgetOrderBook('MeanRev')end_t<-Sys.time()

Update the portfolio and view the trade statistics

updatePortf('MeanRev', stock.str)chart.Posn(Portfolio='MeanRev',Symbol=stock.str)tradeStats('MeanRev', stock.str)View(t(tradeStats('MeanRev'))).Th2 = c(.3,.4).Th1 = c(.5,.6)require(foreach)require(doParallel)registerDoParallel(cores=2)stratMR<-add.distribution(stratMR,paramset.label='THTFunc',component.type= 'indicator',component.label = 'THTT', variable = list(Thresh = .Th1),label = 'THTT1')stratMR<-add.distribution(stratMR,paramset.label='THTFunc',component.type= 'indicator',component.label = 'THTT', variable = list(Thresh2 = .Th2),label = 'THTT2')results<-apply.paramset(stratMR, paramset.label='THTFunc', portfolio.st=portfolio.st, account.st=account.st, nsamples=4, verbose=TRUE)stats <- results$tradeStatsView(t(stats))

Here is the complete code

require(quantstrat)ym_xts <- as.xts(read.zoo("~/webinar//N1.csv",sep = "," , header=TRUE,format = "%m/%d/%Y %H:%M", tz=""))NSEI<-ym_xtscolnames(NSEI)<-c("Open","High","Low","Close")stock.str='NSEI' # stock we trying it oncurrency('INR')stock(stock.str,currency='INR',multiplier=1)initEq=1000initDate = index(NSEI[1])#should always be before/start of dataportfolio.st='MeanRev'account.st='MeanRev'initPortf(portfolio.st,symbols=stock.str, initDate=initDate)initAcct(account.st,portfolios='MeanRev', initDate=initDate)initOrders(portfolio=portfolio.st,initDate=initDate)addPosLimit(portfolio.st, stock.str, initDate, 1, 1 ) #set max posstratMR <- strategy("MeanRev", store = TRUE)THTFunc<-function(CompTh=NSEI,Thresh=6, Thresh2=3){numRow<- nrow(CompTh)xa<-coredata(CompTh)[,4]xb<-xatht<-xa[1]for(i in 2:numRow){ if(xa[i]>(tht+Thresh)){ tht<-xa[i]} if(xa[i]<(tht-Thresh)){ tht<-xa[i]} xb[i]<-tht}up <- xb + Thresh2dn<- xb-Thresh2res <- cbind(xb, dn,up)colnames(res) <- c("THT", "DOWN", "UP")reclass(res,CompTh)}stratMR <- add.indicator(strategy = stratMR, name = "THTFunc", arguments = list(CompTh=quote(mktdata), Thresh=0.5, Thresh2=0.3), label='THTT')stratMR <- add.signal(stratMR,name="sigCrossover",arguments = list(columns=c("Close","UP"),relationship="gt"),label="Cl.gt.UpperBand")stratMR <- add.signal(stratMR,name="sigCrossover",arguments = list(columns=c("Close","DOWN"),relationship="lt"),label="Cl.lt.LowerBand")stratMR <- add.rule(stratMR,name='ruleSignal', arguments = list(sigcol="Cl.gt.UpperBand",sigval=TRUE, prefer = 'close', orderqty=-1, ordertype='market', orderside=NULL, threshold=NULL,osFUN=osMaxPos),type='enter')stratMR <- add.rule(stratMR,name='ruleSignal', arguments = list(sigcol="Cl.lt.LowerBand",sigval=TRUE, prefer = 'close', orderqty= 1, ordertype='market', orderside=NULL, threshold=NULL,osFUN=osMaxPos),type='enter')start_t<-Sys.time()out<-try(applyStrategy(strategy=stratMR , portfolios='MeanRev') )getOrderBook('MeanRev')end_t<-Sys.time()updatePortf('MeanRev', stock.str)chart.Posn(Portfolio='MeanRev',Symbol=stock.str)tradeStats('MeanRev', stock.str)View(t(tradeStats('MeanRev'))).Th2 = c(.3,.4).Th1 = c(.5,.6)require(foreach)require(doParallel)registerDoParallel(cores=2)stratMR<-add.distribution(stratMR,paramset.label='THTFunc',component.type = 'indicator',component.label = 'THTT', variable = list(Thresh = .Th1),label = 'THTT1')stratMR<-add.distribution(stratMR,paramset.label='THTFunc',component.type='indicator',component.label = 'THTT', variable = list(Thresh2 = .Th2),label = 'THTT2')results <- apply.paramset(stratMR, paramset.label='THTFunc', portfolio.st=portfolio.st, account.st=account.st, nsamples=4, verbose=TRUE)stats <- results$tradeStatsView(t(stats))

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.

The post Quantitative Trading Strategy Using R: A Step by Step Guide appeared first on .

Related

To leave a comment for the author, please follow the link and comment on their blog: R programming.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Quantitative Trading Strategy Using R: A Step by Step Guide (2024)

FAQs

How to build a quantitative trading strategy? ›

There are four main steps in quant trading: Strategy identification, backtesting, execution, and risk management. Strategy identification, which we will explore in greater detail, is the selection of a technique to be used in your mathematical model.

Can you do quant trading by yourself? ›

The required skills to start quant trading on your own are mostly the same as for a hedge fund. You'll need exceptional mathematical knowledge, so you can test and build your statistical models. You'll also need a lot of coding experience to create your system from scratch.

How to start quant trading at home? ›

Creating a quant trading system typically involves several steps: Formulating a trading strategy: This involves identifying a market inefficiency or opportunity and developing a hypothesis about how to profit from it. Back testing: Use historical data to test the strategy and determine its potential profitability.

How to learn quantitative trading? ›

How to become a quantitative trader
  1. Pursue a relevant degree. ...
  2. Develop your understanding of the four major components of this role. ...
  3. Gain professional experience. ...
  4. Pursue certification or additional coursework. ...
  5. Computer programming and use. ...
  6. Understanding of trading concepts. ...
  7. Ability to perform under pressure. ...
  8. Mathematics.
Jan 26, 2023

How does quantitative trading work for beginners? ›

Quantitative trading (also called quant trading) involves the use of computer algorithms and programs—based on simple or complex mathematical models—to identify and capitalize on available trading opportunities. Quant trading also involves research work on historical data with an aim to identify profit opportunities.

What is the simplest most profitable trading strategy? ›

One of the simplest and most widely known fundamental strategies is value investing. This strategy involves identifying undervalued assets based on their intrinsic value and holding onto them until the market recognizes their true worth.

What do quant traders do all day? ›

Quantitative traders, or quants for short, use mathematical models to identify trading opportunities and buy and sell securities. The influx of candidates from academia, software development, and engineering has made the field quite competitive.

How much do first year quant traders make? ›

Yes, quants tend to command high salaries, in part because they are in demand. Hedges funds and other trading firms generally offer the highest compensation. Entry-level positions may earn only $125,000 or $150,000, but there is usually room for future growth in both responsibilities and salary.

What is the math behind quant trading? ›

“In order to research the data, run tests, and implement the trade, you should understand a few different mathematical concepts.” This includes calculus, linear algebra, and differential equations, and probability and statistics.

What is an example of a quantitative trading strategy? ›

Consider the case of a trader who believes in momentum investing. They can choose to write a simple program that picks out the winners during an upward momentum in the markets. During the next market upturn, the program will buy those stocks. This is a fairly simple example of quantitative trading.

What is the best major for quant trading? ›

While an undergraduate degree in mathematics, theoretical physics, computer science or EEE are most appropriate for quant roles, there are also other degrees that can lead to a top quant role, usually via a postgraduate route.

Who is the most famous quant trader? ›

Jim Simons is a renowned mathematician and investor. Known as the "Quant King," he incorporated the use of quantitative analysis into his investment strategy. Simons is the founder of Renaissance Technologies and its Medallion Fund.

What are the basic quant strategies? ›

Quantitative investment strategies include statistical arbitrage, factor investing, risk parity, machine learning techniques, and artificial intelligence approaches. Commonly used factors in quantitative analyses include value, momentum, size, quality, and volatility.

How many hours do quantitative traders work? ›

The culture often seems more supportive than finance in general (though it depends on the firm). Your colleagues will be very smart, but the pace is faster than academia. You're expected to work 50-60 hours per week – considerably better than investment banking or tech startups.

What is the salary of a quantitative trader? ›

Quantitative Trader salary in India ranges between ₹ 2.2 Lakhs to ₹ 400.0 Lakhs with an average annual salary of ₹ 13.5 Lakhs.

What is the most profitable trading strategy of all time? ›

Three most profitable Forex trading strategies
  1. Scalping strategy “Bali” This strategy is quite popular, at least, you can find its description on many trading websites. ...
  2. Candlestick strategy “Fight the tiger” ...
  3. “Profit Parabolic” trading strategy based on a Moving Average.
Jan 19, 2024

How long does it take to learn quantitative trading? ›

Depending upon your background, aptitude and time commitments, it can take anywhere from six months to two years to be familiar with the necessary material before being able to apply for a quantitative position.

Top Articles
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 6361

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.