거래 전략을 정량화하는 KDJ 지표

저자:작은 꿈, 2017-01-16 15:00:09, 업데이트: 2019-08-01 09:22:39

거래 전략을 정량화하는 KDJ 지표

선물과 주식 시장에서 가장 많이 사용되는 기술 분석 도구인 KDJ 지표, 정식 이름인 무작위 지표 (Stochastics) 는 조지 라인 (George Lane) 박사가 만든 것이다. 동력 개념과 강점 지표의 몇 가지 장점을 합친 KDJ 지표는 특정 주기에 나타난 최고 가격, 최저 가격, 폐쇄 가격의 세 가지 사이의 비율 관계를 기초 데이터로 계산하여, 도출된 K값, D값 및 J값을 곡선 그래프로 연결하여 가격 변동 경향을 반영하는 KDJ 지표를 형성한다.

  • 계산 방법: 먼저 주기의 RSV 값을 계산하고 K값, D값, J값을 계산합니다. 9일 주기의 KDJ 예를 들어:

    RSVt=(Ct-L9)/(H9-L9) * 100 (Ct=그날의 종결 가격; L9=9일 최저 가격; H9=9일 최상 가격)

    K값은 RSV값 3일 평평한 이동평균, 공식은: Kt=RSVt/3+2*t-1/3

    D값은 K값의 3일 평평한 이동평균이고, 공식은: Dt=Kt/3+2*Dt-1/3

    J값은 3배 K값 빼기 2배 D값입니다.Dt-2Kt

    KDJ 지표의 적용 시 고려해야 할 몇 가지 주요 사항은 다음과 같습니다.

    1.K와 D의 평가, 범위는 0-100이며, 80개 이상의 부문이 과잉 구매 현상을 나타내며, 20개 이하의 부문이 과잉 판매 현상을 나타냅니다.

    2.买进信号:K值在上涨趋势中﹤D值,K线向上突破D线时;卖出信号:K值在下跌趋势中﹥D值,K线向下跌破D线。

    3.交易不活跃、发行量小的股票并不适用KD指标,而对大盘和热门大盘的准确性却很高。

    4.在KD处在高位或低位,如果出现与股价走向的背离,则是采取行动的信号。

    5. J의 취득값>100은 오버파인, <0은 오버팔인, 모두 가격의 비정상적인 영역에 속한다.

    6.短期转势预警信号:K值和D值上升或者下跌的速度减弱,倾斜度趋于平缓

    일반적으로 K,D,J 세 값은 20-80 사이로 영역으로 관찰이 좋습니다. 감수성 측면에서 가장 강한 것은 J 값이며 K가 다음으로 느리고 가장 느린 것은 D이며 안전성 측면에서는 정반대의 것입니다.

  • 전략 코드 (非發明者量化 코드)

import numpy as np
import pandas as pd
from pandas import DataFrame
import talib as ta

start = '2006-01-01'                        # 回测起始时间
end = '2015-08-17'                          # 回测结束时间
benchmark = 'HS300'                         # 策略参考标准
universe = set_universe('HS300')
capital_base = 100000                        # 起始资金
refresh_rate = 1                           # 调仓频率,即每 refresh_rate 个交易日执行一次 handle_data() 函数
longest_history=20
MA=[5,10,20,30,60,120]                       #移动均线参数

def initialize(account):
    account.kdj=[]
    
def handle_data(account):  
   
    # 每个交易日的买入卖出指令
    
    sell_pool=[]
    hist = account.get_history(longest_history)
        #data=DataFrame(hist['600006.XSHG'])
    stock_pool,all_data=Get_all_indicators(hist)
    pool_num=len(stock_pool)
    if account.secpos==None:
        print 'null'
        for i in stock_pool:
            buy_num=int(float(account.cash/pool_num)/account.referencePrice[i]/100.0)*100 
            order(i, buy_num)
    else:
        
        for x in account.valid_secpos:
            if all_data[x].iloc[-1]['closePrice']<all_data[x].iloc[-1]['ma1'] and (all_data[x].iloc[-1]['ma1']-all_data[x].iloc[-1]['closePrice'])/all_data[x].iloc[-1]['ma1']>0.05 :
                sell_pool.append(x)
                order_to(x, 0)
        
        
        
        if account.cash>500 and pool_num>0:
            
            try:
                sim_buy_money=float(account.cash)/pool_num
                for l in stock_pool:
                    #print sim_buy_money,account.referencePrice[l]
            
                    buy_num=int(sim_buy_money/account.referencePrice[l]/100.0)*100
           
                    #buy_num=10000
                    order(l, buy_num)
            except Exception as e:
                #print e
                pass
           

        
def Get_kd_ma(data):
    indicators={}
    #计算kd指标
    indicators['k'],indicators['d']=ta.STOCH(np.array(data['highPrice']),np.array(data['lowPrice']),np.array(data['closePrice']),\
    fastk_period=9,slowk_period=3,slowk_matype=0,slowd_period=3,slowd_matype=0)
    indicators['ma1']=pd.rolling_mean(data['closePrice'], MA[0])
    indicators['ma2']=pd.rolling_mean(data['closePrice'], MA[1])
    indicators['ma3']=pd.rolling_mean(data['closePrice'], MA[2])
    indicators['ma4']=pd.rolling_mean(data['closePrice'], MA[3])
    indicators['ma5']=pd.rolling_mean(data['closePrice'], MA[4])
    indicators['closePrice']=data['closePrice']
    indicators=pd.DataFrame(indicators)
    return indicators

def Get_all_indicators(hist):
    stock_pool=[]
    all_data={}
    for i in hist:
        try:
            indicators=Get_kd_ma(hist[i])
            all_data[i]=indicators
        except Exception as e:
            #print 'error:%s'%e
            pass
        if indicators.iloc[-2]['k']<indicators.iloc[-2]['d'] and indicators.iloc[-1]['k']>indicators.iloc[-2]['d']:
            stock_pool.append(i)
        elif indicators.iloc[-1]['k']>=10 and indicators.iloc[-1]['d']<=20 and indicators.iloc[-1]['k']>indicators.iloc[-2]['k'] and indicators.iloc[-2]['k']<indicators.iloc[-3]['k']:
            stock_pool.append(i)
    return stock_pool,all_data

프로그램 트레이더에서 가져온


더 많은