Shorting at High: Algo Trading Strategy in R

Shorting at High - Algo Trading Strategy in R

By Milind Paradkar

Milind ParadkarMilind began his career in Gridstone Research, building earnings models and writing earnings notes for NYSE listed companies, covering Technology and REITs sectors. Milind has also worked at CRISIL and Deutsche Bank, where he was involved in modeling of Structured Finance deals covering Asset Backed Securities (ABS), and Collateralized Debt Obligations (CDOs) for the US and EMEA region.

Milind holds a MBA in Finance from the University of Mumbai, and a Bachelor’s degree in Physics from St. Xavier’s College, Mumbai.


The Executive Programme in Algorithmic Trading (EPAT) exposed me to all the requisite subjects needed to learn algorithmic trading. As part of the EPAT project work I tried coding many strategies. Since I am a novice to algorithmic trading I wanted to code the simplest, and the most basic strategies. Although simple and basic, one should not underestimate the power of such strategies, as they can generate good returns.

“Shorting at High” was one of the strategies that I formulated for my project work. This post explains the strategy in brief and the coding part. I welcome the readers to give suggestions, improvise or to use the strategy.

Strategy in brief

The strategy is to short the best stocks which cross the set percentage threshold on the upside (say 8%-9%) during intraday trading. The expectation for the shorted stocks is to fall by an amount as predicted in the metrics sheet which is generated upon executing the code.

The code works in two parts:

First, we set a high percentage threshold limit in the code. On executing the code, it scans all the stocks in the stock list, and determines which of the stocks have crossed the set threshold limit.

Second, for each of such stocks, it then computes certain metrics like number of times the stock crossed the set threshold in the past one year, average percentage rise during these times, average absolute decline in price for the next three days, RSI, correlation etc. These metrics can then be used to ascertain which stock is the best candidate for taking a short position. The position is squared off at the close or based on one’s profit target.

Strategy code in R

Step 1: Load the packages, read the stock symbols, and initialize a data frame

First, load the necessary R packages. Set the high threshold level in percentage terms. The next line in the code reads the csv file containing the stocks list. Using this file, we create a vector containing the symbols, and another vector containing the leverage for each stock as provided by the broker.

We also initialize a data frame that will contain basic stock information for each stock after executing the first part of the code. Only those stocks which cross the given threshold will be included in this data frame.

Step 2: Generating the data frame

In the next step, we pull the 1-minute intraday price data for the current day and the previous day from google finance for each stock. I have custom built scrip for the same. You can use your own script to download data from Google finance or any other source. The downloaded file is then read, and we compute the absolute price change and the percentage price change from the previous day’s closing price. The current price used is the latest price corresponding to the time when the code is run during intraday trading hours.

Join EPAT!

If the computed percentage price change is greater than the set threshold, we add that stock to the data frame. For such stocks, the data frame adds information like – the leverage, previous day’s closing price, current price, the absolute change in price, and the percentage change in price.

The resultant data frame after executing the code for all stocks is written to an excel file, which is named as “Shorting at High.xlsx”. All the stock files downloaded from google finance in the R directory are deleted using the unlink command.


Let’s set the threshold at 4%. We have 146 stock symbols in our stock list. When we execute the code, out of the 146 stock symbols, the code has shortlisted 6 stocks which crossed the threshold of 4% during intraday market hours. The table below illustrates the initial output which gets save in the “Shorting at High.xlsx” workbook after executing the code.

Step 2 - Generating the data frame

Step 3: Compute metrics to determine the best stock for shorting

This part of the code uses the stock symbols present in the “Shorting at High.xlsx” sheet. Based on a lookback period of 1 year, the codes in this section compute the following metrics:

  • RSI – Relative Strength Index
  • Count – The number of times the stock crossed the threshold in the given lookback period
  • Avg High % – The average percentage high when the stock went above the threshold
  • Abs Avg Decline – The absolute average decline in rupees from the Avg High %
  • Next 3-d price move – This gives the absolute price change over the next three days
  • Negative last 15-days – No. of times the stock was negative in the last 15-days
  • 1-Year High & 1-Year Low for the stock
  • Correlation of the stock with NIFTY
Step 4: Adding the metrics to the excel sheet

The metrics computed in the previous section are added to the “Shorting at High.xlsx” workbook. The codes shown in the previous section also generate a trade summary for each stock symbol. The trade summary gives details of all the historical trades undertaken in the lookback period whenever the stock crossed the threshold percentage. The trade summaries are automatically saved in the R working directory under the name, “symbol past performance.xlsx” (e.g. BEL past performance.xlsx).

Step 5: Analyzing the summary sheet

The table below shows the various metrics that are added to the initial output. We had set a threshold of 4%. From the table we can see that BEL has crossed 4% only 16 times during the last 1 year, and on an average it has declined by Rs. 25.48 from an average high of 5.66%. Also, the next 3-day price move for BEL is negative during such times. BEL appears to be a good candidate for shorting.

Step 5 - Analyzing the summary sheet

One can set further rules using these metrics to determine the best stock for shorting. Upon determining the best stock, one can automate the order placement and execution through any of the brokers offering algorithmic trading platform. Stop loss and profit targets can be added as per one’s risk-return targets.


The strategy attempts to profit from decline in price upon crossing the high threshold. The code can be further optimized to improve the execution speed. One can also code a similar strategy which will go long when the stocks go low beyond a certain threshold.  I have posted the strategy code on GitHub (Shorting at High.R) and I welcome readers for their suggestions and comments.

Next Steps

If you are a coder or a tech professional looking to start your own automated trading desk, learn automated trading from live Interactive lectures by daily-practitioners. Executive Programme in Algorithmic Trading covers training modules like Statistics & Econometrics, Financial Computing & Technology, and Algorithmic & Quantitative Trading. Enroll now!

Download Data Files


2 thoughts on “Shorting at High: Algo Trading Strategy in R

  1. August 16, 2016

    nick4291 Reply

    source(“Stock price data.R”) , where is this function . do I need to download it or something ?

  2. October 26, 2016

    K Harikumar Reply

    Yes, you have to download the file that is provided at the end of the article.

Leave a Reply

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