ZhuLinsen/daily_stock_analysis · error · DataFetchError

Pytdx 未查询到 {stock_code} 的数据

Error message

Pytdx 未查询到 {stock_code} 的数据

What it means

DataFetchError raised when api.get_security_bars(...) returns None or an empty list for the requested market/code — the TDX server accepted the connection but has no bars for that symbol (invalid code for the market, suspended/delisted stock, or a symbol served only on a different TDX market).

Source

Thrown at data_provider/pytdx_fetcher.py:360

        days = (end_dt - start_dt).days
        count = min(max(days * 5 // 7 + 10, 30), 800)  # 估算交易日,最大 800 条
        
        logger.debug(f"调用 Pytdx get_security_bars(market={market}, code={code}, count={count})")
        
        with self._pytdx_session() as api:
            try:
                # 获取日 K 线数据
                # category: 9-日线, 0-5分钟, 1-15分钟, 2-30分钟, 3-1小时
                data = api.get_security_bars(
                    category=9,  # 日线
                    market=market,
                    code=code,
                    start=0,  # 从最新开始
                    count=count
                )
                
                if data is None or len(data) == 0:
                    raise DataFetchError(f"Pytdx 未查询到 {stock_code} 的数据")
                
                # 转换为 DataFrame
                df = api.to_df(data)
                
                # 过滤日期范围
                df['datetime'] = pd.to_datetime(df['datetime'])
                df = df[(df['datetime'] >= start_date) & (df['datetime'] <= end_date)]
                
                return df
                
            except Exception as e:
                if isinstance(e, DataFetchError):
                    raise
                raise DataFetchError(f"Pytdx 获取数据失败: {e}") from e
    
    def _normalize_data(self, df: pd.DataFrame, stock_code: str) -> pd.DataFrame:
        """
        标准化 Pytdx 数据

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Verify the code exists on the inferred market and correct the market mapping in _get_market_code logic if codes are misrouted.
  2. Confirm the stock actually has trading history within [start_date, end_date] (listed, not long-suspended).
  3. Fall back to Akshare/Tushare which have authoritative symbol metadata, then reconcile your code normalization.

Example fix

# before
df = pytdx_fetcher.get_stock_data("000001", start, end)  # empty bars -> DataFetchError if market misrouted

# after
# ensure market inference matches listing venue; verify via akshare
info = ak.stock_individual_info_em(symbol="000001")
df = manager.get_stock_data("000001", start, end)  # let manager fail over
Defensive patterns

Strategy: try-catch

Validate before calling

# cheap existence check via a provider with symbol metadata before pytdx
info = ak.stock_individual_info_em(symbol=code)  # raises if not listed
# also confirm listing date precedes start_date

Try / catch

try:
    df = pytdx_fetcher.get_stock_data(code, start, end)
except DataFetchError as e:
    if "未查询到" in str(e):
        logger.warning(f"{code}: no bars from pytdx; verifying symbol and window")
        df = manager.get_stock_data(code, start, end)
    else:
        raise

Prevention

When it happens

Trigger: Calling _fetch_raw_data with a code whose market prefix (SH/SZ from _get_market_code) does not match the listing venue; newly listed stocks with no history in the requested window; delisted or suspended tickers; typos in the 6-digit code.

Common situations: Wrong market inference for codes like 3xxxxx/6xxxxx edge cases; querying a date range before IPO; code normalized incorrectly upstream (e.g. Shenzhen code treated as Shanghai).

Related errors


AI-assisted analysis of ZhuLinsen/daily_stock_analysis@5159bd72e8 (2026-08-15). Data as JSON: /api/errors/5f1dca3aca2251ab. Report an issue: GitHub.