Kdj indicator calculation program code

First look at the KDJ index calculation formula:
KDJ calculation is more complicated. First, calculate the RSV value of the period (n days, n weeks, etc.), that is, the immature stochastic index value, and then calculate the K value, D value, J value, etc. Taking the calculation of KDJ value on n days as an example, the calculation formula is
RSV on n days=(Cn-Ln)/(Hn-Ln)×100. In the
formula, Cn is the closing price on the nth day; Ln is the lowest price in n days; Hn is the highest price in n days, generally n takes 9.
Secondly, calculate K value and D value:
K value of the day = 2/3 × K value of the previous day + 1/3 × RSV of the
day D value of the day = 2/3 × D value of the previous day + 1/3 × K value of the day
When using the pandas ewm function to calculate the K and D values, please note that this is 1/3 × RSV of the day, so the pandas ewm function parameter should use com instead of span. The com setting is 1/3, and the span setting is 2/ 3.
J value=3*K value of the day-2*D value of the day
KDJ indicator calculation code is as follows:

import tushare as ts
import pandas as pd
price = ts.get_k_data('300816', start = '2020-02-10', end = '2020-04-03', ktype = 'D')
price['rolling_high'] = price['high'].rolling(window = 9, min_periods = 1).max()
price['rolling_low'] = price['low'].rolling(window = 9, min_periods = 1).min()
price['fastk'] = (price['close'] - price['rolling_low']) / (price['rolling_high'] - price['rolling_low']) * 100
price['fastd'] = price['fastk'].ewm(com = 2, adjust = False).mean()
price['K'] = price['fastd']
price['D'] = price['K'].ewm(com = 2, adjust = False).mean()
price['J'] = 3 * price['K'] - 2 * price['D']

 

Guess you like

Origin blog.csdn.net/u012724887/article/details/105375800