Python quantitative stock trading (3) --- trend indicator MACD

Humbly condescend to oneself, the foundation of being blessed. The person who is full of air must not be a remote weapon, and it is useless to have a vertical hair.

What is MACD

The full name of MACD is Moving Average Convergence and Divergence, which is the smoothing moving average of convergence and divergence often referred to in the stock market. It was first proposed by Geral Appel in 1979. It belongs to a trend indicator, consisting of a fast line DIF, a slow line DEA, and a red and green histogram.

Among them, DIF and DEA are two lines that cross the X axis as the central axis, and the histogram is obtained by subtracting DEA from DIF. We often use the MACD red and green column contraction as an auxiliary indicator to study the market in the stock market. . Therefore, we can conclude that the most important thing in MACD drawing is to obtain DIF and DEA.

Among them, DIF is obtained by subtracting the short-term exponential moving average EMA1 of the closing price and the long-term exponential moving average EMA2. As for DEA, it is only a secondary movement smoothing of the DIF value, which is mainly used to assist in observing changes.

Theoretically speaking, in a stock market that continues to rise, the short-term EMA1 line is above the long-term EMA2 line, and the positive deviation (+DIF) between them will become larger and larger, the DIF distance DEA will also become larger, and the histogram will also Expansion; on the contrary, in the accelerated decline, the negative deviation interpolation (-DIF) will become smaller and smaller. When the market reverses, the distance between DIF and DEA will gradually decrease, that is, the often said indicator has diverged, corresponding to the stock price can be reflected in the second round of rise/fall although it surpassed the high point of the first round of stock price/ Low point, but the kinetic energy of the second round of operation is lower than that of the first round, indicating that the trend is at the end of the day.

MACD indicator calculation

MACD indicator calculation is divided into 4 steps:

(1) As mentioned above, MACD is composed of DIF, DEA and histogram, among which DIF is obtained by subtracting EMA1 and EMA2. Therefore, we first need to calculate the values ​​of EMA1 and EMA2. It should be noted that EMA is different from ordinary moving averages, it is an exponentially weighted moving average, that is, the window period of EMA1 is 12 days, and the window period of EMA2 is 26 days. Calculated as follows:

EMA1 (moving average of closing price on the 12th) = EM1 (12) 11/13 of the previous day + closing price of today 2/13

EMA2 (moving average of closing price on the 26th) = EMA2 (26) 25/27 of the previous day + closing price of today 2/27

Now we directly calculate these two values ​​through the code, the specific steps are as follows:

EMA1=df["close"].ewm(span=12, adjust=False).mean()
EMA2=df["close"].ewm(span=26, adjust=False).mean()

(2) After getting EMA1 and EMA2, we can calculate the value of DIF and DEA. Usually the DEA window period is 9 days, the specific formula is as follows:

DIF (Difference Value)=EMA1-EMA2

DEA (average deviation) = DEA 8/10 of the previous day + DIF 2/10 of today

After replacing it with python code, it looks like this:

DIF=EMA1-EMA2
DEA=DIF.ewm(9,adjust=False).mean()

(3) Finally, the histogram is obtained through DIF and DEA, the specific formula is as follows:

BAR (Bar value)=2*(DIF-DEA)

After replacing it with the code, it looks like this:

BAR=2*(DIF-DEA)

But we have seen that the histogram on other stock software is not a constant layer, but red and green, so here we also need to classify the value of BAR to display the red and green histogram. code show as below:

red_bar=np.where(BAR>0,BAR,0)
blue_bar=np.where(BAR<0,BAR,0)

Draw MACD chart

Now that we have got all the values ​​for drawing MACD, now we can draw the MACD indicator chart directly, the complete code is as follows:

import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime

fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)

df = pd.read_excel("歌尔股份k.xlsx")
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].apply(lambda x: x.strftime('%Y-%m-%d'))
EMA1=df["close"].ewm(span=12, adjust=False).mean()
EMA2=df["close"].ewm(span=26, adjust=False).mean()
DIF = EMA1 - EMA2
DEA = DIF.ewm(span=9, adjust=False).mean()
BAR = 2 * (DIF - DEA)

red_bar = np.where(BAR > 0, BAR, 0)
blue_bar = np.where(BAR < 0, BAR, 0)

ax.plot(np.arange(0, len(df)), DIF)
ax.plot(np.arange(0, len(df)), DEA)

ax.bar(np.arange(0, len(df)), red_bar, color="red")
ax.bar(np.arange(0, len(df)), blue_bar, color="blue")
ax.xaxis.set_major_locator(ticker.MaxNLocator(20))

def format_date(x, pos=None):
    if x < 0 or x > len(df['date']) - 1:
        return ''
    return df['date'][int(x)]

ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
plt.title("MACD")
plt.show()

After running, the results obtained are shown in the following figure:
MACD chart
MACD is explained here, and the next article will introduce Jincha and Sicha.

Guess you like

Origin blog.csdn.net/liyuanjinglyj/article/details/112755758