Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Algorithmic Trading in Commodity Markets by Sunil Guglani


Published on

Algorithmic Trading in Commodity Markets by Sunil Guglani

Session Outline:
- Introduction
- Stages of Algorithmic Trading:
- Formulating the Trading Concept/Logic
- Filtering criteria to choose the scripts
- Verification of Logic (at High Level)
- Backtesting
- Optimization of Parameters
- Paper Trading aka Forward Testing or Simulation Trading, in the real environment
- Deployment in the real environment
- Resources for learning Algorithmic Trading
- A walkthrough with a sample strategy in Python
And so much more...

Who should attend?
- Discretionary/manual traders (ex. professional traders, part-time traders) who are looking to upskill and get better returns
- Commodity Traders looking to implement quant strategies
- Technology professionals, who want to leverage their technical skills to invest wisely in the financial markets
- Students and other enthusiasts who wish to make a career in quantitative finance

Speaker Profile:
Sunil Guglani (Assistant Vice President at NCDEX)
Sunil is currently working with NCDEX (National Commodity and Derivatives Exchange Ltd) as Assistant Vice President. He has a vast experience of around 20 years working within the IT industry. An Algorithmic Trader today, Sunil is an EPAT Alumni who changed his domain from IT management to the rapidly growing domain of Algo Trading 1.5 years back.

Sunil primarily uses Python for developing his Algorithms. His strategies are based on price pattern recognition, probability, correlation/cointegration, autocorrelation, pair trading, stationary series, momentum identification, Hedging and ML/DL algorithms. He developed his own backtesting and technical indicator libraries as well.

Learn more about our EPAT® course here:
OR Visit us at:

Like and Follow us on:

Published in: Education
  • Be the first to comment

Algorithmic Trading in Commodity Markets by Sunil Guglani

  1. 1. Algorithmic Trading with Agriculture-Commodities
  2. 2. NCDEX
  3. 3. 5 Overview of NCDEX Launched in 2003 Now India’s most vibrant platform for price discovery and risk management for agricultural commodities. Product Offering Trading in 20 commodities Network More than 300 members and 487K clients Logistics Approx. 500 approved warehouses
  4. 4. Commodity Complex Cereals / Pulses •Barley •Maize Kharif •Maize Rabi •Wheat •Chana •Moong •Paddy Spices •Coriander •Jeera •Turmeric •Pepper Fibres •Kapas •Cotton Seed Oilcake •29 mm Cotton Guar Complex •Guar Seed •Guar Gum Oil & Oil Seeds •Soybean •Refined Soy Oil •Degummed Soy Oil •Mustard Seed •Crude Palm Oil Sweeteners •Sugar M
  5. 5. Directional Hedging Arbitrage 23 Various approaches in the market
  6. 6. 6 Hedging Ø What: An investment to mitigate risk from price fluctuations in the primary investment asset. Ø Why: To mitigate the risk on underlying asset for farmers and investors. Ø How: Hedging between underlying asset and corresponding Futures/Options contracts. Ø Prerequisite: High correlation is required between the hedging instruments. Ø Advantage: Less investment for mitigation from price uncertainty.
  7. 7. 7 Arbitrage Calendar Spread: Ø What: Difference between two Futures Calendar contracts. Ø Attributes: Ø Builds Stationary Series with hedge ratio -1. Ø Mean reverting Ø Lower margin requirement - requires approximately 1/4th of margin Ø Less market risk and excellent profit potential Pair Trading: Ø What: Trading between two/more highly negatively/positively fundamentally correlated commodities. Ø Attributes: Ø Difference between two Futures Commodity contracts.(if positively correlated) Ø Builds Stationary Series with hedge ratio Ø Usually Mean reverting Ø Less market risk and excellent profit potential
  8. 8. Algorithmic Trading Stages
  9. 9. 9 Algo Trading Stages Trading Concept Filtering Criteria Visualize the Model Backtesting Optimization Paper Trading Go Live
  10. 10. Algo/Quant Trading Strategies Mean Reversion Stationary Series Arbitrage Pair Trading Correlation /Co- integration Momentum Moving Average Linear Regression Logistic Regression Probability Distribution Infrastructure Connect with Broker Data Provider API Order Management API Algo Hosting In-Permise Cloud Google Cloud Platform MS Azure Oracle Cloud AWS Alibaba Cloud Data Visualization TradingView Tableau PowerBI Matplotlib / Seaborn/ Plotly Algo Development Tools Python Metatrader Amibroker Ninjatrade r Algo Trading Platforms Quantopian(Pyt hon) Blueshift(Pyth on) Quantiacs Zerodha Streak(UI) Python Libs Backtesting TALib Backtrader bt MibianLib Data Preprocessing Urllib Pandas Numpy Scrapy beutifulsoup Sentiment Analysis Stream- python Feedparse r Tweepy Textblob NLP Algo Trading Resources
  11. 11. Trading Concept
  12. 12. 12 Trading Concept Activities in Formulate the Trading Concept: Ø Brainstorming ideas Ø Finalize Trading logic/idea Ø Frequency of trades Ø Choose market segment (Equity/Commodity/FX/Crypto) Ø Back testing period Ø Automation tools/languages
  13. 13. 13 Brainstorming ideas- Fetch the Data Annual and Quarterly GDP of various sectors. Source: MOSPI(
  14. 14. 14 Brainstorming ideas- Visualize-1
  15. 15. 15 Brainstorming ideas- Visualize-2
  16. 16. 16 Brainstorming ideas- Visualize-3
  17. 17. 17 Trading Concept Example: Agriculture commodities are generally less volatile in nature and they revolve around the same price range. Considering above idea, answers to the following are : a. logic to achieve my goal(Buy at Low and Sell at High)?: -mean reversion trading strategy. use Bollinger band. -Buy: if Close price goes below -2 standard deviation from mean. -square off position: if Close price goes above +2 standard deviation from mean b. What will be the frequency of my trades? : -Daily frequency c. Which segment will it work most effectively(Equity/Commodity/FX/Crypto..): -Agri commodity segment d. How much should be backtesting period?: -1 years.(longer the better) e. Which automation tools/languages will be most useful for this logic?: -Python
  18. 18. Filtering criteria
  19. 19. 19 Filtering criteria Ø What: Determine filter criteria to choose scripts/instruments, which fits best with the logic Ø Why: fitment for the logic Ø How: Screeners, logic built in the algo for screening Ø Prerequisite: Sample Data and Formulation of Logic Ø Next Step: Verification of Logic The selection/filtration of scripts can be done before or during the trading hours(real time). It all depends on your core logic. Example: As we have decided, we will use Agri commodity scripts and high liquid scripts only, therefore filtering criteria to be used as follows: a. Segment== Agri. b. Volume>1000
  20. 20. Visualize the Model
  21. 21. 21 Visualize the Model ØWhat: Preliminary verification of logic ØWhy: To save time and efforts in backtesting ØHow: Use visualization tools like Tableau/Power BI or sample data with Excel ØPrerequisite: Sample Data and Formulation of Logic ØNext Step: Detailed backtesting
  22. 22. 22 Visualize the Model It is a 1 year graph of Chana on daily frequency. And SMA, STD(-2,+2) is applied on the 20 days lookback period.(Courtesy: the visual below, gives us the confirmation about our logic.
  23. 23. Backtesting
  24. 24. 24 Backtesting ØWhat: Verification of logic using Historical Data ØWhy: To save time and efforts and money ØHow: Backtesting tools ØPrerequisite: Historical Data and Formulation of Logic ØNext Step: Paper/Simulation Trading
  25. 25. 25 Backtesting - Overview One should consider the following parameters in this stage: Various performance parameters Ø Returns Ø Max drawdown Ø Max continuous drawdown Ø Max profit Ø Max continuous profit Ø Number of transactions Ø Average returns per transaction Ø Transaction charges Ø Slippages,etc. Few more points to focus are: Ø Stop loss/Trailing stop loss Ø Target price Ø Entry Criteria Ø Exit criteria
  26. 26. 26 Backtesting - Overview We need to perform the following activities in this stage: 0.Download the csv file from 1. Import the necessary libraries 2. Fetch the historical OHLC data for an instrument. 3. Write the supporting functions to achieve our logic 4. Generate the buy/sell signals using candlesticks 5. Visualize the output 6. Checking returns of the strategy Note: To review steps used in backtesting please refer to my article candlestick-patterns-a755f7fa6674
  27. 27. 27 Backtesting – Fetch Data Example: 0.Download the csv file from Go to, search for Chana and download the Historical data by selecting the range:
  28. 28. 28 Backtesting- algo walthrough 1. Import the necessary libraries 2. Fetch the historical OHLC data for an instrument. 3. Write the supporting functions to achieve our logic 4. Generate the buy/sell signals using candlesticks 5. Visualize the output >> GO TO PYTHON EDITOR AND EXPLAIN THE ALGO(pls refer attached python file)
  29. 29. 29 Backtesting - Candlestick chart Visualize the Output
  30. 30. 30 Backtesting - Results **************BACKTEST RESULTS OF : Chana ************************ Sum of returns in % 13.788230372932315 Average returns per transaction in % 3.4470575932330787 Absolute returns 552.0 Absolute returns per trx 138.0 Max drawdown for a trx -339.0 Max returns for a trx 421.0 Losing trx 1 Winning trx 3 Win/Lose ratio 3.0
  31. 31. 31 Backtesting Results
  32. 32. Optimization
  33. 33. 33 Optimization ØWhat: Optimization of logic parameters to fit the best. Continuous process. ØWhy: The price movement and behavior of the instrument may keep changing. ØHow: Backtesting Data, Optimization algorithms ØPrerequisite: Backtesting performance ØNext Step: Paper/Simulation Trading Things to consider are : ØOver fitting: is optimizing the logic and parameters to the extent that the program will work best in some specific situations and scenarios. ØAvoid overfitting of parameters.
  34. 34. Paper Trading
  35. 35. 35 Paper Trading Paper/simulation trading is the way of verification of your logic in the real environment. One can do this by using the feature provided by his/her broker, or you can also develop your framework to test the same. Pros: Ø One doesn’t need to invest actual money in this stage. Ø It gives very accurate and precise results. Ø One can expect same/similar results in the real environment. Cons: Ø It is time consuming activity.
  36. 36. Go Live
  37. 37. 37 Go Live Functionally following aspects are required to be managed: 1. Order management 2. Risk Management 3. Money/Fund Management 4. Diversification of assets 5. Portfolio management 6. User Management 7. Slippages Technically following aspects are required to be managed: 1. Establish Connection with the broker api. 2. Passing the buy/sell orders using the broker connection, 3. Establish Connection with the data api(if data vendor is different from broker) 4. Accessing the real time and historical data using data api connection.
  38. 38. 38 Conclusion To summarize the following algo trading strategies, Algo can be considered as a software product and all the stages can be easily mapped with “Software Product Development Life Cycle”: All the stages has their own importance and is critical to success of the algo. • Formulate the trading logic/idea • Filtering criteria to choose the scripts • Verification of Logic(Visualization) • Backtesting • Optimization of Parameters • Paper Trading or Forward Testing or Simulation Trading • Deployment in the real environment
  39. 39. 39 Conclusion
  40. 40. Questions & Answers