Use Python's Pandas and Matplotlib to Draw Stock KDJ Indicator Lines

  I recently published a book, "Python introductory actual combat video teaching version based on stock big data analysis", Jingdong link: https://item.jd.com/69241653952.html , which gives MACD, KDJ and other indicators The drawing method of the graph. Here we will calculate and draw the KDJ indicator line based on the KDJ algorithm.

1 The calculation process of KDJ indicator

    The KDJ indicator is also called the stochastic indicator, which was first proposed by Dr. George Lane. This indicator includes the strengths of the strength and weakness indicators, the concept of momentum, and the advantages of moving averages, and can be used to measure the degree of deviation of stock prices from the normal price range.

    The calculation process of the KDJ indicator is to first obtain the highest price, lowest price and the closing price of the last trading day that occurred in the specified period (usually 9 days), and then calculate the immature random through the proportional relationship between the three Value RSV, and then use the smooth moving average to calculate the K, D, and J values ​​on this basis. After the calculation is completed, draw the value of KDJ into a graph to predict the stock trend. The specific algorithm is shown below.

    The first step: Calculate the RSV value in the period (n days, n weeks, etc., n is generally 9). RSV is also called the immature stochastic index value, which is the basis for calculating the K value, D value and J value. Taking the calculation unit of n-day cycle as an example, the calculation formula is as follows.

    n日RSV =(Cn-Ln)/(Hn-Ln)× 100

    Among them, Cn is the closing price on the nth day (usually the last day), Ln is the lowest price in the range of n days, and Hn is the highest price in the range of n days. According to the above formula, the RSV value range is 1 to 100. If you want to calculate the RSV value for n weeks, Cn is still the closing price of the last day, but Ln and Hn are the lowest and highest prices in n weeks.

    Step 2: Calculate K and D values ​​according to RSV, the method is as follows.

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

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

    In the calculation process, if there is no K value or D value of the previous day, the number 50 can be used instead.

    In actual use, the KD line is generally calculated on a 9-day cycle. According to the above formula, the first is to calculate the RSV value of the last 9 days, that is, the immature random value. The calculation formula is 9-day RSV = (C-L9 )÷(H9-L9)×100. The meaning of each parameter has been mentioned in step 1, and then calculate the K and D values ​​of the day as shown in this step.

    It should be noted that the smoothing factors 2/3 and 1/3 in the above formula can be changed, but in the practice of stock market trading, these two values ​​have been set to 2/3 and 1/3 by default.

    The third step: Calculate the J value. The calculation formula of the J index is: J = 3×K-2×D. From the point of view of use, the essence of J is to reflect the degree of deviation between the K value and the D value. Its range can exceed 100 at the top and below 0 at the bottom.

The earliest KDJ indicators were only K-line and D-line. At that time, they were also called KD indicators. With the development of analysis technology, KD indicators gradually evolved into KDJ indicators. After the introduction of J indicators, it can improve the prediction of KDJ indicators. Ability.

    After calculating the three values ​​of K, D and J for each day according to the above three steps, connect them to see the KDJ indicator line.

2 Draw a static KDJ indicator line

    According to the KDJ algorithm given in the previous section, the KDJ trend chart of the stock "Jinshi Resources" (stock code 603505) from September 2018 to May 2019 will be drawn in the sample program drawKDJ.py below.    

 !/usr/bin/env python
2    # coding=utf-8
3    import matplotlib.pyplot as plt
4    import pandas as pd
5    # 计算KDJ
6    def calKDJ(df):
7        df['MinLow'] = df['Low'].rolling(9, min_periods=9).min()
8        # 填充NaN数据
9        df['MinLow'].fillna(value = df['Low'].expanding().min(), inplace = True)
10        df['MaxHigh'] = df['High'].rolling(9, min_periods=9).max()
11        df['MaxHigh'].fillna(value = df['High'].expanding().max(), inplace = True)
12        df['RSV'] = (df['Close'] - df['MinLow']) / (df['MaxHigh'] - df['MinLow']) * 100 
15 if i==0: # first day
14 for i in range(len(df)):
13 # Calculate the KDJ value of each trading day through the for loop
16 df.ix[i,'K']=50
17 df.ix [i, 'D'] = 50 
18 if i> 0: 
19 df.ix [i, 'K'] = df.ix [i-1, 'K']*2/3 + 1/ 3*df.ix [i, 'RSV'] 
20 df.ix [i, 'D'] = df.ix [i-1, 'D']*2/3 + 1/3*df.ix [i , 'K'] 
21 df.ix [i, 'J'] = 3*df.ix [i, 'K']-2*df.ix [i, 'D'] 
22 return df

    In the calKDJ method defined in the program statement from line 6 to line 22, the KDJ value within the specified time range will be calculated according to the input parameter df.

    The specific calculation step is to use df['Low'].rolling(9, min_periods=9).min() in the 8th row to set the value of the'MinLow' attribute of each row (that is, each trading day) to The minimum closing price (Low) within 9 days.

    If only this sentence is executed, the MinLow attribute value of the 1st to 8th trading days will be NaN, so the MinLow attribute value of these trading days must be set to the closing price within 9 days (Low) through the program code on line 9 The minimum value. In the same way, set the value of the'MaxHigh' attribute of each trading day to the highest price within 9 days through the program code on line 10, and also use the fillna method on line 11 to fill in the value of the'MaxHigh' attribute of the previous 8 days. Then calculate the RSV value for each trading day in line 12 according to the algorithm.

    After calculating the RSV value, through the for loop on line 14, traverse each trading day in turn, and calculate the KDJ value corresponding to each trading day according to the KDJ algorithm during the traversal.

    Please note that if it is the first trading day, set the K and D values ​​to the default 50 in the program code on lines 16 and 17. If it is not the first trading day, pass the 19th and 19th lines. The 20-line algorithm calculates the K value and D value. After calculating the values ​​of K and D, use the program code on line 21 to calculate the value of J for each trading day.

    From the above code, you can see three operation skills about the DataFrame object:

    First, as shown in line 9, if you want to write the modified data back to the DataFrame, you must add the parameter inplace = True;

    Second, in the 12th row, variable values ​​such as df['Close'] are in the unit of column, that is to say, in the DataFrame, the operation can be performed directly in the unit of column;

    Third, the code in line 16 df.ix[i,'K']=50, here is that ix accesses the object through the index value and the label value, and the loc and iloc methods that achieve similar functions can only be passed Index value to access.    

Draw KDJ line 
24 def drawKDJ(): 
25 df = pd.read_csv('D:/stockData/ch8/6035052018-09-012019-05-31.csv', 
encoding= 'gbk') 26 stockDataFrame = calKDJ(df) 
27 print(stockDataFrame) 
28 # Start drawing 
29 plt.figure() 
30 stockDataFrame['K'].plot(color="blue",label='K') 
31 stockDataFrame['D'].plot(color=" green",label='D') 
32 stockDataFrame['J'].plot(color="purple",label='J') 
33 plt.legend(loc='best') # 画图例
34 # Set the x axis Coordinate label and rotation angle major_index=stockDataFrame.index[stockDataFrame.index%10==0] 
35 major_xtics=stockDataFrame['Date'][stockDataFrame.index%10==0]index%10==0]
36        plt.xticks(major_index,major_xtics)
37 plt.setp(plt.gca().get_xticklabels(), rotation=30) 
38 # With grid lines, and set the grid style 
39 plt.grid(linestyle='-.') 
40 plt.title(" The KDJ picture of Jinshi Resources") 
41 plt.rcParams['font.sans-serif']=['SimHei'] 
42 plt.show() 
43 # Call method 
44 drawKDJ()

    The operation of drawing KDJ is implemented in the drawKDJ method on line 24. The key step is to read the stock trading data from the specified csv file through the program code on line 25, and then call the plot method to draw with three different colors in the program code from line 30 to line 32 For the KDJ line, because the label is set by the label parameter when drawing, the program code on line 33 can be executed to draw the legend.

    The x-axis text label and rotation angle are set in the code from line 34 to line 37. This part of the code is very similar to the previous code for drawing the MACD indicator line. In order not to display the date too much on the x-axis, so use stockDataFrame .index%10 == 0, only display the date whose index value is a multiple of 10.

    In line 44, the drawKDJ method is called to draw the KDJ. After running this sample program, you can see the result as shown in the figure, in which the three curves of KDJ are drawn in blue, green and purple respectively (because the book is printed in black and white, the color cannot be seen, please read it on your computer Run this sample program on).

    The figure below is the KDJ trend chart of the stock "Jinshi Resources" obtained from the stock software during the same time period. The trend of the two is basically the same.

    

 This article can be reprinted, please reprint the full text when reprinting, without any abridgement, and give the original link in the form of a link. Otherwise, you may encounter rights protection from publishers.

 

 

     Text related links:

Use Python's Pandas and Matplotlib to draw stock Tangqian channel, Bollinger band channel and crocodile group line 

Use Python to crawl stock data, draw candlesticks and moving averages, and use machine learning to predict stock prices (from my book) 

Draw the effect of stock market OBV indicator with Python language  

How do programmers learn Python efficiently, and how to make money with Python efficiently 

Use matplotlib and pandas to draw stock MACD indicators and verify trading strategies 

Introduce my new book to everyone: "Practical Python entry based on stock big data analysis"

Predict the stock trend through the linear regression algorithm of machine learning (implemented in Python)  

In my new book, I try to use stock cases to tell the knowledge of Python crawler big data visualization and so on. 

Take the stock RSI indicator as an example, learn Python's email function (including RSI indicator to determine the selling point strategy) 

Getting started with the case of predicting the rise and fall of stocks based on SVM machine learning 

Use python's matplotlib and numpy libraries to draw the integration effect of stock K-line moving average and trading volume (content verification trading strategy code) 

Use python's matplotlib and numpy libraries to draw the integration effect of stock K-line moving averages (including crawling data from the network interface and verifying the trading strategy code)    

Guess you like

Origin blog.csdn.net/sxeric/article/details/108272172