SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
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

Contenu connexe

Plus de 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
 

Plus de 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
 

Dernier

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 

Dernier (20)

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

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