python stock quantitative trading (4) --- golden fork and dead fork

Purely the heart of saving the world, it is the end. Gou has the heart of charming the world, that is, music. Pure love is the end. A bit of cynicism is a song. Pure respect for others is the end. A bit of cynicism is music.

What is Golden Cha and Si Cha

In the previous article, we mentioned the moving average. To understand the golden cross, we need to understand another concept, the moving average crossover. It refers to the phenomenon that the moving averages of different periods cross each other as the trading time advances.

The most common one is the 5-day moving average and the 10-day moving average drawn by us. If they cross, it is called a moving average crossover phenomenon. The golden cross refers to the intersection formed when the short-term moving average crosses the longer-term moving average from below the long-term moving average.

If this kind of golden cross occurs, it can be regarded as an indicator that the market turns from short to long (bullish); conversely, when the short-period moving average falls from upward to break the long-period moving average, we call it a dead cross, which can be regarded as a market. An indicator of changing from long to short (bearish).

Let's first look at a picture, as shown below: The
Insert picture description here
above picture is also the K-line chart and the moving average chart of the first blog post. The orange is the 10-day moving average and the blue is the 5-day moving average. Among them, the intersection marked by 1 is the short-period 5-day moving average breaking upward through the long-term 10-day moving average, which is bullish (Golden Cross). The intersection marked by 2 is the 10-day long-period moving average falling below the 5-day short-period moving average, it will be bearish (die cross).

However, from the picture of GoerTek, the 1, 2 intersections are only in line with the 2nd market. On the contrary, the third intersection did rise for many days in a row. Therefore, for stocks, it is not meaningful to look at this kind of golden fork alone, and it needs to be observed in combination with other indicators.

Operation of Golden Cha and Si Cha

Here, we need to re-acquire the data of a stock. After all, for the moving average, one-month data is of little reference. We need to obtain at least 3 months of stock data. The specific code is as follows:

import akshare as ak
df = ak.stock_zh_a_daily(symbol="sz002241", start_date="20200101", end_date="20210115",
                         adjust="qfq")
df.to_excel("歌尔股份year.xlsx")

Here, we obtain the 3-month data of Goertek and draw its 20-day and 30-day moving averages. The specific code is as follows:

df = pd.read_excel("歌尔股份year.xlsx")
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].apply(lambda x: x.strftime('%Y-%m-%d'))
df["SMA20"]=df["close"].rolling(20).mean()
df["SMA30"]=df["close"].rolling(30).mean()
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
ax.plot(df["date"],df["SMA20"])
ax.plot(df["date"],df["SMA30"])
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.show()

After running, the displayed effect diagram is as follows:
Insert picture description here
As shown in the above diagram, generally speaking, this kind of diagram looks very laborious, after all, it does not mark the intersection for you. If there are many intersections, it is often very time-consuming to find them by yourself. In order to make the graph of our stocks more intuitive, we need to mark the intersections. However, before marking, we need to find the location of the intersection.

The code is as follows:

diff=np.sign(df["SMA20"]-df["SMA30"])

sign() is a function to take the number sign (the sign before the number) in Python's Numpy. Looking at the above chart, you will find that when SMA20 is above SMA30, the difference is positive, and vice versa.

For the sequence diff obtained after subtraction, use the DataFrame.shift() function to shift 1 value to the right to obtain a new sequence, and then subtract the sequence and get the sign, you can get the cross signal of the two moving averages. When the sign is negative, it is a dead cross, and when the sign is positive, it is a golden cross. The corresponding code is as follows:

signal=np.sign(diff-diff.shift(1))
down_cross=df[signal<0]
up_cross=df[signal>0]

Draw the golden fork and the dead fork

Next, let's draw the golden fork and the dead fork, the specific code is as follows:

#标记金叉
for key, val in df.items():
    for index, today in up_cross.iterrows():
        x_posit = df.index.get_loc(index-1)
        ax.annotate("{}\n{}".format("金叉",today["date"]), xy=(x_posit, today["SMA20"]),xytext=(-30,-up_cross["SMA20"].mean()+100), xycoords="data",
                    fontsize=18, textcoords="offset points", arrowprops=dict(arrowstyle="simple", color="r"))
#标记死叉
for key, val in df.items():
    for index, today in down_cross.iterrows():
        x_posit = df.index.get_loc(index-1)
        ax.annotate("{}\n{}".format("死叉",today["date"]), xy=(x_posit, today["SMA20"]),xytext=(-30,-down_cross["SMA20"].mean()-100), xycoords="data",
                    fontsize=18, textcoords="offset points", arrowprops=dict(arrowstyle="simple", color="g"))

Here we use annotate to assist in marking the intersections on the image. The specific code is to traverse the classification intersections just now, and then draw them separately.

The complete code is as follows:

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
import numpy as np

df = pd.read_excel("歌尔股份year.xlsx")
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].apply(lambda x: x.strftime('%Y-%m-%d'))
df["SMA20"] = df["close"].rolling(20).mean()
df["SMA30"] = df["close"].rolling(30).mean()
diff = np.sign(df["SMA20"] - df["SMA30"])
signal = np.sign(diff - diff.shift(1))
down_cross = df[signal < 0]
up_cross = df[signal > 0]
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
plt.rcParams['font.sans-serif'] = ['SimHei']
ax.plot(df["date"], df["SMA20"])
ax.plot(df["date"], df["SMA30"])
for key, val in df.items():
    for index, today in up_cross.iterrows():
        x_posit = df.index.get_loc(index-1)
        ax.annotate("{}\n{}".format("金叉",today["date"]), xy=(x_posit, today["SMA20"]),xytext=(-30,-up_cross["SMA20"].mean()+100), xycoords="data",
                    fontsize=18, textcoords="offset points", arrowprops=dict(arrowstyle="simple", color="r"))

for key, val in df.items():
    for index, today in down_cross.iterrows():
        x_posit = df.index.get_loc(index-1)
        ax.annotate("{}\n{}".format("死叉",today["date"]), xy=(x_posit, today["SMA20"]),xytext=(-30,-down_cross["SMA20"].mean()-100), xycoords="data",
                    fontsize=18, textcoords="offset points", arrowprops=dict(arrowstyle="simple", color="g"))
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.show()

After running, the displayed effect is as shown in the figure below:
Insert picture description here
Careful readers must find that when we get the time, we move the index forward by one place (index-1). This is because for the convenience of calculating the golden fork and the dead fork, The function shift is used to shift 1 value to the right. In order to make the arrow correspond to the intersection, we need to move back to the time point in reverse. (Because the three-month data has too many intersections, so here we only use the second half of the moving average)

We will explain the golden fork and the dead fork here. In the next article, we will introduce the visualization of the stock price gap.

Guess you like

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