3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 ptrade 量化交易平台中,order_target、order_value 和 order_target_value 等高级下单函数确实不支持国债逆回购交易。要实现逆回购的“全仓卖出”(即把账户所有可用资金用于参与逆回购),你需要手动计算可用资金所能购买的逆回购数量,并使用基础的 order 函数进行下单。
context.portfolio.cash 获取当前账户的可用资金。以下是一个在每天尾盘自动将所有可用资金进行深市 1 天期国债逆回购(131810.SZ)的策略示例:
def initialize(context):
# 设置逆回购标的,例如深市1天期逆回购
g.security = '131810.SZ'
set_universe(g.security)
# 设定每天 14:50 执行逆回购操作(交易场景下时间可根据券商配置调整)
run_daily(context, reverse_repo_all_cash, time='14:50')
def reverse_repo_all_cash(context):
# 1. 获取当前可用资金
available_cash = context.portfolio.cash
# 2. 计算可以申购的张数
# 逆回购面值100元/张,10张起步,必须是10的整数倍
# 计算最大可买张数
max_amount = int(available_cash / 100)
# 向下取整到10的倍数
trade_amount = (max_amount // 10) * 10
# 3. 判断是否满足最低申购门槛(10张)
if trade_amount >= 10:
# 逆回购委托方向为卖出,amount 必须为负数
order(g.security, -trade_amount)
log.info(f"全仓卖出逆回购 {g.security},数量:{-trade_amount}张,占用资金约:{trade_amount * 100}元")
else:
log.info(f"可用资金不足1000元,无法参与逆回购。当前可用资金:{available_cash}元")
def handle_data(context, data):
pass
order 函数中,逆回购的 amount 必须传入负数(例如 -10 表示卖出 10 张)。trade_amount 小于 10,会导致委托失败,因此必须进行 >= 10 的判断。limit_price,系统会默认使用行情快照的最新价(即当前的年化收益率)进行报单。如果需要指定收益率,可以传入 limit_price 参数(例如 limit_price=2.5)。