SlideShare a Scribd company logo
1 of 40
Download to read offline
Algorithmic Trading
with Agriculture-Commodities
NCDEX
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
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
Directional
Hedging
Arbitrage
23
Various approaches in the market
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
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
Algorithmic Trading Stages
9
Algo Trading Stages
Trading
Concept
Filtering
Criteria
Visualize the Model
Backtesting
Optimization
Paper Trading
Go Live
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
Trading Concept
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
Brainstorming ideas- Fetch the Data
Annual and Quarterly GDP of various sectors. Source: MOSPI(http://mospi.nic.in/data)
14
Brainstorming ideas- Visualize-1
15
Brainstorming ideas- Visualize-2
16
Brainstorming ideas- Visualize-3
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
Filtering criteria
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
Visualize the Model
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
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: investing.com). the visual below, gives us the confirmation about our
logic.
Backtesting
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
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
Backtesting - Overview
We need to perform the following activities in this stage:
0.Download the csv file from investing.com
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
https://medium.com/@sunil.guglani/how-to-develop-your-first-trading-bot-using-python-by-recognising-
candlestick-patterns-a755f7fa6674
27
Backtesting – Fetch Data
Example:
0.Download the csv file from investing.com
Go to investing.com, search for Chana and download the Historical data by selecting the range:
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
Backtesting - Candlestick chart
Visualize the Output
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
Backtesting Results
Optimization
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.
Paper Trading
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.
Go Live
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
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
Conclusion
Questions & Answers

More Related Content

More from QuantInsti

Big Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingBig Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingQuantInsti
 
Backtest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexBacktest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexQuantInsti
 
Pairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketPairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketQuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated TradingQuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated TradingQuantInsti
 
Quantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantInsti
 
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...QuantInsti
 
How to automate an options day trading strategy
How to automate an options day trading strategyHow to automate an options day trading strategy
How to automate an options day trading strategyQuantInsti
 
Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...QuantInsti
 
How Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisHow Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisQuantInsti
 
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...QuantInsti
 
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...QuantInsti
 
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...QuantInsti
 
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsAlgorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsQuantInsti
 
Risk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth PresentationRisk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth PresentationQuantInsti
 
How EPAT Can Help You! Presentation
How EPAT Can Help You! PresentationHow EPAT Can Help You! Presentation
How EPAT Can Help You! PresentationQuantInsti
 
Modelling Trading Strategies In Equities Presentation
Modelling Trading Strategies In Equities PresentationModelling Trading Strategies In Equities Presentation
Modelling Trading Strategies In Equities PresentationQuantInsti
 
Webinar Mean Reversion Strategies Presentation
Webinar Mean Reversion Strategies PresentationWebinar Mean Reversion Strategies Presentation
Webinar Mean Reversion Strategies PresentationQuantInsti
 
AMA Session On Algorithmic Trading Presentation
AMA Session On Algorithmic Trading PresentationAMA Session On Algorithmic Trading Presentation
AMA Session On Algorithmic Trading PresentationQuantInsti
 
Classification of quantitative trading strategies webinar ppt
Classification of quantitative trading strategies webinar pptClassification of quantitative trading strategies webinar ppt
Classification of quantitative trading strategies webinar pptQuantInsti
 

More from QuantInsti (20)

Big Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingBig Data And The Future Of Retail Investing
Big Data And The Future Of Retail Investing
 
Backtest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexBacktest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX Index
 
Pairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketPairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock Market
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
 
Quantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of Cryptocurrencies
 
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
 
How to automate an options day trading strategy
How to automate an options day trading strategyHow to automate an options day trading strategy
How to automate an options day trading strategy
 
Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...
 
How Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisHow Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative Analysis
 
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
 
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
 
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
 
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsAlgorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
 
Risk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth PresentationRisk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth Presentation
 
How EPAT Can Help You! Presentation
How EPAT Can Help You! PresentationHow EPAT Can Help You! Presentation
How EPAT Can Help You! Presentation
 
Modelling Trading Strategies In Equities Presentation
Modelling Trading Strategies In Equities PresentationModelling Trading Strategies In Equities Presentation
Modelling Trading Strategies In Equities Presentation
 
Webinar Mean Reversion Strategies Presentation
Webinar Mean Reversion Strategies PresentationWebinar Mean Reversion Strategies Presentation
Webinar Mean Reversion Strategies Presentation
 
AMA Session On Algorithmic Trading Presentation
AMA Session On Algorithmic Trading PresentationAMA Session On Algorithmic Trading Presentation
AMA Session On Algorithmic Trading Presentation
 
Classification of quantitative trading strategies webinar ppt
Classification of quantitative trading strategies webinar pptClassification of quantitative trading strategies webinar ppt
Classification of quantitative trading strategies webinar ppt
 

Recently uploaded

Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 

Recently uploaded (20)

FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 

Algorithmic Trading in Commodity Markets by Sunil Guglani

  • 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. 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
  • 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 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
  • 9. 9 Algo Trading Stages Trading Concept Filtering Criteria Visualize the Model Backtesting Optimization Paper Trading Go Live
  • 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
  • 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 Brainstorming ideas- Fetch the Data Annual and Quarterly GDP of various sectors. Source: MOSPI(http://mospi.nic.in/data)
  • 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
  • 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
  • 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 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: investing.com). the visual below, gives us the confirmation about our logic.
  • 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 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 Backtesting - Overview We need to perform the following activities in this stage: 0.Download the csv file from investing.com 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 https://medium.com/@sunil.guglani/how-to-develop-your-first-trading-bot-using-python-by-recognising- candlestick-patterns-a755f7fa6674
  • 27. 27 Backtesting – Fetch Data Example: 0.Download the csv file from investing.com Go to investing.com, search for Chana and download the Historical data by selecting the range:
  • 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 Backtesting - Candlestick chart Visualize the Output
  • 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
  • 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.
  • 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.
  • 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 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