3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在盘中交易中,板块轮动和动量追涨是捕捉市场热点、获取超额收益(Alpha)的有效手段。PTrade 平台提供了实盘专用的 get_sort_msg 函数,能够实时获取板块或行业的涨幅排名,以及板块内的领涨股票,方便投资者实现自动化的板块轮动策略。
get_sort_msg 函数简介get_sort_msg 函数主要用于交易模块中,可以按指定字段(如涨跌幅 px_change_rate、总成交额等)对特定类型的板块或行业进行实时排序,并返回排序后的列表及板块领涨/领跌股。
get_sort_msg(sort_type_grp=None, sort_field_name=None, sort_type=1, data_count=100)
sort_type_grp (str/list): 板块或行业组代码。常见分组包括:
'XBHS.HY': 行业板块'XBHS.GN': 概念板块'XBHS.DY': 地域板块'XBHS.ZJHHY': 证监会行业sort_field_name (str): 排序字段,例如:
'px_change_rate': 涨跌幅'business_balance': 总成交额'preclose_px': 昨日收盘价sort_type (int): 排序方式,1 表示降序(从大到小),0 表示升序。data_count (int): 返回的数据条数,默认 100。返回一个包含字典元素的列表,每个字典对应一个板块信息,关键字段包括:
prod_code: 板块代码prod_name: 板块名称px_change_rate: 板块涨跌幅rise_first_grp: 领涨股票列表(包含 prod_code、prod_name、last_px、px_change_rate 等)run_daily 或 run_interval 在盘中定期检查行业排名。get_sort_msg(sort_type_grp='XBHS.HY', sort_field_name='px_change_rate', sort_type=1) 提取涨幅排名第一的行业。rise_first_grp(领涨股)。order_value 或 order 调仓买入强停或领涨个股。以下策略演示如何在每日盘中(如 10:00)寻找涨幅第一的行业,并全仓买入该行业涨幅第一的领涨股:
def initialize(context):
# 允许在盘中运行,设置通用订阅,设置交易标的初值
g.security = '600570.SS'
set_universe(g.security)
# 设定盘中定时任务:每天 10:00 执行板块轮动逻辑
run_daily(context, sector_rotation, time='10:00')
def sector_rotation(context):
# 仅在实盘/模拟交易场景下执行(get_sort_msg 支持交易模块)
if not is_trade():
log.info("当前非交易环境,跳过实时板块排序查询。")
return
# 1. 获取行业板块按涨跌幅降序排列
sort_data = get_sort_msg(sort_type_grp='XBHS.HY', sort_field_name='px_change_rate', sort_type=1, data_count=10)
if not sort_data:
log.warning("未能获取到板块排序数据")
return
# 2. 获取排名第一的行业及其领涨股
top_sector = sort_data[0]
sector_name = top_sector.get('prod_name', '')
sector_pct = top_sector.get('px_change_rate', 0.0)
log.info("当前涨幅第一行业: %s, 涨跌幅: %.2f%%" % (sector_name, sector_pct))
rise_first_list = top_sector.get('rise_first_grp', [])
if not rise_first_list:
log.warning("该板块暂无领涨股票数据")
return
# 3. 提取领涨第一的股票代码
target_stock_code = rise_first_list[0].get('prod_code')
# PTrade 格式适配:6位代码补全后缀
if target_stock_code.startswith('6'):
target_security = target_stock_code + '.SS'
elif target_stock_code.startswith('0') or target_stock_code.startswith('3'):
target_security = target_stock_code + '.SZ'
else:
target_security = target_stock_code
log.info("拟买入行业领涨股: %s (%s)" % (rise_first_list[0].get('prod_name'), target_security))
# 4. 调仓逻辑:卖出非目标持仓,买入目标股票
current_positions = context.portfolio.positions
for sec in list(current_positions.keys()):
if sec != target_security and current_positions[sec].amount > 0:
order_target(sec, 0)
log.info("卖出非领涨股: %s" % sec)
# 5. 买入目标领涨股
cash = context.portfolio.cash
if cash > 2000:
order_value(target_security, cash)
log.info("买入领涨股 %s 成功" % target_security)
def handle_data(context, data):
pass
get_sort_msg 仅在 交易模块 可用,回测模块中不适用该接口。rise_first_grp 返回的 prod_code 为 6 位纯数字无后缀(如 '002105'),下单前需补充适配 .SS 或 .SZ 后缀。check_limit() 或 get_gear_price() 检查档位挂单,避免废单或高位追涨。