目录
上一篇用多因子策略回测后,发现回撤过大,增加止损策略。
-
策略逻辑
每个月选择归属母公司净利润增长率前五的股票,平掉掉出前五的,买入新增的,回撤超过10%,即平仓,先订阅每天的交易数据,事件驱动根据推送数据判断是否平仓。
-
增量代码
def init(context):
# 每月第一个交易日的09:40 定时执行algo任务
schedule(schedule_func=algo, date_rule='1m', time_rule='09:40:00')
# 数据滑窗
# context.date = 5
# 设置开仓的最大资金量
context.ratio = 0.8
# 沪深300 SHSE.000300,创业板指 SZSE.399006
context.index = "SHSE.000300"
context.num = 5
context.list =[]
subscribe(symbols= context.index, frequency='1d', count=2)
context.symbol="SHSE.000300"
# 默认回撤超过10%即止损
context.stop_loss = 0.1
context.high = 0
context.high_dict=dict()
def on_bar(context, bars):
for symbol in context.list:
try:
context.symbol=symbol
stop_loss(context)
except Exception as e:
print('stop_loss error',e)
# 止损策略
def stop_loss(context):
data = history_n(symbol=context.symbol, frequency='1d', end_time=context.now, fields='high,low,close', count=2, df=True)
price = data.close.values[-1]
# 获取现有持仓
pos = context.account().position(symbol=context.symbol, side=PositionSide_Long)
if not context.high_dict or (context.symbol not in context.high_dict):
context.high_dict[context.symbol]=price
return
high=context.high_dict[context.symbol]
if price > high:
context.high_dict[context.symbol] = price
elif (high - price) / high > context.stop_loss and pos:
print(context.now, context.symbol,'以市价单止损:',price,'high:',high)
context.high_dict.pop(context.symbol)
order_target_percent(symbol=context.symbol, percent=0, order_type=OrderType_Market,
position_side=PositionSide_Long)
# 查看最终的回测结果
def on_backtest_finished(context, indicator):
print(indicator)
-
回测结果
未加止损的回测:
加止损的回测:
-
结果分析
比较发现增加止损后,回撤几乎下降一半,实际上最终收益只增加了5%,回撤下降是因为无止损的原有收益更高,止损的效果有,但是不大。