hsliuping/TradingAgents-CN · error · ValueError

股票代码必须是6位数字

Error message

股票代码必须是6位数字

What it means

A Pydantic validator on the StockBaseModel.symbol field requires the symbol to be exactly 6 numeric digits (Chinese A-share style, e.g. '600519'). Any value failing v.isdigit() or len(v) != 6 causes pydantic.ValidationError wrapping this ValueError at model instantiation. This enforces the A-share symbol convention before data enters the pipeline.

Source

Thrown at tradingagents/models/stock_data_models.py:95

    board: str = Field(..., description="板块")
    industry: str = Field(..., description="行业")
    industry_code: Optional[str] = Field(None, description="行业代码")
    sector: str = Field(..., description="所属板块")
    list_date: date = Field(..., description="上市日期")
    delist_date: Optional[date] = Field(None, description="退市日期")
    area: str = Field(..., description="所在地区")
    market_cap: Optional[float] = Field(None, description="总市值")
    float_cap: Optional[float] = Field(None, description="流通市值")
    total_shares: Optional[float] = Field(None, description="总股本")
    float_shares: Optional[float] = Field(None, description="流通股本")
    currency: str = Field(default="CNY", description="交易货币")
    status: StockStatus = Field(default=StockStatus.LISTED, description="上市状态")
    is_hs: bool = Field(default=False, description="是否沪深港通标的")

    @validator('symbol')
    def validate_symbol(cls, v):
        if not v.isdigit() or len(v) != 6:
            raise ValueError('股票代码必须是6位数字')
        return v


class StockDailyQuote(BaseStockModel):
    """股票日线行情模型"""
    symbol: str = Field(..., description="股票代码")
    trade_date: date = Field(..., description="交易日期")
    open: float = Field(..., description="开盘价")
    high: float = Field(..., description="最高价")
    low: float = Field(..., description="最低价")
    close: float = Field(..., description="收盘价")
    pre_close: float = Field(..., description="前收盘价")
    change: float = Field(..., description="涨跌额")
    pct_chg: float = Field(..., description="涨跌幅(%)")
    volume: float = Field(..., description="成交量(股)")
    amount: float = Field(..., description="成交额(元)")
    turnover_rate: Optional[float] = Field(None, description="换手率(%)")
    volume_ratio: Optional[float] = Field(None, description="量比")

View on GitHub (pinned to 74783e8817)

Solutions

  1. Strip exchange suffixes before constructing the model: use '600519' not '600519.SH' or '600519.SZ'.
  2. Normalize upstream data: symbol.split('.')[0] or regex-extract the 6-digit core, and zero-pad shorter codes with zfill(6).
  3. If you need non-A-share symbols, validate the market first and only route A-share data through these models, or extend the validator for other markets.

Example fix

# before
quote = StockDailyQuote(symbol="600519.SH", ...)

# after
quote = StockDailyQuote(symbol="600519.SH".split(".")[0], ...)  # or normalize: symbol.zfill(6)
Defensive patterns

Strategy: type-guard

Validate before calling

import re
def normalize_a_share_symbol(sym) -> str:
    s = str(sym).strip()
    m = re.search(r"\d{6}", s)  # extract 6-digit core from '600519.SH' etc.
    if not m:
        raise ValueError(f"{sym!r} is not a valid A-share symbol")
    return m.group(0)

quote = StockDailyQuote(symbol=normalize_a_share_symbol(raw_symbol), ...)

Type guard

def is_a_share_symbol(v) -> bool:
    """Type guard: True if v is a bare 6-digit A-share code."""
    return isinstance(v, str) and v.isdigit() and len(v) == 6

Try / catch

from pydantic import ValidationError
try:
    quote = StockDailyQuote(symbol=sym, ...)
except ValidationError as e:
    if "股票代码必须是6位数字" in str(e):
        sym = normalize_a_share_symbol(sym)
        quote = StockDailyQuote(symbol=sym, ...)
    else:
        raise

Prevention

When it happens

Trigger: Instantiating any StockBaseModel subclass (e.g. StockDailyQuote) with symbol='AAPL', '00700.HK', '600519.SH', '0001', or '60051a' — anything not a bare 6-digit string.

Common situations: Feeding US/HK tickers or suffixed A-share codes (with .SH/.SZ/.BJ) from external data sources into these models; frontends passing integers or zero-stripped codes; migrating from a library that accepted exchange-suffixed symbols.

Understand the failure class

Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.

Related errors


AI-assisted analysis of hsliuping/TradingAgents-CN@74783e8817 (2026-08-28). Data as JSON: /api/errors/9a96dde39d16aa49. Report an issue: GitHub.