Example 2: Trend Following Strategy Using Moving Averages
One of the most often used and straightforward techniques for trend analysis is the moving average. By displaying the average price over a given duration, they mitigate the impact of price changes. A moving average can serve as a dynamic level of support or resistance that shows the trend’s strength and direction. Using two moving averages of differing lengths and trading on their crossings is a popular trend-following method. When a shorter-term moving average crosses above a longer-term moving average, signifying an uptrend, for instance, a positive signal is produced. A shorter-term moving average crossing below a longer-term moving average, signifying a decline, generates a negative signal.
I’ll use the Apple stock (AAPL) daily closing prices from January 1, 2020, to December 31, 2020, for this example. As trend indicators, I’ll employ a 50-day and a 200-day simple moving average (SMA). Additionally, to prevent overbought and oversold situations, I’ll employ a 14-day relative strength index (RSI) as a filter. On a scale ranging from 0 to 100, the relative strength index, or RSI, gauges the velocity and deviation of price fluctuations. In general, overbought situations are indicated by an RSI above 70, while oversold conditions are indicated by an RSI below 30. The following is the strategy:
- Purchase when the RSI is below 70 and the 50-day SMA crosses over the 200-day SMA.
- Sell when the RSI is over 70 or the 50-day SMA crosses below the 200-day SMA.
- Otherwise, have cash on hand.
The code for this approach is as follows:
Python3
# Import libraries import pandas as pd import yfinance as yf import matplotlib.pyplot as plt # Download data data = yf.download( "AAPL" , start = "2020-01-01" , end = "2020-12-31" ) # Calculate moving averages data[ "SMA_50" ] = data[ "Close" ].rolling( 50 ).mean() data[ "SMA_200" ] = data[ "Close" ].rolling( 200 ).mean() # Calculate RSI delta = data[ "Close" ].diff() gain = delta.clip(lower = 0 ) loss = delta.clip(upper = 0 ). abs () avg_gain = gain.ewm(com = 13 , adjust = False ).mean() avg_loss = loss.ewm(com = 13 , adjust = False ).mean() rs = avg_gain / avg_loss data[ "RSI" ] = 100 - ( 100 / ( 1 + rs)) # Define signals data[ "signal" ] = 0 data.loc[(data[ "SMA_50" ] > data[ "SMA_200" ]) & (data[ "RSI" ] < 70 ), "signal" ] = 1 data.loc[(data[ "SMA_50" ] < data[ "SMA_200" ]) | (data[ "RSI" ] > 70 ), "signal" ] = - 1 # Calculate returns data[ "return" ] = data[ "Close" ].pct_change() data[ "strategy_return" ] = data[ "return" ] * data[ "signal" ].shift( 1 ) # Plot results plt.figure(figsize = ( 12 , 8 )) plt.subplot( 211 ) plt.plot(data[ "Close" ], label = "Price" ) plt.plot(data[ "SMA_50" ], label = "SMA_50" ) plt.plot(data[ "SMA_200" ], label = "SMA_200" ) plt.scatter(data.index, data[ "Close" ], c = data[ "signal" ], cmap = "coolwarm" , marker = "o" , alpha = 0.5 , label = "Signal" ) plt.title( "AAPL Trend Following Strategy Using Moving Averages" ) plt.xlabel( "Date" ) plt.ylabel( "Price" ) plt.legend() plt.subplot( 212 ) plt.plot(( 1 + data[ "strategy_return" ]).cumprod(), label = "Strategy" ) plt.plot(( 1 + data[ "return" ]).cumprod(), label = "Buy and Hold" ) plt.title( "Cumulative Returns" ) plt.xlabel( "Date" ) plt.ylabel( "Return" ) plt.legend() plt.tight_layout() plt.show() |
Output:
As you can see, the strategy generates buy and sell signals based on the moving average crossovers and the RSI filter. The strategy outperforms the buy-and-hold strategy in terms of cumulative returns, especially during the downtrend in March and April 2020. However, the strategy also suffers from some whipsaws and false signals, such as in June and September 2020, when the price oscillates around the moving averages. This is a common drawback of trend-following strategies, as they tend to lag behind the price movements and are prone to noise and volatility.
Understanding Trend Analysis and Trend Trading Strategies
Consider being able to forecast future changes in the financial markets, such as the stock market. Here’s where trend trading tactics and trend analysis are useful. We will explain trend analysis fundamentals in this post and provide newbies with a thorough overview of comprehending and using trend trading techniques. Trend analysis and trend trading are two popular techniques that traders use to identify and profit from the market’s direction.
In this article, we will explain these techniques, how they work, and how you can apply them to your trading.
Table of Content
- What is Trend Analysis?
- Steps in Trend Analysis
- What is Trend Trading?
- Trend Trading Strategies
- How to Trade the Trend – Trend Trading Strategies
- Example 1: Using a synthetic dataset
- Example 2: Trend Following Strategy Using Moving Averages
- Example 3: Trend Reversal Strategy Using Bollinger Bands
- Trend Trading Strategy – Pros and Cons
- Final Word – Why Trend Trading is a Highly Effective Technique to Trade Financial Markets?