🚀 AI 一键生成 joinquant 策略代码

JoinQuant 聚宽策略中如何正确获取前一日收盘价?

joinquant | 发布时间: 2026/5/21
以下内容由 EasyQuant 生成。

问题描述

data[security].price取值问题

回测数据和实际对不上,看了半天,用日志打出来,发现是current_price = data[security].price取值问题,我以为取得是前一日的收盘价,但是看来取得的是前一日的收盘均价,不知道应该怎么取得前一日的收盘价?

解决方案

在 JoinQuant (聚宽) 平台中,data[security].price 确实不是前一日的收盘价。根据官方 API 文档说明,price 属性已经过时,为了向前兼容,它等同于 avg,即这段时间的平均价(天级别为成交额除以成交量)。

如果您想要获取前一日的收盘价,有以下几种常用的正确方法:

方法一:使用 data[security].pre_close (最简单直接)

handle_data 函数中,data 对象包含了当前单位时间的前一个单位时间的数据。您可以直接使用 pre_close 属性来获取前一日的收盘价。

def handle_data(context, data):
    security = '000001.XSHE'
    # 获取前一日的收盘价
    prev_close = data[security].pre_close
    log.info("前一日收盘价为: %s" % prev_close)

方法二:使用 attribute_history 函数

如果您不仅需要前一日的收盘价,还需要过去几天的收盘价,可以使用 attribute_history 函数。它专门用于获取单只股票的历史属性数据。

def handle_data(context, data):
    security = '000001.XSHE'
    # 获取过去 1 天的收盘价数据
    close_data = attribute_history(security, 1, '1d', ['close'])
    # 取得前一日收盘价
    prev_close = close_data['close'][-1]
    log.info("前一日收盘价为: %s" % prev_close)

方法三:使用 history 函数

如果您需要同时获取多只股票的前一日收盘价,使用 history 函数会更加高效。

def handle_data(context, data):
    securities = ['000001.XSHE', '000002.XSHE']
    # 获取多只股票过去 1 天的收盘价
    h_data = history(1, '1d', 'close', securities)
    
    prev_close_1 = h_data['000001.XSHE'][-1]
    prev_close_2 = h_data['000002.XSHE'][-1]
    
    log.info("平安银行前一日收盘价: %s, 万科A前一日收盘价: %s" % (prev_close_1, prev_close_2))

总结与建议

  • 避免使用 data[security].price:因为它实际上返回的是均价(avg),容易引起逻辑混淆。
  • 获取昨日收盘价:推荐直接使用 data[security].pre_close,代码最简洁。
  • 获取历史多日数据:推荐使用 attribute_history(单标的)或 history(多标的)。

另外,请注意复权设置。如果您在 initialize 中设置了 set_option('use_real_price', True),通过上述 API 获取到的历史价格默认是前复权价格,这在计算涨跌幅和均线时是正确的做法。