🚀 AI 一键生成 joinquant 策略代码
立即体验
👉 AI 生成代码 👈

JoinQuant聚宽API:如何获取昨日所有持仓标的价值?

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

问题描述

如何获取昨日所有标的价值

获取今日的标的价值是

context.portfolio.positions[stock].value
那么昨日的标的价值应该怎么写?

解决方案

在 JoinQuant (聚宽) 平台中,context.portfolio.positions 对象保存的是当前时刻的持仓快照。因此,API 并没有直接提供类似 context.portfolio.positions[stock].yesterday_value 的属性来直接获取昨日价值。

要获取昨日的标的价值,你需要通过**“昨日收盘价 × 昨日持仓数量”**来进行手动计算。

假设在今天开盘前或盘中尚未对该股票进行交易(即今天的持仓量等于昨天的持仓量),你可以通过以下代码获取昨日的标的价值:

实现代码

def get_yesterday_position_value(context, stock):
    # 1. 检查当前是否持有该股票
    if stock not in context.portfolio.positions:
        return 0.0
        
    # 2. 获取当前持仓数量(假设今日未交易,当前数量即为昨日收盘数量)
    amount = context.portfolio.positions[stock].total_amount
    
    # 3. 获取该股票昨日的收盘价
    # 使用 attribute_history 获取过去1天的日线数据,不包含今天
    hist = attribute_history(stock, 1, '1d', ['close'])
    if hist.empty:
        return 0.0
        
    yesterday_close = hist['close'][0]
    
    # 4. 计算昨日价值
    yesterday_value = amount * yesterday_close
    
    return yesterday_value

批量获取所有持仓的昨日价值

如果你想一次性获取账户中所有持仓标的的昨日总价值,可以遍历 positions 并结合 history 函数批量获取价格以提高运行效率:

def get_all_yesterday_values(context):
    # 获取当前所有持仓的股票代码列表
    stock_list = list(context.portfolio.positions.keys())
    if not stock_list:
        return {}
        
    # 批量获取这些股票昨日的收盘价
    # history 返回的 DataFrame 行是时间,列是股票代码
    hist_prices = history(1, '1d', 'close', stock_list)
    
    yesterday_values = {}
    for stock in stock_list:
        amount = context.portfolio.positions[stock].total_amount
        # 获取昨日收盘价
        yesterday_close = hist_prices[stock][0]
        # 计算并保存昨日价值
        yesterday_values[stock] = amount * yesterday_close
        
    return yesterday_values

注意事项

  1. 持仓变动:上述逻辑基于“今日未发生交易”的前提。如果你在盘中已经进行了买卖,context.portfolio.positions[stock].total_amount 已经是变动后的数量。如果需要严格意义上的“昨日收盘时的价值”,且盘中已有交易,你需要自己维护一个全局变量(如 g.yesterday_positions)在每天开盘前(before_trading_start)记录当时的持仓量。
  2. 复权问题attribute_historyhistory 默认返回前复权价格。如果开启了真实价格模式 (set_option('use_real_price', True)),计算出的价值是基于复权价格的理论价值,这在绝大多数策略逻辑中是适用且正确的。