python stock quantitative trading (2) --- oscillating index KDJ

What is your destiny? I don’t know how? I want to be prosperous, and I often think about loneliness; when I am going smoothly, I often think about rebellion; that is, I have enough food in front of my eyes, and I often think about poverty; that is, people love and respect each other, and often think about fear; that is, family history He is heavy, and often thinks humble; that is, he is well-learned, and he often thinks shallowly.

What is KDJ

Speaking of KDJ, we first need to mention the William Index. The calculation of this indicator first selects a specific time span, such as 14 days, and then finds the highest price and the lowest price at this specific time to form a price change range, and then Analyze the relative position of the closing price at the last time point of this time span with the highest and lowest prices during the period to measure the overbought or oversold phenomenon of the market.

The KDJ indicator was originally the KD indicator proposed by Chicago futures trader George Lane, which is also known as the stochastic oscillator. Unlike the William Index, this indicator integrates the idea of ​​moving average in the ratio of the relative position of the closing price to the highest and lowest prices, and uses more information to capture overbought and oversold in the market. As the name suggests, KDJ is one more J line than the William Index, which further improves the accuracy of the data.

KDJ calculation formula

Regarding the calculation of KDJ, we can divide it into 4 steps:

(1) First, the RSV value needs to be calculated, and its formula is as follows:

RSV= (closing price on the nth day-the lowest price in the last n days) ÷ (the highest price in the last n days-the lowest price in the last n days) * 100

In this formula, n is the time span, and the specific application depends on the length of the data you need to observe. The RSV value range is between 0 and 100. The larger the value, the higher the relative position of the closing price in the price range, and the market may be overbought, and vice versa.

(2) Calculate the K value. The K value is calculated by the exponential moving average (EMA) of the RSV value, that is, the K value of the previous day and the current RSV value are added after a certain weight adjustment. The calculation formula is as follows:

K value = 2/3 of the K value of the previous day + 1/3 of the RSV value of the day

(3) Calculate the D value. The D value is calculated from the exponential moving average of the K value, that is, the previous day's D value and the current K value are added after a certain weight adjustment. The calculation formula is as follows:

D value = 2/3 D value of the previous day + 1/3 K value of the day

(4) Calculate the J value. The J value is an auxiliary index of KD, which further reflects the degree of multiplication and separation of the K index and the D index. The calculation formula is as follows:

J value = 3 K value-2 D value

Calculate the value of KDJ

Here, we choose the time span as 9 days, which is the same as the moving average explained before. But unlike the moving average, the RSV value is still available for the first 8 days, but it is invalid, and the data on the 9th day and after are valid.

According to the above formula, we first need to calculate the lowest price in the last 9 days and the highest price in the last 9 days. Here, we still use the stock data in the Goertek k.xlsx file obtained at the beginning of the previous chapter. The specific code is as follows:

low_list = df["close"].rolling(9, min_periods=1).min()
high_list = df["high"].rolling(9, min_periods=1).max()

After obtaining these two values, we can calculate the RSV value. The specific code is as follows (applying formula 1):

rsv = (df["close"] - low_list) / (high_list - low_list) * 100

After getting the RSV value, we can derive the KDJ value according to the above formula. The specific code is as follows:

df["K"] = rsv.ewm(com=2, adjust=False).mean()
df["D"] = df["K"].ewm(com=2, adjust=False).mean()
df["J"] = 3 * df["K"] - 2 * df["D"]

Let's first analyze the ewm method, its specific definition is as follows:

DataFrame.ewm(self, com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0)

This method is an exponential weighted function. When adjust is False, the weighted average is calculated recursively. The formula is as follows:
Insert picture description here
When com is 2, then a=1/3, apply the second formula in the above figure, and get The K value is (2/3) the K value of the previous day + 1/3 the RSV value of the day, so the K value can be calculated using ewm.

The same is true for the D value, but the RSV is replaced by the K value. As for the final J value, it is the simplest, just apply it directly.

Draw KDJ curve

Now that the KDJ values ​​have been calculated, the curve can naturally be drawn directly. We can directly substitute the 3 values ​​into the drawing library method. The specific code is as follows (full code):

import matplotlib.pyplot as plt
plt.figure(figsize=(12, 8))
df = pd.read_excel("歌尔股份k.xlsx")
low_list = df["close"].rolling(9, min_periods=1).min()
high_list = df["high"].rolling(9, min_periods=1).max()
rsv = (df["close"] - low_list) / (high_list - low_list) * 100
df["K"] = rsv.ewm(com=2, adjust=False).mean()
df["D"] = df["K"].ewm(com=2, adjust=False).mean()
df["J"] = 3 * df["K"] - 2 * df["D"]
plt.plot(df["date"], df["K"], label ="K")
plt.plot(df["date"], df["D"], label ="D")
plt.plot(df["date"], df["J"], label ="J")
plt.legend()
plt.show()

After running, the displayed KDJ curve is as follows:
KDJ curve
KDJ indicator we will talk about here, the next article introduces the MACD indicator chart drawing.

Guess you like

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