Understanding Moving Averages and Their Signal System
Written on
The code to recreate this chart will be provided at the end; this article primarily focuses on the theoretical aspects rather than the coding.
Understanding Moving Averages: More Complex Than They Seem
While many consider the moving average (MA) straightforward, the simple moving average (SMA) often lags behind, making it too simplistic and slow to accurately reflect price movements.
Investopedia explains:
> “Moving averages are calculated to identify the trend direction of a stock or to determine its support and resistance levels. It is a trend-following or lagging indicator because it is based on past prices.”
This leads to the understanding that:
> The longer the period for the moving average, the greater the lag. For instance, a 200-day moving average will exhibit a significantly higher lag than a 20-day MA since it accounts for prices over the last 200 days. The 50-day and 200-day moving averages are commonly monitored by investors and traders as key trading signals.
Let’s avoid diving into how to make the Moving Average more responsive, such as through the Exponential Moving Average (EMA) or MACD for observing convergence/divergence between two Moving Averages. Instead, I want to concentrate on the basic form of MA and the common mistakes associated with its usage.
First, let’s revisit the definition, as it’s essential to refresh our understanding.
Moving Average: The Calculation
A simple moving average (SMA) is determined by calculating the arithmetic mean of a specified set of values over a designated time period. To find the average stock prices, the values are summed and then divided by the total number of prices in that set. The formula for calculating the simple moving average of a security is:
With a fixed time period n,
A1 + A2 + A3 + … + An
When the moving average increases, it signifies an upward trend, while a decline indicates a downward trend as the average price over the past n days falls.
Golden Crossovers
When a short-term moving average, such as a 10-day MA, crosses above a longer-term moving average, like a 50-day MA, it signifies a bullish momentum, suggesting that prices are likely to rise. Conversely, if the short-term crosses below the longer-term moving average, it indicates a bearish trend. This phenomenon is known as a golden crossover.
Now, let’s pose a question.
Assuming we are working with a 10-day moving average, where A0, A1, A2 represent the stock average prices over the past 10 days:
- Today marks day 10 with the stock average value A10.
- Yesterday’s moving average is calculated as:
(A0 + A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8 + A9) ÷ 10
- Today’s moving average is:
(A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8 + A9 + A10) ÷ 10
- Since A0 is outside the moving average window of 10, it is no longer relevant.
- The new value A10 is included in today’s moving average calculation.
In the accompanying Tesla stock chart, a closer view highlights the imminent crossover between the 10-day MA (red line) and the 25-day MA (yellow line).
Question: What is the minimum closing price for TSLA today that would result in a bullish golden crossover for the 10-day moving average to surpass the 25-day moving average?
Let’s take a moment to consider this.
What we need to determine is:
Today MA = (A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8 + A9 + A10) ÷ 10 > Yesterday MA = (A0 + A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8 + A9) ÷ 10
This simplifies to:
A10 > A0.
The difference between A0 and A10 represents the closing price from Day 0 compared to the closing price today on Day 10.
In simpler terms:
"If today’s closing price exceeds the closing price from 10 days ago using the MA-10 indicator, the MA10 will show an increase in value." This logic holds true for 25, 100 days, and beyond.
To clarify this further, I plotted a circle for each of the last 10 days' prices for the MA10 indicator, the last 25 days' prices for MA25, and the last 50 days' prices for MA50:
- MA10 Closing Price on Day 0 = 179.83
- MA25 Closing Price on Day 0 = 176.54
- MA50 Closing Price on Day 0 = 191.59
- Current Price = 171.76
To enhance readability, I shifted these dots to the far right, allowing us to visualize the price levels of MA10, MA25, and MA50 days, indicating: "If today’s closing price is above this level, the MA will trend upward; otherwise, it will remain flat or decline."
The Ideal Traffic Light System
If the closing price exceeds the red dot of the 10-day MA, the MA10 will trend upward. If it surpasses the yellow dot of the 25-day MA, the MA25 will rise as well. Finally, if the price exceeds the green dot of the 50-day MA, the MA50 will increase.
- Bullish: Price > Short-term MA > Mid-term MA > Long-term MA
- Bearish: Price < Short-term MA < Mid-term MA < Long-term MA
I encourage you to explore the price behavior when it falls between these indicators, especially when the sequence transitions from bullish to bearish or vice versa.
Examples:
- Bullish: On April 24, 2024, Google’s price of $161 is above the short-term 10-day MA (A0 of MA10). The indicators will likely indicate an upward trend unless it falls below $160.79.
- Bearish: Apple’s price of $193.05 drops below the 10-day MA. If it closes below $191.45, both the MA10 and MA25 will decline, testing the crossover. The bearish crossover will not occur unless the closing price later rises above MA10’s A0.
Final Thoughts
Utilizing the above indicators enables us to analyze the sequence of traffic lights and how prices react upon reaching specific levels—not solely based on the Moving Average value, but also from the relationships between the underlying components, such as A10 vs. A0 (or A100 vs. A0 for longer durations).
Indeed, while moving averages are lagging indicators, many trading systems depend on moving average crossovers to execute trades. By understanding whether indicators are poised to cross based on key price support/resistance levels (at A0), we can leverage the moving average traffic light system to strategically plan our entries and exits using A10/A50/A250 against their corresponding A0 values.
Different patterns emerge when utilizing various moving average combinations for value versus growth stocks.
Commonly used moving averages across different assets include: - 5, 8, 13 - 10, 20, 50
I personally favor using 3, 5, 7, 10 for short-term changes, combined with 30, 50, 70, and 100 for long-term trends on the same chart. In the future, we can delve deeper into how to effectively use Moving Averages and this Traffic Light system to inform our decision-making processes.
Thank you for reading! Have a fantastic weekend and happy coding and trading!
Feel free to check out my other articles; I hope they inspire you to think differently.
Everyone can visualize stock trends with these Python codes!
Let’s make stock selection more efficient!
medium.com
If you enjoy this type of coding content, please leave some feedback so I know to continue sharing fresh ideas weekly! I also publish articles on leadership and other technical topics if you’re interested.
I appreciate your support! Please subscribe to my email for insights on various topics from time to time.
Here’s the code to generate and test different ideas.
#!/usr/bin/env python3 # -- coding: utf-8 -- """ Created on Fri Apr 26 2024
@author: michaelwai """
import yfinance as yf import matplotlib.pyplot as plt import mplfinance as mpf
movingaverages = [10, 25, 50] mav_colors = ['red', 'orange', 'green', 'skyblue', 'blue'] symbol = 'GOOG' # Example: Nvidia Inc.
def plot_candlestick_with_moving_average(symbol):
# Fetch historical data
data = yf.download(symbol, period="1y")
# Customize the candlestick plot
customstyle = mpf.make_mpf_style(base_mpf_style='yahoo',
y_on_right=False,
facecolor='white')
# Plot candlestick chart with moving averages and volume
fig, ax = mpf.plot(data, type='candle', title='chart for ' + symbol,
volume=True, show_nontrading=True,
mav=movingaverages, mavcolors=mav_colors,
style=customstyle,
returnfig=True,
figsize=(10, 8))
# Mark traffic light position
for i, ma in enumerate(movingaverages):
last_price_on_ma = data['Close'].iloc[-ma]
ma_date = data.index[-ma]
last_date = data.index[-1]
# Plot the indicator on the far right of the chart for easier visualization
ax[0].scatter(last_date, last_price_on_ma, color=mav_colors[i])
ax[0].text(last_date, last_price_on_ma, f'MA{ma}: {last_price_on_ma:.2f}', size=8)
# Plot settings
plt.suptitle(f'Chart of {symbol} - US$' + str(f"{data['Close'].iloc[-1]:.2f}") + ' on ' + str(data.index[-1]))
plt.xlabel('Date')
ax[0].set_ylabel('Price')
plt.show()
plot_candlestick_with_moving_average(symbol)