Mean Reversion Strategies In Python
₹13750/-₹54999/-
75% OFF
Get for ₹11000 with Course Bundle
- Live Trading
- Learning Track
- Prerequisites
- Syllabus
- About author
- Testimonials
- Faqs
Apply Mean Reversion Strategies
- Create four different types of mean reverting strategies
- Perform statistical test for identifying stationarity and co-integration
- Backtest pairs trading, triplets, index arbitrage and long-short strategy
- Explain the role of risk management
- Paper trade and live trade your strategies without any installations or downloads

Skills Required for Mean Reversion Trading
Mean Reversion Strategies
- Statistical Arbitrage
- Triplets Trading
- Index Arbitrage
- Long-short strategy
Math Concepts
- Correlation, Co-integration
- Stationarity
- Linear Regression
- ADF and Johansen Test
- Half Life
Python
- Adfuller,
- Statstools,
- Johansen,
- NumPy, Pandas,
- Matplotlib

learning track 8
This course is a part of the Learning Track: Advanced Algorithmic Trading Strategies
Course Fees
Full Learning Track
These courses are specially curated to help you with end-to-end learning of the subject.
Course Features
- Community
Faculty Support on Community
- Interactive Coding Exercises
Interactive Coding Practice
- Trade & Learn Together
Trade and Learn Together
- Get Certified
Get Certified
Prerequisites
It is expected that you have some trading experience and understand basic financial markets terminology like sell, buy, margin, entry, exit positions. Some familiarity with t-statistics and autoregressive model is useful but not mandatory. If you want to be able to code strategies in Python, then experience to store, visualise and manage data using Pandas DataFrame is required. These skills are covered in our course 'Python for Trading'.
Mean Reversion Trading Course
- Introduction to the CourseThis section gives an overview of the mean reversion strategy through examples. You will go through the course structure and understand how the course is structured in videos, quizzes, strategy codes and interactive coding exercises. This will make sure that not only do you understand the mechanics of mean reversion but also implement trading strategies in live markets.Introduction by Dr. Ernest Chan2m 19sIntroduction to Mean Reversion Strategy3m 48sCourse Structure Flow Diagram10mQuantra Features and Guidance3m 48sTypes of Statistical Arbitrage Strategies5m 7sFrequently Asked Questions10m
Stationarity of Time Series
Stationary is one of the essential concepts upon which pairs trading and other cointegrated trading is built. This section discusses the concept of stationary through real price data and how it is different from the random walk.What is Stationarity?2m 15sMean Reversion Trading Approach2mTemporary Mean Reversion2mStationarity2mStatistical Test for Stationarity2m- Why Use the ADF TestIn this section, you will understand why you should use the ADF (Augmented Dickey-Fuller) Test and understand the significance of the lambda parameter in the context of the test. Additionally, you will also develop the intuition behind the calculation of lambda within a price series, providing insights into its role in identifying stationarity.Why Use the ADF Test?2mIssue With Visual Approach5mAugmented Dickey-Fuller Test5mAdvantage of Using ADF Test5mTerms of ADF Test Equation2mRole of Lambda In ADF Test2mNull Hypothesis in ADF Test5mInterpretation of Negative Value in Lambda5mInterpretation of Non-Negative Value of Lambda5mAlternative Hypothesis in ADF Test5mUse of Lambda in ADF Test5mPre Reading Materials10mCalculation of Lambda in Price Series2mImplication of Mean Reversion5mRole of Covariance5mShort Form of ADF Test Equation5m
Intuition of ADF Test Equation
In this section, you will explore the intuition behind the ADF test equation, focusing on the role of lambda and standard error in determining stationarity, and learn how to interpret the results using critical values.Intuition of ADF Test Equation2mFirst Step in Stationary Series Determination5mComparison to Critical Values Table5mInterpretation of Critical Values Table5mObservation of Value Less Than Critical Values Table5m- Augmented Dickey-Fuller TestThis section starts with the revision of the mathematics behind the Augmented Dickey-Fuller (ADF) test, which is used to check whether the price series is stationary or not. You will also learn to check the stationarity of currency pairs in Python.Math Behind ADF Test (Optional)5mCritical Value and Test Statistics2mHow to Use Jupyter Notebook?2m 5sADF Test on CADUSD Pair10mCalculate Test Statistics5mImport Library and Read CSV5mLimitations of the ADF Test2mLow Power in Small Samples5mLag Length Sensitivity5mStructural Breaks in Time Series5mNon-Linear Trends and the ADF Test5mDetecting Near-Unit Root Processes5mModel Dependency5mFAQs on ADF Test2mAdditional Reading10m
Mean Reversion Strategy
In this section, you will learn to create and backtest a trading strategy based on the concept of mean reversion. You will learn to use the Bollinger Bands to create a mean reversion strategy on a currency pair.Mean Reversion Strategy1m 47sUpper Band2mTrading Based on Mean Reversion2mMean Reversion Strategy on AUDCAD10mCalculate Moving Average and Standard Deviation5mUpper and Lower Band5mLong Entry and Exit5mShort Entry and Exit3mLong and Short Positions5mForward Fill Missing Positions5mConsolidate the Positions5mCompute PnL5mRecap1m 47sFrequently Asked Questions10mTest on Stationarity, ADF and Mean Reversion16m- Live Trading on BlueshiftThis section will walk you through the steps involved in taking your trading strategy live. You will learn about backtesting and live trading platform, Blueshift. You will learn about code structure, various functions used to create a strategy and finally, paper or live trade on Blueshift.Uninterrupted Learning Journey with Quantra2mSection Overview2m 19sLive Trading Overview2m 41sVectorised vs Event Driven2mProcess in Live Trading2mReal-Time Data Source2mBlueshift Code Structure2m 57sImportant API Methods10mSchedule Strategy Logic2mFetch Historical Data2mPlace Orders2mBacktest and Live Trade on Blueshift4m 5sAdditional Reading10mBlueshift Data FAQs10m
- Live Trading TemplateIn this section, a live trading strategy template will be provided to you. The template strategy will be on the mean reversion strategy covered in the previous section. You can tweak the code by changing different currency pairs, date range to backtest and finally analyse the strategy performance in more detail.Paper/Live Trading FX Mean Reversion Strategy10mFAQs for Live Trading on Blueshift10m
Cointegration
If a linear combination of two or more price series is stationary, then the individual price series are said to be cointegrated with each other. This section introduces cointegration between two-time series and covers a test for detecting cointegration of a portfolio of instruments called the cointegrated augmented Dickey-Fuller (CADF) test.What is Cointegration?2m 58sCointegration2mCorrelation2mWhat is Hedge Ratio?5m 48sPortfolio Formation Using Hedge Ratio2mHedge Ratio Code2m 26sImport Library5mCalculate Hedge Ratio5mWhat is CADF Test?4m 2sCheck Cointegration using CADF Test5mOrder Dependence of CADF10m- Pairs TradingMost financial instruments are not stationary, and creating a mean reversion strategy is not possible on such a price series. To overcome this issue, you need two price series which are cointegrated with each other. In this section, you will learn to create a pairs trading strategy using the Bollinger Bands. You will also learn to backtest the same in Python.Mean Reversion Strategy on Pairs2m 49sMean Reversion Strategy on GLD-GDX10mTake Long Entry and Exit5mCompute Strategy PnL5mPaper/Live Trading Pair Trading Strategy10mAdditional Reading10mRecap2m 14sMean Reversion Strategy15m 35s
- TripletsThis section discusses failure of the mean reversion strategy of the GLD-GDX pair. Based on the possible reason we will arrive at the conclusion of choosing a triplet to improve the mean reversion strategy. The working of Johansen test will be explained to arrive at the hedge ratios for the new mean reversion strategy for triplets. This section also covers the concept of half-life of mean reversion along with Ornstein-Uhlenbeck formula for computing the half-life of mean reversion.Cointegration Breakdown in the GLD-GDX Pair5m 5sReason of Breakdown of Cointegration2mSignificance of Cointegration2mSurviving Breakdown of Cointegration5m 17sHow to Survive Breakdown of Cointegration?2mBreakdown Remedies2mOptimization Problems2mEigenvalues and Eigenvectors2mWhat is Johansen Test?6m 27sCADF Shortcomings2mLinear Combination2mGLD-GDX Cointegration Test4mMean Reversion on Triplets3m 49sMean Reversion on Triplets Code10mGLD-GDX-USO Cointegration Test4mCointegration Test2mTaking Positions2mRecap1m 11sFrequently Asked Questions10m
- Half LifeThis section explains how long would it it take for the time series to revert back to the mean. And the importance of half-life to select the right instruments to trade in.Half Life of Mean Reverting Time Series4m 12sHalf Life2mHalf Life Formula2mHalf-Life Using Johansen Test10mCompute Half-Life of GLD-GDX5mFrequently Asked Questions10m
- Risk ManagementThis section explains the importance and two common usages of stop loss in mean reverting strategies. Further, you will learn to backtest mean-reverting strategy with and without stop and compare the performance of the strategy.Stop-Loss5mMean Reversion Strategy With Stop Loss10m
- Best Markets to Pair TradeThis section explains the pros and cons of mean reversion strategies in different markets such as exchange traded funds (ETFs), stocks, currencies, and futures. Further, in the section, will understand how economically related pairs do not co-integrate, cover the basic concept of crack spread and test for stationarity of crack spread.Best Markets To Pair Trade5m 18sMean Reversion of ETF Pairs2mMean Reversion of Stock Pairs2mMean Reversion of Currencies and Futures2mCointegration Test of CL and BZ10mCointegration Test of Crack Spread10mIdentify Cointegrated Stock Pairs10m
- Index ArbitrageThis section explains Index Arbitrage Strategy which is an extension of pairs and triplets, how to construct a basket of instruments and see the difficulties of trading an Index Arbitrage strategy.Index Arbitrage Strategy3m 49sWorking of Index Arbitrage Strategy2mCustom Basket2mIndex Arbitrage Strategy Code10mDifficulties in Index Arbitrage2m
Long Short Portfolio
This section explains the concept of long-short portfolio strategy, how it is different from other mean reversion strategies. Further, will construct a long-short portfolio of stocks in the S&P 500, understand the importance of universe selection of stocks on strategy and learn to refine a strategy.Long-Short portfolio Strategy3m 39sLong-Short Portfolio2mStrategy Formula2mLong-Short Portfolio Strategy Code10mCalculate Stock Returns5mCalculate Market Returns5mCalculate Dollar Allocation for Each Stock5mCalculate Sharpe Ratio5mPaper/Live Trading Long-Short Strategy10mAnalysis of Strategy Performance5mTest on Trading Based on Mean Reversion18m- Run Codes Locally on Your MachineLearn to install the Python environment in your local machine.Python Installation Overview2m 18sFlow Diagram10mInstall Anaconda on Windows10mInstall Anaconda on Mac10mKnow your Current Environment2mTroubleshooting Anaconda Installation Problems10mCreating a Python Environment10mChanging Environments2mQuantra Environment2mTroubleshooting Tips For Setting Up Environment10mHow to Run Files in Downloadable Section?10mTroubleshooting For Running Files in Downloadable Section10m
- Automated Trading Using IBridgePyA live trading strategy template will be provided to you. You can tweak the template to deploy your strategies on Interactive Brokers using IBridgePy API.Additional Reading10mSample Strategy to Run on Interactive Brokers2m
- SummaryCourse Summary3m 52sPython Codes and Data2m
Registered Successfully!
You will receive webinar joining details on your registered email
Would you like to start learning immediately?
about author


Why quantra®?
- More in Less Time
Gain more in less time
- Expert Faculty
Get taught by practitioners
- Self-paced
Learn at your own pace
- Data & Strategy Models
Get data & strategy models to practice on your own
Faqs
- When will I have access to the course content, including videos and strategies?
You will gain access to the entire course content including videos and strategies, as soon as you complete the payment and successfully enroll in the course.
- Will I get a certificate at the completion of the course?
Yes, you will be awarded with a certification from QuantInsti after successfully completing the online learning units.
- Are there any webinars, live or classroom sessions available in the course?
No, there are no live or classroom sessions in the course. You can ask your queries on community and get responses from fellow learners and faculty members.
- Is there any support available after I purchase the course?
Yes, you can ask your queries related to the course on the community: https://quantra.quantinsti.com/community
- What are the system requirements to do this course?
Fast-speed internet connection and a browser application are required for this course. For best experience, use Chrome.
- What is the admission criteria?
There is no admission criterion. You are recommended to go through the prerequisites section and be aware of skill sets gained and required to learn most from the course.
- Is there a refund available?
We respect your time, and hence, we offer concise but effective short-term courses created under professional guidance. We try to offer the most value within the shortest time. There are a few courses on Quantra which are free of cost. Please check the price of the course before enrolling in it. Once a purchase is made, we offer complete course content. For paid courses, we follow a 'no refund' policy.
- Is the course downloadable?
Some of the course material is downloadable such as Python notebooks with strategy codes. We also guide you how to use these codes on your own system to practice further.
- Can the python strategies provided in the course be immediately used for trading?
We focus on teaching these quantitative and machine learning techniques and how learners can use them for developing their own strategies. You may or may not be able to directly use them in your own system. Please do note that we are not advising or offering any trading/investment services. The strategies are used for learning & understanding purposes and we don't take any responsibility for the performance or any profit or losses that using these techniques results in.
- I want to develop my own algorithmic trading strategy. Can I use a Quantra course notebook for the same?
Quantra environment is a zero-installation solution to get beginners to start off with coding in Python. While learning you won't have to download or install anything! However, if you wish to later implement the learning on your system, you can definitely do that. All the notebooks in the Quantra portal are available for download at the end of each course and they can be run in the local system just the same as they run in the portal. The user can modify/tweak/rework all such code files as per his need. We encourage you to implement different concepts learnt from different learning tracks into your trading strategy to make it more suited to the real-world scenario.
- If I plug in the Quantra code to my trading system, am I sure to make money?
No. We provide you guidance on how to create strategy using different techniques and indicators, but no strategy is plug and play. A lot of effort is required to backtest any strategy, after which we fine-tune the strategy parameters and see the performance on paper trading before we finally implement the live execution of trades.
- Do you need to have knowledge of coding in order to learn through Quantra courses?
You can learn with or without coding knowledge. If you would like to do the analysis on excel, we would suggest you to start with course on Statistical Arbitrage in Trading. You can create and test your trading strategies using excel.
Alternatively, you can do the course on Python for Trading which will help you gain knowledge in all these fields: Python, Analysis and Financial markets. - What does "lifetime access" mean?
Lifetime access means that once you enroll in the course, you will have unlimited access to all course materials, including videos, resources, readings, and other learning materials for as long as the course remains available online. There are no time limits or expiration dates on your access, allowing you to learn at your own pace and revisit the content whenever you need it, even after you've completed the course. It's important to note that "lifetime" refers to the lifetime of the course itself—if the platform or course is discontinued for any reason, we will inform you in advance. This will allow you enough time to download or access any course materials you need for future use.
- What is the Mean Reversion Strategy?
Definition
Mean reversion strategy is a popular trading approach to exploit the tendency of securities such as stocks, commodities to revert to their mean price over time. It is based on the assumption that if the price of an asset deviates significantly from its average, it is likely to eventually move back towards the mean. Mean reversion trading seeks to identify these deviations and profit from them.
Basic Strategies
One common mean reversion strategy uses Bollinger Bands, which consist of an upper band, a lower band, and a middle band representing the moving average. When the price of an asset moves above the upper band or below the lower band, it is considered overbought or oversold, respectively, signaling a potential reversion towards the middle band.
Formula
A basic formula used in mean reversion strategies is the z-score. The z-score measures the deviation of an asset's price from its mean in terms of standard deviations. The formula for calculating the z-score is:
z = (X - μ) / σ
Where
- z is the z-score,
- X is the current price of the asset,
- μ is the mean or average price, and
- σ is the standard deviation of prices.
Examples
Steps to trade a mean-reversion strategy on Amazon stock:- Calculate the mean and standard deviation of the Amazon stock's historical prices.
- Determine the current price of the stock.
- Calculate the z-score using the formula: z = (X - μ) / σ.
- If the z-score exceeds a certain threshold, such as +1 or -1, it indicates a potential mean reversion opportunity.
- If the z-score is positive and above the threshold, consider selling the stock. If it is negative and below the threshold, consider buying the stock.
- Monitor the stock's price and adjust your positions accordingly as the price reverts to the mean.
- Add stop loss if the stock price doesn't revert to mean
- What are the types of arbitrage?
Depending on the underlying factor you use to analyse the stock markets, you can find a number of arbitrage types. Some of them are:
Risk arbitrage: If two companies are in the midst of a merger, traders will go long on the acquired company and short the buying company's stocks.
Statistical arbitrage: It is based on the statistical mispricing of one or more assets compared to the expected future value of these assets. - What is statistical arbitrage trading?
Statistical Arbitrage (or Stat Arb) is based on the statistical mispricing of one or more assets compared to the expected future value of these assets. Statistical arbitrage is a computational and quantitative approach to trading.
Stat Arb Strategies depend on the below-mentioned factors:
Number and type of instruments in the portfolio
Instrument matching criteria
Instrument ranking technique
Percentage of instruments to short and go long
Rebalancing frequency
Risk-taking capacity - How does a long-short strategy work?
The long-short strategy is a type of mean reversion strategy where we buy the underperformers and sell the overperformers. The logic here is that at some point, the two stocks will return to their mean and thus you can earn a profit from both sides of the transaction.
- What is triple arbitrage?
Triple arbitrage can mean triangular arbitrage, which is basically taking advantage of the pricing inefficiencies between three currencies to book a profit.
A simple explanation would be the following:
If we take three currencies: the dollar, yuan, yen. Let`s say we buy 694 yuan for 100 dollars. Now we see that 1 yuan is 17 yen. Thus, we buy 11798 yen with 694 yuan. Further, we see that 1 yen is 0.0092 dollar. Thus 11798 yen gives us 108.54.
Of course, this is a rare case as the forex market is highly liquid and this inefficiency will be covered in a short span of time.