Simple MACD

来源:https://uqer.io/community/share/560a3007f9f06c597665ef61

MACD 公式算法:

  • 短期EMA: 短期(例如12日)的收盘价指数移动平均值(Exponential Moving Average)
  • 长期EMA: 长期(例如26日)的收盘价指数移动平均值(Exponential Moving Average)
  • DIF线: (Difference)短期EMA和长期EMA的离差值
  • DEA线: (Difference Exponential Average)DIF线的M日指数平滑移动平均线
  • MACD线: DIF线与DEA线的差 策略实现:

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

  • 相反,如DIF从上往下穿过DEA,卖出。

策略中使用talib计算MACD

  1. import pandas as pd
  2. import numpy as np
  3. import talib
  4. start = '2012-01-01'
  5. end = '2015-09-28'
  6. benchmark = 'HS300'
  7. universe = set_universe('HS300')
  8. capital_base = 1000000
  9. refresh_rate = 5
  10. ## 使用talib计算MACD的参数
  11. short_win = 12 # 短期EMA平滑天数
  12. long_win = 26 # 长期EMA平滑天数
  13. macd_win = 20 # DEA线平滑天数
  14. stk_num = 20 # 持仓股票数量
  15. longest_history = 100
  16. def initialize(account):
  17. account.universe = universe
  18. def handle_data(account):
  19. all_close_prices = account.get_attribute_history('closePrice', longest_history)
  20. long_bucket = []
  21. short_bucket = []
  22. for stk in account.universe:
  23. prices = all_close_prices[stk]
  24. if prices is None:
  25. continue
  26. try:
  27. # talib计算MACD
  28. macd_tmp = talib.MACD(prices, fastperiod=short_win, slowperiod=long_win, signalperiod=macd_win)
  29. DIF = macd_tmp[0]
  30. DEA = macd_tmp[1]
  31. MACD = macd_tmp[2]
  32. except:
  33. continue
  34. # 判断MACD走向
  35. if MACD[-1] > 0 and MACD[-4] < 0:
  36. long_bucket.append(stk)
  37. elif MACD[-1] < 0 and MACD[-4] > 0:
  38. short_bucket.append(stk)
  39. hold = []
  40. # 处理持仓中的股票
  41. for stk in account.valid_secpos:
  42. # 在short_bucket中的,卖出
  43. if stk in short_bucket:
  44. order_to(stk, 0)
  45. # 不在short_bucket中的,留着
  46. else:
  47. hold.append(stk)
  48. buy_list = hold
  49. for stk in long_bucket:
  50. if stk not in hold:
  51. buy_list.append(stk)
  52. if len(buy_list) > 0:
  53. # 无论buy_list中有多少只股票,都将仓位分成stk_num份,每份买入一只股票
  54. amount_per_stk = account.referencePortfolioValue/stk_num
  55. for stk in buy_list:
  56. amount = int(amount_per_stk/account.referencePrice[stk] / 100.0) * 100
  57. order_to(stk, amount)

Simple MACD - 图1