这个运行成功,但未检测到输出内容,有高手给指点一下吗?

用户头像hgh**c
2025-12-03 发布

这个运行成功,但未检测到输出内容,有高手给指点一下吗?

def initialize(context):
"""初始化策略参数"""

核心参数配置

context.hold_num = 5 # 目标持股数量
context.max_hold_days = 5 # 最大持股天数
context.profit_threshold = 1.09 # 盈利触发阈值(9%)
context.drawdown_threshold = 0.94 # 回撤止盈阈值(6%)
context.liquidity_threshold = 1000000# 流动性阈值(近20日平均成交量≥1000万)

持仓信息存储:key=股票代码,value=

context.position_info = {}

调仓频率:每日14:30执行(避开尾盘波动)

run_daily(handle_strategy, time='14:30')
def handle_strategy(context, data):
"""核心策略逻辑:先卖后买"""

步骤1:处理现有持仓的卖出条件

handle_sell(context, data)

步骤2:筛选符合条件的候选股票池

candidate_stocks = select_candidates(context, data)

步骤3:执行买入操作,补满持仓

handle_buy(context, data, candidate_stocks)
def handle_sell(context, data):
"""处理卖出逻辑:到期卖出+盈利回撤卖出"""
current_date = context.current_dt.date()
current_positions = list(context.portfolio.positions.keys())
sell_list = []

for stock in current_positions:
# 跳过停牌股(无法交易)
if data.is_suspended(stock):
continue

# 获取该股票的持仓记录
pos_info = context.position_info.get(stock)
if not pos_info:  # 异常情况:无持仓记录则强制卖出
    sell_list.append(stock)
    continue

# 提取关键数据
entry_price = pos_info['entry_price']
entry_date = pos_info['entry_date']
current_price = data.current(stock, 'close')

# 更新持仓期间的最大价格
if current_price > pos_info['max_price']:
    context.position_info[stock]['max_price'] = current_price
max_price = pos_info['max_price']

# 条件1:持股天数到期(自然日计算)
hold_days = (current_date - entry_date).days
if hold_days >= context.max_hold_days:
    sell_list.append(stock)
    log.info(f"股票{stock}持股到期({hold_days}天),执行卖出")
    continue

# 条件2:盈利9%后回撤6%
profit_reached = max_price >= entry_price * context.profit_threshold
drawdown_reached = current_price <= max_price * context.drawdown_threshold
if profit_reached and drawdown_reached:
    sell_list.append(stock)
    log.info(f"股票{stock}盈利回撤触发止盈:建仓价{entry_price:.2f},最大价{max_price:.2f},当前价{current_price:.2f}")
    continue

执行卖出操作(清仓)

for stock in sell_list:
order_target_percent(stock, 0)
if stock in context.position_info:
del context.position_info[stock]
def select_candidates(context, data):
"""筛选候选股票池:创业板+科创板+非风险股+小市值+高流动性"""

1. 筛选板块:创业板(300开头)+ 科创板(688开头)

all_stocks = get_all_securities(['stock'], context.current_dt)
target_board_stocks = [
stock for stock in all_stocks
if stock.startswith(('300', '688'))
]
if not target_board_stocks:
log.warning("无符合板块要求的股票")
return []

2. 基础风险过滤:非ST、非*ST、非退市、非停牌

关键修复:用续行符\明确换行,注释移到行尾且不干扰语法

valid_stocks = []
for stock in target_board_stocks:
if not data.is_st(stock) and
not data.is_delisted(stock) and
not data.is_suspended(stock): # 排除ST/*ST、退市股、停牌股
valid_stocks.append(stock)
if not valid_stocks:
log.warning("无符合基础风险要求的股票")
return []

3. 流动性过滤:近20日平均成交量≥1000万(避免流动性陷阱)

liquid_stocks = []
for stock in valid_stocks:
volume_history = data.get_attribute_history(stock, 'volume', 20, '1d')
if len(volume_history) < 20: # 确保有足够的历史数据
continue
avg_volume = volume_history['volume'].mean()
if avg_volume >= context.liquidity_threshold:
liquid_stocks.append(stock)
if not liquid_stocks:
log.warning("无符合流动性要求的股票")
return []

4. 小市值排序:按总市值从小到大筛选

查询基本面数据(总市值)

q = query(
fundamentals.eod_derivative_indicator.stockcode,
fundamentals.eod_derivative_indicator.total_market_cap
).filter(
fundamentals.eod_derivative_indicator.stockcode.in_(liquid_stocks)
)
market_cap_df = get_fundamentals(q, date=context.current_dt)
if market_cap_df.empty:
log.warning("无法获取市值数据")
return []

整理并按市值排序(从小到大)

market_cap_df = market_cap_df.set_index('stockcode').sort_values('total_market_cap')

5. 排除当前持仓股(避免重复持仓)

current_holdings = list(context.portfolio.positions.keys())
candidate_stocks = [
stock for stock in market_cap_df.index
if stock not in current_holdings
]

return candidate_stocks
def handle_buy(context, data, candidate_stocks):
"""执行买入操作:平均持仓,补满目标持股数"""
current_hold_num = len(context.portfolio.positions)
need_buy_num = context.hold_num - current_hold_num

if need_buy_num <= 0:
return # 已达目标持股数,无需买入

候选股不足时,按实际可用数量买入

buy_stocks_list = candidate_stocks[:need_buy_num]
if not buy_stocks_list:
log.warning("无可用候选股,无法完成买入")
return

平均持仓:每只股票仓位 = 1/目标持股数

position_percent = 1.0 / context.hold_num

for stock in buy_stocks_list:
# 再次验证股票状态(避免筛选后状态变化)
if data.is_suspended(stock) or data.is_st(stock) or data.is_delisted(stock):
continue

# 执行买入(按目标仓位下单)
order_target_percent(stock, position_percent)

# 记录持仓信息
entry_price = data.current(stock, 'close')
entry_date = context.current_dt.date()
context.position_info[stock] = {
    'entry_price': entry_price,
    'entry_date': entry_date,
    'max_price': entry_price  # 初始最大价格 = 建仓价
}
log.info(f"买入股票{stock}:建仓价{entry_price:.2f},仓位{position_percent:.1%}")

策略辅助函数:日志输出优化(可选)

def log_info(context, msg):
"""自定义日志输出格式"""
log_date = context.current_dt.strftime('%Y-%m-%d')
log.info(f"[{log_date}] {msg}")

评论

用户头像
2025-12-03 10:50:10
评论