[关闭]
@Channelchan 2018-01-11T14:06:23.000000Z 字数 4857 阅读 125603

止损风控

  1. 固定止损
  2. 追踪止损
  3. 时间止损

1. 固定价位止损

  1. import rqalpha
  2. from rqalpha.api import *
  3. import talib
  4. def init(context):
  5. context.s1 = "000001.XSHE"
  6. context.SHORTPERIOD = 10
  7. context.LONGPERIOD = 30
  8. context.stoplossmultipler= 0.98 #止损 乘数
  9. context.takepofitmultipler= 3 #止盈 乘数
  10. def handle_bar(context, bar_dict):
  11. entry_exit(context, bar_dict)
  12. stop_loss(context, bar_dict)
  13. def stop_loss(context,bar_dict):
  14. for stock in context.portfolio.positions:
  15. if bar_dict[stock].last<context.portfolio.positions[stock].avg_price*context.stoplossmultipler:# 现价低于 原价一定比例
  16. order_target_percent(stock,0)
  17. elif bar_dict[stock].last>context.portfolio.positions[stock].avg_price*context.takepofitmultipler:# 现价高于原价一定比例
  18. order_target_percent(stock,0)
  19. def entry_exit(context, bar_dict):
  20. prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')
  21. short_avg = talib.SMA(prices, context.SHORTPERIOD)
  22. long_avg = talib.SMA(prices, context.LONGPERIOD)
  23. cur_position = context.portfolio.positions[context.s1].quantity
  24. if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:
  25. order_target_value(context.s1, 0)
  26. if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:
  27. order_target_percent(context.s1, 1)
  28. config = {
  29. "base": {
  30. "start_date": "2015-06-01",
  31. "end_date": "2017-12-30",
  32. "accounts": {'stock': 1000000},
  33. "benchmark": "000300.XSHG"
  34. # "strategy_file_path": os.path.abspath(__file__)
  35. },
  36. "extra": {
  37. "log_level": "error",
  38. },
  39. "mod": {
  40. "sys_analyser": {
  41. "enabled": True,
  42. "plot": True
  43. }
  44. }
  45. }
  46. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

output_1_0.png-66.1kB

2. 追踪止损

用字典存储股票最高价

stoploss_max = 允许最大回撤

if 现价<持股股票最高价*(1-stoploss_max):

卖出止损

else:

继续持有

  1. import rqalpha
  2. from rqalpha.api import *
  3. import talib
  4. def init(context):
  5. context.s1 = "000001.XSHE"
  6. context.SHORTPERIOD = 10
  7. context.LONGPERIOD = 30
  8. context.stoploss_max= 0.4
  9. context.max = {}
  10. def handle_bar(context, bar_dict):
  11. entry_exit(context, bar_dict)
  12. stop_loss(context, bar_dict)
  13. def update_high(context, stock):
  14. high = history_bars(stock, 1, '1d', 'high')[0]
  15. try:
  16. Max = context.max[stock]
  17. except KeyError:
  18. Max = high
  19. context.max[stock] = high
  20. if high > Max:
  21. context.max[stock] = high
  22. return high
  23. else:
  24. return Max
  25. def stop_loss(context,bar_dict):
  26. for stock in context.portfolio.positions.keys():
  27. high = update_high(context, stock)
  28. close = history_bars(stock, 1, '1d', 'close')[0]
  29. if close < high*(1-context.stoploss_max):
  30. order_target_percent(stock,0)
  31. context.max.pop(stock)
  32. def entry_exit(context, bar_dict):
  33. prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')
  34. short_avg = talib.SMA(prices, context.SHORTPERIOD)
  35. long_avg = talib.SMA(prices, context.LONGPERIOD)
  36. cur_position = context.portfolio.positions[context.s1].quantity
  37. if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:
  38. order_target_value(context.s1, 0)
  39. if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:
  40. order_target_percent(context.s1, 1)
  41. config = {
  42. "base": {
  43. "start_date": "2015-06-01",
  44. "end_date": "2017-12-30",
  45. "accounts": {'stock':1000000},
  46. "benchmark": "000300.XSHG"
  47. # "strategy_file_path": os.path.abspath(__file__)
  48. },
  49. "extra": {
  50. "log_level": "error",
  51. },
  52. "mod": {
  53. "sys_analyser": {
  54. "enabled": True,
  55. "plot": True
  56. }
  57. }
  58. }
  59. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

output_3_0.png-68.1kB

3. 时间止损

if 持股时间 >holdperiod and 周期内涨幅少于 total_return:

卖出止损

  1. import rqalpha
  2. from rqalpha.api import *
  3. import talib as ta
  4. def init(context):
  5. context.to_buy = "000001.XSHE"
  6. context.SHORTPERIOD = 10
  7. context.LONGPERIOD = 30
  8. context.time = []
  9. context.holdperiod = 60
  10. context.total_return=0.1
  11. def stop_loss( context,bar_dict):
  12. for stock in context.portfolio.positions:
  13. buytime=context.time # 获取买入时间
  14. currenttime=context.now.replace(tzinfo=None) # 获取当前时间
  15. # print ('buytime='+str(buytime))
  16. # print('currenttime='+str(currenttime))
  17. total_return=context.portfolio.positions[stock].market_value/(context.portfolio.positions[stock].avg_price*context.portfolio.positions[stock].quantity) # 计算回报
  18. hold_time=(currenttime-buytime).days # 计算持有天数
  19. if hold_time>context.holdperiod and total_return<1+context.total_return:
  20. order_target_percent(stock, 0)
  21. elif total_return>1+2*context.total_return:
  22. order_target_percent(stock, 0)
  23. # else:
  24. # print(str(stock)+ '持仓未到' +str(context.holdperiod)+'天,继续持有')
  25. def handle_bar(context, bar_dict):
  26. entry_exit(context, bar_dict)
  27. stop_loss(context, bar_dict)
  28. def entry_exit(context, bar_dict):
  29. prices = history_bars(context.to_buy, context.LONGPERIOD+1, '1d', 'close')
  30. short_avg = ta.SMA(prices, context.SHORTPERIOD)
  31. long_avg = ta.SMA(prices, context.LONGPERIOD)
  32. cur_position = context.portfolio.positions[context.to_buy].quantity
  33. shares = context.portfolio.cash/bar_dict[context.to_buy].close
  34. if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:
  35. order_target_value(context.to_buy, 0)
  36. if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:
  37. order_shares(context.to_buy, shares)
  38. #记录买入时间
  39. buy_time = context.now.replace(tzinfo=None)
  40. context.time = buy_time
  41. config = {
  42. "base": {
  43. "start_date": "2015-06-01",
  44. "end_date": "2017-12-30",
  45. "accounts": {'stock': 100000},
  46. "benchmark": "000001.XSHE"
  47. # "strategy_file_path": os.path.abspath(__file__)
  48. },
  49. "extra": {
  50. "log_level": "error",
  51. },
  52. "mod": {
  53. "sys_analyser": {
  54. "enabled": True,
  55. "plot": True
  56. }
  57. }
  58. }
  59. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

output_5_1.png-68.4kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注