AShareHub Python SDK
Simple, Pythonic access to Chinese market data
Query A-shares, ETFs, indices, financial statements, capital flows, real-time
quotes, news, and reference data from Python. Every endpoint returns a familiar
pandas.DataFrame.
Website · Documentation · API Reference · Get an API Key · Report an Issue
AShareHub is the official open-source Python client for the hosted AShareHub market data API. It gives analysts, researchers, and developers one consistent interface for working with Chinese market data without maintaining their own collection and normalization pipeline.
Contents
- Why AShareHub
- Quick start
- Data coverage
- Common workflows
- Data conventions
- Client configuration
- Error handling
- Documentation and ecosystem
- Development
- Contributing
Why AShareHub
- DataFrame first — every public method returns a
pandas.DataFrame, and an empty result returns an empty DataFrame. - One code convention — stocks, indices, sectors, ETFs, and other
instruments use the public
symbolfield consistently. - Broad market coverage — use one client for prices, fundamentals, financial statements, flows, holdings, ETFs, real-time quotes, and news.
- Discoverable contracts — inspect request parameters and response fields locally through the packaged machine-readable public contract.
- Small, familiar API — install from PyPI, authenticate with one API key, and receive analysis-ready tabular results.
Quick start
1. Install
pip install asharehub
AShareHub requires Python 3.10 or newer.
2. Get an API key
Create an account in the AShareHub console and generate an API key. Keep the key outside source control, for example in an environment variable:
export ASHAREHUB_API_KEY="ash_your_key_here"
3. Query market data
import os
from asharehub import AShareHub
with AShareHub(api_key=os.environ["ASHAREHUB_API_KEY"]) as client:
daily = client.market_daily(
symbol="000001.SZ",
start_date="20240101",
end_date="20241231",
)
print(daily[["trade_date", "open", "high", "low", "close", "vol"]].head())
daily is a regular DataFrame, so it works directly with pandas, notebooks,
visualization libraries, and research pipelines.
Data coverage
| Area | Examples | Selected SDK methods |
|---|---|---|
| Market and valuation | Daily OHLC, valuation ratios, adjustment factors, technical factors, price limits | market_daily, fundamentals, adj_factor, technical_factors, limit_list |
| Capital flows and holdings | Stock Connect flows, individual-stock money flow, northbound and southbound holdings | moneyflow_hsgt, moneyflow, northbound_holdings, southbound_holdings |
| Financials and corporate data | Statements, indicators, forecasts, dividends, audits, main business | income, balance_sheet, cash_flow, financial_indicators, forecast, dividend |
| Indices and concepts | Index prices and weights, concept sectors and constituents | index_daily, index_weight, concepts, concept_members |
| ETFs | Directory, prices, adjustment factors, NAV, shares, portfolios, baskets | etf_basic, etf_daily, etf_nav, etf_portfolio, etf_sh_basket, etf_sz_basket |
| Market activity | Margin data, block trades, top lists, institutional seats, shareholder activity | margin, block_trade, top_list, top_inst, shareholders, holder_trade |
| Reference and alternative data | Security lists, industries, calendars, chip distribution, FX | stock_list, industry_list, trade_calendar, chip_distribution, fx_daily |
| Live and research feeds | Real-time quotes, flash news, analyst reports | realtime, news_flash, analyst_reports |
See the API documentation for endpoint-specific parameters, response schemas, and examples.
Common workflows
Compare an ETF with its benchmark
with AShareHub(api_key=os.environ["ASHAREHUB_API_KEY"]) as client:
etf = client.etf_daily(symbol="510300.SH", start_date="20240101")
index = client.index_daily(symbol="000300.SH", start_date="20240101")
Load financial statements
with AShareHub(api_key=os.environ["ASHAREHUB_API_KEY"]) as client:
income = client.income(symbol="600519.SH", period="20241231")
balance_sheet = client.balance_sheet(symbol="600519.SH", period="20241231")
cash_flow = client.cash_flow(symbol="600519.SH", period="20241231")
Explore a concept sector and its constituents
with AShareHub(api_key=os.environ["ASHAREHUB_API_KEY"]) as client:
sectors = client.concepts(name="AI")
members = client.concept_members(
symbol="BK0425.DC",
con_symbol="000001.SZ",
)
Fetch real-time quotes
with AShareHub(api_key=os.environ["ASHAREHUB_API_KEY"]) as client:
quotes = client.realtime(symbol="000001.SZ,600519.SH,510300.SH")
Data conventions
Instrument codes
Public instrument fields use one stable naming contract:
- Use
symbolfor the primary stock, index, Eastmoney sector, ETF, or other instrument code. - Use
con_symbolwhen a request or record contains a second constituent security. - Use suffixed codes such as
000001.SZ,600519.SH,000300.SH,510300.SH, orBK0425.DC.
This convention is shared by the REST API, Python SDK, MCP server, public documentation, and packaged contract.
Dates and results
- Dates use
YYYYMMDD, for example20240819. - The default
v2client returns public fields such assymboland native JSON numbers. - Every method returns a DataFrame; no rows means
df.empty == True. - Method signatures vary intentionally. Use the contract or endpoint docs for the exact filters supported by each method.
Inspect the public contract
The package includes the authoritative SDK/MCP method signatures, request parameters, and response fields:
from asharehub import PUBLIC_CONTRACT, get_contract
daily_contract = get_contract("market_daily")
print(daily_contract["request_parameters"])
print(daily_contract["response_fields"])
print(PUBLIC_CONTRACT["version"])
Client configuration
Use the client as a context manager when possible so the underlying HTTP connection is closed automatically:
with AShareHub(
api_key=os.environ["ASHAREHUB_API_KEY"],
timeout=60.0,
) as client:
data = client.market_daily(symbol="000001.SZ")
For development or a compatible deployment, provide a custom base URL:
client = AShareHub(
api_key=os.environ["ASHAREHUB_API_KEY"],
base_url="https://your-api.example.com",
)
The client targets API v2 by default. Existing integrations can explicitly
select the legacy response surface with version="v1"; public SDK method
parameters continue to use symbol.
Error handling
HTTP errors are raised as httpx.HTTPStatusError, so standard httpx handling
works without an SDK-specific exception hierarchy:
import httpx
try:
data = client.market_daily(symbol="000001.SZ")
except httpx.HTTPStatusError as exc:
if exc.response.status_code == 401:
print("Check your API key")
elif exc.response.status_code == 429:
print("Rate limit reached")
else:
raise
Authentication and usage limits
Requests authenticate through the X-API-Key header, which the SDK configures
from the api_key argument. A free tier is available; current quotas and paid
plans are maintained on the pricing page.
Never commit API keys to a repository, notebook, image, or issue report.
Documentation and ecosystem
| Resource | Use it for |
|---|---|
| Python SDK guide | Installation and the first authenticated request |
| REST API documentation | Endpoint reference, schemas, authentication, and limits |
| A-share market data | Prices, volume, adjustment factors, and trading data |
| ETF data | ETF reference data, prices, NAV, shares, portfolios, and baskets |
| Financial data | Statements, indicators, forecasts, and dividends |
| MCP server | Connecting MCP-compatible clients and AI agents |
| Agent Skill | Guided AShareHub workflows for coding agents |
Development
Clone the repository and install the package in editable mode:
git clone https://github.com/ChuYiCui1/AshareHub.git
cd AShareHub
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
pytest -q
Tests that require a live API are skipped unless both environment variables are set. When an API server is available, run the integration suite with:
ASHAREHUB_API_KEY="ash_your_key_here" \
ASHAREHUB_BASE_URL="http://localhost:8000" \
pytest -v
Contributing
Issues and pull requests are welcome. Before opening a change:
- Search existing issues for related work.
- Keep the public
symbol/con_symbolcompatibility contract intact. - Add or update tests for behavior changes.
- Run
pytest -qand describe the user-visible impact in the pull request.
For questions, bug reports, or endpoint requests, open a GitHub issue.
Releases and support
- Install releases from PyPI.
- Review version history on GitHub Releases.
- Read the documentation.
- Contact
support@asharehub.comfor account or service support.
License
The SDK is available under the MIT License.
Disclaimer
AShareHub provides data access tooling, not investment advice. Verify data, licensing requirements, and applicable terms before using it in research, production systems, or trading decisions.
Built for the global investment community
Institutional research and monthly stock picks (0.10.0+)
V2 only: institutional_surveys, survey_participants, and broker_recommendations return DataFrames with explicit limit=100, offset=0 pagination. Event rows do not duplicate transcripts per institution. Fetch full text with include_content=True, limit=20 or less. Participant counts represent stored records, not unique institutions. Monthly broker picks use month="YYYYMM" and differ from analyst earnings forecasts.
events = client.institutional_surveys(start_date="20261101", limit=100)
picks = client.broker_recommendations(month="202611", limit=1000)
Metadata
Release files for asharehub 0.10.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| asharehub-0.10.0.tar.gz | 24.9 kB | With provenance | Details for asharehub-0.10.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| asharehub-0.10.0-py3-none-any.whl | Python 3 | none | any | Details for asharehub-0.10.0-py3-none-any.whl |
Total release size: 44.2 kB
Security for asharehub 0.10.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.