@Channelchan
2018-01-11T06:06:23.000000Z
字数 4857
阅读 125802
import rqalphafrom rqalpha.api import *import talibdef init(context):context.s1 = "000001.XSHE"context.SHORTPERIOD = 10context.LONGPERIOD = 30context.stoplossmultipler= 0.98 #止损 乘数context.takepofitmultipler= 3 #止盈 乘数def handle_bar(context, bar_dict):entry_exit(context, bar_dict)stop_loss(context, bar_dict)def stop_loss(context,bar_dict):for stock in context.portfolio.positions:if bar_dict[stock].last<context.portfolio.positions[stock].avg_price*context.stoplossmultipler:# 现价低于 原价一定比例order_target_percent(stock,0)elif bar_dict[stock].last>context.portfolio.positions[stock].avg_price*context.takepofitmultipler:# 现价高于原价一定比例order_target_percent(stock,0)def entry_exit(context, bar_dict):prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')short_avg = talib.SMA(prices, context.SHORTPERIOD)long_avg = talib.SMA(prices, context.LONGPERIOD)cur_position = context.portfolio.positions[context.s1].quantityif short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:order_target_value(context.s1, 0)if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:order_target_percent(context.s1, 1)config = {"base": {"start_date": "2015-06-01","end_date": "2017-12-30","accounts": {'stock': 1000000},"benchmark": "000300.XSHG"# "strategy_file_path": os.path.abspath(__file__)},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

用字典存储股票最高价
stoploss_max = 允许最大回撤
if 现价<持股股票最高价*(1-stoploss_max):
卖出止损
else:
继续持有
import rqalphafrom rqalpha.api import *import talibdef init(context):context.s1 = "000001.XSHE"context.SHORTPERIOD = 10context.LONGPERIOD = 30context.stoploss_max= 0.4context.max = {}def handle_bar(context, bar_dict):entry_exit(context, bar_dict)stop_loss(context, bar_dict)def update_high(context, stock):high = history_bars(stock, 1, '1d', 'high')[0]try:Max = context.max[stock]except KeyError:Max = highcontext.max[stock] = highif high > Max:context.max[stock] = highreturn highelse:return Maxdef stop_loss(context,bar_dict):for stock in context.portfolio.positions.keys():high = update_high(context, stock)close = history_bars(stock, 1, '1d', 'close')[0]if close < high*(1-context.stoploss_max):order_target_percent(stock,0)context.max.pop(stock)def entry_exit(context, bar_dict):prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')short_avg = talib.SMA(prices, context.SHORTPERIOD)long_avg = talib.SMA(prices, context.LONGPERIOD)cur_position = context.portfolio.positions[context.s1].quantityif short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:order_target_value(context.s1, 0)if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:order_target_percent(context.s1, 1)config = {"base": {"start_date": "2015-06-01","end_date": "2017-12-30","accounts": {'stock':1000000},"benchmark": "000300.XSHG"# "strategy_file_path": os.path.abspath(__file__)},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

if 持股时间 >holdperiod and 周期内涨幅少于 total_return:
卖出止损
import rqalphafrom rqalpha.api import *import talib as tadef init(context):context.to_buy = "000001.XSHE"context.SHORTPERIOD = 10context.LONGPERIOD = 30context.time = []context.holdperiod = 60context.total_return=0.1def stop_loss( context,bar_dict):for stock in context.portfolio.positions:buytime=context.time # 获取买入时间currenttime=context.now.replace(tzinfo=None) # 获取当前时间# print ('buytime='+str(buytime))# print('currenttime='+str(currenttime))total_return=context.portfolio.positions[stock].market_value/(context.portfolio.positions[stock].avg_price*context.portfolio.positions[stock].quantity) # 计算回报hold_time=(currenttime-buytime).days # 计算持有天数if hold_time>context.holdperiod and total_return<1+context.total_return:order_target_percent(stock, 0)elif total_return>1+2*context.total_return:order_target_percent(stock, 0)# else:# print(str(stock)+ '持仓未到' +str(context.holdperiod)+'天,继续持有')def handle_bar(context, bar_dict):entry_exit(context, bar_dict)stop_loss(context, bar_dict)def entry_exit(context, bar_dict):prices = history_bars(context.to_buy, context.LONGPERIOD+1, '1d', 'close')short_avg = ta.SMA(prices, context.SHORTPERIOD)long_avg = ta.SMA(prices, context.LONGPERIOD)cur_position = context.portfolio.positions[context.to_buy].quantityshares = context.portfolio.cash/bar_dict[context.to_buy].closeif short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:order_target_value(context.to_buy, 0)if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:order_shares(context.to_buy, shares)#记录买入时间buy_time = context.now.replace(tzinfo=None)context.time = buy_timeconfig = {"base": {"start_date": "2015-06-01","end_date": "2017-12-30","accounts": {'stock': 100000},"benchmark": "000001.XSHE"# "strategy_file_path": os.path.abspath(__file__)},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)
