: | : | :期货程序化 | :期货程序化研究 | :期货量化学习 | :期货量化 |
返回列表 发帖

量化交易策略—鳄鱼法则交易系统(2)

量化交易策略—鳄鱼法则交易系统(2)

关于交易系统的介绍和相关概念见上一篇:《量化交易策略—鳄鱼法则交易系统》

1.选股

    选择沪深300指数成分股;沉睡的鳄鱼(选择连续20交易日处于沉睡状态的股票,建立buy_stock池);每6个月更新股票池;benchmark沪深300指数。

2.入场

    存在有效碎形;有效碎形被突破;AO指标连续5日上行;AC指标连续3日上行;收盘价高于前一日收盘价;按g.amount=总资金/股票池股数×乘数因子3买入。

3.止损&止盈

    个股累计收益率(以成本价为基准)超过30%,全部卖出;
    个股累计收益率下跌10%,全部卖出;
    大盘3日累计收益率下跌3%,全部股票清仓。

4.加仓&减仓

    AO连续5日下跌,AC连续3日下跌减仓10%;AO连续5日上行,AC连续3日上行加仓10%。

5.退出

    存在有效向下碎形,向下碎形被突破,全部卖出。

收益风险



  1. t numpy as np
  2. def initialize(context):
  3.     g.up_price = {} #向上碎形最高价
  4.     g.low_price = {} #向下碎形最低价
  5.     g.up_fractal_exists = {} #判断有效向上碎形
  6.     g.down_fractal_exists = {} #判断有效向下碎形
  7.     g.AO_index = {} #存放连续的AO指标数据
  8.     g.cal_AC_index = {} #计算AC指标中转存储
  9.     g.AC_index = {} #存放连续的AC指标数据
  10.     g.amount = {} #满仓仓位
  11.     g.stock = get_index_stocks('000300.XSHG')
  12.     g.buy_stock = []
  13.     set_benchmark('000300.XSHG')
  14.     g.month = context.current_dt.month
  15.     run_monthly(select_universe,1,'open')

  16. #重置全局变量
  17. def reset_global():
  18.     g.up_price = {} #向上碎形最高价
  19.     g.low_price = {} #向下碎形最低价
  20.     g.up_fractal_exists = {} #判断有效向上碎形
  21.     g.down_fractal_exists = {} #判断有效向下碎形
  22.     g.AO_index = {} #存放连续的AO指标数据
  23.     g.cal_AC_index = {} #计算AC指标中转存储
  24.     g.AC_index = {} #存放连续的AC指标数据
  25.     g.amount = {} #满仓仓位
  26.     g.buy_stock = []

  27. def initial_stock_global(stock):
  28.     g.up_price[stock] = 0
  29.     g.low_price[stock] = 0
  30.     g.up_fractal_exists[stock] = False
  31.     g.down_fractal_exists[stock] = False #判断有效向下碎形
  32.     g.AO_index[stock] = [0] #存放连续的AO指标数据
  33.     g.cal_AC_index[stock] = [0]  #计算AC指标中转存储
  34.     g.AC_index[stock] = [0] #存放连续的AC指标数据
  35.     g.amount[stock] = 0 #满仓仓位

  36. #轮换选股后清空持仓
  37. def reset_position(context):
  38.     for stock in g.buy_stock:
  39.         order_target(stock,0)
  40.         log.info("sell %s for reset position"%stock)
  41. #选股
  42. def select_universe(context):
  43.     #每三个月操作一次
  44.     month = context.current_dt.month
  45.     if month%6 != g.month%6:
  46.         return
  47.     #清空全局变量
  48.     reset_position(context)
  49.     reset_global()
  50.     hist = history(30,'1d','close',g.stock,df = False)
  51.     for stock in g.stock:
  52.         if is_sleeping_alligator(stock,hist,20):
  53.             g.buy_stock.append(stock)
  54.             #初始化该股票全局变量
  55.             initial_stock_global(stock)
  56.     print g.buy_stock
  57.     return None

  58. #睡着的鳄鱼
  59. def is_sleeping_alligator(stock,hist,nday):
  60.     for i in range(nday):
  61.         if is_struggle(stock,hist,i) == False:
  62.             return False
  63.     return True

  64. #均线纠缠,BRG三线非常接近
  65. def is_struggle(stock,hist,delta):
  66.     blue_line = hist[stock][-21-delta:-8-delta].mean()
  67.     red_line = hist[stock][-13-delta:-5-delta].mean()
  68.     green_line = hist[stock][-8-delta:-3-delta].mean()
  69.     if abs(blue_line/red_line-1)<0.02 and abs(red_line/green_line-1)<0.02:
  70.         return True
  71.     else:
  72.         return False

  73. #判断 向上 或 向下 碎形
  74. def is_fractal(stock,direction):
  75.     hist = history(5,'1d',direction,[stock],df = False)
  76.     if direction == 'high'\
  77.     and hist[stock][2] > hist[stock][0]\
  78.     and hist[stock][2] > hist[stock][1]\
  79.     and hist[stock][2] > hist[stock][3]\
  80.     and hist[stock][2] > hist[stock][4]:
  81.         g.up_price[stock] = hist[stock][2]
  82.         return True
  83.     elif direction == 'low'\
  84.     and hist[stock][2] < hist[stock][0]\
  85.     and hist[stock][2] < hist[stock][1]\
  86.     and hist[stock][2] < hist[stock][3]\
  87.     and hist[stock][2] < hist[stock][4]:
  88.         g.low_price[stock] = hist[stock][2]
  89.         return True
  90.     return False

  91. #通过比较碎形与红线位置,判断碎形是否有效
  92. def is_effective_fractal(stock, direction):
  93.     if is_fractal(stock,direction):
  94.         hist = history(13,'1d','close',[stock],df = False)
  95.         red_line = hist[stock][:-5].mean()
  96.         close_price = hist[stock][-1]
  97.         if direction == 'high':
  98.             if close_price > red_line:
  99.                 g.up_fractal_exists[stock] = True
  100.             else:
  101.                 g.up_fractal_exists[stock] = False
  102.         elif direction == 'low':
  103.             if close_price < red_line:
  104.                 g.down_fractal_exists[stock] = True
  105.             else:
  106.                 g.down_fractal_exists[stock] = False

  107. #N日内最高价格的N日线
  108. def nday_high_point(stock,n):
  109.     hist = history(2*n,'1d','high',[stock],df = False)[stock]
  110.     high_point = []
  111.     for i in range(n):
  112.         high_point.append(max(hist[-5-i:-1-i]))
  113.     return np.array(high_point).mean()

  114. #N日内最低价格的N日线
  115. def nday_low_point(stock,n):
  116.     hist = history(2*n,'1d','low',[stock],df = False)[stock]
  117.     low_point = []
  118.     for i in range(n):
  119.         low_point.append(max(hist[-5-i:-1-i]))
  120.     return np.array(low_point).mean()

  121. #AO=5日内(最高-最低)/2的5日移动平均-34日内(最高-最低)/2的34日移动平均
  122. def AO_index(stock):
  123.     g.AO_index[stock].append(nday_high_point(stock,5)/2 + nday_low_point(stock,5)/2\
  124.                       - nday_high_point(stock,34)/2 - nday_low_point(stock,34)/2)
  125.     return None

  126. #AO-AO的5日平均值的5日平均
  127. def AC_index(stock):
  128.     AO_index(stock)
  129.     if len(g.AO_index[stock]) >= 5:
  130.         g.cal_AC_index[stock].append(g.AO_index[stock][-1] - np.array(g.AO_index[stock][-5:]).mean())
  131.         if len(g.cal_AC_index[stock]) >=5:
  132.             g.AC_index[stock].append(np.array(g.cal_AC_index[stock][-5:]).mean())

  133. #判断序列n日上行
  134. def is_up_going(alist,n):
  135.     if len(alist) < n:
  136.         return False
  137.     for i in range(n-1):
  138.         if alist[-(1+i)] <= alist[-(2+i)]:
  139.             return False
  140.     return True

  141. #判断序列n日下行
  142. def is_down_going(alist,n):
  143.     if len(alist) < n:
  144.         return False
  145.     for i in range(n-1):
  146.         if alist[-(1+i)] >= alist[-(2+i)]:
  147.             return False
  148.     return True

  149. #碎形被突破
  150. def active_fractal(stock,direction):
  151.     close_price = history(1,'1d','close',[stock],df=False)[stock][0]
  152.     if direction == 'up' and close_price > g.up_price[stock]:
  153.         return True
  154.     elif direction == 'down' and close_price < g.low_price[stock]:
  155.         return True
  156.     return False

  157. #进场,初始仓位
  158. def set_initial_position(stock,context):
  159.     close_price = history(1,'1d','close',[stock],df=False)[stock][0]
  160.     g.amount[stock] = context.portfolio.cash/close_price/len(g.buy_stock)*3
  161.     order(stock, g.amount[stock])
  162.     log.info("buying %s 股数为 %s"%(stock,g.amount[stock]))
  163.     g.down_fractal_exists[stock] = False

  164. #卖出
  165. def sell_all_stock(stock,context):
  166.     order_target(stock,0)
  167.     log.info("selling %s"%stock)
  168.     g.up_fractal_exists[stock] = False

  169. #加仓
  170. def adjust_position(stock,context,position):
  171.     order(stock,g.amount[stock]*position)
  172.     log.info("adjust position buying %s 股数为 %s"%(stock,g.amount[stock]*position))

  173. # 计算股票前n日收益率
  174. def security_return(days,security_code):
  175.     hist1 = attribute_history(security_code, days + 1, '1d', 'close',df=False)
  176.     security_returns = (hist1['close'][-1]-hist1['close'][0])/hist1['close'][0]
  177.     return security_returns

  178. # 止损,根据前n日收益率
  179. def conduct_nday_stoploss(context,security_code,days,bench):
  180.     if  security_return(days,security_code)<= bench:
  181.         for stock in g.buy_stock:
  182.             order_target_value(stock,0)
  183.             log.info("Sell %s for stoploss" %stock)
  184.         return True
  185.     else:
  186.         return False

  187. # 计算股票累计收益率(从建仓至今)
  188. def security_accumulate_return(context,data,stock):
  189.     current_price = data[stock].price
  190.     cost = context.portfolio.positions[stock].avg_cost
  191.     if cost != 0:
  192.         return (current_price-cost)/cost
  193.     else:
  194.         return None

  195. # 个股止损,根据累计收益
  196. def conduct_accumulate_stoploss(context,data,stock,bench):
  197.     if security_accumulate_return(context,data,stock) != None\
  198.     and security_accumulate_return(context,data,stock) < bench:
  199.         order_target_value(stock,0)
  200.         log.info("Sell %s for stoploss" %stock)
  201.         return True
  202.     else:
  203.         return False

  204. # 个股止盈,根据累计收益
  205. def conduct_accumulate_stopwin(context,data,stock,bench):
  206.     if security_accumulate_return(context,data,stock) != None\
  207.     and security_accumulate_return(context,data,stock) > bench:
  208.         order_target_value(stock,0)
  209.         log.info("Sell %s for stopwin" %stock)
  210.         return True
  211.     else:
  212.         return False

  213. def handle_data(context,data):
  214.     #大盘止损
  215.     if conduct_nday_stoploss(context,'000300.XSHG',3,-0.03):
  216.         return
  217.     for stock in g.buy_stock:
  218.         #个股止损
  219.         if conduct_accumulate_stopwin(context,data,stock,0.3)\
  220.         or conduct_accumulate_stoploss(context,data,stock,-0.1):
  221.             return
  222.         #计算AO,AC指标
  223.         AC_index(stock)
  224.         #空仓时,寻找机会入场
  225.         if context.portfolio.positions[stock].amount == 0:
  226.             #计算向上碎形
  227.             is_effective_fractal(stock,'high')
  228.             #有效向上碎形存在,并被突破,买入
  229.             if g.up_fractal_exists and active_fractal(stock,'up'):
  230.                 close_price = history(5, '1d', 'close', [stock],df = False)
  231.                 if is_up_going(g.AO_index[stock],5)\
  232.                 and is_up_going(g.AC_index[stock],3)\
  233.                 and is_up_going(close_price[stock],2):
  234.                     set_initial_position(stock,context)
  235.         #有持仓时,加仓或离场
  236.         else:
  237.             #计算向下碎形
  238.             is_effective_fractal(stock,'low')
  239.             #出场条件1:有效向下碎形存在,并被突破,卖出
  240.             if g.down_fractal_exists and active_fractal(stock,'down'):
  241.                 sell_all_stock(stock,context)
  242.                 return
  243.             #出场条件2:
  244.             #加仓10%:AO,AC同时5日上行,且收盘价走高
  245.             # if is_up_going(g.AO_index[stock],5)\
  246.             # and is_up_going(g.AC_index[stock],3)\
  247.             # and is_up_going(close_price[stock],2):
  248.             #     adjust_position(stock,context,0.1)
  249.             # #减仓10%:AO,AC同时3日下行,且收盘价走低
  250.             # if is_down_going(g.AO_index[stock],5)\
  251.             # and is_down_going(g.AC_index[stock],3)\
  252.             # and is_down_going(close_price[stock],2):
  253.             #     adjust_position(stock,context,-0.1)
复制代码


论坛官方微信、群(期货热点、量化探讨、开户与绑定实盘)
 
期货论坛 - 版权/免责声明   1.本站发布源码(包括函数、指标、策略等)均属开放源码,用意在于让使用者学习程序化语法撰写,使用者可以任意修改语法內容并调整参数。仅限用于个人学习使用,请勿转载、滥用,严禁私自连接实盘账户交易
  2.本站发布资讯(包括文章、视频、历史记录、教材、评论、资讯、交易方案等)均系转载自网络主流媒体,内容仅为作者当日个人观点,本网转载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。本网不对该类信息或数据做任何保证。不对您构成任何投资建议,不能依靠信息而取代自身独立判断,不对因使用本篇文章所诉信息或观点等导致的损失承担任何责任。
  3.本站发布资源(包括书籍、杂志、文档、软件等)均从互联网搜索而来,仅供个人免费交流学习,不可用作商业用途,本站不对显示的内容承担任何责任。请在下载后24小时内删除。如果喜欢,请购买正版,谢谢合作!
  4.龙听期货论坛原创文章属本网版权作品,转载须注明来源“龙听期货论坛”,违者本网将保留追究其相关法律责任的权力。本论坛除发布原创文章外,亦致力于优秀财经文章的交流分享,部分文章推送时若未能及时与原作者取得联系并涉及版权问题时,请及时联系删除。联系方式:http://www.qhlt.cn/thread-262-1-1.html
如何访问权限为100/255贴子:/thread-37840-1-1.html;注册后仍无法回复:/thread-23-1-1.html;微信/QQ群:/thread-262-1-1.html;网盘链接失效解决办法:/thread-93307-1-1.html

学习了

TOP

返回列表