3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在可转债交易中,临近到期日或面临强制赎回时,如果未及时转股或卖出,投资者可能会面临巨大的价格回撤或无谓的损失。因此,在量化策略中加入临期债提前强平风控至关重要。
在 ptrade 平台中,我们可以通过 get_cb_info() 接口获取所有可转债的到期日(maturity_date),并结合当前交易日期进行比对,当距离到期日不足设定天数(例如 15 天)时,自动对该转债进行一键清仓。
get_cb_info():获取可转债基础信息,返回的 DataFrame 中包含 bond_code(可转债代码)和 maturity_date(到期日,格式通常为 'YYYY-MM-DD')。get_position(security):获取当前标的的持仓信息,通过 amount 判断是否持有该转债。order_target(security, 0):将目标标的持仓调整为 0,实现自动清仓。以下是一个完整的 ptrade 策略示例,策略在每天盘前(before_trading_start)扫描持仓中的可转债,计算其距离到期日的天数,并在盘中(handle_data)对临期转债执行自动清仓。
import datetime
def initialize(context):
# 设置初始股票池(可包含您关注的转债或股票)
g.security = ['110033.SS', '123002.SZ']
set_universe(g.security)
# 风控参数:提前多少天必须清仓
g.risk_days_limit = 15
# 记录需要强平的临期债列表
g.bonds_to_liquidate = []
def before_trading_start(context, data):
"""
盘前处理:获取可转债基础信息,筛选出临近到期的持仓转债
"""
g.bonds_to_liquidate = []
# 获取当前账户的所有持仓代码
current_positions = list(context.portfolio.positions.keys())
if not current_positions:
return
# 获取可转债基础信息表
cb_df = get_cb_info()
if cb_df.empty:
log.warning("无法获取可转债基础信息,跳过今日风控扫描")
return
# 获取当前回测/交易日期
current_date = context.blotter.current_dt.date()
# 遍历持仓,检查是否有临期转债
for security in current_positions:
# 兼容代码格式,提取纯数字代码或匹配前缀
raw_code = security.split('.')[0]
# 在可转债信息中匹配该持仓
bond_info = cb_df[cb_df['bond_code'] == raw_code]
if not bond_info.empty:
maturity_date_str = bond_info.iloc[0]['maturity_date']
try:
# 将到期日字符串转换为 date 对象
maturity_date = datetime.datetime.strptime(maturity_date_str, '%Y-%m-%d').date()
# 计算距离到期的剩余天数
days_left = (maturity_date - current_date).days
log.info("持仓转债 %s 距离到期日 %s 还有 %d 天" % (security, maturity_date_str, days_left))
# 如果剩余天数小于或等于设定的风控天数,加入强平名单
if days_left <= g.risk_days_limit:
g.bonds_to_liquidate.append(security)
log.warning("【风控预警】转债 %s 触发临期强平阈值(<= %d 天),今日将执行清仓!" % (security, g.risk_days_limit))
except Exception as e:
log.error("解析转债 %s 到期日出错: %s" % (security, str(e)))
def handle_data(context, data):
"""
盘中处理:对触发风控的临期转债执行清仓
"""
if g.bonds_to_liquidate:
for security in g.bonds_to_liquidate:
pos = get_position(security)
if pos.amount > 0:
log.warning("【风控执行】正在强平临期可转债: %s, 当前持仓: %d" % (security, pos.amount))
# 卖出所有股票/转债,使最终持有量为 0
order_target(security, 0)
9:10 后的 before_trading_start 阶段运行。通过 get_cb_info() 获取全市场转债的最新到期日,避免了手动维护到期日列表的繁琐工作。(maturity_date - current_date).days 动态计算每日剩余天数,不受回测或实盘时间轴变化的干扰。handle_data 中使用 order_target(security, 0)。该接口会自动计算当前可用持仓并一次性申报卖出,确保临期债能够安全、快速地变现避险。