Conversely, the model generates a signal for a sell order when the stock price remains in the resistance tolerance margin after the same waiting period. The long-only model will purchase the stock at the opening of day one and hold the stock through the entire time. Instead, we will change the waiting period from two days to one day, three days, four days, and five days. In this Take2 iteration, the mean-reversion trading strategy with a waiting period of one day returned Unfortunately this is far simpler to code in an iterative manner as opposed to a vectorised approach and thus it is slow to calculate.
To iterate over a pandas DataFrame which admittedly is NOT a common operation it is necessary to use the iterrows method, which provides a generator over which to iterate:. Now we need to create a portfolio to keep track of the market value of the positions. The first task is to create a positions column that combines the long and short signals. Once the ETF market values have been created, we sum them to produce a total market value at the end of every bar. Subsequent lines of code clear up the bad entries NaN and inf elements and finally calculate the full equity curve. The intraday CSV files are located at the datadir path.
How To Build A Mean Reversion Trading Strategy
Make sure to modify the code below to point to your particular directory. In order to determine how sensitive the strategy is to the lookback period it is necessary to calculate a performance metric for a range of lookbacks. You can see in the following code that the previous functions are wrapped in a for loop across this range, with other thresholds held fixed. The final task is to use matplotlib to create a line chart of lookbacks vs returns:. The chart of lookback period vs returns can now be seen.
Note that there is a "global" maximum around a lookback equal to bars.
QuantConnect Community
If we had seen a situation where lookback was independent of returns this would have been cause for concern:. No backtesting article would be complete without an upwardly sloping equity curve! Thus if you wish to plot a curve of the cumulated returns vs time, you can use the following code. It will plot the final portfolio generated from the lookback parameter study.
Thus it will be necessary to choose the lookback depending upon which chart you wish to visualise. The chart also plots the returns of SPY in the same period to aid comparison:.

Note that the drawdown of SPY is significant in during the period of the financial crisis. The strategy also had a volatile period at this stage. Note that we still have to take into account the lookahead bias when calculating the z-score of the spread. Further, all of these calculations have been carried out without transaction costs. This strategy would certainly perform very poorly once these factors are taken into consideration.
In addition the strategy is trading in fractional units of ETFs, which is also very unrealistic. In later articles we will create a much more sophisticated event-driven backtester that will take these factors into consideration and give us significantly more confidence in our equity curve and performance metrics. Despite this, mean reversion is a powerful concept that traders can use to find an edge and built trading strategies around. A simple mean reversion strategy would be to buy a stock after an unusually large drop in price betting that the stock rebounds to a more normal level.
However, there are numerous other ways that investors and traders apply the theory of mean reversion.
Start With Why
Technical indicators like RSI can be used to find extreme oversold or overbought price levels. These can act as good levels to enter and exit mean reversion trades. Standard deviation, Bollinger Bands, Money Flow, distance from a moving average, can all be used to locate extreme or unusual price moves. If a company reports strong quarterly earnings way above its long term average, the next quarter it will probably report closer to its average.
There are many factors at play which can contribute to extreme results. Many of which suffer from natural mean reversion. For example, the weather. Similarly, if a stock has an unusually low PE ratio, an investor might buy the stock betting that the company is undervalued and the PE will revert to a more average level. Many investors trim their exposure to the stock market as a result.
Since the market is a reflection of the crowd, some investors will look at sentiment indicators like investor confidence to find turning points. Historically, investor surveys have shown investors become more pessimistic near market lows and more confident near market peaks. There are peaks in investor sentiment near market highs such as in January There are also troughs near market bottoms such as March and May Pairs trading is a fertile ground for mean reversion trades because you can bet on the spread between two similar products rather than attempting to profit from outright movement which can be riskier.
If two markets are correlated for example gold and silver or Apple and Microsoft and all of a sudden that correlation disappears, that can be an opportunity to bet on the correlation returning. Let it be said that there are many other ways that you could measure mean reversion so you are limited only in your imagination. Proponents of efficient market theories like Ken French believe that markets reflect all available information. It is therefore not possible to beat the market with mean reversion or any other strategy without some form of inside information or illegal advantage.
The stock has fallen to price in the latest information and there is no reason why the stock should bounce back just because it had a big fall. CAPE has a good record of market timing over the last years which is why it has become such a popular tool. But closer inspection reveals that most of the gains came in the first first 50 years.
In the most recent 50 years, the ratio has actually done worse than buy and hold. There is an argument that some mean reversion indicators like CAPE are based on insufficient sample sizes. A hundred or two hundred years may sound like long enough but if only a few signals are generated, the sample size may still be too small to make a solid judgement. One flaw with a mean reversion strategy is that in theory, the more a stock falls, the better the setup becomes. This can cause issues with risk management. Even though you are losing money, a mean reversion strategy will likely see the drop as another buy signal.
Mean reversion requires you to hold on to your loser or even increase your position in this scenario. From a risk management point of view it can make more sense to cut your losses at this point. But this goes against the concept of mean reversion. This results in a logical inconsistency.
- what percentage of forex traders make money;
- zone options binary option.
- forex karlstad.
- Mean Reversion & Statistical Arbitrage - QuantInsti?
- option plus services and trading corp contact number.
In reality, however, successful mean reversion traders know all about this issue and have developed simple rules to overcome it. For example, they will use time based exits, fixed stop losses or techniques to scale in to trades gradually. Despite some of the arguments against mean reversion trading strategies there are clearly many successful investors who have taken this approach and been successful. On a personal level, I have found mean reversion to be a powerful way to trade the markets and I have developed numerous mean reversion systems over the last few years.
Well, for 12 years, I have been missing the meat in the middle, but I have made a lot of money at tops and bottoms. Now we have talked about some background, I am going to detail more about my process for building mean reversion trading systems. I think we can break this process down into roughly 10 steps.
It all begins with getting ready the right tools for the job. An important part of building a trading strategy is to have a way to backtest your strategy on historical data. Backtesting does not guarantee that you will find a profitable strategy but it is the best tool we have for finding strategies that work. I use Amibroker which is quick and works very well for backtesting strategies on stocks and ETFs.
I also use other software depending on the task at hand. There are numerous other software programs available and each comes with its own advantages and disadvantages. You can also do plenty of analysis with Microsoft Excel. A key part of learning how to use backtesting software involves understanding any weaknesses within the program itself that might lead to backtesting errors. For example, how easy is it to program rules that look into the future?
How easy is to analyse your results and test for robustness? One of the deadliest mistakes a system developer can make is to program rules that rely on future data points. A classic example is using the closing price to calculate a buy entry but actually entering the stock on the open of the bar. In other words you trade before the signal. Generally, if your entry signal is based on the close of one bar, have the system execute its trade on the next bar along. The next step is to get hold of some good quality data with which to backtest your strategies.