Skip to content

Latest commit

 

History

History
213 lines (149 loc) · 14.2 KB

README.en.md

File metadata and controls

213 lines (149 loc) · 14.2 KB

ashareapi

ashareapi — Official Python SDK for the A-Share Data API

Quotes / K-lines / Financials / Money flow / Dragon-Tiger list / Sectors / Factor screening / Quant backtest — 40 endpoints, and the free endpoints require no sign-up.

Python

pandas

PyPI

CI

License

中文 · English

Website · Docs · Endpoint list · MCP · Agent Skill

Source · Issues · Changelog

Popular endpoint docs: K-line · Factor screening · Health check

pip install ashareapi            # base (returns list[dict])
pip install "ashareapi[pandas]"  # adds DataFrame support (recommended)

There is also a Node.js / TypeScript SDK: npm install ashareapi — npm

What this is

The official Python SDK for the A-Share Data API — it wraps the HTTP endpoints into one-line method calls, so you skip building URLs, handling retries and parsing response shapes. After pip install ashareapi:

from ashareapi import AShareAPI
cli = AShareAPI(api_key="ct-your-key")   # or set the ASHARE_API_KEY env var
print(cli.quote("sh600667"))             # quotes
print(cli.backtest(code="sh600667", strategy="mom20"))   # quant backtest

5 endpoints need no key (they work as soon as you install): /v1/quote · /v1/kline · /v1/hot · /v1/market-overview · /v1/changedist. The rest need a key (get one, from ¥9.9).

30-second quickstart

from ashareapi import AShareAPI

cli = AShareAPI()                     # free endpoints need no key
df = cli.quote("sh600667")            # real-time quote → DataFrame
print(df[["date", "last", "turnover"]])

print(cli.kline("600667.SH", count=5))  # any code format works (auto-normalized)
print(cli.hot(limit=10))                # hot-search ranking

Paid endpoints (financials / money flow / Dragon-Tiger list / screening, etc.) need a key — get one from ¥9.9:

cli = AShareAPI("ct-your-key")          # or set the ASHARE_API_KEY env var
df = cli.screen(preset="low_pe", orderby="ROETTM", limit=10)
print(df.head())

Why use it

  • Free endpoints are genuinely key-free: quote / kline / hot / market-overview / changedist work immediately, no registration
  • Ticker format tolerant: sh600667 / 600667.SH / 600667 all accepted (drop it into existing projects as-is)
  • Automatic source failover: 70 data sources back each other up on the backend; a failed fetch switches source automatically and does not consume your quota
  • Fixed conventions, no post-processing: K-line is forward-adjusted server-side (there is no adjust parameter), so you never double-adjust
  • Nothing for you to maintain: multi-source failover / caching / health checks all live on the server — the client just calls
  • Clear error taxonomy: AuthError / RateLimitError / UpstreamError / EmptyResultError (no data ≠ failure) — each one tells you what to do next
  • pandas is optional: works without pandas too (returns list[dict])

Endpoints

Method Description Key-free
quote(code) Real-time quote snapshot ✅
kline(code, period, count, start, end) K-line (daily / weekly / monthly / quarterly / yearly + minute bars m1–m120) · adjustment fixed server-side (qfq for daily and above · raw for minute bars) ✅ daily and above / ⚠️ paid for minute bars
minute(code, days) Intraday tick chart (today / last 5 sessions) · paid —
hot(limit) Hot-search ranking ✅
market_overview(type) Market overview (profile / valuation / style rotation) ✅
changedist() Advance-decline distribution (market breadth) ✅
finance(code, num) The three financial statements —
fund(code) Money flow + Dragon-Tiger list + block trades + margin trading —
technical(code) MA / MACD / KDJ / RSI / BOLL —
lhb(type) Dragon-Tiger sub-rankings (institutions / hot money / active seats) —
screen(expr/preset, ...) Factor screening —
search(q) Search with disambiguation —
kline_full(code, fq, start, end) Full-history daily bars in one call (~2,465 rows) · fq is qfq/hfq/nofq —
backtest(strategy, mode, code, ...) Quant backtest (single stock live / portfolio preset ranges · weighting = equal or inverse-volatility) —
backtest_batch(codes, strategies, ...) Batch backtest (many stocks × many strategies comparison matrix · ≤20 × 10) —
strategies() Quant strategy list (20 single-stock + 9 portfolio, with parameter ranges) —
factors(category, kind) Quant factor library (88 factors + 50 screening shortcuts + 22 presets) —
playbooks(category, id) Quant playbook library (13 "how to judge the market" workflows) —
ip_whitelist(action, ips) IP allow-list (lock a key to fixed IPs · action = get/set/clear) —

⚠️ K-line prices are always forward-adjusted (qfq) — no gaps on ex-dividend dates, and there is no adjust parameter. Do not adjust them yourself (that would double-adjust).

(All 40 endpoints: endpoint list)

Return shapes

With pandas installed, methods return a DataFrame (otherwise list[dict]), so you can select columns by name:

df = cli.quote("sh600667")
print(df[["date", "last", "turnover"]])

Use raw=True when you need the raw envelope (with endpoint / tier / elapsed_ms / source):

cli = AShareAPI(raw=True)
env = cli.quote("sh600667")
# { 'ok': True, 'endpoint': '/v1/quote', 'tier': 'free', 'elapsed_ms': 862, 'source': '...', 'data': [...] }

⚠️ Three return shapes: most endpoints are a single table → DataFrame; finance() returns a list of tables (list[list[dict]]); shareholder() / calendar() return a sectioned structure ({tables, data}, kept as a plain dict). The latter two are not wrapped into a DataFrame.

Error handling

from ashareapi import AShareAPI, AuthError, RateLimitError, UpstreamError, EmptyResultError

cli = AShareAPI()
try:
    df = cli.fund("sh600667")
except AuthError as e:          # 401 / missing key → go get a key
    print(e)
except RateLimitError as e:     # 429 → slow down / solve the PoW challenge for a higher quota / upgrade
    print(e)
except UpstreamError as e:      # upstream fetch failed (source already switched, quota not charged) → one retry usually fixes it
    print(e)
except EmptyResultError as e:   # no data right now (e.g. no block trades today) → not billed; change conditions or retry later
    print(e)

Also works with AI agents (MCP / Agent Skill)

Besides the Python SDK, we offer two ways to plug into AI agents:

  • MCP server (Streamable HTTP) — server URL https://api.ashareapi.com/mcp

    (⚠️ use that endpoint URL; the site page ashareapi.com/en/mcp/ is the guide, not the endpoint)

  • Per-client configuration (Claude Code / Cursor / VS Code / Codex and 19 clients in total, every key name checked against official docs):

    https://ashareapi.com/en/mcp/

  • Agent Skill (an endpoint manual for AI agents + a downloadable package; drop it into your skills directory): https://ashareapi.com/en/skill/

Free tools/endpoints need no key; paid tools take Authorization: Bearer <your-key> in the request header.

Examples

Runnable examples live in examples/:

File What it does
examples/quickstart.py Fetch quotes / K-lines / hot search from free endpoints (no key) + commented examples for paid endpoints
python examples/quickstart.py

Requirements

  • Python ≥ 3.9
  • Only depends on requests (≥ 2.28)
  • pandas optional: installed → returns DataFrame, not installed → returns list[dict]
  • Example code: examples/quickstart.py

Related

Official SDKs: Python pip install ashareapi · Node.js / TypeScript npm install ashareapi

MCP server: https://api.ashareapi.com/mcp (setup)

Agent Skill (an interface manual for AI agents): https://ashareapi.com/en/skill/

Version history

Current version: 0.2.0 (2026-10-08)

Version Changes
0.2.0 New quant methods backtest() / backtest_batch() / strategies() / factors() / playbooks(); added kline_full() (full-history K-line) and ip_whitelist(); POST/DELETE support in the core
0.1.11 New minute() intraday method; kline() now supports minute bars m1–m120 and start/end date ranges; PoW raise changed from 60/min to 15/min
0.1.10 429 message now states the anonymous quota precisely (max 250 rows per request / 100k rows per day) · distinguishes "per-minute rate exceeded" from "daily row cap exceeded" (PoW does not help for the latter) · no behavior change
0.1.9 Documentation: README gains "Requirements", "Return shapes" and "Examples" · added GitHub repo / Issues links and the CI badge · source comments and docs wording aligned (no behavior change)
0.1.8 Documentation wording: price convention (forward-adjusted) unified across README / method docs / CHANGELOG · MCP URL and Agent Skill descriptions clarified
0.1.7 Documentation: MCP server URL https://api.ashareapi.com/mcp made explicit · Agent Skill section added (/skill) · changelog links switched to clickable absolute URLs
0.1.6 Documentation: kline() now states the price convention (forward-adjusted · no adjust parameter · do not double-adjust)
0.1.5 Documentation: turnover field example updated to turnover · added the 0.1.3 / 0.1.4 rows · metadata Changelog points to the site changelog
0.1.4 finance() now returns the table list as-is · shareholder() / calendar() sectioned structures locked down · User-Agent version unified
0.1.3 Documentation revision (snapshot() / orderbook() boundaries) · added CHANGELOG.md + MANIFEST.in
0.1.2 Added snapshot() (full-field profile) · methods 31 → 32
0.1.1 Added orderbook() (5-level depth) · methods 30 → 31
0.1.0 First release (30 methods · 5 free endpoints)

⚠️ The endpoints themselves are always current (the service evolves server-side, no SDK upgrade needed) — upgrading only gets you the new convenience methods.

Full changelog → CHANGELOG.md in the package · site changelog · PyPI release history

License

MIT · Data is for research reference only and is not investment advice