3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 PTrade 融资融券(两融)量化交易中,融券卖出与买券还券是实现空头策略或对冲交易的核心操作。本文将详细介绍核心 API 的参数用法,并提供一个完整的双均线空头交易策略源码。
marginsec_open用于融券卖出指定数量的股票建立空头头寸。
marginsec_open(security, amount, limit_price=None)security (str):股票代码,如 '600030.SS'amount (int):融券卖出数量,需为正整数(必须为100的整数倍)limit_price (float, 可选):委托限价,若不传则默认取当前最新价委托order_id)或 Nonemarginsec_close用于买入股票以偿还融券负债。
marginsec_close(security, amount, limit_price=None)security (str):股票代码amount (int):买券还券数量,需为正整数limit_price (float, 可选):委托限价,若不传则默认取当前最新价委托order_id)或 Noneget_marginsec_stocks用于获取上交所、深交所最新披露的可融券标的列表,避免对非融券标的下单导致报单失败。
以下策略展示了当短期均线(5日)下穿长期均线(10日)时触发融券卖出,当短期均线上穿长期均线时触发买券还券的完整逻辑:
import pandas as pd
def initialize(context):
# 设置标的(需为两融标的,如中信证券)
g.security = '600030.SS'
set_universe(g.security)
# 交易标识
g.short_opened = False
def before_trading_start(context, data):
# 盘前检查标的是否在可融券列表中
marginsec_stocks = get_marginsec_stocks()
if g.security not in marginsec_stocks:
log.warning("标的 %s 当前不在可融券列表中!" % g.security)
def handle_data(context, data):
security = g.security
# 获取过去10天的日线收盘价
df = get_history(10, '1d', 'close', security, fq=None, include=False)
if df is None or len(df) < 10:
return
# 计算5日与10日均线
ma5 = round(df['close'][-5:].mean(), 3)
ma10 = round(df['close'][-10:].mean(), 3)
# 获取当前持仓对象
pos = get_position(security)
# 死叉(5日线下穿10日线):融券卖出开空
if ma5 < ma10 and not g.short_opened:
# 假设每次融券卖出1000股
order_amount = 1000
order_id = marginsec_open(security, order_amount)
if order_id:
log.info("触发死叉,融券卖出开仓 %s 数量: %d" % (security, order_amount))
g.short_opened = True
# 金叉(5日线上穿10日线):买券还券平空
elif ma5 > ma10 and g.short_opened:
# 针对当前持仓进行还券(或使用固定数量)
order_amount = 1000
order_id = marginsec_close(security, order_amount)
if order_id:
log.info("触发金叉,买券还券平仓 %s 数量: %d" % (security, order_amount))
g.short_opened = False
marginsec_open 和 marginsec_close 仅支持 PTrade 客户端环境下的两融实盘/模拟盘模块,普通股票账户不可用。marginsec_open 和 marginsec_close 的 amount 参数必须为正整数。