ZhuLinsen/daily_stock_analysis · warning · DataFetchError

Baostock 未查询到 {stock_code} 的数据

Error message

Baostock 未查询到 {stock_code} 的数据

What it means

A DataFetchError raised when bs.query_history_k_data_plus succeeds (error_code '0') but iterating rs.next() yields zero rows. The query was valid but returned an empty set: no trading data for that code in the given window. Distinct from a query failure (error 137) — here baostock explicitly confirmed success with no data.

Source

Thrown at data_provider/baostock_fetcher.py:244

                rs = bs.query_history_k_data_plus(
                    code=bs_code,
                    fields="date,open,high,low,close,volume,amount,pctChg",
                    start_date=start_date,
                    end_date=end_date,
                    frequency="d",  # 日线
                    adjustflag="2"  # 前复权
                )
                
                if rs.error_code != '0':
                    raise DataFetchError(f"Baostock 查询失败: {rs.error_msg}")
                
                # 转换为 DataFrame
                data_list = []
                while rs.next():
                    data_list.append(rs.get_row_data())
                
                if not data_list:
                    raise DataFetchError(f"Baostock 未查询到 {stock_code} 的数据")
                
                df = pd.DataFrame(data_list, columns=rs.fields)
                
                return df
                
            except Exception as e:
                if isinstance(e, DataFetchError):
                    raise
                raise DataFetchError(f"Baostock 获取数据失败: {e}") from e
    
    def _normalize_data(self, df: pd.DataFrame, stock_code: str) -> pd.DataFrame:
        """
        标准化 Baostock 数据
        
        Baostock 返回的列名:
        date, open, high, low, close, volume, amount, pctChg
        
        需要映射到标准列名:

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Check the date range covers at least one A-share trading day (avoid CN holidays/weekends).
  2. Verify the code exists and trades in that window (cross-check on Akshare/East Money).
  3. If empty windows are expected, treat this as a skip signal and catch it rather than failing the batch.
  4. Widen or shift the range slightly for suspended stocks.

Example fix

# before
try:
    df = baostock_fetcher.fetch(code, '2025-10-01', '2025-10-08')  # CN holiday week
except DataFetchError:
    raise  # job aborts

# after
try:
    df = baostock_fetcher.fetch(code, '2025-10-01', '2025-10-08')
except DataFetchError as e:
    if '未查询到' in str(e):
        df = pd.DataFrame()  # expected: holiday window, skip
    else:
        raise
Defensive patterns

Strategy: validation

Validate before calling

from datetime import date
# ensure the window contains at least one weekday outside major CN holidays
assert any(date.fromordinal(d).weekday() < 4 for d in range(date.fromisoformat(start_date).toordinal(), date.fromisoformat(end_date).toordinal() + 1))

Try / catch

try:
    df = baostock_fetcher.fetch(code, start, end)
except DataFetchError as e:
    if '未查询到' in str(e):
        df = pd.DataFrame()  # expected for holiday-only windows / suspended stocks
    else:
        raise

Prevention

When it happens

Trigger: Date range covering only non-trading days (holidays, weekends) for a valid code; a suspended stock with no trades in the window; a valid-prefix but nonexistent code (baostock returns empty rather than an error); start_date after the stock's listing date window or a future-dated range.

Common situations: Chinese New Year / National Day holiday windows returning empty; newly listed codes queried before IPO date; code typos that still convert to a well-formed sh./sz. code (e.g. 'sh.600520' that doesn't exist); delisted symbols.

Related errors


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