HKUDS/Vibe-Trading · error · TushareFallbackUnavailable

tushare import failed

Error message

tushare import failed: {exc}

What it means

_pro_api raises this when `import tushare` fails while building the fallback client. The tushare package is an optional dependency in this project, so any ImportError/ModuleNotFoundError during import is wrapped in TushareFallbackUnavailable instead of crashing the caller. The underlying exception text is chained and included in the message.

Solutions

  1. Install tushare into the same interpreter/venv the agent runs on (e.g. pip install tushare or add it to the optional extras)
  2. If the import error mentions another package (pandas, numpy), upgrade/align that dependency
  3. Confirm with `python -c "import tushare"` in the runtime environment
  4. If Tushare is intentionally unused, catch TushareFallbackUnavailable and skip the fallback path

Example fix

# before: package missing in runtime env
pip install tushare  # skipped / wrong venv

# after
pip install tushare
python -c "import tushare; print(tushare.__version__)"
Defensive patterns

Strategy: try-catch

Validate before calling

def tushare_importable() -> bool:
    try:
        import tushare  # noqa: F401
        return True
    except Exception:
        return False

if tushare_importable() and tushare_ready():
    data = fetch_dragon_tiger(trade_date=d)
else:
    data = primary_source(d)

Try / catch

try:
    data = fetch_margin_trading(symbol, days=d)
except TushareFallbackUnavailable as exc:
    if str(exc).startswith('tushare import failed'):
        # optional dependency missing in this env; degrade gracefully
        data = primary_source(symbol, days=d)
    else:
        raise

Prevention

When it happens

Trigger: Calling any of fetch_fund_flow, fetch_dragon_tiger, fetch_northbound_flow, or fetch_margin_trading on an environment where the tushare package is not installed, is installed for a different interpreter/virtualenv, or fails at import time due to a broken dependency (e.g. missing pandas or an incompatible numpy).

Common situations: Deploying without the extras/optional dependency group that includes tushare; running under a different Python than the one used by pip; a transitive dependency version conflict breaking the import; partially corrupted site-packages.

Related errors


AI-assisted analysis of HKUDS/Vibe-Trading@80ffdda44c (2026-08-28). Data as JSON: /api/errors/7577c89cdcecf4f6. Report an issue: GitHub.

Appendix: source

Thrown at agent/src/tools/tushare_fallbacks.py:29

from typing import Any

from src.config.accessor import get_env_config

_TUSHARE_TOKEN_PLACEHOLDERS = {"", "your-tushare-token"}


class TushareFallbackUnavailable(RuntimeError):
    """Raised when the optional Tushare fallback cannot be used."""


def _pro_api() -> Any:
    token = get_env_config().data.tushare_token.strip()
    if token in _TUSHARE_TOKEN_PLACEHOLDERS:
        raise TushareFallbackUnavailable("TUSHARE_TOKEN is not configured")
    try:
        import tushare as ts
    except Exception as exc:  # noqa: BLE001 - import errors vary by install
        raise TushareFallbackUnavailable(f"tushare import failed: {exc}") from exc
    return ts.pro_api(token)


def _records(frame: Any) -> list[dict[str, Any]]:
    if frame is None:
        return []
    if bool(getattr(frame, "empty", False)):
        return []
    if hasattr(frame, "to_dict"):
        rows = frame.to_dict("records")
        return [row for row in rows if isinstance(row, dict)]
    if isinstance(frame, list):
        return [row for row in frame if isinstance(row, dict)]
    return []


def _compact_date(value: str) -> str:
    digits = str(value).strip().replace("-", "")

View on GitHub (pinned to 80ffdda44c)