4.9 KDJ • KDJ 策略

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

  1. import numpy as np
  2. import pandas as pd
  3. from pandas import DataFrame
  4. import talib as ta
  5. start = '2006-01-01' # 回测起始时间
  6. end = '2015-08-17' # 回测结束时间
  7. benchmark = 'HS300' # 策略参考标准
  8. universe = set_universe('HS300')
  9. capital_base = 100000 # 起始资金
  10. refresh_rate = 1 # 调仓频率,即每 refresh_rate 个交易日执行一次 handle_data() 函数
  11. longest_history=20
  12. MA=[5,10,20,30,60,120] #移动均线参数
  13. def initialize(account):
  14. account.kdj=[]
  15. def handle_data(account):
  16. # 每个交易日的买入卖出指令
  17. sell_pool=[]
  18. hist = account.get_history(longest_history)
  19. #data=DataFrame(hist['600006.XSHG'])
  20. stock_pool,all_data=Get_all_indicators(hist)
  21. pool_num=len(stock_pool)
  22. if account.secpos==None:
  23. print 'null'
  24. for i in stock_pool:
  25. buy_num=int(float(account.cash/pool_num)/account.referencePrice[i]/100.0)*100
  26. order(i, buy_num)
  27. else:
  28. for x in account.valid_secpos:
  29. 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 :
  30. sell_pool.append(x)
  31. order_to(x, 0)
  32. if account.cash>500 and pool_num>0:
  33. try:
  34. sim_buy_money=float(account.cash)/pool_num
  35. for l in stock_pool:
  36. #print sim_buy_money,account.referencePrice[l]
  37. buy_num=int(sim_buy_money/account.referencePrice[l]/100.0)*100
  38. #buy_num=10000
  39. order(l, buy_num)
  40. except Exception as e:
  41. #print e
  42. pass
  43. def Get_kd_ma(data):
  44. indicators={}
  45. #计算kd指标
  46. indicators['k'],indicators['d']=ta.STOCH(np.array(data['highPrice']),np.array(data['lowPrice']),np.array(data['closePrice']),\
  47. fastk_period=9,slowk_period=3,slowk_matype=0,slowd_period=3,slowd_matype=0)
  48. indicators['ma1']=pd.rolling_mean(data['closePrice'], MA[0])
  49. indicators['ma2']=pd.rolling_mean(data['closePrice'], MA[1])
  50. indicators['ma3']=pd.rolling_mean(data['closePrice'], MA[2])
  51. indicators['ma4']=pd.rolling_mean(data['closePrice'], MA[3])
  52. indicators['ma5']=pd.rolling_mean(data['closePrice'], MA[4])
  53. indicators['closePrice']=data['closePrice']
  54. indicators=pd.DataFrame(indicators)
  55. return indicators
  56. def Get_all_indicators(hist):
  57. stock_pool=[]
  58. all_data={}
  59. for i in hist:
  60. try:
  61. indicators=Get_kd_ma(hist[i])
  62. all_data[i]=indicators
  63. except Exception as e:
  64. #print 'error:%s'%e
  65. pass
  66. if indicators.iloc[-2]['k']<indicators.iloc[-2]['d'] and indicators.iloc[-1]['k']>indicators.iloc[-2]['d']:
  67. stock_pool.append(i)
  68. 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']:
  69. stock_pool.append(i)
  70. return stock_pool,all_data

4.9 KDJ • KDJ 策略 - 图1