3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在量化投资中,机构持仓变动(如十大股东/十大流通股东的增减持)通常代表了基本面与主力资金的偏好,而热门板块则代表了市场当下的资金关注度与流动性。将两者结合,可以筛选出“既有资金底仓支持、又有短期动能”的优质标的。
本文将指导您如何在 QMT 平台中使用 Python API 编写一个结合十大股东变动与热门板块成分股的事件驱动动态选股模型。
沪深300、行业板块或自定义板块)的成分股列表。changNum > 0)的股票。set_universe)。ContextInfo.get_stock_list_in_sector(sectorname, realtime):获取指定板块在特定时间点的成分股代码列表。ContextInfo.get_top10_share_holder(stock_list, data_name, start_time, end_time):获取股票的十大股东/十大流通股东数据。返回 DataFrame 或 Series。
data_name: 'flow_holder' (流通股东) 或 'holder' (股东)。ContextInfo.set_universe(stocklist):动态更新策略运行的股票池。passorder(...) / order_shares(...):执行下单交易。#encoding:gbk
import pandas as pd
import datetime
def init(ContextInfo):
# 1. 设定资金账号
ContextInfo.account = '60000001'
ContextInfo.set_account(ContextInfo.account)
# 2. 全局参数设置
ContextInfo.target_sector = '沪深300' # 目标观察板块
ContextInfo.selected_stocks = [] # 筛选出的股票池
# 3. 设置定时器:每月或开盘时执行一次选股逻辑(此处示例在init中初始化选股)
filter_stocks(ContextInfo)
def filter_stocks(ContextInfo):
"""
事件驱动选股逻辑:结合板块成分股与十大股东增持事件
"""
# 获取当前 bar 的毫秒时间戳
timetag = ContextInfo.get_bar_timetag(ContextInfo.barpos) if ContextInfo.barpos >= 0 else int(datetime.datetime.now().timestamp() * 1000)
# 1. 获取目标板块的成分股
sector_stocks = ContextInfo.get_stock_list_in_sector(ContextInfo.target_sector, timetag)
if not sector_stocks:
print(f"未获取到板块 [{ContextInfo.target_sector}] 的成分股")
return
print(f"板块 [{ContextInfo.target_sector}] 共包含 {len(sector_stocks)} 只股票,开始筛选十大股东增持事件...")
# 2. 查询最近一年的十大流通股东数据
now = datetime.datetime.now()
start_date = (now - datetime.timedelta(days=365)).strftime('%Y%m%d')
end_date = now.strftime('%Y%m%d')
filtered_pool = []
# 获取十大流通股东变动
holder_data = ContextInfo.get_top10_share_holder(sector_stocks, 'flow_holder', start_date, end_date)
for stock in sector_stocks:
try:
# 判断返回数据类型并提取该股票的股东数据
if isinstance(holder_data, dict) and stock in holder_data:
df = holder_data[stock]
elif isinstance(holder_data, pd.DataFrame):
df = holder_data[holder_data['stockCode'] == stock] if 'stockCode' in holder_data.columns else pd.DataFrame()
else:
continue
if df.empty or 'changNum' not in df.columns:
continue
# 筛选最近一次财报中有股东增持(changNum > 0)的记录
recent_increase = df[df['changNum'] > 0]
if not recent_increase.empty:
filtered_pool.append(stock)
except Exception as e:
continue
print(f"筛选完成!符合机构增持事件的股票共 {len(filtered_pool)} 只: {filtered_pool}")
# 3. 动态更新策略股票池
ContextInfo.selected_stocks = filtered_pool
ContextInfo.set_universe(filtered_pool)
def handlebar(ContextInfo):
"""
K线驱动函数:执行买入与持仓管理
"""
# 仅在最后一根 Bar 或确定信号时进行交易操作
if not ContextInfo.is_last_bar():
return
if not ContextInfo.selected_stocks:
print("当前股票池为空,暂不交易")
return
# 简易交易示例:对筛选出的股票等权重买入
target_num = len(ContextInfo.selected_stocks)
weight = 1.0 / target_num if target_num > 0 else 0
for stock in ContextInfo.selected_stocks:
# 检查是否停牌
if ContextInfo.is_suspended_stock(stock):
continue
# 使用目标比例下单函数买入(例如占总资产的指定比例)
order_target_percent(stock, weight * 0.8, 'LATEST', ContextInfo, ContextInfo.account)
print(f"对股票 {stock} 下单,目标仓位占比: {weight * 0.8:.2%}")
ContextInfo.run_time() 定时器或按月/季运行选股逻辑。ContextInfo.get_factor_data(),加入估值(PE/PB)、动量指标(RSI/MACD)进行二次过滤,提升策略胜率。