Mean-Reverting Trading System-Quantitative Trading in Python

In a previous post, we demonstrated the mean-reverting and trending properties of SP500. In this follow-up post, we will develop a simple trading system exploiting the mean-reverting behaviour of this market index.

To generate buy and sell signals, we will use simple moving averages as noise filters. The simple moving average takes an average value of a stock over a certain period of time. It has been used for decades by technical traders and investors around the world.  There exist other types of moving averages such as exponential moving averages, but we will use the simple ones in this post.

Since we know that the SP500 is mean-reverting in a short term, we will use short-term moving averages. The trading rules are as follows,

If 3-day simple moving average < 20-day simple moving average, buy $10000 worth of stock

Exit if 3-day simple moving average >= 20-day simple moving average

We downloaded SPY data from Yahoo Finance and implemented the above trading rules in a Python program. The picture below shows the equity line of the strategy. We note that using the 3-  and 20-day simple moving averages the strategy is overall profitable.

Quantitative Trading in Python

Next, we proceed to test the robustness of this system. To do so, we vary the length of the second moving averages (20 days in the previous example).  The graph below shows the total PnL as a function of the length of the second moving average. We observe that the overall profit remains positive when we change the length of the moving average. This would indicate that the strategy performance is stable in this parameter regime.

Quantitative trading in python

In summary, we developed a simple trading strategy exploiting the mean-reverting behavior of SP500. In the next installment, we will design a trend-following system on this market index.

Further questions

What's your question? Ask it in the discussion forum

Have an answer to the questions below? Post it here or in the forum


Leave a Reply to Giovanni Santostasi Cancel reply