<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ashish Mohan on Medium]]></title>
        <description><![CDATA[Stories by Ashish Mohan on Medium]]></description>
        <link>https://medium.com/@ashish.spavj?source=rss-58f3e47631c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qY9nWvOMHUANnefI.jpg</url>
            <title>Stories by Ashish Mohan on Medium</title>
            <link>https://medium.com/@ashish.spavj?source=rss-58f3e47631c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:56:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashish.spavj/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scalping day Trading strategy in Python in Plain English]]></title>
            <link>https://python.plainenglish.io/scalping-day-trading-strategy-in-python-in-plain-english-c7c6f90bc89d?source=rss-58f3e47631c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7c6f90bc89d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading-ideas]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Ashish Mohan]]></dc:creator>
            <pubDate>Sat, 30 May 2020 00:55:00 GMT</pubDate>
            <atom:updated>2020-05-30T19:53:06.405Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Last week I wrote about the coding the scalping strategy (read my previous </em><a href="https://medium.com/@ashish.spavj/make-money-with-algorithmic-trading-how-to-code-scalping-day-trading-stratgey-1-a0b5364ecfd8"><em>blog</em></a><em> 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.</em></p><h4><strong>Brief Overview of Scalping Strategy</strong></h4><p>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.</p><p><em>Market Making: As per </em><a href="https://www.investopedia.com/articles/trading/05/scalping.asp"><em>investopedia</em></a><em>, 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.</em></p><p><em>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.</em></p><p>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.</p><p>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.</p><h4><em>How ATR based scalping strategy works?</em></h4><p>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.</p><h4><strong>Steps involved in developing strategy in Python</strong></h4><p>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.</p><p>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:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*meztDdj7K3h7RWDKg0YiqA.png" /><figcaption>1 minute data of yes bank from 1st april to 29th may 2020 with date as an index</figcaption></figure><p>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.</p><h4><em>ATR Breakout</em></h4><p>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.</p><h4><em>Checking for direction of price movement</em></h4><p>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.</p><p>In the same way , if low candle of breakout is lower than the 3 candle low before it then we take a short position.</p><h4><em>Trading Signal</em></h4><p>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.</p><h4><em>Calculating the returns on exit</em></h4><p>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.</p><p>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.</p><p>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:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*1qrJIIC0ULOupRyg8fikdw.png" /><figcaption>details of each trade made</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV0hUBYTBDHwz14VwO3k7g.png" /><figcaption>Using Matplotlib to graphically illustrate process.</figcaption></figure><p>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.</p><h4><strong>Optimizing the Strategy</strong></h4><p>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: <br>1) Optimize the Exits Threshold <br>2) Optimizing code i.e creating a single function for entry signal generation, and PnL calculation in single function.</p><p>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:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kT5SyjBlE9cvBW7PO5XSiw.png" /><figcaption>stop loss vs take profit grid</figcaption></figure><p>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.</p><p>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.</p><p>So we can see that for yes bank we can take stop_loss threshold at 0.03, and take_profit at 0.04.</p><p>Codes for the same can be found at: <a href="https://github.com/ashish2704/Scalping-Day-Trading-Strategy-">https://github.com/ashish2704/Scalping-Day-Trading-Strategy-</a></p><h4><strong>A note In Plain English</strong></h4><p>Did you know that we have four publications and a YouTube channel? You can find all of this from our homepage at <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> — show some love by giving our publications a follow and <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>subscribing to our YouTube channel</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7c6f90bc89d" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/scalping-day-trading-strategy-in-python-in-plain-english-c7c6f90bc89d">Scalping day Trading strategy in Python in Plain English</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Money with Algorithmic Trading- How to code scalping Day Trading Stratgey — 1]]></title>
            <link>https://medium.com/@ashish.spavj/make-money-with-algorithmic-trading-how-to-code-scalping-day-trading-stratgey-1-a0b5364ecfd8?source=rss-58f3e47631c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0b5364ecfd8</guid>
            <category><![CDATA[money]]></category>
            <category><![CDATA[day-trading]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Ashish Mohan]]></dc:creator>
            <pubDate>Fri, 22 May 2020 02:10:12 GMT</pubDate>
            <atom:updated>2020-05-22T11:22:34.226Z</atom:updated>
            <content:encoded><![CDATA[<h3>Make Money with Algorithmic Trading- How to Code Scalping Day Trading Strategy</h3><p><em>In the year 2017, I developed my interest for algorithmic trading. For some one with no background in programming, it was a daunting task. Although I was active in financial markets but I had no idea how to even write a print (“Hello World”) command. I struggled and looked for various online resources and was lost. It was like swimming in ocean with no end. But with few set backs I developed my own curriculum, and restricted my self to only few courses and focussed more on practice. After three years, when I feel more comfortable in programming, I feel like its time to give back. This is just first in series of many blogs to come, where I will break down the pieces of algorithmic trading, so that any one can get a taste of it.</em></p><p><em>Disclaimer: In the article I have assumed that you have fair knowledge of jupyter notebook and you know the basics of python command.</em></p><p><strong><em>So what is Scalping Strategy?</em></strong></p><p>Scalping is a day trading stratgey where a trader holds an instrument for few minutes. For example buy a share of “Reliance Industries” at 10:30 AM and then sell it off at 10:32 AM. You typically hold a position for few minutes and you try to capture the fractional price movement. During the day you repeat the strategy multiple times. Scalping strategy can be effective in short term volatility, i.e when we see frequent change in prices.</p><p>In this blog, we will focus on specific version of scalping stratgey called ATR scalping strategy. ATR stands for <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjJu4rcosbpAhXej3IEHTzzDEoQFjAaegQIAhAB&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FAverage_true_range&amp;usg=AOvVaw0DtDCVYeq1WDw0XdKpmVbl">Average True Range</a>. This is how the strategy works:-</p><p><em>Step 1:</em> Use ATR to identify when short term volatility increase</p><p><em>Step 2:</em> Once we identify the moment of volatility increase, we look for pattern whether price is going up or going down. We will use candle highs or lows to identify price pattern</p><p><em>Step 3:</em> We will exit the position based on certain profit levels or stop loss.</p><p><strong><em>Coding the Strategy in Ipython notebook</em></strong></p><p><strong><em>Step 1: Import All the dependencies</em></strong></p><p>Import talib for technical analysis, numpy for computing , pandas for data analysis, matplotlib and seaborn for data visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a16G26tedzQtNlsfoPx1JQ.png" /><figcaption>importing all the dependencies</figcaption></figure><p><strong><em>Step 2: Import the data</em></strong></p><p>I have used kite api call for data collection. To import the data from kite api you need to have access premium access to it. There are other free resources sucha as yahoo finance to get the data but most of them have limited data characteristics<em>. Logging process for kite is as follows:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_im936rD6q7vTE68NsVHA.png" /><figcaption>for privacy concerns I have hidden my api key, people should replace this with their own api key</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*S3QijF0rhPfdDl3OemVxmA.png" /><figcaption>from the url opy the api key and assign it to a varriable</figcaption></figure><p>assign api_key and api_secret to varriables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3dOMRYObnGcDTQsOz2N6Q.png" /><figcaption>connecting to kit for using access token to generate session</figcaption></figure><p>for this blog purpose, we will use one minute data of Reliance equity. Reiliance equity is identified as instrument_token = 738561, within a time period of 1st of April, 2020 to 15th of May 2020. Data is stored in variable df.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DA2VgVzmNd6wOLuTnMhLdQ.png" /></figure><p><strong><em>Step 3: Working with Data using pandas data frame</em></strong></p><p>In this step, we will clean the data and modify it for our further use. First we will store the data in pandas dataframe. Pandas dataframe stores data in two dimensional metrix and it works more like microsoft excel. And then we will use index column to “<em>date</em>”. Indexing adds a data structure to the file so that we can easily locate any data point. Then we will use .head() function to see the first five columns of our data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoHLumVkS5zRNc8FeyjDiQ.png" /><figcaption>making a pandas data frame</figcaption></figure><p>data should look like something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*h78RFvR0BgaZzzLNLnWdgA.png" /><figcaption>df0.head() function displays the first five rows of a data base</figcaption></figure><p><strong><em>Step 4. Code the ATR scalping strategy</em></strong></p><p>This involves multiple mini steps:</p><p>a) calculate Average True Range with a time period of 30 minutes</p><p>b) calculate the rolling mean for 5 minutes</p><p>c) identify the minutes where ATR breaks out its rolling mean</p><p>d) calculate three candle rolling high and check if the fourth candle is higher than previous 3 candles. similarly we will calculate for low candles.</p><p>e) we will buy(Long) the stock when there is a ATR break out &amp; fourth candle is higher than previous3.</p><p>F) we will sell(Short) the stock when there is a ATR breakout &amp; fourth candle is lower than previous 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7a8ACU57xbAt0XSpjLVXtQ.png" /><figcaption>Coding the Scalping Strategy</figcaption></figure><p><strong><em>Step 5: Backtest the Strategy</em></strong></p><p>Now we will backtest the strategy on dataset to see how it would have performed. For the demonstration purpose, we will exit a trade when price is increased by 0.03 or we will exit a trade with stop loss at 0.01. So our risk to reward ratio for this stratgey is 1:3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2hUt1LuFIm2y0fOzPaFvg.png" /><figcaption>calculating profit and loss for each trade</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opZquExhvs_BUOyuGhdn8w.png" /><figcaption>Entery and Exit positions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4rEp8uMQ30PlpQCFUkfqQ.png" /><figcaption>Table showing trade signals, entry and exit price</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*WiXLXTlLrBEoi5YxH7kY2Q.png" /></figure><p>Further Analyzing the performance, we can see that we had winning percentage of 34% and we lost trade 65%. For every winning trade we would have had made Rs.44 and on every loosing trade we would have lost rs 15.</p><p>So we need to further optimize our strategy but thats for another blog post. Till then enjoy experimenting and keep practicing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0b5364ecfd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>