etf_MomentumRotation_test.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. # 克隆自聚宽文章:https://www.joinquant.com/post/34314
  2. # 标题:8年10倍,回撤小,有滑点!ETF动量简单轮动策略!
  3. # 作者:萌新王富贵
  4. '''
  5. 优化说明:
  6. 1.使用修正标准分
  7. rsrs_score的算法有:
  8. 仅斜率slope,效果一般;
  9. 仅标准分zscore,效果不错;
  10. 修正标准分 = zscore * r2,效果最佳;
  11. 右偏标准分 = 修正标准分 * slope,效果不错。
  12. 2.将原策略的每次持有两只etf改成只买最优的一个,收益显著提高
  13. 3.将每周调仓换成每日调仓,收益显著提高
  14. 4.因为交易etf,所以手续费设为万分之三,印花税设为零,未设置滑点
  15. 5.修改股票池中候选etf,删除银行,红利等收益较弱品种,增加纳指etf以增加不同国家市场间轮动的可能性
  16. 6.根据研报,默认参数介已设定为最优
  17. 7.加入防未来函数
  18. 8.增加择时与选股模块的打印日志,方便观察每笔操作依据
  19. '''
  20. #导入函数库
  21. from jqdata import *
  22. import numpy as np
  23. #初始化函数
  24. def initialize(context):
  25. # 设定沪深300作为基准
  26. set_benchmark('000300.XSHG')
  27. # 用真实价格交易
  28. set_option('use_real_price', True)
  29. # 打开防未来函数
  30. set_option("avoid_future_data", True)
  31. # 将滑点设置为0.001
  32. set_slippage(FixedSlippage(0.001))
  33. # 设置交易成本万分之三
  34. set_order_cost(OrderCost(open_tax=0, close_tax=0, open_commission=0.0003, close_commission=0.0003, close_today_commission=0, min_commission=5),
  35. type='fund')
  36. # 过滤order中低于error级别的日志
  37. log.set_level('order', 'error')
  38. # 初始化各类全局变量
  39. #股票池
  40. g.fund_pool = [
  41. # '510050.XSHG', #上证50
  42. '159915.XSHE', #创业板
  43. '513100.XSHG', #纳指
  44. '159928.XSHE', #中证消费
  45. # '510300.XSHG', # 沪深300ETF
  46. '510500.XSHG', # 中证500ETF
  47. '159939.XSHE', # 信息技术
  48. '512010.XSHG', # 医药ETF
  49. '159940.XSHE', # 全指金融
  50. '512980.XSHG', # 传媒ETF
  51. '159920.XSHE', # 恒生ETF
  52. # '513050.XSHG', # 中概互联
  53. # '162411.XSHE', # 华宝油气lof
  54. # '501018.XSHG', # 南方原油lof
  55. '512880.XSHG', # 证券ETF
  56. # '163119.XSHE', # 申万健康lof
  57. '512580.XSHG', # 环保etf
  58. '513500.XSHG', # 标普500
  59. # '513030.XSHG', # 德国30
  60. # '513880.XSHG' # 日经225
  61. ]
  62. #动量轮动参数
  63. g.stock_num = 1 #买入评分最高的前stock_num只股票
  64. g.momentum_day = 257 #最新动量参考最近momentum_day的
  65. #rsrs择时参数
  66. g.ref_stock = '000300.XSHG' #用ref_stock做择时计算的基础数据
  67. g.N = 17 # 计算最新斜率slope,拟合度r2参考最近N天
  68. g.M = 900 # 计算最新标准分zscore,rsrs_score参考最近M天
  69. g.score_threshold = 0.7 # rsrs标准分指标阈值
  70. #ma择时参数
  71. g.mean_day = 20 #计算结束ma收盘价,参考最近mean_day
  72. g.mean_diff_day = 3 #计算初始ma收盘价,参考(mean_day + mean_diff_day)天前,窗口为mean_diff_day的一段时间
  73. g.slope_series = initial_slope_series()[:-1] # 除去回测第一天的slope,避免运行时重复加入
  74. # 设置交易时间,每天运行
  75. run_daily(my_trade, time='11:30', reference_security='000300.XSHG')
  76. run_daily(check_lose, time='open', reference_security='000300.XSHG')
  77. run_daily(print_trade_info, time='15:30', reference_security='000300.XSHG')
  78. #1-1 选股模块-动量因子轮动
  79. #基于股票年化收益和判定系数打分,并按照分数从大到小排名
  80. def get_rank(context, stock_pool):
  81. score_list = []
  82. fund_list = g.fund_pool
  83. fund_list = filter_new_fund(context, g.fund_pool)
  84. for fund in fund_list:
  85. data = attribute_history(fund, g.momentum_day, '1d', ['close'])
  86. y = data['log'] = np.log(data.close)
  87. x = data['num'] = np.arange(data.log.size)
  88. slope, intercept = np.polyfit(x, y, 1)
  89. annualized_returns = math.pow(math.exp(slope), 250) - 1
  90. r_squared = 1 - (sum((y - (slope * x + intercept))**2) / ((len(y) - 1) * np.var(y, ddof=1)))
  91. score = annualized_returns * r_squared
  92. score_list.append(score)
  93. stock_dict=dict(zip(fund_list, score_list))
  94. sort_list=sorted(stock_dict.items(), key=lambda item:item[1], reverse=True) #True为降序
  95. code_list=[]
  96. for i in range((len(fund_list))):
  97. code_list.append(sort_list[i][0])
  98. rank_stock = code_list[0:g.stock_num]
  99. print(code_list[0:5])
  100. return rank_stock
  101. #2-1 择时模块-计算线性回归统计值
  102. #对输入的自变量每日最低价x(series)和因变量每日最高价y(series)建立OLS回归模型,返回元组(截距,斜率,拟合度)
  103. def get_ols(x, y):
  104. slope, intercept = np.polyfit(x, y, 1)
  105. r2 = 1 - (sum((y - (slope * x + intercept))**2) / ((len(y) - 1) * np.var(y, ddof=1)))
  106. return (intercept, slope, r2)
  107. #2-2 择时模块-设定初始斜率序列
  108. #通过前M日最高最低价的线性回归计算初始的斜率,返回斜率的列表
  109. def initial_slope_series():
  110. data = attribute_history(g.ref_stock, g.N + g.M, '1d', ['high', 'low'])
  111. return [get_ols(data.low[i:i+g.N], data.high[i:i+g.N])[1] for i in range(g.M)]
  112. #2-3 择时模块-计算标准分
  113. #通过斜率列表计算并返回截至回测结束日的最新标准分
  114. def get_zscore(slope_series):
  115. mean = np.mean(slope_series)
  116. std = np.std(slope_series)
  117. return (slope_series[-1] - mean) / std
  118. #2-4 择时模块-计算综合信号
  119. #1.获得rsrs与MA信号,rsrs信号算法参考优化说明,MA信号为一段时间两个端点的MA数值比较大小
  120. #2.信号同时为True时返回买入信号,同为False时返回卖出信号,其余情况返回持仓不变信号
  121. def get_timing_signal(stock):
  122. #计算MA信号
  123. close_data = attribute_history(g.ref_stock, g.mean_day + g.mean_diff_day, '1d', ['close'])
  124. today_MA = close_data.close[g.mean_diff_day:].mean()
  125. before_MA = close_data.close[:-g.mean_diff_day].mean()
  126. #计算rsrs信号
  127. high_low_data = attribute_history(g.ref_stock, g.N, '1d', ['high', 'low'])
  128. intercept, slope, r2 = get_ols(high_low_data.low, high_low_data.high)
  129. g.slope_series.append(slope)
  130. rsrs_score = get_zscore(g.slope_series[-g.M:]) * r2
  131. #综合判断所有信号
  132. if rsrs_score > g.score_threshold:# and today_MA > before_MA:
  133. print('BUY')
  134. return "BUY"
  135. elif rsrs_score < -g.score_threshold:# and today_MA < before_MA:
  136. print('SELL')
  137. return "SELL"
  138. else:
  139. print('KEEP')
  140. return "KEEP"
  141. #3-1 过滤模块-过滤停牌股票
  142. #输入选股列表,返回剔除停牌股票后的列表
  143. def filter_paused_stock(stock_list):
  144. current_data = get_current_data()
  145. return [stock for stock in stock_list if not current_data[stock].paused]
  146. #3-2 过滤模块-过滤ST及其他具有退市标签的股票
  147. #输入选股列表,返回剔除ST及其他具有退市标签股票后的列表
  148. def filter_st_stock(stock_list):
  149. current_data = get_current_data()
  150. return [stock for stock in stock_list
  151. if not current_data[stock].is_st
  152. and 'ST' not in current_data[stock].name
  153. and '*' not in current_data[stock].name
  154. and '退' not in current_data[stock].name]
  155. #3-3 过滤模块-过滤涨停的股票
  156. #输入选股列表,返回剔除未持有且已涨停股票后的列表
  157. def filter_limitup_stock(context, stock_list):
  158. last_prices = history(1, unit='1m', field='close', security_list=stock_list)
  159. current_data = get_current_data()
  160. # 已存在于持仓的股票即使涨停也不过滤,避免此股票再次可买,但因被过滤而导致选择别的股票
  161. return [stock for stock in stock_list if stock in context.portfolio.positions.keys()
  162. or last_prices[stock][-1] < current_data[stock].high_limit]
  163. #3-4 过滤模块-过滤跌停的股票
  164. #输入股票列表,返回剔除已跌停股票后的列表
  165. def filter_limitdown_stock(context, stock_list):
  166. last_prices = history(1, unit='1m', field='close', security_list=stock_list)
  167. current_data = get_current_data()
  168. return [stock for stock in stock_list if stock in context.portfolio.positions.keys()
  169. or last_prices[stock][-1] > current_data[stock].low_limit]
  170. #4-1 交易模块-自定义下单
  171. #报单成功返回报单(不代表一定会成交),否则返回None,应用于
  172. def order_target_value_(security, value):
  173. if value == 0:
  174. log.debug("Selling out %s" % (security))
  175. else:
  176. log.debug("Order %s to value %f" % (security, value))
  177. # 如果股票停牌,创建报单会失败,order_target_value 返回None
  178. # 如果股票涨跌停,创建报单会成功,order_target_value 返回Order,但是报单会取消
  179. # 部成部撤的报单,聚宽状态是已撤,此时成交量>0,可通过成交量判断是否有成交
  180. return order_target_value(security, value)
  181. #4-2 交易模块-开仓
  182. #买入指定价值的证券,报单成功并成交(包括全部成交或部分成交,此时成交量大于0)返回True,报单失败或者报单成功但被取消(此时成交量等于0),返回False
  183. def open_position(security, value):
  184. order = order_target_value_(security, value)
  185. print(order) # 查看订单的信息
  186. if order != None and order.filled > 0:
  187. return True
  188. return False
  189. #4-3 交易模块-平仓
  190. #卖出指定持仓,报单成功并全部成交返回True,报单失败或者报单成功但被取消(此时成交量等于0),或者报单非全部成交,返回False
  191. def close_position(position):
  192. security = position.security
  193. order = order_target_value_(security, 0) # 可能会因停牌失败
  194. if order != None:
  195. if order.status == OrderStatus.held and order.filled == order.amount:
  196. return True
  197. return False
  198. #4-4 交易模块-调仓
  199. #当择时信号为买入时开始调仓,输入过滤模块处理后的股票列表,执行交易模块中的开平仓操作
  200. def adjust_position(context, buy_stocks):
  201. for stock in context.portfolio.positions:
  202. if stock not in buy_stocks:
  203. log.info("[%s]已不在应买入列表中" % (stock))
  204. position = context.portfolio.positions[stock]
  205. close_position(position)
  206. else:
  207. log.info("[%s]已经持有无需重复买入" % (stock))
  208. # 根据股票数量分仓
  209. # 此处只根据可用金额平均分配购买,不能保证每个仓位平均分配
  210. position_count = len(context.portfolio.positions)
  211. if g.stock_num > position_count:
  212. value = context.portfolio.cash / (g.stock_num - position_count)
  213. for stock in buy_stocks:
  214. if context.portfolio.positions[stock].total_amount == 0:
  215. if open_position(stock, value):
  216. if len(context.portfolio.positions) == g.stock_num:
  217. break
  218. #4-5 交易模块-择时交易
  219. #结合择时模块综合信号进行交易
  220. def my_trade(context):
  221. #获取选股列表并过滤掉:st,st*,退市,涨停,跌停,停牌
  222. check_out_list = get_rank(context,g.fund_pool) # 获得排名
  223. # 感觉不需要这些,都只是对应股票的
  224. # check_out_list = filter_st_stock(check_out_list) # 去掉st
  225. # check_out_list = filter_limitup_stock(context, check_out_list) # 去掉涨停
  226. # check_out_list = filter_limitdown_stock(context, check_out_list) # 去掉跌停
  227. # check_out_list = filter_paused_stock(check_out_list) # 去掉停牌
  228. print('今日自选股:{}'.format(check_out_list))
  229. #获取综合择时信号
  230. timing_signal = get_timing_signal(g.ref_stock) # 判断买卖的信号
  231. print('今日择时信号:{}'.format(timing_signal))
  232. #开始交易
  233. if timing_signal == 'SELL':
  234. for stock in context.portfolio.positions:
  235. position = context.portfolio.positions[stock]
  236. close_position(position)
  237. elif timing_signal == 'BUY' or timing_signal == 'KEEP':
  238. adjust_position(context, check_out_list)
  239. else:
  240. pass
  241. #4-6 交易模块-止损
  242. #检查持仓并进行必要的止损操作
  243. def check_lose(context):
  244. for position in list(context.portfolio.positions.values()):
  245. securities=position.security
  246. cost=position.avg_cost
  247. price=position.price
  248. ret=100*(price/cost-1)
  249. value=position.value
  250. amount=position.total_amount
  251. #这里设定80%止损几乎等同不止损,因为止损在指数etf策略中影响不大
  252. if ret <=-80:
  253. order_target_value(position.security, 0)
  254. print("!!!!!!触发止损信号: 标的={},标的价值={},浮动盈亏={}% !!!!!!"
  255. .format(securities,format(value,'.2f'),format(ret,'.2f')))
  256. #5-1 复盘模块-打印
  257. #打印每日持仓信息
  258. def print_trade_info(context):
  259. #打印当天成交记录
  260. trades = get_trades()
  261. for _trade in trades.values():
  262. print('成交记录:'+str(_trade))
  263. #打印账户信息
  264. for position in list(context.portfolio.positions.values()):
  265. securities=position.security
  266. cost=position.avg_cost
  267. price=position.price
  268. ret=100*(price/cost-1)
  269. value=position.value
  270. amount=position.total_amount
  271. print('代码:{}'.format(securities))
  272. print('成本价:{}'.format(format(cost,'.2f')))
  273. print('现价:{}'.format(price))
  274. print('收益率:{}%'.format(format(ret,'.2f')))
  275. print('持仓(股):{}'.format(amount))
  276. print('市值:{}'.format(format(value,'.2f')))
  277. print('一天结束')
  278. print('———————————————————————————————————————分割线————————————————————————————————————————')
  279. # 过滤次新基金
  280. def filter_new_fund(context, fund_list):
  281. return [fund for fund in fund_list if (context.previous_date - datetime.timedelta(days=200)) > get_security_info(fund).start_date] #? 应该是按照300天在计算