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?

Similar Reads

What is Trend Analysis?

Trend analysis is a type of technical analysis that attempts to forecast the future direction of the market based on historical price movements and trading volume. The fundamental tenet of trend analysis is that prices move in continuous upward or downward trends, or trends. Traders can predict the mood of the market and possible price movements by examining the patterns....

Steps in Trend Analysis

Identify the time frame: To begin trend analysis, choose a timeframe that suits your investment goals. Common timeframes include daily, weekly, or monthly charts. Chart Reading: Learn to read charts, which are graphical representations of an asset’s historical price movements. The most common types are line charts, bar charts, and candlestick charts. Recognizing Trends: Look for patterns indicating upward (bullish), downward (bearish), or sideways trends. Bullish trends show upward movements, bearish trends show downward movements and sideways trends show a lack of clear direction. Support and Resistance Levels: Identify support and resistance levels. Support is where the price tends to stop falling, and resistance is where it stops rising. These levels help in predicting potential trend reversals....

What is Trend Trading?

Trend trading, often referred to as trend following, is a trading method in which one tracks the direction of market trends and tries to ride them as long as possible. The goal of trend traders is to profit from the majority of price moves that occur inside a trend, disregarding smaller oscillations. The foundation of trend trading is the belief that market trends often endure over time and have a higher probability of continuing than reversing....

Trend Trading Strategies

Following the Trend: Adopt the mantra “The trend is your friend.” Trend followers aim to ride the momentum of an existing trend until signs of a reversal appear. Moving Averages: Utilize moving averages, which smooth out price data to create a single flowing line. The intersection of short-term and long-term moving averages can signal trend changes. Relative Strength Index (RSI): RSI is a momentum indicator that measures the speed and change of price movements. It helps identify overbought or oversold conditions, indicating potential reversals. Trendlines: Draw trendlines connecting the highs or lows of price movements. Breakouts or breakdowns from these trendlines can signal a change in trend direction....

How to Trade the Trend – Trend Trading Strategies

Trend trading is a popular strategy among traders, aiming to capitalize on teh direction of the market trend . Here are some example of trend trading strategies, each utilizing different indicators and techniques:...

Example 1: Using a synthetic dataset with moving averages

In this example, we will use a synthetic dataset of daily prices of a hypothetical stock. We will generate the dataset using the numpy and pandas libraries. We will also use the matplotlib library to plot the data and the results. The code is as follows:...

Example 2: Trend Following Strategy Using Moving Averages

...

Example 3: Trend Reversal Strategy Using Bollinger Bands

...

Trend Trading Strategy – Pros and Cons

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....

Final Word – Why Trend Trading is a Highly Effective Technique to Trade Financial Markets?

...

FAQs on Trend Analysis and Trend Trading Analysis

Another well-liked and adaptable tool for trend research is the Bollinger Band. A simple moving average (SMA) and two standard deviations above and below the SMA make up the three lines that make them up. The standard deviations show the price range and volatility, while the SMA shows the direction of the trend. Because Bollinger Bands tend to shrink when the price moves within a limited range and to expand when the price breaks out of the range, they may be used to spot trend reversals. I’ll use the daily closing Bitcoin (BTC-USD) values from January 1, 2020, to December 31, 2020, for this example. For the Bollinger Bands, I’ll use a 20-day SMA and a 2-standard deviation; for the momentum indicator, I’ll use a 14-day stochastic oscillator. The strategy is as follows:...