A quick primer on Algo-Trading in Python.
Lets get straight to the point, I assume you already know Python reasonably well. Also, that you do stock trading yourself and so are familiar with Technical Analysis and the related indicators and terminologies. If you know both of these, this article can get you kick-started in the area of algo-trading with Python in the shortest possible time. If not, you are still welcome to read, but it may not make much sense to you anyway.
We begin by deciding upon our trading universe as the first step. Our trading universe will be NIFTY 500 stocks, which is the list of top 500 businesses listed on NIFTY. You can download the CSV file of all 500 stocks from the NSE website (link given below):
https://nsearchives.nseindia.com/content/indices/ind_nifty500list.csv
Next, we need to extract the Symbols of the companies from this CSV file. The third column in the csv file is the "Symbol". The next step would be to add the suffix ".NS" to each Symbol (we will understand why later on!). We can make a new column in excel by dragging the following formula for the entire column:
="'"&C3&".NS'," (assuming that Symbol is in cell C3)
Copy the entire new column and paste with transpose so that all values are horizontally placed in columns and then use the CONCAT worksheet function in excel to bring all these Symbols in a single cell. Now we have the "list" of all Symbols comprising of our Trading Universe.
Python Environment
Next, we move into Python environment - it can be Jupyterlab or Notebook or Visual Studio Code or any other environment that is ready and working.
We define a list of Symbols.
We shall be looping through this list to screen out stocks which fulfill the conditions defined by our strategy or rules till the previous trading day. Simultaneously we will also run back-tests on the signals to evaluate the returns and only finalize those trades which have given returns of > 10% during our time horizon. The time horizon for us would be last 10 years.
Next, we import all the required libraries and modules:
"pandas" needs no introduction. However, "pandas_ta" is a Python library that provides most functionality required for Technical Analysis.
"backtesting" is a library that provides the functionality for back-testing of strategies along a certain timeframe.
"yfinance" is a library that maintains historical data for all major stock exchanges across the world.
Now you will understand why we added the suffix "NS" to each Symbol. The "yfinance" library being a global library uses suffixes to identify the stock exchanges, so ".NS" here denotes "NSEI" (National Stock Exchange of India).
"pytz" is a library that is used to convert dates into the appropriate timezone. With the "yfinance" library, I have consistently used "America/ New York" timezone as the library throws errors at times when we do not define the timezone explicitly.
Before we go into the next step, lets consider the strategy we are going to use. We are mostly going to use a combination of RSI and ADX Technical Indicators for deciding on our BUY or SELL calls. In our example, we have considered the following:
BUY WHEN RSI (14) < __ & ADX > __ & 200 EMA crossover
SELL WHEN RSI (14) > __
The numbers have been intentionally kept blank above.
Next, we add two helper functions totalSignal - which actually executes the strategy and addemasignal which adds the "EMA" signal.
Next, we define a Python class MyStrat and a helper function Signal which simply returns a copy of a dataframe object. The class MyStrat defines the back-testing logic, which then gets passed into the backtesting module imported earlier.
Next, we actually execute our strategy with the help of our helper functions. The code is commented at each step for better understanding. Comments are in gray and they will help you understand what each step of the code is doing.
Important: The above code will give you the "stat" variable which has all the backtesting statistics computed for all the eligible trades. If you wish to deepdive into your back-testing results, you need to print(stat) or output stat and review the results. The stat variables will give you the "Win Rate" which is the percentage of successful trades, the "Return %" which is the total back-tested return during the time horizon had we deployed this strategy. And it will also show you the "Buy and Hold Return %". There are other statistics which are also interesting. Using the stat variable for all Nifty 500 stocks, and by drawing a trendline, interesting insights can be found which are outside the scope of this article. The returns computed are pre-tax returns and you need to independently factor in tax rates in your code to arrive at the final cash returns.
Finally we output our two accumulated trade lists as below: The first file, "lastest_output.csv" has the list of all trades as of "the previous trading day only" for which back-testing results have been successful. The second file "total_output.csv" has all eligible trades during the chosen time horizon for back-testing. While the first file should give you inputs to actually pass on to your broker's API engine for execution of live trades every morning, the second file is only for reference.
Output:
Running the above code for the entire Nifty 500 stocks takes approximately 10 minutes. According to the output, the first trade to be executed on 28th February 2025 was for XXXXXXXX. (Name deliberately hidden). The output can be validated using the following chart of the stock. The signals and the price movement have been marked in green circles and are self-explanatory ! It is always a good idea to actually validate your output by verifying charts and indicators online.
Integration with Zerodha using API:
While this is beyond the scope of this article and I might cover this in a separate topic some other time, however, if you wish to try your hand, here is the link to the Zerodha "pykiteconnect" documentation and GITHUB pages.
https://github.com/zerodha/pykiteconnect
Conclusion:
Algorithmic trading in Python offers a powerful and flexible way to automate trading strategies. By leveraging popular libraries like "pandas_ta" and "backtesting" traders can quickly develop and backtest trading strategies. While short term trading is important to maintain liquidity, always remember that the simple "buy and hold" strategy almost always outperforms any short term trading strategy consistently!
The next step can include creation of an Algo Trading AI Agent, which can do Technical Analysis, autonomously take trading decisions and also back-test, improvise and learn.
As we conclude, we hope that you now possess a solid foundation to embark on your own algorithmic trading journey! For any questions or if you need the code or for any help in running or debugging, feel free to reach out at prasad.athalye@gmail.com. I shall be happy to help in any way. Comments, feedback are always welcome!
Note: This article and the examples provided are for educational purposes only and should not be considered as investment advice. Algorithmic trading carries significant risks, and traders should thoroughly evaluate their strategies before deploying them in live markets.
Analyst - Credit Admin|| MSQE ISI Kolkata' 24 || ARSD, DU' 2
4moNice resource sir!