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.
The calculation of MACD (Moving Average Convergence Divergence) can be effortlessly performed using the TA-Lib library.
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
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.
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.
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
Trend analysis using the size of the Histogram can be conducted in two significant ways:
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.
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.
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.
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.
CloneCoding
Innovation Starts with a Single Line of Code!