@烟花三月ETF 楼主这是已经******了是么。我还在跑模拟。^_^
我找代码在聚宽里跑了下你说的这个卖一和买一价的思路,感觉tick级的回测偏离比较少,分钟级的回测会有一些偏离。仅供参考。
# 导入聚宽函数库
import jqdata
def initialize(context):
# 设置我们要验证的标的,例如平安银行
g.security = '000001.XSHE'
# 设置基准
set_benchmark('000300.XSHG')
# 开启动态复权模式 (真实价格)
set_option('use_real_price', True)
# 【关键设置】将系统的默认滑点设置为 0!
# 聚宽默认有 0.00246 的滑点来模拟真实交易摩擦。
# 为了纯粹验证撮合价格,我们先把它关掉,否则成交价会被人为加减。
set_slippage(FixedSlippage(0))
# 设定每天 10:00 模拟买入,14:00 模拟卖出
run_daily(simulate_buy, time='10:00')
run_daily(simulate_sell, time='14:00')
def simulate_buy(context):
current_dt = context.current_dt
# 1. 获取买入瞬间的真实 Tick 数据
ticks = get_ticks(g.security, end_dt=current_dt, count=1, fields=['time', 'current', 'a1_p', 'b1_p'])
if len(ticks) > 0:
tick = ticks[0]
tick_a1 = tick['a1_p'] # 卖一价 (市价买入理论上应该吃掉卖一)
tick_b1 = tick['b1_p'] # 买一价
tick_current = tick['current']
# 2. 执行市价买入 100 股
order_obj = order(g.security, 100)
# 3. 验证与对比
if order_obj is not None and order_obj.filled > 0:
deal_price = order_obj.price # 获取真实的成交均价
log.info(f"========== 【买入验证】 时间: {current_dt} ==========")
log.info(f"抓取瞬间盘口 -> 卖1价(应买价): {tick_a1}, 买1价: {tick_b1}, 最新成交价: {tick_current}")
log.info(f"系统实际买入成交价: {deal_price}")
if deal_price == tick_a1:
log.info("✅ 结论:买入价格 严格等于 【卖1价】")
if deal_price == tick_current:
log.info("⚠️ 结论:买入价格 等于 【最新成交价】 (分钟回测的常见机制)")
if deal_price != tick_a1 and deal_price != tick_current :
log.info(f"❌ 结论:买入价格 ({deal_price}) 与卖1价 ({tick_a1}) 不符。可能是因为使用了分钟K线开/收盘价撮合。")
print("-" * 50)
def simulate_sell(context):
current_dt = context.current_dt
# 1. 获取卖出瞬间的真实 Tick 数据
ticks = get_ticks(g.security, end_dt=current_dt, count=1, fields=['time', 'current', 'a1_p', 'b1_p'])
if len(ticks) > 0:
tick = ticks[0]
tick_a1 = tick['a1_p']
tick_b1 = tick['b1_p'] # 买一价 (市价卖出理论上应该砸给买一)
tick_current = tick['current']
# 2. 执行市价卖出 100 股
order_obj = order(g.security, -100)
# 3. 验证与对比
if order_obj is not None and order_obj.filled > 0:
deal_price = order_obj.price # 获取真实的成交均价
log.info(f"========== 【卖出验证】 时间: {current_dt} ==========")
log.info(f"抓取瞬间盘口 -> 卖1价: {tick_a1}, 买1价(应卖价): {tick_b1}, 最新成交价: {tick_current}")
log.info(f"系统实际卖出成交价: {deal_price}")
if deal_price == tick_b1:
log.info("✅ 结论:卖出价格 严格等于 【买1价】")
if deal_price == tick_current:
log.info("⚠️ 结论:卖出价格 等于 【最新成交价】 (分钟回测的常见机制)")
if deal_price != tick_b1 and deal_price != tick_current :
log.info(f"❌ 结论:卖出价格 ({deal_price}) 与买1价 ({tick_b1}) 不符。")
print("-" * 50)
16天前