4.7 DMI • DMI 指标体系的构建及简单应用

来源:https://uqer.io/community/share/561727aaf9f06c4ca92fb5a4

DMI指标又叫动向指标或趋向指标,是通过分析股票价格在涨跌过程中买卖双方力量均衡点的变化情况,即多空双方的力量的变化受价格波动的影响而发生由均衡到失衡的循环过程,从而提供对趋势判断依据的一种技术指标。其由美国技术分析大师威尔斯·威尔德(Wells Wilder)所创造,是一种中长期股市技术分析方法。

DMI指标体系的构建:

  1. TR = SUM(MAX(MAX(HIGH - LOW, ABS(HIGH-REF(CLOSE,1))), ABS(LOW - REF(CLOSE, 1))), N)
  2. HD = HIGH - REF(HIGH, 1)
  3. LD = REF(LOW, 1) - LOW
  4. DMP = SUM(IF(HD>0 AND HD>LD, HD, 0), N)
  5. DMM = SUM(IF(LD>0 AND LD>HD, LD, 0), N)
  6. PDI = DMP*100/TR
  7. MDI = DMM*100/TR
  8. DX = ABS(MDI - PDI)/(MDI + PDI)*100
  9. ADX = MA(ABS(MDI - PDI)/(MDI + PDI)*100, M)

其中变量与函数定义如下:

  • CLOSE:引用收盘价(在盘中指最新价)
  • HIGH:引用最高价
  • LOW:引用最低价
  • REF(X, N):引用X在N个周期前的值
  • ABS(X):求X的绝对值
  • MAX(A, B):求A,B中的较大者
  • SUM(X, N):得到X在N周期内的总和
  • IF(C, A, B):如果C成立返回A,否则返回B 此外,PDI简记为+DIMDI简记为-DI;参数:N=14(默认),M=14 (默认)。

实际上从数学上看,DXADX的构建并不一定需要PDIMDI,有DMPDMM就行了。计算PDIMDI是将指标数值控制在0到100之间。

  1. #计算某一天的股票DMP与DMM值
  2. def eq_DMPandDMM(stk_list,current_date,N=14):
  3. cal = Calendar('China.SSE')
  4. period = '-' + str(N+1) + 'B'
  5. begin_date = cal.advanceDate(current_date,period,BizDayConvention.Unadjusted)
  6. end_date = cal.advanceDate(current_date,'-1B',BizDayConvention.Unadjusted)
  7. eq_hd = {}
  8. eq_ld = {}
  9. dmp_sum = 0
  10. dmm_sum = 0
  11. eq_dmp = {}
  12. eq_dmm = {}
  13. eq_Price = DataAPI.MktEqudAdjGet(secID=stk_list,beginDate=begin_date.strftime('%Y%m%d'),endDate=end_date.strftime('%Y%m%d'),field=['secID','highestPrice','lowestPrice'],pandas="1")
  14. avaiable_list = eq_Price['secID'].drop_duplicates().tolist()
  15. eq_Price.set_index('secID',inplace=True)
  16. for stk in avaiable_list:
  17. if len(eq_Price.ix[stk]) == (N+1):
  18. eq_hd[stk] = np.array(eq_Price.ix[stk]['highestPrice'][1:] - eq_Price.ix[stk]['highestPrice'][:-1])
  19. eq_ld[stk] = np.array(eq_Price.ix[stk]['lowestPrice'][:-1] - eq_Price.ix[stk]['lowestPrice'][1:])
  20. for i in xrange(len(eq_ld[stk])):
  21. if eq_hd[stk][i] > 0 and eq_hd[stk][i] > eq_ld[stk][i]:
  22. dmp_sum = dmp_sum + eq_hd[stk][i]
  23. if eq_ld[stk][i] > 0 and eq_ld[stk][i] > eq_hd[stk][i]:
  24. dmm_sum = dmm_sum + eq_ld[stk][i]
  25. eq_dmp[stk] = dmp_sum
  26. eq_dmm[stk] = dmm_sum
  27. dmm_sum = 0
  28. dmp_sum = 0
  29. return eq_dmp,eq_dmm
  1. #计算某一天股票的TR值
  2. def eq_TR(stk_list,current_date,N=14):
  3. cal = Calendar('China.SSE')
  4. period = '-' + str(N+1) + 'B'
  5. begin_date = cal.advanceDate(current_date,period,BizDayConvention.Unadjusted)
  6. end_date = cal.advanceDate(current_date,'-1B',BizDayConvention.Unadjusted)
  7. eq_hl = {} #HIGH - LOW
  8. eq_hc = {} #HIGH - CLOSE
  9. eq_lc = {} #LOW - CLOSE
  10. eq_tr = {}
  11. tr_sum = 0
  12. eq_Price = DataAPI.MktEqudAdjGet(secID=stk_list,beginDate=begin_date.strftime('%Y%m%d'),endDate=end_date.strftime('%Y%m%d'),field=['secID','highestPrice','lowestPrice','closePrice'],pandas="1")
  13. avaiable_list = eq_Price['secID'].drop_duplicates().tolist()
  14. eq_Price.set_index('secID',inplace=True)
  15. for stk in avaiable_list:
  16. if len(eq_Price.ix[stk]) == (N+1):
  17. eq_hl[stk] = np.array(eq_Price.ix[stk]['highestPrice'][1:] - eq_Price.ix[stk]['lowestPrice'][1:])
  18. eq_hc[stk] = np.array(eq_Price.ix[stk]['highestPrice'][1:] - eq_Price.ix[stk]['closePrice'][:-1])
  19. eq_lc[stk] = np.array(eq_Price.ix[stk]['lowestPrice'][:-1] - eq_Price.ix[stk]['closePrice'][1:])
  20. for i in xrange(len(eq_hl[stk])):
  21. tr_sum = tr_sum + max(max(eq_hl[stk][i],abs(eq_hc[stk][i])),abs(eq_lc[stk][i]))
  22. eq_tr[stk] = tr_sum
  23. tr_sum = 0
  24. return eq_tr
  1. #计算某一天股票的ADX
  2. def eq_ADX(stk_list,current_date,N=14):
  3. cal = Calendar('China.SSE')
  4. period = '-' + str(N) + 'B'
  5. begin_date = cal.advanceDate(current_date,period,BizDayConvention.Unadjusted)
  6. end_date = cal.advanceDate(current_date,'-1B',BizDayConvention.Unadjusted)
  7. timeSeries = cal.bizDatesList(begin_date,end_date)
  8. eq_adx = {}
  9. adx_sum = 0
  10. #初始化eq_adx
  11. eq_Price = DataAPI.MktEqudAdjGet(secID=stk_list,beginDate=begin_date.strftime('%Y%m%d'),endDate=end_date.strftime('%Y%m%d'),field=['secID','highestPrice','lowestPrice'],pandas="1")
  12. avaiable_list = eq_Price['secID'].drop_duplicates().tolist()
  13. eq_Price.set_index('secID',inplace=True)
  14. for stk in avaiable_list:
  15. if len(eq_Price.ix[stk]) == N:
  16. eq_adx[stk] = 0
  17. #计算ADX
  18. for i in xrange(len(timeSeries)):
  19. eq_dmp,eq_dmm = eq_DMPandDMM(stk_list,timeSeries[i],N)
  20. for stk in eq_dmp:
  21. if eq_dmp[stk] == 0 and eq_dmm[stk] == 0: #当DMP与DMM都为零时,认为无趋势DX=0
  22. pass
  23. else:
  24. eq_adx[stk] = eq_adx[stk] + abs(eq_dmp[stk] - eq_dmm[stk])/(eq_dmp[stk] + eq_dmm[stk])*100
  25. for stk in eq_adx:
  26. eq_adx[stk] = eq_adx[stk] / len(timeSeries)
  27. return eq_adx

简单应用:

DMP上穿DMM时,意味着,上涨倾向强于下跌倾向,一个买入信号生成。反之则反。而ADX用于反映趋向变动的程度,在买入信号时,ADX伴随上升,则预示股价的涨势可能更强劲。

  1. import numpy as np
  2. import pandas as pd
  3. from CAL.PyCAL import *
  4. start = '2012-08-01' # 回测起始时间
  5. end = '2015-08-01' # 回测结束时间
  6. benchmark = 'HS300' # 策略参考标准
  7. universe = set_universe('HS300') # 证券池,支持股票和基金
  8. capital_base = 1000000 # 起始资金
  9. freq = 'd' # 策略类型,'d'表示日间策略使用日线回测,'m'表示日内策略使用分钟线回测
  10. refresh_rate = 20 # 调仓频率,表示执行handle_data的时间间隔,若freq = 'd'时间间隔的单位为交易日,若freq = 'm'时间间隔为分钟
  11. cal = Calendar('China.SSE')
  12. def initialize(account): # 初始化虚拟账户状态
  13. pass
  14. def handle_data(account): # 每个交易日的买入卖出指令
  15. eq_dmp_now,eq_dmm_now = eq_DMPandDMM(account.universe,account.current_date,14)
  16. eq_adx = eq_ADX(account.universe,account.current_date,14)
  17. yestoday = cal.advanceDate(account.current_date,'-1B',BizDayConvention.Unadjusted)
  18. eq_dmp_before,eq_dmm_before = eq_DMPandDMM(account.universe,yestoday,14)
  19. eq_adx_before = eq_ADX(account.universe,yestoday,14)
  20. long_bucket = []
  21. short_bucket = []
  22. for stk in account.universe:
  23. try:
  24. if eq_dmp_now[stk] > eq_dmm_now[stk] and eq_dmp_before[stk] < eq_dmm_before[stk] and eq_adx[stk] > eq_adx_before[stk]:
  25. long_bucket.append(stk)
  26. else:
  27. short_bucket.append(stk)
  28. except:
  29. pass
  30. #调仓逻辑是调仓时将所有满足条件的股票等权
  31. stk_num = len(account.valid_secpos) + len(long_bucket)
  32. for stk in account.valid_secpos:
  33. if stk in short_bucket:
  34. order_to(stk,0)
  35. stk_num = stk_num - 1
  36. for stk in account.valid_secpos:
  37. if stk not in short_bucket:
  38. order_to(stk,account.referencePortfolioValue/account.referencePrice[stk]/stk_num)
  39. for stk in long_bucket:
  40. if stk not in account.avail_secpos:
  41. order_to(stk,account.referencePortfolioValue/account.referencePrice[stk]/stk_num)

4.7 DMI • DMI 指标体系的构建及简单应用 - 图1