ZhuLinsen/daily_stock_analysis · error · ValueError

Cannot convert {stock_code} to Longbridge symbol

Error message

Cannot convert {stock_code} to Longbridge symbol

What it means

Raised by LongbridgeFetcher._fetch_raw_data when the helper _to_longbridge_symbol(stock_code) returns None, meaning the stock code cannot be mapped to a Longbridge-compatible symbol (e.g. US/HK/A-share formats outside its supported mapping). It is a ValueError raised before any network call, acting as a market-coverage guard so the DataFetcherManager can fail over to another provider.

Source

Thrown at data_provider/longbridge_fetcher.py:877

            f"[Longbridge] {symbol} 行情获取成功: "
            f"价格={price}, 量比={volume_ratio}, 换手率={turnover_rate}"
        )
        return quote

    # ------------------------------------------------------------------
    # BaseFetcher abstract methods (historical daily data)
    # ------------------------------------------------------------------

    def _fetch_raw_data(
        self, stock_code: str, start_date: str, end_date: str
    ) -> pd.DataFrame:
        """Fetch historical candlesticks from Longbridge."""
        if not self.is_available_for_request("daily_data"):
            raise RuntimeError("Longbridge temporarily unavailable for daily_data")

        symbol = _to_longbridge_symbol(stock_code)
        if symbol is None:
            raise ValueError(f"Cannot convert {stock_code} to Longbridge symbol")

        ctx = self._get_ctx()
        if ctx is None:
            raise RuntimeError("Longbridge QuoteContext not available")

        from longbridge.openapi import Period, AdjustType

        start_dt = datetime.strptime(start_date, "%Y-%m-%d").date()
        end_dt = datetime.strptime(end_date, "%Y-%m-%d").date()

        try:
            candles = ctx.history_candlesticks_by_date(
                symbol,
                Period.Day,
                AdjustType.ForwardAdjust,
                start_dt,
                end_dt,
            )

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Verify the stock code is a market Longbridge supports and normalize it before calling the fetcher.
  2. Check/extend _to_longbridge_symbol in data_provider/longbridge_fetcher.py to cover the code format you pass in.
  3. If the market is intentionally unsupported, exclude LongbridgeFetcher from that market's data source priority list so the manager picks Akshare/Yfinance instead.

Example fix

// before
fetcher = LongbridgeFetcher()
df = fetcher.get_stock_data("600519.XSHG", "2026-01-01", "2026-02-01")  # ValueError

// after
from src.utils.stock_utils import normalize_stock_code
symbol_supported = _to_longbridge_symbol(normalize_stock_code("600519")) is not None
if symbol_supported:
    df = fetcher.get_stock_data(normalize_stock_code("600519"), "2026-01-01", "2026-02-01")
else:
    df = manager.get_stock_data(...)  # route via DataFetcherManager fallback
Defensive patterns

Strategy: validation

Validate before calling

from data_provider.longbridge_fetcher import _to_longbridge_symbol
from src.utils.stock_utils import normalize_stock_code

def longbridge_supports(stock_code: str) -> bool:
    return _to_longbridge_symbol(normalize_stock_code(stock_code)) is not None

Type guard

def is_longbridge_symbol(code: str) -> bool:
    """True when the code maps to a Longbridge symbol."""
    return _to_longbridge_symbol(normalize_stock_code(code)) is not None

Try / catch

try:
    df = longbridge_fetcher.get_stock_data(code, start, end)
except ValueError as e:
    if "Cannot convert" in str(e):
        df = manager.get_stock_data(code, start, end)  # next provider
    else:
        raise

Prevention

When it happens

Trigger: Calling fetch of historical daily data (BaseFetcher._fetch_raw_data) via LongbridgeFetcher with a stock code whose market/prefix is not covered by _to_longbridge_symbol, e.g. unsupported exchange suffixes, malformed codes, or markets Longbridge does not serve.

Common situations: Routing the whole stock universe (A股/港股/美股) through LongbridgeFetcher without market filtering; typos or non-normalized codes reaching the fetcher; adding a new market to the pipeline without extending _to_longbridge_symbol.

Related errors


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