SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Pairs Trading in Python
Introduction and application of classical pairs trading
www.quantconnect.com
Jared Broad
CEO and Founder
Outline
▪ Introduction to QuantConnect
▪ General Idea of Pairs Trading
▪ Implementing the Model
▪ Testing and Researching
▪ Weaknesses of Pairs Trading
▪ Summary
February-2018 QuantConnect – Pairs Trading with Python Page 2
What is QuantConnect?
We empower investors with powerful
investment tools and connect the brightest
minds from around the world with capital they need.
February-2018 QuantConnect – Pairs Trading with Python Page 3
What is QuantConnect?
QuantConnect is a community of 50,000 Engineers, Data Scientists, Programmers
From 6,100 Cities and 173 Countries
February-2018 QuantConnect – Pairs Trading with Python Page 4
Building Thousands of Algorithms Every Day
February-2018 QuantConnect – Pairs Trading with Python Page 5
We’ve built a web algorithm lab where thousands of
people test their ideas on financial data we provide; for free.
LEAN ALGO
TECHNOLOGY
FINANCIAL
DATA
POWER
COMPUTING
How do we do it?
EQUITIES
OPTIONS
FUTURES
FOREX
CRYPTO
February-2018 QuantConnect – Pairs Trading with Python Page 6
Pairs Trading – Market Neutral Trading Strategy
Pairs trading is a type of statistical arbitrage
Basic Idea:
1) Select two stocks which move similarly.
2) Find where the price diverges.
3) Sell the high priced stock and buy the low priced stock.
February-2018 QuantConnect – Pairs Trading with Python Page 7
February-2018 QuantConnect – Pairs Trading with Python Page 8
The Price Ratio
To standardize the prices – we make a
Price Ratio. This allows us to compare
Stock A and Stock B over time.
Price Ratio = Stock A / Stock B
If the Ratio changes significantly,
it’s a signal to trade.
We can measure this change with
standard deviation.
0
2
4
6
8
10
12
14
Jan-08 Feb-08 Mar-08 Apr-08 May-08 Jun-08 Jul-08 Aug-08
Price Series of Stock A and B Stock A Stock B
Price(B) = 2 * Price(A) + 1
0
2
4
6
8
10
12
14
16
Jan-08 Feb-08 Mar-08 Apr-08 May-08 Jun-08 Jul-08 Aug-08
Price Divergence Stock A Stock B
Example Price Divergence
February-2018 QuantConnect – Pairs Trading with Python Page 9
Basic Idea of Pairs Trading
Buy CVX
Sell XOM
Buy XOM
Sell CVX
Buy CVX
Sell XOM
Buy XOM
Sell CVX
Ratio Upper Threshold
Ratio Lower Threshold
When assets cross divergence threshold; trigger trade.
February-2018 QuantConnect – Pairs Trading with Python Page 10
StandardDeviations
Can we apply this idea to trading strategy?
To apply this concept;
❖ We model price with the log of stock price. This follows Brownian Motion N(0, ∆𝑡).
❖ This way the difference of the asset prices are cointegrated.
i.e. log(pricex) – log(pricey) is “One-Order Cointegrated”.
Stationary & Mean Reversion
February-2018 QuantConnect – Pairs Trading with Python Page 10
Step 1: Generate the spread of two log price series
𝑆𝑝𝑟𝑒𝑎𝑑 𝑡 = log(𝑌𝑡) − (𝛼 + 𝛽log(𝑋𝑡))
Step 2: Set the range of spread series [lower, upper]
If 𝑆𝑝𝑟𝑒𝑎𝑑 𝑡 > 𝑢𝑝𝑝𝑒𝑟 𝑡ℎ𝑟𝑒𝑠ℎ𝑜𝑙𝑑 Buy 𝑋𝑡, Sell 𝑌𝑡
If 𝑆𝑝𝑟𝑒𝑎𝑑 𝑡 < 𝑙𝑜𝑤𝑒𝑟 𝑡ℎ𝑟𝑒𝑠ℎ𝑜𝑙𝑑 Buy 𝑌𝑡, Sell 𝑋𝑡
Exploratory Research
❖ Find two likely cointegrated stocks: e.g. XOM, CVX
❖ Estimate spreads between each stock.
❖ Check for stationarity.
QuantBook Research
February-2018 QuantConnect – Pairs Trading with Python Page 12
Pairs Trading Weaknesses
❖ Double the fees.
❖ Capitalize on small price movements.
❖ Risk correlation will break down (e.g. CEO
change, new technology)
❖ Execution risk (slippage).
February-2018 QuantConnect – Pairs Trading with Python Page 13
LEAN Implementation
Backtest
❖ Create our Trading Signal.
❖ Run Backtest in QuantConnect.
February-2018 QuantConnect – Pairs Trading with Python Page 14
Summary
❖ We use cointegration to detect a long term relationship of two stocks.
❖ Changes in that relationship might signal a chance to profit by pairs trading.
Next Steps – Defining Trading Rules, Setting Thresholds
Total Trades Drawdown Net Profit Sharpe Ratio
270 12.9% 34% 0.555
February-2018 QuantConnect – Pairs Trading with Python Page 15
www.quantconnect.com
Thank you.
Appendix
Cointegration and Stationary
• Cointegration is a statistical property of a time
series(like the stock price series).
• Cointegration specifies a co-movement relationship of
price – the long term relationship.
• The mean and the variance of the
series do not vary over time
Cointegration Stationary
• If two series {𝑋𝑡} and {𝑌𝑡} are not stationary
• But their linear combination 𝑌𝑡 = 𝛽𝑋𝑡 − 𝛼 is a stationary process
{𝑿 𝒕} and {𝒀 𝒕} are cointegrated
How to test if two series are cointegrated?
Augmented Dickey-Fuller test
February-2018 QuantConnect – Pairs Trading with Python Page 18
Our Research Environment
February-2018 QuantConnect – Pairs Trading With Python Page 19
Coding the Idea, The Algorithm Lab
February-2018 QuantConnect – Pairs Trading With Python Page 20
Going Live, Deploying to Live Trading
February-2018 QuantConnect – Pairs Trading with Python Page 21

Weitere ähnliche Inhalte

Was ist angesagt?

"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an..."Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
Quantopian
 
Order Flow Imbalance Trading Algorithm
Order Flow Imbalance Trading AlgorithmOrder Flow Imbalance Trading Algorithm
Order Flow Imbalance Trading Algorithm
Reed Jessen
 
Best strategies for trading
Best strategies for tradingBest strategies for trading
Best strategies for trading
TeyYeeShen
 

Was ist angesagt? (20)

"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an..."Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
 
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob..."Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
 
Market Timing, Big Data, and Machine Learning by Xiao Qiao at QuantCon 2016
Market Timing, Big Data, and Machine Learning by Xiao Qiao at QuantCon 2016Market Timing, Big Data, and Machine Learning by Xiao Qiao at QuantCon 2016
Market Timing, Big Data, and Machine Learning by Xiao Qiao at QuantCon 2016
 
Statistical arbitrage
Statistical arbitrageStatistical arbitrage
Statistical arbitrage
 
Pairs Trading
Pairs TradingPairs Trading
Pairs Trading
 
Overview of price action trading
Overview of price action tradingOverview of price action trading
Overview of price action trading
 
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ..."How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
 
BUILDING AUTOMATED TRADING STRATEGIES
BUILDING AUTOMATED TRADING STRATEGIESBUILDING AUTOMATED TRADING STRATEGIES
BUILDING AUTOMATED TRADING STRATEGIES
 
Order Flow Imbalance Trading Algorithm
Order Flow Imbalance Trading AlgorithmOrder Flow Imbalance Trading Algorithm
Order Flow Imbalance Trading Algorithm
 
16 Stock trading strategies
16 Stock trading strategies16 Stock trading strategies
16 Stock trading strategies
 
Top 8 Forex Trading Strategies That Pro Traders Use
Top 8 Forex Trading Strategies That Pro Traders UseTop 8 Forex Trading Strategies That Pro Traders Use
Top 8 Forex Trading Strategies That Pro Traders Use
 
QuantConnect - Options Backtesting
QuantConnect - Options BacktestingQuantConnect - Options Backtesting
QuantConnect - Options Backtesting
 
Secrets Of Successful Traders
Secrets Of  Successful  TradersSecrets Of  Successful  Traders
Secrets Of Successful Traders
 
"From Trading Strategy to Becoming an Industry Professional – How to Break in...
"From Trading Strategy to Becoming an Industry Professional – How to Break in..."From Trading Strategy to Becoming an Industry Professional – How to Break in...
"From Trading Strategy to Becoming an Industry Professional – How to Break in...
 
CANDLESTICK PROFITS.pdf
CANDLESTICK PROFITS.pdfCANDLESTICK PROFITS.pdf
CANDLESTICK PROFITS.pdf
 
Quant insti webinar on algorithmic trading for technocrats!
Quant insti webinar on algorithmic trading for technocrats!Quant insti webinar on algorithmic trading for technocrats!
Quant insti webinar on algorithmic trading for technocrats!
 
10 Patrones Técnicos
10 Patrones Técnicos10 Patrones Técnicos
10 Patrones Técnicos
 
Best strategies for trading
Best strategies for tradingBest strategies for trading
Best strategies for trading
 
Learn A Simple Range Trading Strategy
Learn A Simple Range Trading StrategyLearn A Simple Range Trading Strategy
Learn A Simple Range Trading Strategy
 
Secrets of Price Action Trading
Secrets of Price Action TradingSecrets of Price Action Trading
Secrets of Price Action Trading
 

Ähnlich wie QuantConnect - Introduction to Pairs Trading

RSDeltabookforthecloud
RSDeltabookforthecloudRSDeltabookforthecloud
RSDeltabookforthecloud
Brian Crone
 
Quantlogic Product Presentation
Quantlogic Product PresentationQuantlogic Product Presentation
Quantlogic Product Presentation
nscarr
 

Ähnlich wie QuantConnect - Introduction to Pairs Trading (20)

QuantConnect ETF Momentum Asset Allocation
QuantConnect ETF Momentum Asset AllocationQuantConnect ETF Momentum Asset Allocation
QuantConnect ETF Momentum Asset Allocation
 
Melbourne Datathon Challenge 2019 (Buy Low Sell High)
Melbourne Datathon Challenge 2019 (Buy Low Sell High)Melbourne Datathon Challenge 2019 (Buy Low Sell High)
Melbourne Datathon Challenge 2019 (Buy Low Sell High)
 
Roadblocks for Institutional Adoption of Crypto - Andrew Rollins Shift Money ...
Roadblocks for Institutional Adoption of Crypto - Andrew Rollins Shift Money ...Roadblocks for Institutional Adoption of Crypto - Andrew Rollins Shift Money ...
Roadblocks for Institutional Adoption of Crypto - Andrew Rollins Shift Money ...
 
AlgoBit - One Pager
AlgoBit - One PagerAlgoBit - One Pager
AlgoBit - One Pager
 
Financial Data Mining and Algo Trading presented at the SAS Data Mining Confe...
Financial Data Mining and Algo Trading presented at the SAS Data Mining Confe...Financial Data Mining and Algo Trading presented at the SAS Data Mining Confe...
Financial Data Mining and Algo Trading presented at the SAS Data Mining Confe...
 
RSDeltabookforthecloud
RSDeltabookforthecloudRSDeltabookforthecloud
RSDeltabookforthecloud
 
Symmedian Technologies NEW 4SYTE.NET Supply Chain Data Virtualization Tool
Symmedian Technologies NEW 4SYTE.NET Supply Chain Data Virtualization ToolSymmedian Technologies NEW 4SYTE.NET Supply Chain Data Virtualization Tool
Symmedian Technologies NEW 4SYTE.NET Supply Chain Data Virtualization Tool
 
Robo advisory-online-fow dw-asia-gs_khooalgo2008
Robo advisory-online-fow dw-asia-gs_khooalgo2008Robo advisory-online-fow dw-asia-gs_khooalgo2008
Robo advisory-online-fow dw-asia-gs_khooalgo2008
 
Qraft company deck_202003_rf
Qraft company deck_202003_rfQraft company deck_202003_rf
Qraft company deck_202003_rf
 
Crowdsource Earnings Predictions and the Quantopian Research Platform
Crowdsource Earnings Predictions and the Quantopian Research PlatformCrowdsource Earnings Predictions and the Quantopian Research Platform
Crowdsource Earnings Predictions and the Quantopian Research Platform
 
Unique Value of Digital Assets Part IV Interpolative Value with Appendix
Unique Value of Digital Assets Part IV Interpolative Value with AppendixUnique Value of Digital Assets Part IV Interpolative Value with Appendix
Unique Value of Digital Assets Part IV Interpolative Value with Appendix
 
Adaptix_2013
Adaptix_2013Adaptix_2013
Adaptix_2013
 
Quantopian: Crowd-sourced Systematic Alpha
Quantopian: Crowd-sourced Systematic AlphaQuantopian: Crowd-sourced Systematic Alpha
Quantopian: Crowd-sourced Systematic Alpha
 
Uwe Wystup (MathFinance) on FX Derivatives Innovation
Uwe Wystup (MathFinance) on FX Derivatives InnovationUwe Wystup (MathFinance) on FX Derivatives Innovation
Uwe Wystup (MathFinance) on FX Derivatives Innovation
 
ClearTH Test Automation Framework: Case Study in IRS & CDS Swaps Lifecycle Mo...
ClearTH Test Automation Framework: Case Study in IRS & CDS Swaps Lifecycle Mo...ClearTH Test Automation Framework: Case Study in IRS & CDS Swaps Lifecycle Mo...
ClearTH Test Automation Framework: Case Study in IRS & CDS Swaps Lifecycle Mo...
 
What is Value Stream Management and why do you need it?
What is Value Stream Management and why do you need it?What is Value Stream Management and why do you need it?
What is Value Stream Management and why do you need it?
 
Quantlogic Product Presentation
Quantlogic Product PresentationQuantlogic Product Presentation
Quantlogic Product Presentation
 
資産運用とビッグデータ解析_2
資産運用とビッグデータ解析_2資産運用とビッグデータ解析_2
資産運用とビッグデータ解析_2
 
The Informative Guide_ White Label Crypto Exchange.pptx
The Informative Guide_ White Label Crypto Exchange.pptxThe Informative Guide_ White Label Crypto Exchange.pptx
The Informative Guide_ White Label Crypto Exchange.pptx
 
Internet Software and Services - Transactions Summary
Internet Software and Services - Transactions SummaryInternet Software and Services - Transactions Summary
Internet Software and Services - Transactions Summary
 

Kürzlich hochgeladen

VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 

QuantConnect - Introduction to Pairs Trading

  • 1. Pairs Trading in Python Introduction and application of classical pairs trading www.quantconnect.com Jared Broad CEO and Founder
  • 2. Outline ▪ Introduction to QuantConnect ▪ General Idea of Pairs Trading ▪ Implementing the Model ▪ Testing and Researching ▪ Weaknesses of Pairs Trading ▪ Summary February-2018 QuantConnect – Pairs Trading with Python Page 2
  • 3. What is QuantConnect? We empower investors with powerful investment tools and connect the brightest minds from around the world with capital they need. February-2018 QuantConnect – Pairs Trading with Python Page 3
  • 4. What is QuantConnect? QuantConnect is a community of 50,000 Engineers, Data Scientists, Programmers From 6,100 Cities and 173 Countries February-2018 QuantConnect – Pairs Trading with Python Page 4
  • 5. Building Thousands of Algorithms Every Day February-2018 QuantConnect – Pairs Trading with Python Page 5
  • 6. We’ve built a web algorithm lab where thousands of people test their ideas on financial data we provide; for free. LEAN ALGO TECHNOLOGY FINANCIAL DATA POWER COMPUTING How do we do it? EQUITIES OPTIONS FUTURES FOREX CRYPTO February-2018 QuantConnect – Pairs Trading with Python Page 6
  • 7. Pairs Trading – Market Neutral Trading Strategy Pairs trading is a type of statistical arbitrage Basic Idea: 1) Select two stocks which move similarly. 2) Find where the price diverges. 3) Sell the high priced stock and buy the low priced stock. February-2018 QuantConnect – Pairs Trading with Python Page 7
  • 8. February-2018 QuantConnect – Pairs Trading with Python Page 8 The Price Ratio To standardize the prices – we make a Price Ratio. This allows us to compare Stock A and Stock B over time. Price Ratio = Stock A / Stock B If the Ratio changes significantly, it’s a signal to trade. We can measure this change with standard deviation.
  • 9. 0 2 4 6 8 10 12 14 Jan-08 Feb-08 Mar-08 Apr-08 May-08 Jun-08 Jul-08 Aug-08 Price Series of Stock A and B Stock A Stock B Price(B) = 2 * Price(A) + 1 0 2 4 6 8 10 12 14 16 Jan-08 Feb-08 Mar-08 Apr-08 May-08 Jun-08 Jul-08 Aug-08 Price Divergence Stock A Stock B Example Price Divergence February-2018 QuantConnect – Pairs Trading with Python Page 9
  • 10. Basic Idea of Pairs Trading Buy CVX Sell XOM Buy XOM Sell CVX Buy CVX Sell XOM Buy XOM Sell CVX Ratio Upper Threshold Ratio Lower Threshold When assets cross divergence threshold; trigger trade. February-2018 QuantConnect – Pairs Trading with Python Page 10 StandardDeviations
  • 11. Can we apply this idea to trading strategy? To apply this concept; ❖ We model price with the log of stock price. This follows Brownian Motion N(0, ∆𝑡). ❖ This way the difference of the asset prices are cointegrated. i.e. log(pricex) – log(pricey) is “One-Order Cointegrated”. Stationary & Mean Reversion February-2018 QuantConnect – Pairs Trading with Python Page 10 Step 1: Generate the spread of two log price series 𝑆𝑝𝑟𝑒𝑎𝑑 𝑡 = log(𝑌𝑡) − (𝛼 + 𝛽log(𝑋𝑡)) Step 2: Set the range of spread series [lower, upper] If 𝑆𝑝𝑟𝑒𝑎𝑑 𝑡 > 𝑢𝑝𝑝𝑒𝑟 𝑡ℎ𝑟𝑒𝑠ℎ𝑜𝑙𝑑 Buy 𝑋𝑡, Sell 𝑌𝑡 If 𝑆𝑝𝑟𝑒𝑎𝑑 𝑡 < 𝑙𝑜𝑤𝑒𝑟 𝑡ℎ𝑟𝑒𝑠ℎ𝑜𝑙𝑑 Buy 𝑌𝑡, Sell 𝑋𝑡
  • 12. Exploratory Research ❖ Find two likely cointegrated stocks: e.g. XOM, CVX ❖ Estimate spreads between each stock. ❖ Check for stationarity. QuantBook Research February-2018 QuantConnect – Pairs Trading with Python Page 12
  • 13. Pairs Trading Weaknesses ❖ Double the fees. ❖ Capitalize on small price movements. ❖ Risk correlation will break down (e.g. CEO change, new technology) ❖ Execution risk (slippage). February-2018 QuantConnect – Pairs Trading with Python Page 13
  • 14. LEAN Implementation Backtest ❖ Create our Trading Signal. ❖ Run Backtest in QuantConnect. February-2018 QuantConnect – Pairs Trading with Python Page 14
  • 15. Summary ❖ We use cointegration to detect a long term relationship of two stocks. ❖ Changes in that relationship might signal a chance to profit by pairs trading. Next Steps – Defining Trading Rules, Setting Thresholds Total Trades Drawdown Net Profit Sharpe Ratio 270 12.9% 34% 0.555 February-2018 QuantConnect – Pairs Trading with Python Page 15
  • 18. Cointegration and Stationary • Cointegration is a statistical property of a time series(like the stock price series). • Cointegration specifies a co-movement relationship of price – the long term relationship. • The mean and the variance of the series do not vary over time Cointegration Stationary • If two series {𝑋𝑡} and {𝑌𝑡} are not stationary • But their linear combination 𝑌𝑡 = 𝛽𝑋𝑡 − 𝛼 is a stationary process {𝑿 𝒕} and {𝒀 𝒕} are cointegrated How to test if two series are cointegrated? Augmented Dickey-Fuller test February-2018 QuantConnect – Pairs Trading with Python Page 18
  • 19. Our Research Environment February-2018 QuantConnect – Pairs Trading With Python Page 19
  • 20. Coding the Idea, The Algorithm Lab February-2018 QuantConnect – Pairs Trading With Python Page 20
  • 21. Going Live, Deploying to Live Trading February-2018 QuantConnect – Pairs Trading with Python Page 21