MACD平滑异同移动平均线方法

来源:https://uqer.io/community/share/55a4e581f9f06c6dd0e17efa

策略思路:

MACD(Moving Average Convergence and Divergence)是Geral Appel 于1979年提出的,利用收盘价的短期(常用为12日)指数移动平均线与长期(常用为26日)指数移动平均线之间的聚合与分离状况,对买进、卖出时机作出研判的技术指标。

公式算法:

  • 短期EMA: 短期(例如12日)的收盘价指数移动平均值(Exponential Moving Average)
  • 长期EMA: 长期(例如26日)的收盘价指数移动平均值(Exponential Moving Average)
  • DIF线: (Difference)短期EMA和长期EMA的离差值
  • DEA线: (Difference Exponential Average)DIF线的M日指数平滑移动平均线
  • MACD线: DIF线与DEA线的差 参数:SHORT(短期)、LONG(长期)、M天数,一般为12、26、9。指数加权平滑系数为:

  • 短期EMA平滑系数: 2/(SHORT+1)

  • 长期EMA平滑系数: 2/(LONG+1)
  • DEA线平滑系数: 2/(M+1) 策略实现:

  • DIF从下而上穿过DEA,买进;

  • 相反,如DIF从上往下穿过DEA,卖出。
  1. import pandas as pd
  2. start = datetime(2013, 1, 1)
  3. end = datetime(2015, 7, 13)
  4. benchmark = 'HS300'
  5. #universe = ['601398.XSHG', '600028.XSHG', '601988.XSHG', '600036.XSHG', '600030.XSHG',
  6. #'601318.XSHG', '600000.XSHG', '600019.XSHG', '600519.XSHG', '601166.XSHG']
  7. universe = set_universe('SH50')
  8. capital_base = 200000
  9. refresh_rate = 1
  10. window = 1
  11. initMACD = -10000.0
  12. histMACD = pd.DataFrame(initMACD, index = universe, columns = ['preShortEMA', 'preLongEMA', 'preDIF', 'preDEA'])
  13. shortWin = 26 # 短期EMA平滑天数
  14. longWin = 52 # 长期EMA平滑天数
  15. macdWin = 15 # DEA线平滑天数
  16. longest_history = window
  17. def initialize(account):
  18. account.amount = 10000
  19. account.universe = universe
  20. account.days = 0
  21. def handle_data(account):
  22. account.days = account.days+1
  23. for stk in account.universe:
  24. all_close_prices = account.get_attribute_history('closePrice', 1)
  25. prices = all_close_prices[stk]
  26. if prices is None:
  27. continue
  28. preShortEMA = histMACD.at[stk, 'preShortEMA']
  29. preLongEMA = histMACD.at[stk, 'preLongEMA']
  30. preDIF = histMACD.at[stk, 'preDIF']
  31. preDEA = histMACD.at[stk, 'preDEA']
  32. if preShortEMA == initMACD or preLongEMA == initMACD:
  33. histMACD.at[stk, 'preShortEMA'] = prices[-1]
  34. histMACD.at[stk, 'preLongEMA'] = prices[-1]
  35. histMACD.at[stk, 'preDIF'] = 0
  36. histMACD.at[stk, 'preDEA'] = 0
  37. return
  38. shortEMA = preShortEMA*1.0*(shortWin-1)/(shortWin+1) + prices[-1]*2.0/(shortWin+1)
  39. longEMA = preLongEMA*1.0*(longWin-1)/(longWin+1) + prices[-1]*2.0/(longWin+1)
  40. DIF = shortEMA - longEMA
  41. DEA = preDEA*1.0*(macdWin-1)/(macdWin+1) + DIF*2.0/(macdWin+1)
  42. histMACD.at[stk, 'preShortEMA'] = shortEMA
  43. histMACD.at[stk, 'preLongEMA'] = longEMA
  44. histMACD.at[stk, 'preDIF'] = DIF
  45. histMACD.at[stk, 'preDEA'] = DEA
  46. if account.days > longWin and account.days%1 == 0:
  47. #if DIF > 0 and DEA > 0 and preDIF > preDEA and DIF < DEA:
  48. if preDIF > preDEA and DIF < DEA:
  49. order_to(stk, 0)
  50. #if DIF < 0 and DEA < 0 and preDIF < preDEA and DIF > DEA:
  51. if preDIF < preDEA and DIF > DEA:
  52. amount = account.amount/prices[-1]
  53. order_to(stk, amount)

MACD平滑异同移动平均线方法 - 图1