Scalping day Trading strategy in Python in Plain English

Ashish Mohan
Python in Plain English
6 min readMay 30, 2020

--

Last week I wrote about the coding the scalping strategy (read my previous blog for more details). In this blog, I will first briefly explain what scalping strategy is? What are the steps involved in coding a simple Average True Rang based scalping strategy? Then expanding from the previous blog, I will elaborate the steps for optimizing the scalping strategy so that maximum returns can be reaped.

Brief Overview of Scalping Strategy

Scalping is day trading strategy, in which a trader holds a position for faction of seconds to a few minutes. Through out the day multiple trades are made to make a decent profit. There are three different types of scalping strategy: 1) Market Making, 2) Fractional Price Movement, 3) Signal based.

Market Making: As per investopedia, in this strategy a trader tries to capitalize on the spread by simultaneously posting a bid and an offer for specific stock. This strategy can only succeed with big trade volume without any real major price change, i.e a stock which has very negligible price change and is being traded with large volumes.

Fractional Price Movement: In this strategy, a trader enters into a position with a large position (typically in order of thousands), and exits the position after fraction change in price. This change in price can vary from 1 cent to 1 $ move. For this type of strategy to work, a stock needs to have high liquidity.

Signal Based Scalping: This strategy is signal based and mostly based on technical indicators. A trader enters and exits a position based on trading signals generated from his trading set up.

In this blog, we will discuss focus on Average True Range (ATR) based scalping strategy. This roughly belongs to the signal based scalping strategy. ATR is a technical analysis which provides the degree of price volatility. It is calculated as average of true range, where true range is defined as the largest of a. most recent period’s high — recent period’s low, b. absolute difference of recent period high and previous close, c. absolute difference of most recent period’s low and previous close.

How ATR based scalping strategy works?

First we will use ATR to identify when short term volatility increases. Once we identify the moment of volatility increase, we will look for pattern whether price is going up or going down. For this we will use candle highs or lows to identify price pattern. We will exit the position based on certain profit levels or stop loss.

Steps involved in developing strategy in Python

The first step in select a equity, and import data. We will test the strategy on yes bank stock. We will gather data from Zerodha kite api (Zerodha is a discount brokerage firm in India). The process is bit tricky but details can be found in code repository under section (Import data). We will look into 1 minute price data from 1st of April, 2020 to 29th May 2020.

After connecting with zerodha server, I made a data frame called token list which stores all the instruments currently traded under zerodha. From the dataframe object token_list we will get the instrument id of Yes bank which is 3050241. 1 minute Data for yes bank:

1 minute data of yes bank from 1st april to 29th may 2020 with date as an index

After generating dataframe for the 1 minute data of yes bank, the next step in the process is calculate the Average True Range(ATR) for each minute in the dataset. ATR was calculated using talib module taking high, low, close data with a timeperiod of 30 minute. I also calculated 5 minute rolling mean of ATR using .rolling().mean() function.

ATR Breakout

After ATR and Rolling mean, we need to find out each minute where ATR surpasses its won 5 minute rolling mean. The minute when it surpasses, it is called ATR break out. A breakout means that short term volatility is higher than long term volatility.

Checking for direction of price movement

Once we identify the the increase in volatility through ATR breakout, we need to check for price movement. To check wether price is moving up, we will check if the high price at the candle of ATR breakout is greater than the previous 3 candle high. If this happens we take the long position.

In the same way , if low candle of breakout is lower than the 3 candle low before it then we take a short position.

Trading Signal

for simplicity, we take +1 for long signals, and -1 for short signals. This is based on above mentioned rule under checking for direction of price movement i.e 1) ATR breakout 2) 4 candle high-low.

Calculating the returns on exit

Once we have entered a position — either a long or short position, we would want to exit the position — to take either profit or loss, so the next step in the process is we calculate the exit return for a position we entered.

So we manually set the take profit to 0.5 and stop loss threshold to 0.1. After that we iterate over each minute in yes_bank data frame and take a long short position on signals we got earlier. For simplicity, we would take one one position at a time.

We would store all the results from the trade in trades data frame with columns “Position”, Entry time, “Entry Price”, “Exit Time”, “Exit Price”, “PNL”. Top five columns we got following results:

details of each trade made
Using Matplotlib to graphically illustrate process.

After analyzing all trades, we can see that we made a total 123 trades, out of which 57 where for long trades, and 66 were short trader. Strategy loss percentage was 76% and win percentage was 24%. So clearly, we need to optimize the strategy.

Optimizing the Strategy

In above strategy, our winning percentage was much less as compared to our losses. So we need to optimize our strategy. At the same time, we had our different functions for long short positions, and profit loss calculation, so we need to optimize the code as wells. So following optimization needed:
1) Optimize the Exits Threshold
2) Optimizing code i.e creating a single function for entry signal generation, and PnL calculation in single function.

In order to optimize, we need to split the data into training set and testing test. We have a total of 13876 minutes of data. We split 2/3 of those in training data set, and rest for testing. We will iterate over the first two third of the training data and calculate profit and loss for a given value of stoop loss and take profit. After iterating over stop-loss and take profit values, we got the highest profit of 5.69, and optimal stop loss as 0.04, and profit taking values as 0.05. If we plot the same in heat map we get:

stop loss vs take profit grid

We can see the maximum profit is on the right side of the grid. Profit can be seen in green, and lowest values can be seen in red or orange.

Now, we would run a minute level ATR strategy for the last one third of minutes in dataset. We return the profit and loss for optimal take profit and optimal loss using the brute force method, and we also calculate the same using manually set the threshold. At stop loss 0.03 and take_profit threshold 0.04, we can see that average profit for last one third minute data at mannual threshold of (stop loss: 0.03, and profit : 0.04) is 2.6 and average profit and loss at optimal threshold is -0.95.

So we can see that for yes bank we can take stop_loss threshold at 0.03, and take_profit at 0.04.

Codes for the same can be found at: https://github.com/ashish2704/Scalping-Day-Trading-Strategy-

A note In Plain English

Did you know that we have four publications and a YouTube channel? You can find all of this from our homepage at plainenglish.io — show some love by giving our publications a follow and subscribing to our YouTube channel!

--

--

A self taught data analytics professional with expertise in data analytics in financial sectors. Love to use data backed decisions in all aspects.