[策略]基于胜率的趋势交易策略

来源:https://uqer.io/community/share/565bbfa4f9f06c6c8a91ae7a

策略说明

简单构建了一个基于胜率的趋势交易策略。认为过去一段时间(N天)内胜率较高、信息比率较高的股票会在紧随其后的几天有较好的表现

1)先根据胜率要求筛选出过去N天胜率高的股票作为预选股票(benchmark可以是定义的确定阈值,或者是某个指数相应的收益率),用aprior算法进行快速筛选。第i只股票胜率的计算方式如下:

  1. winRate(i) = sum([sign(ret(i,t)-ret(bm,t))==1]/N)|t~(t-N,t)
  2. ret(i,t): i股票在第t天的收益率;
  3. retbm,t): benchmark在第t天的收益率;

2)从筛选出的股票中选择过去N天信息比率(收益率/波动率)高的部分股票构建备选投资组合;3)依据被选投资组合做买入操作,使用可用资金的50%~70%;4)设定股票止损位在收益下跌至0.95,止损时将仓位调整至原仓位的40%~60%;5)调仓频率为5天,股票池为沪深300。

  1. import numpy as np
  2. from CAL.PyCAL import *
  3. ################################################################################
  4. # Back Test Functions
  5. ################################################################################
  6. def initialize(account): # 初始化虚拟账户状态
  7. pass
  8. ####init the univese of the choosen stock
  9. def universeInit():
  10. stockComponent = DataAPI.MktTickRTSnapshotIndexGet(securityID=u"000300.XSHG",field=u"lastPrice,shortNM")
  11. stockCount = len(stockComponent)
  12. stockTicker = stockComponent['ticker']
  13. stockExchgID = stockComponent['exchangeCD']
  14. stockID = []
  15. for index in range(stockCount):
  16. stockID.append(stockTicker[index] + '.' + stockExchgID[index])
  17. return stockID
  18. ####deal with the trading signals
  19. def handle_data(account): # 每个交易日的买入卖出指令
  20. ####Presettings
  21. histLength = 10
  22. stockDataThres = 0
  23. ####Dictionary of the return Rate
  24. closePrice = account.get_attribute_history('closePrice',histLength)
  25. retRate = {}
  26. for index in account.universe:
  27. retRate[index] = ((closePrice[index][1:] - closePrice[index][:-1])/closePrice[index][:-1]).tolist()
  28. ###ret list of the benchmark
  29. calendar = Calendar('China.SSE')
  30. startDate = calendar.advanceDate(account.current_date,'-'+str(histLength)+'B').toDateTime()
  31. benchmark = DataAPI.MktIdxdGet(ticker = "000300",
  32. field = "closeIndex",
  33. beginDate = startDate,
  34. endDate = account.current_date,pandas = '1')
  35. bmClose = benchmark['closeIndex'].tolist()
  36. bmRet = []
  37. for index in range(len(bmClose)-1):
  38. bmRet.append((bmClose[1:][index]-bmClose[:-1][index])/bmClose[:-1][index])
  39. ####List of transactions
  40. transactions = []
  41. for index in range(histLength-1):
  42. tmpt = []
  43. for stock in account.universe:
  44. if retRate[stock][index] > stockDataThres:
  45. # if retRate[stock][index] > bmRet[index]:
  46. tmpt.append(stock)
  47. transactions.append(tmpt)
  48. ####List of hot stocks
  49. hotStock = []
  50. hotStockDict,hotStockList = apriori(transactions,0.95)
  51. for index in hotStockList:
  52. for stock in index:
  53. if stock not in hotStock:
  54. hotStock.append(stock)
  55. ####List of the portfolio
  56. retRate = {}
  57. fluctRate = {}
  58. sharpRate = {}
  59. for index in hotStock:
  60. retRate[index] = ((closePrice[index][-1] - closePrice[index][0])/closePrice[index][0])
  61. fluctRate[index] = np.std(closePrice[index])
  62. sharpRate[index] = retRate[index]/fluctRate[index]
  63. portfolio = [index[0] for index in sorted(sharpRate.items(),key = lambda sharpRate:sharpRate[1])[-len(sharpRate)/2:]]
  64. ####Stop loss at -0.05
  65. validSecHist = account.get_attribute_history('closePrice',2)
  66. for index in account.valid_secpos:
  67. if (validSecHist[index][-1] - validSecHist[index][0])/validSecHist[index][0] < -0.05:
  68. order_to(index,0.45*account.valid_secpos[index])
  69. ####Buy portfolio
  70. for index in portfolio:
  71. amount = 0.65*account.cash/len(hotStock)/account.referencePrice[index]
  72. order(index,amount)
  73. return
  74. ########################################################################################
  75. # Aprior algorithm
  76. ########################################################################################
  77. def elementsDet(datasets):
  78. if type(datasets) == list:
  79. elements = {}
  80. for index in datasets:
  81. for index1 in index:
  82. if elements.has_key(index1) == False:
  83. elements[index1] = 1
  84. else:
  85. elements[index1] += 1
  86. return elements
  87. if type(datasets) == dict:
  88. elements = {}
  89. for index in datasets:
  90. if type(index) == tuple:
  91. index = list(index)
  92. for index1 in index:
  93. if elements.has_key(index1) == False:
  94. elements[index1] = 0
  95. else:
  96. elements[index] = 0
  97. return elements
  98. pass
  99. def checkAssociation(subset,objset):
  100. for index in subset:
  101. if index not in objset:
  102. return False
  103. return True
  104. pass
  105. def support(subset,datasets):
  106. count = 0
  107. for transaction in datasets:
  108. if checkAssociation(subset,transaction) == True:
  109. count += 1
  110. return 1.0*count/len(datasets)
  111. pass
  112. def apriori(datasets,minsup):
  113. candidateIterator = []
  114. electIterator = []
  115. length = len(datasets)
  116. ##init part
  117. #the candidate
  118. elements = elementsDet(datasets)
  119. candidate = {}
  120. for index in elements:
  121. candidate[index] = 1.0*elements[index]/length
  122. candidateIterator.append(candidate)
  123. #the elect
  124. elect = {}
  125. for index in candidate:
  126. if candidate[index] > minsup:
  127. elect[index] = candidate[index]
  128. electIterator.append(elect)
  129. ##the update part
  130. itera = 1
  131. while(len(electIterator[-1]) != 0):
  132. candidateOld = candidateIterator[-1]
  133. electOld = electIterator[-1]
  134. elementsOld = elementsDet(electOld)
  135. # print elementsOld
  136. candidate = {}
  137. ##the candidate
  138. for index in electOld:
  139. for index1 in elementsOld:
  140. if type(index) != list and type(index) != tuple:
  141. if index1 != index:
  142. tmp = []
  143. tmp.append(index)
  144. tmp.append(index1)
  145. tmp.sort()
  146. if candidate.has_key(tuple(tmp)) == False:
  147. candidate[tuple(tmp)] = 0
  148. if type(index) == tuple:
  149. tmp = list(index)
  150. if tmp.count(index1) == False:
  151. tmp1 = tmp
  152. tmp1.append(index1)
  153. tmp1.sort()
  154. if candidate.has_key(tuple(tmp1)) == False:
  155. candidate[tuple(tmp1)] = 0
  156. candidateIterator.append(candidate)
  157. ##the elect
  158. elect = {}
  159. for index in candidate:
  160. candidate[index] = support(index,datasets)
  161. for index in candidate:
  162. if candidate[index] > minsup:
  163. elect[index] = candidate[index]
  164. electIterator.append(elect)
  165. # print 'iteartion ' + str(itera) + ' is finished!'
  166. itera += 1
  167. ##the elected frequency sets dictionary: the value is the key's support
  168. electedDict = {}
  169. for index in electIterator:
  170. for index1 in index:
  171. electedDict[index1] = index[index1]
  172. ##the elected frequency sets lists
  173. electedList = []
  174. for index in electIterator:
  175. tmp = []
  176. for index1 in index:
  177. if type(index1) == tuple:
  178. tmp1 = []
  179. for ele in index1:
  180. tmp1.append(ele)
  181. tmp.append(tmp1)
  182. else:
  183. tmp.append([str(index1)])
  184. tmp.sort()
  185. for index1 in tmp:
  186. electedList.append(index1)
  187. return electedDict,electedList
  188. ################################################################################
  189. # Back Test Presetting
  190. ################################################################################
  191. start = '2011-01-01' # 回测起始时间
  192. end = '2015-11-01' # 回测结束时间
  193. benchmark = 'HS300' # 策略参考标准
  194. universe = set_universe('HS300')
  195. # universe = universeInit() # 证券池,支持股票和基金
  196. capital_base = 100000 # 起始资金
  197. freq = 'd' # 策略类型,'d'表示日间策略使用日线回测,'m'表示日内策略使用分钟线回测
  198. refresh_rate = 5 # 调仓频率,表示执行handle_data的时间间隔,若freq = 'd'时间间隔的单位为交易日,若freq = 'm'时间间隔为分钟

[策略]基于胜率的趋势交易策略 - 图1

策略表现

  • 策略能产生一定的alpha;
  • 策略表现与起点强相关,sharpRatio不稳定;
  • 策略表现会受到自身参数设定的影响,例如胜率选择周期、筛选阈值、调仓频率、建仓头寸、止损仓位等,需要依据表现对其进行优化;
  • 策略在2011年4月至12月、2015年6月到11月有相对好的表现,可见其相对较适用于趋势下跌的市场环境。

问题探讨

因子选股模型的流程应该是怎样的?

小编认为构建因子选股的模型需要有如下过程:

  • 大类配置:根据宏观判断市场,进行市场判断(根据不同市场选择不同因子)、资产配置(不同风险性证券的配比选择➡️不同热度的行业配比选择)和策略选择(市场中性、单边做多等);
  • 选股-alpha端:对选股因子进行有效性分析,包括单因子的预测性、因子间相关性,构建多因子模型使得选股有尽可能高的alpha;
  • 选股-风险端:对alpha端的多因子模型进行风险评估,根据风险因子优化模型,使模型尽可能达到有效边界;
  • 择时-买卖时点:对根据因子模型选出的股票进行择时分析,进一步筛选投资组合中的股票及判断作何操作; 因子选股中比较basic的问题,欢迎社区的小伙伴们发表看法、评论和拍醒~