Creating Trading Strategies and Backtesting With R (2024)

Create fully functional trading strategies using technical indicators and backtest the results with R and its powerful libraries

R Programming language is an open-source software developed by statisticians and it is widely used among Data Miners for developing Data Analysis. R can be best programmed and developed in RStudio which is an IDE (Integrated Development Environment) for R. The advantages of R programming language include quality plotting and eye catching reports, vast source of packages used for various functions, exemplary source for Data Wrangling, performance of various Machine Learning operations and flashy for Statistics. In my experience, R is the best language for self-learning and also it is very flexible for Financial Analysis and Graphing.

In this article, we are going to create six trading strategies and backtest its results using R and its powerful libraries.

1. Importing required libraries

2. Extracting stock data (Apple, Tesla, Netflix) from Yahoo and Basic Plotting

3. Creating technical indicators

4. Creating trading signals

5. Creating trading strategies

6. Backtesting and Comparing the results

Firstly, to perform our process of creating trading strategies, we have to import the required libraries to our environment. Throughout this process, we will be using some of the most popular finance libraries in R namely Quantmod, TTR and Performance Analytics. Using the library function in R, we can import our required packages. Let’s do it!

Yes! We successfully completed our first step!

Throughout our process, we will be working with stock price data of Apple, Tesla and Netflix. Let’s extract the data of these companies from Yahoo in R.

Now let’s do some visualization of our extracted data! The following code produces a financial bar chart of stock prices along with volume.

There are many technical indicators used for financial analysis but, for our analysis we are going to use six of the most famous technical indicators namely : Simple Moving Average (SMA), Parabolic Stop And Reverse (SAR), Commodity Channel Index (CCI), Rate Of Change (ROC), Stochastic Momentum Index (SMI) and finally Williams %R

Simple Moving Average (SMA) :

The standard interval of time we are going to use is 20 days SMA and 50 days SMA. But, there no restrictions to use any interval of time.

The following code will calculate three companies’ 20 days SMA and 50 days SMA along with a plot:

Parabolic Stop And Reverse (SAR) :

To calculate Parabolic SAR, we have to pass on daily High and Low prices of the companies along with a given acceleration value.

The following code will calculate the companies’ Parabolic SAR along with a plot:

Commodity Channel Index (CCI) :

To calculate CCI, we have to pass on daily High, Low and Close prices of companies along with a specified time period and a constant value. In this step, we are going to take 20 days as time period and 0.015 as the constant value.

The following code will calculate the companies’ CCI along with a plot:

Rate Of Change (ROC)

To calculate ROC, we have to pass on a specified interval of time and there is no restrictions in using any number of period. In this step, we are going to use 25 days as the period of time.

The following code will calculate the companies’ ROC along with a plot:

Stochastic Momentum Index (SMI) :

To calculate SMI, we have to pass on daily High, Low and Close prices of companies, a specified interval of time, two smoothing parameters and a signal value.

The following code will calculate companies’ SMI along with a plot:

Williams %R

To calculate Williams %R, we have to pass on the daily High, Low and Close prices of companies along with a specified number of periods.

The following code will calculate the companies’ Williams %R along with a plot:

In this step, we are going to use the previously created indicators to build ‘BUY’ or ‘SELL’ trading signals. Basically, we will pass on specific conditions and if the condition satisfies a ‘BUY’ signal our created trading signal will turn to 1 which means a buy. If the condition satisfies a ‘SELL’ signal our created trading signal will turn to -1 which means a sell. If it doesn’t satisfies any of the mentioned conditions, then it will turn to 0 which means nothing. It might sounds like a whole bunch of fuzz but, it will be clear once we dive into the coding section. After coding your trading signals, you can use the ‘which’ command in R to see how may ‘BUY’ signals and how many ‘SELL’ signals.

Simple Moving Average

The following code will create SMA trading signals for companies if it satisfies our given condition:

Parabolic Stop and Reverse (SAR)

The following code will create Parabolic SAR trading signal for companies if it satisfies our conditions:

Commodity Channel Index (CCI)

The following code will create CCI trading signals for companies if it satisfies our conditions:

Rate of Change (ROC)

The following code will create Rate Of Change (ROC) trading signals for companies if it satisfies our conditions:

Stochastic Momentum Index (SMI)

The following code will create Stochastic Momentum Index (SMI) trading signals for companies if it satisfies our conditions:

Williams %R

The following code will create Williams %R trading signals for companies if it satisfies our conditions:

This is the most interesting step in our process as we are going to create Trading Strategies using our previously created Trading Signals. In our previous step, we created signals whether to buy or sell and in this step we are going to create conditions to check our holding position in that stock (i.e., whether we hold, bought or sold the stock). The trading strategy we are about to code will return 1 if we hold the stock or returns 0 if we don’t own the stock.

Simple Moving Average

The following code will create a SMA trading strategy if satisfies our given conditions:

Creating Trading Strategies and Backtesting With R (3)

This is an example table of our created SMA Apple trading strategy. In this table we can observe that, on 2019–05–24 SMA 20 went below SMA 50 so our created signal returns -1 (‘SELL’) the next day also our position changes to 0 which means we don’t hold the stock. From this, we can say that our created strategy works as we expected. Now, let’s proceed to the remaining Trading Strategies.

Parabolic Stop And Reverse (SAR)

The following code will create a Parabolic SAR trading strategy if satisfies our given conditions:

Commodity Channel Index (CCI) :

The following code will create a CCI trading strategy if satisfies our given conditions:

Rate Of Change (ROC)

The following code will create a Rate Of Change (ROC) trading strategy if satisfies our given conditions:

Stochastic Momentum Index (SMI)

The following code will create a SMI trading strategy if it satisfies our given conditions:

Williams %R

The following code will create a Williams %R trading strategy if it satisfies our given conditions:

In this step we are going to conduct backtests on our created trading strategies vs our created trading strategies commission adjusted (0.5%) vs the companies’ benchmark returns. Before conducting our backtests, we have calculate our daily benchmark returns i.e., daily returns of Apple, Tesla and Netflix. Let’s do it!

Now, we are set to conduct our backtests.

Simple Moving Average (SMA)

The following code will first calculate SMA strategy daily returns, commission adjusted SMA daily returns and finally runs the backtest (Comparison chart and an Annualized returns table) :

Parabolic SAR

The following code will first calculate Parabolic SAR strategy daily returns, commission adjusted Parabolic SAR daily returns and finally runs the backtest (Comparison chart and an Annualized returns table) :

Commodity Channel Index (CCI)

The following code will first calculate CCI strategy daily returns, commission adjusted CCI daily returns and finally runs the backtest (Comparison chart and an Annualized returns table) :

Rate Of Change (ROC)

The following code will first calculate ROC strategy daily returns, commission adjusted ROC daily returns and finally runs the backtest (Comparison chart and an Annualized returns table) :

Stochastic Momentum Index (SMI)

The following code will first calculate SMI strategy daily returns, commission adjusted SMI daily returns and finally runs the backtest (Comparison chart and an Annualized returns table) :

Williams %R

The following code will first calculate Williams %R strategy daily returns, commission adjusted Williams %R daily returns and finally runs the backtest (Comparison chart and an Annualized returns table) :

Hurrah! We successfully finished our process of creating trading strategies and backtesting the results with R. I want to highlight that, every strategies and backtesting results are only for educational purpose and should not be taken as an investment advice. Apart from our created strategies, you can do your coding and frame your own trading strategies based on our needs and flexibility. If you’ve missed any of the coding sections, no worries. I’ve added the full code file at the end. In this article, we’ve covered only six major technical indicators but, there are more to discover. So, never stop learning and never stop coding!

Happy Coding and Analyzing!

Full Code :

Creating Trading Strategies and Backtesting With R (2024)
Top Articles
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6293

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.