MACD (Moving Average Convergence Divergence) is one of the methods used to analyze the past data of a market to predict future price movements. It's widely utilized for analyzing market trends and momentum. In this article, we will introduce the process of calculating the MACD Line, Signal Line, and Histogram using TA-Lib. We will also thoroughly examine how to use MACD for trend analysis, and the criteria for determining overbought/oversold conditions. You can find how to install TA-Lib in [TA-Lib] #2: Installing TA-Lib for Technical Analysis, and the basic concept of MACD in [TA-Lib] #5 MACD - Analyzing MACD Meaning and Its Role in Market Trends.
Calculating MACD Line, Signal Line, and Histogram Using TA-Lib
The calculation of MACD (Moving Average Convergence Divergence) can be effortlessly performed using the TA-Lib library.
Calculating MACD with Basic Settings
The default formula for MACD in TA-Lib involves the difference between the long-term (typically 26 days) exponential moving average (EMA) and the short-term (typically 12 days) EMA. The Signal Line is composed of the 9-day EMA of this MACD Line. The Histogram, being the difference between the MACD Line and Signal Line, is used to evaluate the market's momentum.
# Importing the library
from yahooquery import Ticker
import talib
import pandas as pd
# Fetching Google (GOOG) stock data
google = Ticker('GOOG')
df = google.history(period='2y') # 2-year data
# Calculating MACD with basic settings
macd_line, signal_line, histogram = talib.MACD(df['close'])
# Adding results to DataFrame
df['macd'] = macd_line
df['signal'] = signal_line
df['histogram'] = histogram
# Printing the results
print(df.tail())
macd signal histogram
date
2023-08-17 1.801564 2.071457 -0.269893
2023-08-18 1.525293 1.962224 -0.436931
2023-08-21 1.356871 1.841153 -0.484282
2023-08-22 1.270081 1.726939 -0.456858
2023-08-23 1.468408 1.675233 -0.206825
Calculating MACD with Custom Settings
If you wish to set the periods for the moving averages customly, you can adjust the fastperiod, slowperiod, signalperiod parameters in TA-Lib's MACD function.
# Calculating MACD with custom moving average periods
# For example, changing fast_period to 10, and slow_period to 22:
macd_line_custom, signal_line_custom, histogram_custom = talib.MACD(df['close'], fastperiod=10, slowperiod=22)
# Adding results to DataFrame
df['macdCustom'] = macd_line_custom
df['signalCustom'] = signal_line_custom
df['histogramCustom'] = histogram_custom
# Printing the results
print(df.tail())
macdCustom signalCustom histogramCustom
date
2023-08-17 1.472135 1.842813 -0.370678
2023-08-18 1.156198 1.705490 -0.549292
2023-08-21 0.979688 1.560330 -0.580642
2023-08-22 0.904435 1.429151 -0.524716
2023-08-23 1.167833 1.376887 -0.209054
Through the above code, you can perform MACD analysis by adjusting the periods of each moving average to suit various market conditions and strategies.
MACD Analysis Using TA-Lib
Trend Following
Identifying MACD Line and Signal Line Crossover Points
The crossover between the MACD Line and Signal Line serves as an important signal for recognizing market fluctuations. By capturing these crossovers, you can discern the possibility of a trend change and make investment decisions accordingly.
- Golden Cross: This occurs when the MACD Line crosses the Signal Line from below. This phenomenon often represents the commencement of an uptrend, and can be interpreted as an opportunity to buy.
- Dead Cross: This happens when the MACD Line crosses the Signal Line from above. This signal may indicate the beginning of a downtrend, and can be considered a point to sell.
import talib
macd, signal, _ = talib.MACD(df['close'])
df['macd'] = macd
df['signal'] = signal
df['upward'] = df['macd'] > df['signal']
df['downward'] = df['macd'] < df['signal']
df['goldenCross'] = (df['upward']) & (~df['upward'].shift(1).fillna(False))
df['deadCross'] = (df['downward']) & (~df['downward'].shift(1).fillna(False))
print('Golden Cross points:')
print(df[df['goldenCross']])
print('Dead Cross points:')
print(df[df['deadCross']])
Golden Cross points:
goldenCross deadCross
date
2021-10-11 True False
...
2023-07-26 True False
Dead Cross points:
goldenCross deadCross
date
2021-11-22 False True
...
2023-08-15 False True
Analyzing Trends Using the Size of the Histogram
Trend analysis using the size of the Histogram can be conducted in two significant ways:
- Strong Trend: If the size of the Histogram is progressively increasing, it signifies that the current trend (either upward or downward) is intensifying. This represents a strong force in the market and can enhance investment strategies in that direction.
- Trend Weakening: If the size is diminishing, the trend is weakening, indicating that it might be time to adjust positions. This implies a need to be wary of trend reversals and respond appropriately.
macd, signal, histogram = talib.MACD(df['close'])
df['macd'] = macd
df['signal'] = signal
df['histogram'] = histogram
# Initializing trend columns
df['strong_bull'] = False
df['strong_bear'] = False
df['weak_bull'] = False
df['weak_bear'] = False
consecutive_increase = 0
consecutive_decrease = 0
prev_hist_size = abs(df['histogram'][0])
for i in df.index:
curr_hist_size = abs(df['histogram'][i])
if curr_hist_size > prev_hist_size:
consecutive_increase += 1
consecutive_decrease = 0
elif curr_hist_size < prev_hist_size:
consecutive_decrease += 1
consecutive_increase = 0
if consecutive_increase >= 5:
trend_col = 'strong_bull' if df['histogram'][i] > 0 else 'strong_bear'
df.at[i, trend_col] = True
consecutive_increase = 0
if consecutive_decrease >= 5:
trend_col = 'weak_bull' if df['histogram'][i] > 0 else 'weak_bear'
df.at[i, trend_col] = True
consecutive_decrease = 0
prev_hist_size = curr_hist_size
print('Starting points of strong bullish trends:')
print(df[df['strong_bull']])
print('Starting points of strong bearish trends:')
print(df[df['strong_bear']])
print('Starting points of weakening bullish trends:')
print(df[df['strong_bear']])
print('Starting points of weakening bearish trends:')
print(df[df['weak_bear']])
Starting points of strong bullish trends:
strong_bull strong_bear weak_bull weak_bear
date
2021-10-19 True False False False
...
2023-05-16 True False False False
Starting points of strong bearish trends:
strong_bull strong_bear weak_bull weak_bear
date
2022-01-07 False True False False
...
2023-08-18 False True False False
Starting points of weakening bullish trends:
strong_bull strong_bear weak_bull weak_bear
date
2021-10-26 False False True False
...
2023-05-30 False False True False
Starting points of weakening bearish trends:
strong_bull strong_bear weak_bull weak_bear
date
2021-12-08 False False False True
...
2023-07-05 False False False True
This code analyzes the trends by tracking five or more consecutive increases or decreases in the size of the Histogram. By following this method, market trends can be more accurately discerned, enabling precise strategy adjustments.
Overbought/Oversold
MACD can be used to determine the overbought and oversold conditions of a market. By analyzing the divergence between the MACD Line and the Signal Line or calculating the crossing with the zero line, one can discern the market state.
Divergence Calculation Between MACD Line and Signal Line
The divergence between the MACD Line and Signal Line can be seen as the distance between the two lines, allowing us to analyze the market condition. A wide distance may indicate that the market is overheated (overbought), potentially signaling a selling opportunity. Conversely, if the distance is narrow, it could signify an oversold market condition, potentially providing a buying opportunity.
The criteria for divergence may vary depending on market conditions and the characteristics of the asset. In the code example below, if the current divergence is 80% or more of the maximum divergence in the past 30 days, it is considered that the two lines are too far apart and is deemed a selling timing. Conversely, if the current divergence is less than 120% of the minimum divergence in the past 30 days, it's considered that the two lines are too close, and is deemed a buying timing.
macd, signal, _ = talib.MACD(df['close'])
df['macd'] = macd
df['signal'] = signal
# Calculate the divergence between MACD Line and Signal Line.
df['divergence'] = df['macd'] - df['signal']
# Calculate the maximum and minimum divergence in the past 30 days.
df['max_divergence'] = df['divergence'].rolling(window=30).max()
df['min_divergence'] = df['divergence'].rolling(window=30).min()
# Sell timing determination: Current divergence is 80% or more of the maximum divergence.
df['sell_signal'] = df['divergence'] >= df['max_divergence'] * 0.8
# Buy timing determination: Current divergence is less than 120% of the minimum divergence.
df['buy_signal'] = df['divergence'] <= df['min_divergence'] * 1.2
print('Overbought')
print(df[df['sell_signal']])
print('Oversold')
print(df[df['buy_signal']])
Overbought
sell_signal buy_signal
date
2022-02-01 True False
...
2023-08-01 True False
Oversold
sell_signal buy_signal
date
2021-11-19 False True
80% and 120% are experimental values and can be adjusted according to individual market conditions and strategies.
Zero Line Crossing Calculation
When the MACD Line crosses the zero line upward or downward, it can be an important trading signal. An upward crossing may signal a buying opportunity, while a downward crossing may signal a selling opportunity.
# Calculate zero line crossing
df['cross_zero_line_up'] = (df['macd'] > 0) & (df['macd'].shift(1) <= 0)
df['cross_zero_line_down'] = (df['macd'] < 0) & (df['macd'].shift(1) >= 0)
print('Crossing Zero Line Upward')
print(df[df['cross_zero_line_up']])
print('Crossing Zero Line Downward')
print(df[df['cross_zero_line_down']])
Crossing Zero Line Upward
cross_zero_line_up cross_zero_line_down
date
2021-10-20 True False
...
2023-07-14 True False
Crossing Zero Line Downward
cross_zero_line_up cross_zero_line_down
date
2021-10-22 False True
...
2023-07-10 False True
MACD is an excellent tool for trend and momentum analysis, serving as an essential indicator in investment decisions. Through this article, you have learned how to effortlessly calculate and analyze MACD using TA-Lib. This enables you to conduct analysis tailored to various market situations and strategies, leading to more precise investment decisions.
FAQs
Can I adjust parameters other than fastperiod, slowperiod, and signalperiod in TA-Lib's MACD function?
- The MACD function in TA-Lib typically allows adjustment of these three key parameters. Additional settings are not generally used unless in special cases.
How should I choose the periods used in MACD analysis?
- The periods used in MACD analysis can vary depending on the strategy and market situation. Common default values are 12, 26, and 9 days, but the optimal values for specific markets or products can be found through experimentation.
How should I interpret a negative MACD Histogram?
- If the MACD Histogram is negative, it indicates that the MACD Line is lower than the Signal Line. This suggests a higher likelihood of a downtrend, and it may be interpreted as a selling signal. Careful analysis is required as interpretation may vary according to specific market conditions and strategies.
How can I perform MACD analysis using yahooquery?
- You can use yahooquery to retrieve stock or financial data for MACD analysis. For detailed information on how to aggregate data with yahooquery and analyze it using TA-Lib's MACD function, please refer to [Python] Yahooquery: Retrieving and Managing Past Stock and Financial Data.
What should I do if I want to analyze MACD without installing TA-Lib?
- It is possible to calculate MACD without TA-Lib, although the code may become more complex. You can implement it directly using libraries like Pandas in Python. However, it is recommended to install TA-Lib to enjoy its convenience and efficiency. Information on installation can be found in [TA-Lib] #2: Installing TA-Lib for Technical Analysis.