In 2019, a quant researcher running a pairs trading strategy on CSI 300 futures noticed something troubling: the same stock, listed on both the Shanghai and Shenzhen exchanges, showed divergent tick data between her primary vendor and a friend's vendor. Both datasets were commercially sourced. Neither was wrong. They were just timestamped differently, filtered differently, and aligned to different reference clocks.

She spent three weeks reconciling the datasets before the alpha in the strategy evaporated.

This is not an edge case. It is the defining challenge of A-share data: the market's fragmented exchange structure, its 3:00 PM closing times, its T+1 settlement rules, and its unique volatility patterns create data requirements that differ sharply from US equities — and most international data vendors treat China as an afterthought.

Tushare has dominated the A-share quantitative community for over a decade. TickDB arrived on the scene positioning itself as a cross-market solution that includes A-shares alongside US equities, HK stocks, crypto, and forex. The question this article answers: when your quant workflow spans multiple markets, which platform serves you better?


Why A-Share Data Is Structurally Different

Before comparing vendors, you need to understand what makes A-share data hard. If you have only worked with US equities, the following differences will catch you off guard in production.

Exchange Fragmentation

A-shares trade on two exchanges: the Shanghai Stock Exchange (SSE, code 600000–603999) and the Shenzhen Stock Exchange (SZSE, code 000000–002999 for main board, 300000–300999 for ChiNext). The same company can have different share classes across exchanges. A data source that ingests only SSE is missing half the float.

Settlement and Trading Hours

Session Trading window
Morning 09:30–11:30 local time (UTC+8)
Afternoon 13:00–15:00 local time (UTC+8)
Pre-opening auction 09:15–09:25
Closing auction 14:57–15:00

Note the 15:00 close. US quant researchers running cross-timezone strategies often process A-share closes during US pre-market. If your data pipeline assumes a 16:00 ET close, you will silently miss the last 15 minutes of the cash session.

T+1 Trading Rule

A-shares cannot be sold on the same day they are purchased. This restricts intraday strategies and creates overnight inventory effects that do not exist in US equities. Your backtest framework must model this constraint, and your data source must provide enough historical context for you to do so accurately.

Price Limit Bands

Stocks on the SSE and SZSE have daily price limit bands (typically ±10% for most stocks, ±20% for ChiNext). Hitting the limit does not halt trading — orders queue at the limit price. A data source that treats a limit-hit as "no trading occurred" will misrepresent liquidity.


Tushare: The A-Share Community Standard

Tushare launched in 2014 and built its dominance through the Chinese quant community. Its primary advantages are breadth of A-share specific metrics and a freemium model that makes it accessible to retail researchers.

Strengths

A-share depth: Tushare covers the full range of Chinese equity fundamentals — PBC repo rates, SHIBOR curves, margin balance data, sector classifications, index composition histories. If you are building macro-factor models on A-shares, Tushare has the datasets that international vendors simply do not offer.

Community ecosystem: The Tushare community has accumulated thousands of shared scripts, backtest frameworks, and data cleaning notebooks. For a researcher starting from zero, this ecosystem reduces onboarding friction significantly.

Cost: The free tier provides meaningful access. The Pro tier, at roughly $30/month, is accessible for individual researchers.

Limitations

Cross-market coverage is not the focus: Tushare's coverage of US equities, HK stocks, and crypto is limited or absent. If your strategy involves trading the Hong Kong-Shanghai Connect flows, or running cross-market arbitrage between A-shares and US-listed ADRs, you will need a second data source.

Real-time data is not native: Tushare's free and Pro tiers are primarily REST-based. Real-time WebSocket streaming requires additional infrastructure or third-party integration. Latency-sensitive event-driven strategies face a structural disadvantage.

API design reflects its age: Tushare's API uses its own conventions that diverge from common Python data science workflows. Dataframes are returned, but field names are in Chinese or proprietary abbreviations that require a translation layer.

Documentation: Documentation exists primarily in Chinese. English-language resources are community-contributed and often incomplete.


TickDB: Cross-Market Architecture

TickDB was designed from the ground up as a multi-market market data API. Its architecture prioritizes three properties: consistent API surface across asset classes, real-time WebSocket streaming, and historical OHLCV data aligned to a common time standard.

Cross-Market Capability

TickDB covers six asset classes through a unified REST and WebSocket API:

Asset class Historical OHLCV Real-time depth Real-time trades
US equities 10+ years L1 (top of book) Not supported
A-shares Available L1 (top of book) Not supported
HK stocks Available L1–L10 Supported
Crypto Available L1–L10 Supported
Forex Available Not supported Not supported
Precious metals / indices Available Not supported Not supported

The key constraint to understand: TickDB does not provide tick-level trade data for US equities or A-shares. Its trades endpoint covers HK stocks and crypto. For US equity and A-share order-flow analysis at the tick level, you need a different data source.

A-Share Specifics in TickDB

For A-share quantitative work, TickDB provides:

  • Daily OHLCV bars aligned to SSE/SZSE trading hours (including pre-opening and closing auction sessions as separate bars or tagged within the main bar)
  • Real-time top-of-book depth for the current trading session
  • Historical daily bars with split-adjusted prices
  • Support for both ticker formats (e.g., 600519.SH for Kweichow Moutai on SSE, 000001.SZ for Ping An on SZSE)

The alignment is critical: every bar is timestamped in UTC, and the session metadata includes the exchange timezone, so your pipeline does not need a separate timezone conversion step.


Side-by-Side Feature Comparison

The following table evaluates both platforms across dimensions relevant to a cross-market quant researcher.

Capability Tushare TickDB
A-share OHLCV coverage Full breadth (including fundamental datasets) Available; 10+ years for major stocks
US equity OHLCV Limited 10+ years; cleaned and aligned
HK stock coverage Minimal Full depth (L1–L10, trades)
Crypto coverage None Full depth and trades
Forex coverage None Available
Real-time WebSocket Via third-party integration Native
Historical tick trades (A-shares) Available Not supported
A-share fundamental data (P/E, sector, margin) Extensive Limited to price/volume
English documentation Partial Full
API consistency across markets Varies by market Unified REST + WebSocket
Free tier Generous (rate-limited) 10,000 credits/month
Paid tier starting price ~$30/month (Pro) $49/month (Starter)

Tushare wins on A-share fundamental data depth. TickDB wins on cross-market consistency and real-time infrastructure.


Code Comparison: Fetching A-Share OHLCV Data

Both platforms provide Python libraries. The code samples below fetch 100 daily bars for Kweichow Moutai (ticker: 600519.SH).

Tushare

import tushare as ts

# Initialize with your token
pro = ts.pro_api('YOUR_TUSHARE_TOKEN')

# Fetch daily bars
df = pro.daily(
    ts_code='600519.SH',
    start_date='20240101',
    end_date='20241231'
)

print(df.head())
print(df.columns.tolist())

Tushare returns a DataFrame with columns: ts_code, trade_date, open, high, low, close, vol, amount. The data is dated in YYYYMMDD string format — you will need to parse this before merging with other datasets.

TickDB

import os
import requests
from datetime import datetime, timedelta

API_KEY = os.environ.get("TICKDB_API_KEY")

def fetch_a_share_klines(symbol: str, interval: str = "1d", limit: int = 100):
    """Fetch historical OHLCV bars for a given A-share symbol."""
    url = "https://api.tickdb.ai/v1/market/kline"
    headers = {"X-API-Key": API_KEY}
    params = {
        "symbol": symbol,
        "interval": interval,
        "limit": limit
    }

    try:
        response = requests.get(
            url,
            headers=headers,
            params=params,
            timeout=(3.05, 10)
        )
        response.raise_for_status()
        data = response.json()

        if data.get("code") != 0:
            raise RuntimeError(
                f"TickDB API error {data.get('code')}: {data.get('message')}"
            )

        bars = data.get("data", {}).get("klines", [])
        return bars

    except requests.exceptions.Timeout:
        raise RuntimeError("Request timed out after 10 seconds")
    except requests.exceptions.RequestException as e:
        raise RuntimeError(f"Request failed: {e}")

# Fetch 100 daily bars for Kweichow Moutai
bars = fetch_a_share_klines("600519.SH", interval="1d", limit=100)

if bars:
    latest = bars[-1]
    print(f"Latest bar: {latest}")
else:
    print("No data returned")

Key differences in practice:

  • TickDB requires explicit API key management via environment variable. Tushare accepts a token string directly (which should still be stored in an environment variable in production — do not hardcode tokens).
  • TickDB returns ISO-format timestamps (UTC) alongside each bar. Tushare returns YYYYMMDD strings in the local timezone, which requires explicit conversion when merging with multi-market datasets.
  • TickDB uses a unified symbol format (600519.SH) that works for all equity endpoints. Tushare also uses this format for its Pro API but has different naming conventions for its legacy free API.

Real-Time Streaming: The Architecture Gap

For event-driven strategies — earnings plays, index rebalancing, futures roll — real-time data is not optional. This is where the architectural gap between the two platforms is widest.

Tushare does not provide native WebSocket streaming in its standard Pro API. Real-time data requires either:

  1. Polling the REST endpoint at short intervals (introducing latency and API quota pressure)
  2. Using a third-party WebSocket aggregator that wraps the Tushare REST feed
  3. Subscribing to a separate real-time data vendor (CTP, for futures; or a broker-provided feed for equities)

Each option adds integration complexity and potential points of failure.

TickDB provides native WebSocket streaming for real-time candles, depth snapshots, and trade ticks (for supported markets). The connection model follows a standard ping/pong heartbeat protocol:

import os
import json
import time
import websocket
import random

API_KEY = os.environ.get("TICKDB_API_KEY")
WS_URL = "wss://api.tickdb.ai/v1/market/ws"

def on_open(ws):
    """Subscribe to real-time depth for an A-share."""
    subscribe_msg = {
        "cmd": "sub",
        "params": {
            "channel": "depth",
            "symbol": "600519.SH",
            "depth": 1
        }
    }
    ws.send(json.dumps(subscribe_msg))
    print("Subscribed to depth channel for 600519.SH")

def on_message(ws, message):
    """Handle incoming depth updates."""
    data = json.loads(message)
    if data.get("cmd") == "ping":
        ws.send(json.dumps({"cmd": "pong"}))
        return

    if data.get("channel") == "depth":
        bid = data.get("bid", [])
        ask = data.get("ask", [])
        print(f"Bid: {bid}, Ask: {ask}")

def on_error(ws, error):
    print(f"WebSocket error: {error}")

def on_close(ws, close_status_code, close_msg):
    print(f"Connection closed: {close_status_code} {close_msg}")

def connect_with_retry(max_retries=5, base_delay=1.0, max_delay=60.0):
    """Connect with exponential backoff and jitter."""
    for attempt in range(max_retries):
        try:
            ws = websocket.WebSocketApp(
                WS_URL,
                on_open=on_open,
                on_message=on_message,
                on_error=on_error,
                on_close=on_close,
                header={"X-API-Key": API_KEY}
            )
            ws.run_forever(ping_interval=30)
        except Exception as e:
            delay = min(base_delay * (2 ** attempt), max_delay)
            jitter = random.uniform(0, delay * 0.1)
            wait_time = delay + jitter
            print(f"Reconnecting in {wait_time:.2f}s (attempt {attempt + 1}/{max_retries})")
            time.sleep(wait_time)

    print("Max retries reached. Connection failed.")

if __name__ == "__main__":
    connect_with_retry()

Engineering notes embedded in the code:

  • The ping_interval=30 parameter sends a WebSocket ping every 30 seconds. If the connection drops silently, the on_close handler triggers a reconnection with exponential backoff.
  • The jitter term (random.uniform(0, delay * 0.1)) prevents thundering-herd reconnection spikes when multiple clients reconnect simultaneously after an upstream outage.
  • For production HFT workloads processing depth updates at sub-100ms latency requirements, this synchronous WebSocketApp model is insufficient — you need an asyncio-based client with a dedicated event loop. Consider aiohttp or websockets with an async runner.

Which Platform Should You Use?

The answer depends on your strategy architecture and where your alpha lives.

Use Tushare if:

  • Your strategies are A-share only, and you rely heavily on fundamental datasets (SHIBOR rates, margin balances, sector rotation data)
  • You are a retail researcher working within a tight budget, and community-shared scripts reduce your development time
  • You do not need sub-second real-time data; end-of-day or hourly bars are sufficient
  • You are comfortable working primarily in Chinese-language documentation and community forums

Use TickDB if:

  • Your strategies span multiple markets — for example, trading A/H share pairs, running cross-market stat-arb, or building crypto-equity correlation models
  • You need a unified API surface with consistent field names and timestamp formats across all asset classes
  • Real-time WebSocket streaming is a core requirement for your event-driven logic
  • You need English-language documentation, predictable API behavior, and production-grade connection resilience built into the SDK

Use both (with careful data reconciliation) if:

  • You need Tushare's A-share fundamental datasets for factor construction, and TickDB's cross-market OHLCV for portfolio-level risk management
  • Be aware: reconciling timestamps, adjusting for split/dividend differences, and aligning exchange timezones between the two sources is a non-trivial engineering task that should be estimated and budgeted

Production Deployment Checklist

If you are integrating either platform into a live trading system, the following checklist applies:

Data quality validation:

  • Verify that A-share timestamps are correctly interpreted as UTC+8, not UTC
  • Confirm that split-adjusted prices are consistent between historical and current datasets
  • Test for survivorship bias — verify that delisted stocks are included in historical queries

Connection resilience:

  • Implement heartbeat detection with reconnection logic
  • Add circuit breakers to halt strategy execution if data feed stalls for more than N seconds
  • Log all connection events and error codes for post-mortem analysis

API quota management:

  • Track request counts against your tier's rate limits
  • Implement request coalescing — batch historical queries instead of sending one request per bar
  • Set alerts for quota usage at 80% of your monthly limit

Backtesting integrity:

  • Ensure that your backtest data and live data use the same adjusted-price methodology
  • Align your backtest session definitions to the actual exchange hours (09:30–15:00 UTC+8, with pre/closing auctions)
  • Account for T+1 settlement constraints in any intraday strategy logic

Conclusion

Tushare and TickDB serve different positions in the quant data ecosystem. Tushare is deep, broad, and community-proven for A-share research. Its fundamental data coverage is unmatched by any international vendor. But it was not designed for cross-market workflows, and its real-time infrastructure requires supplementation.

TickDB trades A-share fundamental depth for cross-market consistency and native real-time streaming. For researchers whose strategies span multiple asset classes — A-shares alongside US equities, HK stocks, crypto, or forex — TickDB reduces the integration surface area significantly. The trade-off is real: if your alpha comes from SHIBOR curve positioning or margin balance factor models, you will need Tushare's data.

The three-week data reconciliation nightmare that opened this article did not have to happen. It happened because the researcher chose two data sources without reconciling their timestamp alignment, filtering rules, and reference clock assumptions in advance. Whether you choose Tushare, TickDB, or both, that reconciliation is on you.


Next Steps

If you are building a cross-market strategy that includes A-shares:

Visit tickdb.ai to sign up for a free API key. The free tier provides 10,000 credits per month — sufficient for backtesting a multi-market strategy across several years of daily bars.

If you need A-share fundamental data beyond OHLCV:

Tushare's Pro tier remains the most cost-effective source for SHIBOR curves, sector classifications, margin balance data, and index composition histories. Use it in combination with TickDB for your cross-market price data layer.

If you are deploying a real-time event-driven system:

TickDB's WebSocket infrastructure handles connection resilience, heartbeat management, and reconnection logic. Review the production-grade WebSocket code in this article and adapt it for your specific latency requirements.

If you use AI coding assistants:

Search for and install the tickdb-market-data SKILL in your AI tool's marketplace for direct integration with TickDB endpoints in your AI-assisted workflow.


This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results. Data sourced from public API endpoints. Verify current data availability and pricing at tickdb.ai before committing to a data architecture.