模拟没有卖出信号
由aimarhu创建,最终由small_q 被浏览 77 用户
请问这个卖出是否哪里设置不对,用这个trade去跑回测是可以正常运行的 也会买入卖出,但是放到模拟里面 他只买入 不卖出
回测引擎:每日数据处理函数,每天执行一次
def bigquant_run(context, data):
# 按日期过滤得到今日的预测数据
ranker_prediction = context.ranker_prediction[
context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
#------------------------------------------止损模块START--------------------------------------------
date = data.current_dt.strftime('%Y-%m-%d')equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
# 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
current_stoploss_stock = []
if len(equities) > 0:
for i in equities.keys():
stock_market_price = data.current(context.symbol(i), 'price') # 最新市场价格
last_sale_date = equities[i].last_sale_date # 上次交易日期
delta_days = data.current_dt - last_sale_datehold_days = delta_days.days # 持仓天数
# 建仓以来的最高价
highest_price_since_buy = data.history(context.symbol(i), 'high', hold_days, '1d').max()
# 确定止损位置
stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.15
record('止损位置', stoploss_line)
# 如果价格下穿止损位置
if stock_market_price < stoploss_line:
context.order_target_percent(context.symbol(i), 0)current_stoploss_stock.append(i)
print('日期:', date , '股票:', i, '出现止损状况')
#-------------------------------------------止损模块END--------------------------------------------------
# 1. 资金分配
# 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
# 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
cash_avg = context.portfolio.portfolio_value
cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
positions = {e.symbol: p.amount * p.last_sale_price
for e, p in context.portfolio.positions.items()}
# 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
if not is_staging and cash_for_sell > 0:
equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
# print('rank order for sell %s' % instruments)
for instrument in instruments:
context.order_target(context.symbol(instrument), 0)
cash_for_sell -= positions[instrument]
if cash_for_sell <= 0:
break
# 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
buy_cash_weights = context.stock_weights
buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
for i, instrument in enumerate(buy_instruments):
cash = cash_for_buy * buy_cash_weights[i]
if cash > max_cash_per_instrument - positions.get(instrument, 0):
# 确保股票持仓量不会超过每次股票最大的占用资金量
cash = max_cash_per_instrument - positions.get(instrument, 0)
if cash > 0:
context.order_value(context.symbol(instrument), cash)
\