How to Troubleshoot Common Data Source Fallback and Timeout Errors in TradingAgents-CN

Enable debug logging and verify your API tokens, then adjust timeout constants in provider files like tushare.py or force a specific fallback via environment variables to resolve most connectivity issues.

TradingAgents-CN orchestrates market data retrieval through a resilient multi-provider architecture designed to handle failures gracefully. When you need to troubleshoot common data source fallback and timeout errors in TradingAgents-CN, understanding the layered provider stack and timeout configuration points is essential for rapid diagnosis.

Understanding the Data Source Architecture

Stacked Provider Model

TradingAgents-CN implements a priority-based fallback system for different markets:

  • China A-shares: Tushare → AKShare → BaoStock
  • US Equities: yfinance → Alpha Vantage → Finnhub
  • News Data: Various web APIs (Google News, Lark, WeChat) with thread-based timeouts

The central coordinator resides in tradingagents/dataflows/data_source_manager.py, where the _try_fallback_sources method iterates through the priority list when the primary provider fails.

Fallback Chain Logic

When a data request initiates, the manager:

  1. Attempts the highest-priority source (e.g., Tushare for China stocks)
  2. Catches any exception or error string containing "❌"
  3. Invokes _try_fallback_sources to query the next provider in the sequence
  4. Returns the first successful result along with the source name
  5. Logs a final error if all sources in the chain fail

Identifying Timeout Configurations

Timeouts are hard-coded or parameterized across multiple provider files. Locate these constants to adjust latency tolerance:

File Timeout Parameter Default Value
tradingagents/dataflows/providers/china/tushare.py test_timeout in asyncio.wait_for 10 seconds
tradingagents/dataflows/providers/china/akshare.py timeout parameter in akshare.stock_zh_a_hist 10 seconds
tradingagents/tools/unified_news_tool.py future.result(timeout=...) 30 seconds
tradingagents/graph/trading_graph.py LLM provider timeout argument 180 seconds
web/app.py requests.get(..., timeout=...) for health checks 5 seconds

When any of these thresholds are exceeded, the system raises TimeoutError (async) or requests.exceptions.Timeout, triggering the fallback mechanism.

Diagnosing Common Failure Scenarios

Tushare Connection Failures

Symptom: Log shows "❌ Tushare连接失败" or TimeoutError after 10 seconds.

Root Cause: Invalid or missing TUSHARE_TOKEN environment variable, or network latency exceeding the test_timeout constant in tradingagents/dataflows/providers/china/tushare.py.

Resolution:

  1. Verify the token is set in .env or the MongoDB datasource_tokens collection
  2. Increase test_timeout from 10 to 20 seconds if operating on a slow network:
    # In tradingagents/dataflows/providers/china/tushare.py
    
    test_timeout = 20  # seconds
    

AKShare Endpoint Blocks

Symptom: "❌ AKShare获取数据失败" appears after 10 seconds, often following a firewall or DNS error in the traceback.

Root Cause: The AKShare API endpoint is unreachable due to network restrictions or temporary service outage.

Resolution:

  • Test connectivity to the AKShare endpoint manually using curl

  • Temporarily force fallback to BaoStock by setting the environment variable:

    export DEFAULT_CHINA_DATA_SOURCE=baostock
  • Alternatively, modify the fallback_order in the datasource_groupings MongoDB collection to prioritize BaoStock

News Tool Timeouts

Symptom: Log entry 🔧 [News] timeout with concurrent.futures._base.TimeoutError after 30 seconds.

Root Cause: External news APIs (WeChat, Lark, or Google News) are not responding within the future.result(timeout=30) window defined in tradingagents/tools/unified_news_tool.py.

Resolution:

  • Increase the timeout threshold in line 270 of unified_news_tool.py:

    result = future.result(timeout=60)  # Extend to 60 seconds
    
  • Verify network connectivity to the specific news endpoint

  • Check if the API key for the news provider has expired

MongoDB Cache Latency

Symptom: "⚠️ 数据库 Token 测试超时 (10秒)" appears even though MongoDB is reachable.

Root Cause: The token validation request within the MongoDB connection pool is stalling due to slow database performance or high connection latency.

Resolution:

  • Increase test_timeout in the respective provider file (e.g., tushare.py)
  • Monitor MongoDB connection pool health using db.serverStatus()
  • Ensure the MongoDB instance has sufficient resources and network bandwidth

Step-by-Step Troubleshooting Workflow

Follow this systematic approach to isolate and resolve data source failures:

  1. Enable debug logging – Set LOG_LEVEL=DEBUG in your .env file or modify app/utils/logging_manager.py to capture detailed provider tracebacks.

  2. Identify the failing provider – Examine log prefixes such as [Tushare], [AKShare], or [Alpha_Vantage] to pinpoint which source raised the exception.

  3. Validate credentials

    • Verify TUSHARE_TOKEN for China markets
    • Check ALPHA_VANTAGE_API_KEY and FINNHUB_API_KEY for US markets
    • Ensure keys are accessible via environment variables or the MongoDB system_configs collection
  4. Test endpoints manually – Use curl or requests to verify direct connectivity to the API endpoint, ruling out network blocks or DNS issues.

  5. Adjust timeout values – Edit the hard-coded constants in the specific provider file (e.g., tradingagents/dataflows/providers/china/tushare.py) to accommodate high-latency networks.

  6. Force specific fallbacks – Temporarily override the priority chain by setting environment variables like DEFAULT_CHINA_DATA_SOURCE=baostock or modifying the datasource_groupings collection in MongoDB.

  7. Check MongoDB status – If using cached data, verify the database service is reachable and responsive; otherwise the system will skip the cache and hit external APIs directly.

  8. Reproduce in isolation – Use the example scripts in the examples/ directory (e.g., examples/test_news_timeout.py) to test the specific failing component outside the full pipeline.

When Fallback Logic Fails

The automatic fallback system may not activate under specific conditions:

  • Error string detection – If a provider returns a string containing "❌" rather than raising an exception, the manager correctly treats this as a failure and continues the chain. However, if a provider returns malformed data without the error marker, the fallback may not trigger.

  • Missing from available sources – During initialization, _check_available_sources verifies that required libraries (e.g., yfinance, akshare) are installed. If a library is missing, that source is excluded from the available_sources list, causing the fallback loop to skip it entirely.

  • Incorrect priority ordering – The datasource_groupings collection in MongoDB defines the fallback order. If this collection places an unavailable source (e.g., one with an expired API key) before a working source, the system will exhaust the failed attempts before reaching the functional provider.

Preventive Actions

Implement these practices to minimize data source disruptions:

  • Unit test providers regularly – Run pytest tests/test_data_sources_simple.py with short timeouts to catch connectivity issues before they affect production workflows.

  • Monitor API key expiration – Schedule a cron job that queries the system_configs and datasource_tokens collections to alert you before keys expire.

  • Synchronize datasource_groupings – Ensure the MongoDB datasource_groupings collection reflects currently installed libraries by cross-referencing with pip list.

  • Version-pin dependencies – Lock requests>=2.31.0 and other timeout-sensitive libraries in requirements.txt to prevent regression bugs that might affect network timeouts.

Code Examples for Quick Fixes

Extending Tushare Timeout

When network latency exceeds the default 10-second test window, modify the constant in tradingagents/dataflows/providers/china/tushare.py:


# tradingagents/dataflows/providers/china/tushare.py

# Increase from 10 to 20 seconds for high-latency networks

test_timeout = 20   # seconds

Forcing BaoStock Fallback

Bypass a flaky AKShare installation by setting an environment variable before initializing the manager:

import os
os.environ["DEFAULT_CHINA_DATA_SOURCE"] = "baostock"

from tradingagents.dataflows.data_source_manager import DataSourceManager
manager = DataSourceManager()

# The manager now starts with BaoStock instead of Tushare or AKShare

Reordering US Data Sources via MongoDB

Adjust the fallback priority for US equities by updating the datasource_groupings collection:

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client.tradingagents

# Set Finnhub as highest priority (3), Alpha Vantage as middle (2), yfinance as lowest (1)

db.datasource_groupings.update_one(
    {"market_category_id": "us_stocks", "data_source_name": "finnhub"},
    {"$set": {"priority": 3}}
)
db.datasource_groupings.update_one(
    {"market_category_id": "us_stocks", "data_source_name": "alpha_vantage"},
    {"$set": {"priority": 2}}
)
db.datasource_groupings.update_one(
    {"market_category_id": "us_stocks", "data_source_name": "yfinance"},
    {"$set": {"priority": 1}}
)

Increasing News Fetch Timeout

When external news APIs respond slowly, extend the future timeout in tradingagents/tools/unified_news_tool.py:


# tradingagents/tools/unified_news_tool.py

# Change from 30 to 60 seconds

result = future.result(timeout=60)

Checking Available Sources at Runtime

Verify which providers are installed and prioritized before executing trades:

from tradingagents.dataflows.data_source_manager import DataSourceManager

mgr = DataSourceManager()
print("Available US sources:", [s.value for s in mgr.available_sources])
print("Current fallback order:", [s.value for s in mgr._get_data_source_priority_order()])

Summary

  • TradingAgents-CN uses a hierarchical fallback system managed by tradingagents/dataflows/data_source_manager.py to switch between Tushare, AKShare, BaoStock, yfinance, Alpha Vantage, and Finnhub when timeouts or errors occur.
  • Timeout values are hard-coded in provider-specific files (typically 10 seconds for China data, 30 seconds for news, and 180 seconds for LLM calls) and can be increased to accommodate high-latency networks.
  • Fallback failures usually stem from missing API keys, uninstalled provider libraries, or incorrect priority orders in the MongoDB datasource_groupings collection.
  • Diagnostic workflow involves enabling debug logging in app/utils/logging_manager.py, validating credentials, testing endpoints manually, and using isolation scripts from the examples/ directory.

Frequently Asked Questions

Why does my Tushare connection timeout even with a valid token?

Network latency or slow MongoDB token validation can exceed the default 10-second test_timeout defined in tradingagents/dataflows/providers/china/tushare.py. Increase the test_timeout constant to 20 seconds and verify that your TUSHARE_TOKEN environment variable or database entry is accessible without high latency.

How can I force TradingAgents-CN to skip a broken data source?

Set the DEFAULT_CHINA_DATA_SOURCE or DEFAULT_US_DATA_SOURCE environment variable to the name of a working provider (e.g., baostock or finnhub) before initializing the DataSourceManager. Alternatively, update the priority field in the MongoDB datasource_groupings collection to place the broken source at the lowest priority level.

What causes the UnifiedNewsTool timeout error?

The unified_news_tool.py uses future.result(timeout=30) to fetch news from external APIs like WeChat or Lark. When these endpoints respond slower than 30 seconds due to network congestion or API throttling, a concurrent.futures._base.TimeoutError is raised. Extend the timeout to 60 seconds in the source file or verify connectivity to the specific news endpoint.

Where are timeout values stored in the codebase?

Timeout constants are distributed across provider-specific implementation files rather than a central configuration. Key locations include tradingagents/dataflows/providers/china/tushare.py (10 seconds), tradingagents/dataflows/providers/china/akshare.py (10 seconds), tradingagents/tools/unified_news_tool.py (30 seconds), and tradingagents/graph/trading_graph.py (180 seconds for LLM calls). Edit these files directly to adjust tolerance for high-latency environments.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →