ZhuLinsen/daily_stock_analysis · error · DataFetchError

pytdx 库未安装

Error message

pytdx 库未安装

What it means

DataFetchError raised inside PytdxFetcher._pytdx_session() when self._get_pytdx() returns None, i.e. the optional pytdx package could not be imported. pytdx is an optional dependency of this project, so the fetcher degrades to this explicit error instead of an ImportError at module load.

Source

Thrown at data_provider/pytdx_fetcher.py:205

        Pytdx 连接上下文管理器
        
        确保:
        1. 进入上下文时自动连接
        2. 退出上下文时自动断开
        3. 异常时也能正确断开
        
        使用示例:
            with self._pytdx_session() as api:
                # 在这里执行数据查询
        """
        if self._is_in_connection_cooldown():
            raise DataSourceUnavailableError(
                f"Pytdx temporarily unavailable: {self._last_unavailable_reason or 'connection cooldown'}"
            )

        TdxHq_API = self._get_pytdx()
        if TdxHq_API is None:
            raise DataFetchError("pytdx 库未安装")
        
        api = TdxHq_API()
        connected = False
        
        try:
            # 尝试连接服务器(自动选择最优)
            for i in range(len(self._hosts)):
                host_idx = (self._current_host_idx + i) % len(self._hosts)
                host, port = self._hosts[host_idx]
                
                try:
                    if api.connect(host, port, time_out=5):
                        connected = True
                        self._current_host_idx = host_idx
                        logger.debug(f"Pytdx 连接成功: {host}:{port}")
                        break
                except Exception as e:
                    logger.debug(f"Pytdx 连接 {host}:{port} 失败: {e}")

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Install pytdx into the active environment: pip install pytdx.
  2. If pytdx is deliberately not shipped (e.g. slim deployments), remove PytdxFetcher from the provider priority chain so it is never selected.
  3. Check at startup whether pytdx is importable and log/skip PytdxFetcher registration when it is not.

Example fix

# before
# pytdx not installed -> DataFetchError("pytdx 库未安装") at request time

# after
pip install pytdx
# or at provider registration time:
try:
    import pytdx  # noqa: F401
    register_fetcher(PytdxFetcher())
except ImportError:
    logger.warning("pytdx not installed; PytdxFetcher disabled")
Defensive patterns

Strategy: type-guard

Validate before calling

def pytdx_available() -> bool:
    try:
        import pytdx  # noqa: F401
        return True
    except ImportError:
        return False

Type guard

def pytdx_available() -> bool:
    """True when the optional pytdx package is importable."""
    try:
        import pytdx  # noqa: F401
        return True
    except ImportError:
        return False

Try / catch

try:
    df = pytdx_fetcher.get_stock_data(code, start, end)
except DataFetchError as e:
    if "未安装" in str(e):
        df = akshare_fetcher.get_stock_data(code, start, end)
    else:
        raise

Prevention

When it happens

Trigger: Any PytdxFetcher data or realtime-quote call when pytdx is not installed in the current interpreter (missing from requirements, different venv, slim Docker image without the extras).

Common situations: Fresh environment where only requirements.txt was installed but pytdx is an optional extra; running in CI or a container built without pytdx; venv mismatch where the package is installed elsewhere.

Related errors


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