[关闭]
@Channelchan 2018-01-24T19:26:20.000000Z 字数 1872 阅读 37088

指数对冲


利用价值因子选股后,在大盘低于MA30时,卖出一张股指期货作为对冲大盘风险。

  1. import numpy as np
  2. import talib as ta
  3. import pandas as pd
  4. import rqalpha
  5. from rqalpha.api import *
  6. from fxdayu_data import DataAPI
  7. from rqalpha.const import INSTRUMENT_TYPE
  8. def init(context):
  9. df = DataAPI.candle('000001.XSHE', 'D')
  10. df['MA_hedge'] = ta.abstract.DEMA(df, 4)
  11. context.df = df
  12. codes = pd.read_excel('factor.xlsx')
  13. context.codes = codes.set_index('date')
  14. def find_pool(context, date):
  15. codes = context.codes.loc[date]
  16. stocks = codes.index[codes == 1]
  17. return stocks
  18. def handle_bar(context, bar_dict):
  19. hedge(context)
  20. buy(context, bar_dict)
  21. def buy(context, bar_dict):
  22. try:
  23. pool = find_pool(context, context.now)
  24. except KeyError:
  25. return
  26. if pool is not None:
  27. stocks_len = len(pool)
  28. for stock in context.portfolio.positions:
  29. instrument = instruments(stock)
  30. if instrument.enum_type == INSTRUMENT_TYPE.FUTURE:
  31. continue
  32. if stock not in pool:
  33. order_target_percent(stock, 0)
  34. result = []
  35. try:
  36. for codes in pool:
  37. data_c = history_bars(codes, 25, '1d', 'close', adjust_type='post')
  38. ma = ta.MA(data_c, timeperiod=20)
  39. if len(ma) > 3 and context.df.close.loc[context.now] > context.df.MA_hedge.loc[context.now]:
  40. if ma[-1] > ma[-2] and ma[-2] > ma[-3] and codes not in result and codes not in context.portfolio.positions:
  41. result.append(codes)
  42. except KeyError:
  43. return
  44. if len(result):
  45. for r in result:
  46. order_target_percent(r, 1.0 / stocks_len)
  47. def hedge(context):
  48. for future in get_future_contracts("IF"):
  49. try:
  50. sell_qty = context.portfolio.positions[future].sell_quantity
  51. if context.df.close.loc[context.now] < context.df.MA_hedge.loc[context.now] and sell_qty == 0:
  52. sell_open(future, 1)
  53. if context.df.close.loc[context.now] > context.df.MA_hedge.loc[context.now] and sell_qty > 0:
  54. buy_close(future, 1)
  55. except KeyError:
  56. continue
  57. config = {
  58. "base": {
  59. "start_date": "2016-08-01",
  60. "end_date": "2017-08-01",
  61. "frequency": '1d',
  62. "accounts": {'stock':1000000, 'future':1000000},
  63. "benchmark": "000300.XSHG"
  64. },
  65. "extra": {
  66. "log_level": "verbose",
  67. },
  68. "mod": {
  69. "sys_analyser": {
  70. "enabled": True,
  71. "plot": True
  72. }
  73. }
  74. }
  75. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注