Skip to main content
Glama
yli769227-jpg

ashare-mcp

ashare-mcp

Превратите финансовую отчетность акций класса A в инструменты, доступные для LLM. An MCP server that turns Chinese A-share financial statements into tools your LLM can call.

Позвольте Claude (или любому другому MCP-клиенту) получить структурированный баланс, отчет о прибылях и убытках или отчет о движении денежных средств с помощью одной фразы, например: "Как дела у Ping An Bank в годовом отчете за 2024 год?". Поля тщательно отобраны, единицы измерения четко определены, а данные оптимизированы для кэширования.

Источником данных является East Money, доступ осуществляется через akshare, все бесплатно и без необходимости использования токенов.


Почему мы создали это

Большинство проектов "финансовых LLM" на GitHub сосредоточены на торговых агентах и RAG для отчетов SEC 10-K — первые слишком однотипны, а вторые обслуживают только рынок США. Комбинация Акции класса A + Китайский язык + протокол MCP практически не представлена.

Позиционирование ashare-mcp очень узкое: делать только одну вещь — финансовую отчетность по акциям класса A, чтобы любой LLM-клиент мог подключиться к ней за десять секунд. Он не прогнозирует цены на акции, не пишет аналитические отчеты и не принимает решения за вас — он просто переносит данные из East Money в вызовы инструментов LLM, обеспечивая чистоту полей, понятность единиц измерения и четкую обработку ошибок.

Related MCP server: sfc-data-mcp

Быстрый старт

git clone https://github.com/yli769227-jpg/ashare-mcp.git
cd ashare-mcp
python3 -m venv .venv && source .venv/bin/activate
pip install -e .

Запуск дымового теста:

python -c "from ashare_mcp.data_source import get_annual_statements; \
  r = get_annual_statements('SZ000001', 2024); \
  print(r['company_name'], r['balance_sheet']['TOTAL_ASSETS'])"
# -> 平安银行 5769270000000.0

Подключение к Claude Desktop

Отредактируйте ~/Library/Application Support/Claude/claude_desktop_config.json (Mac):

{
  "mcpServers": {
    "ashare": {
      "command": "/absolute/path/to/ashare-mcp/.venv/bin/python",
      "args": ["-m", "ashare_mcp.server"]
    }
  }
}

Перезапустите Claude Desktop и задайте вопрос:

Помоги мне проанализировать годовой отчет Ping An Bank за 2024 год: каковы общие активы, общие обязательства, чистая прибыль и операционный денежный поток?

Список инструментов

Инструмент

Входные данные

Выходные данные

get_three_statements

stock_code, year

Три основных отчета (выбрано ~150 полей)

cross_check_balance

stock_code, year

Результаты 3 проверок + погрешность + отраслевая специфика

compare_peers

stock_codes[], year, metrics?

Горизонтальное сравнение N компаний + рейтинг / max-min-avg-std + ROE

Код поддерживает нормализацию форматов: 000001 / SZ000001 / sz.000001 / 000001.SZ.

cross_check_balance в настоящее время включает 4 проверки (первые 3 являются общеотраслевыми, 4-я учитывает специфику отрасли):

  1. Балансовое равенствоTOTAL_ASSETS = TOTAL_LIABILITIES + TOTAL_EQUITY

  2. Тождество денежных потоковNETCASH_OPERATE + NETCASH_INVEST + NETCASH_FINANCE + RATE_CHANGE_EFFECT = CCE_ADD

  3. Сверка денежных средств на начало/конец периодаEND_CCE − BEGIN_CCE = CCE_ADD

  4. Разложение операционной прибыли (с учетом отрасли)

    • Банки:OPERATE_PROFIT = OPERATE_INCOME − OPERATE_EXPENSE

    • Промышленные предприятия:OPERATE_PROFIT = TOTAL_OPERATE_INCOME − TOTAL_OPERATE_COST + OTHER_INCOME + INVEST_INCOME + FAIRVALUE_CHANGE_INCOME + ASSET_IMPAIRMENT_INCOME + CREDIT_IMPAIRMENT_INCOME + ASSET_DISPOSAL_INCOME [+ EXCHANGE_INCOME]

    • Автоматическое определение отрасли: если ACCEPT_DEPOSIT > 1 млрд, используется банковская формула; если есть TOTAL_OPERATE_INCOME + TOTAL_OPERATE_COST, используется промышленная формула, в противном случае skipped (страхование и т.д. пока не поддерживаются)

Допуски: первые 3 проверки — 10 000 юаней (округление отдельных статей), 4-я проверка — 10 000 000 юаней (накопленное округление при суммировании). Если поля отсутствуют или отрасль не определена, проверка помечается как skipped, что не влияет на остальные проверки. Тестирование на 3 отраслях (банки / производство алкоголя / аккумуляторы) и 4 компаниях за 2024 год показало результат 4/4.

Использование lru cache: при последовательном вызове get_three_statements и cross_check_balance, второй вызов выполняется менее чем за 1 мс (данные по акции уже в памяти).

Метрики по умолчанию для compare_peers: TOTAL_ASSETS / TOTAL_OPERATE_INCOME / PARENT_NETPROFIT / NETCASH_OPERATE / TOTAL_EQUITY, автоматически вычисляется ROE = PARENT_NETPROFIT / средний капитал (среднее значение капитала на конец текущего и прошлого года, данные за прошлый год берутся из lru cache практически бесплатно; если данные за прошлый год отсутствуют, используется капитал на конец периода, в поле roe_method ставится отметка ending_equity_fallback). Автоматический fallback: если в банковском секторе отсутствует TOTAL_OPERATE_INCOME, используется OPERATE_INCOME с пометкой в поле fallbacks. Параллельная реализация: ThreadPoolExecutor (max_workers=8), параллельный сбор данных по N компаниям (ошибка в одной компании не прерывает процесс, записывается в errors). Тестирование сравнения 4 крупнейших банков за 2024 год заняло ~38 секунд; ROE China Merchants Bank составил 12,85% (лидер в розничном сегменте).

Архитектура

flowchart LR
    LLM[Claude / 任意 MCP 客户端] -->|JSON-RPC over stdio| Server[ashare-mcp<br/>FastMCP server]
    Server -->|代码归一化| Norm[股票代码归一化<br/>SZ/SH/BJ 自动判断]
    Server -->|拉取三表| DS[数据源封装<br/>akshare 包装层]
    DS -->|缓存命中| Cache[(进程内存缓存<br/>lru_cache)]
    DS -->|缓存未命中| YearlyEM[akshare<br/>by_yearly_em]
    YearlyEM -->|HTTP| EM[东方财富<br/>财报数据接口]
    DS -->|字段过滤| Filter[剔除元数据列<br/>剔除同比列<br/>剔除空/零字段]
    Server -->|结构化 JSON| LLM

Ключевые особенности дизайна:

  • Сохранение оригинальных английских названий полей East Money (TOTAL_ASSETS / LOAN_ADVANCE / NETPROFIT). LLM понимает их напрямую, а поля для разных отраслей (банки / промышленность / страхование) находятся в одном словаре, что избавляет от необходимости сложной логики определения отрасли.

  • Кэширование в памяти процесса делает сравнение одной компании за несколько лет практически бесплатным — при холодном старте загружается полный объем, последующее переключение между годами занимает < 1 мс.

  • Логирование через stderr, чтобы не загрязнять протокол MCP stdio.

Дорожная карта

Версия

Инструмент

Статус

v0

get_three_statements

v1

cross_check_balance (3 общеотраслевые проверки)

v1

compare_peers (горизонтальное сравнение + ROE)

v1.5 (текущая)

cross_check_balance + разложение операционной прибыли (отраслевая специфика)

v1.5 (текущая)

compare_peers обновление до ROE_avg (средний капитал)

v2

Инструмент тренда track_company_history (одна компания за много лет + CAGR)

Ожидание

v2

Квартальные данные + производные показатели (YoY/QoQ)

Ожидание

v2

Публикация в официальном реестре MCP

Ожидание

Локальная разработка

# 增量验证(每次改完跑一遍)
python -c "from ashare_mcp.utils import normalize_stock_code; \
  assert normalize_stock_code('000001') == 'SZ000001'"

python -c "from ashare_mcp.server import mcp; \
  import asyncio; print([t.name for t in asyncio.run(mcp.list_tools())])"

Заявление об отказе от ответственности

  • Источник данных: East Money, через akshare.

  • Задержка данных, методология и точность определяются East Money, не является инвестиционной рекомендацией.

  • Только для образовательных и исследовательских целей.

Лицензия

MIT — см. LICENSE.

Available Tools

3 tools
compare_peersA

同业 N 家公司同年年报横向对比,自动算排名 / 最大最小 / 均值 / 标准差,加派生指标 ROE。

参数: stock_codes: 公司代码列表,如 ['000001', '600036', '601398']。建议 2-10 家。 支持各种格式:'000001' / 'SZ000001' / 'sz.000001' / '000001.SZ'。 year: 年份。 metrics: 可选,自定义对比字段。默认包括: TOTAL_ASSETS / TOTAL_OPERATE_INCOME / PARENT_NETPROFIT / NETCASH_OPERATE / TOTAL_EQUITY。 派生指标 ROE = PARENT_NETPROFIT / TOTAL_EQUITY 总是会算上。 银行业 TOTAL_OPERATE_INCOME 缺失时自动 fallback 到 OPERATE_INCOME(在 fallbacks 字段里标注)。

返回: { "year": 2024, "report_date": "2024-12-31", "metrics": ["TOTAL_ASSETS", ..., "ROE"], "companies": [ { "stock_code": "SZ000001", "company_name": "平安银行", "values": {metric: number}, "ranks": {metric: rank}, # 1 = 最大 "fallbacks": {original_key: actual_key} | null } ], "summary": { metric: {"max", "min", "avg", "std", "count"} }, "errors": [ {"stock_code": "...", "error": "..."} # 单家失败不挂整体 ] }

并发实现: ThreadPoolExecutor(max_workers=8),N 家公司并行拉。 缓存联动: 已经查过的公司走 lru cache,< 1ms 复用。

ParametersJSON Schema
NameRequiredDescriptionDefault
stock_codesYes
yearYes
metricsNo

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully discloses concurrency (ThreadPoolExecutor with 8 workers), caching (lru cache), single-failure tolerance, and fallback logic for bank metrics. Return structure is detailed with example JSON.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with clear sections for parameters, return fields, and implementation details. Every sentence adds value without redundancy. Length is appropriate for a complex tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

No output schema, yet description provides complete return structure with example JSON, concurrency, caching, and error handling. Covers all behavioral aspects needed for correct invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Input schema has 0% coverage, but description fully explains stock_codes formats, year, metrics default and optional, and derived ROE. Provides examples and constraints, compensating completely for schema gaps.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it compares annual reports of N peer companies horizontally, computes ranks, min/max, mean, std, and derived ROE. It distinguishes from siblings like cross_check_balance and get_three_statements by specifying peer comparison logic.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly recommends 2-10 companies, describes default metrics, and explains derived ROE always included. It doesn't explicitly state when not to use or alternatives, but provides clear context for appropriate use.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

cross_check_balanceA

跑财务勾稽校验,检测三大表数据是否互相自洽。返回每条校验的 passed/failed/skipped 状态与误差。

参数: stock_code: A 股代码,支持多种格式(同 get_three_statements)。 year: 年份,如 2024。仅支持年报。

返回: { "stock_code": "SZ000001", "company_name": "平安银行", "report_date": "2024-12-31", "checks": [ { "name": "balance_sheet_equation", "label": "资产负债平衡", "formula": "TOTAL_ASSETS = TOTAL_LIABILITIES + TOTAL_EQUITY", "lhs_value": 5769270000000.0, "rhs_value": 5769270000000.0, "diff": 0.0, "tolerance": 10000.0, "status": "passed" }, ... ], "summary": {"total": 3, "passed": 3, "failed": 0, "skipped": 0} }

当前 v1 包含 3 条行业通用勾稽:

  1. 资产负债平衡: TOTAL_ASSETS = TOTAL_LIABILITIES + TOTAL_EQUITY

  2. 现金流恒等式: 三大现金流 + 汇率影响 = 现金净增加额

  3. 期末/期初现金对账: END_CCE - BEGIN_CCE = CCE_ADD

容忍度 1 万元(财报舍入)。字段缺失时该条 status='skipped',不影响其它校验。

ParametersJSON Schema
NameRequiredDescriptionDefault
stock_codeYes
yearYes

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations given, but description fully covers behavior: checks three specific equations with tolerance, returns passed/failed/skipped status, handles missing fields gracefully, and notes annual-only support.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with intro, parameter details, return format example, and list of checks. Every sentence is informative and no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Despite no output schema, description provides full return example and explains all statuses and tolerance. Parameter semantics are fully covered, and sibling references add context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Adds significant meaning beyond schema: explains stock_code format and links to sibling tool, clarifies year only supports annual reports, and includes example values.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the tool performs financial cross-check validation among three statements, distinguishing it from siblings like get_three_statements and compare_peers.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides parameter specifics (stock_code supports multiple formats, year only annual reports) and lists the three checks. Does not explicitly exclude use cases, but context suffices.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_three_statementsA

拉取 A 股某只股票某年的年报三大财务报表(资产负债表 / 利润表 / 现金流量表)。

参数: stock_code: A 股代码,支持多种格式 —— '000001' / 'SZ000001' / 'sz.000001' / '000001.SZ'。 year: 年份(整数),如 2024。仅支持年报(报告期 12-31)。

返回: { "stock_code": "SZ000001", "company_name": "平安银行", "report_date": "2024-12-31", "currency": "CNY", "unit": "yuan (元)", "balance_sheet": {...}, # 字段如 TOTAL_ASSETS / LOAN_ADVANCE / ACCEPT_DEPOSIT "income_statement": {...}, # 字段如 OPERATE_INCOME / NETPROFIT / PARENT_NETPROFIT "cash_flow_statement": {...}, # 字段如 NETCASH_OPERATE / NETCASH_INVEST / NETCASH_FINANCE }

数据源: 东方财富(via akshare)。字段名为东方财富原始英文(SCREAMING_SNAKE_CASE)。 单位: 人民币元。 缓存: 进程内存缓存,同一只股票多次查询(不同年份)只走一次网络。

ParametersJSON Schema
NameRequiredDescriptionDefault
stock_codeYes
yearYes

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description bears full weight. It discloses caching behavior, data source, currency, unit, and field naming conventions, but does not mention authentication or rate limits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with a brief intro, bullet points for parameters, and a clear return format, though it could be slightly more concise.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity and lack of output schema, the description covers all relevant aspects: purpose, parameters, return structure, data source, caching, and units, making it fully informative.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description adds crucial detail: multiple accepted formats for stock_code and the requirement that year be an integer for annual reports only.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb (拉取/fetch), resource (年报三大财务报表), and scope (A股某只股票某年), distinguishing it from sibling tools like compare_peers and cross_check_balance.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description specifies that only annual reports are supported and provides parameter formats, but does not explicitly compare to sibling tools or state when not to use this tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv0.1.0
    • First observedcompare_peers
    • First observedcross_check_balance
    • First observedget_three_statements

TDQS

A4.4/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clear, distinct purpose: retrieving financial statements, cross-checking consistency, and comparing peers. There is no overlap or ambiguity.

Naming Consistency5/5

All tool names follow a consistent snake_case verb_noun pattern (compare_peers, cross_check_balance, get_three_statements), making them predictable and clear.

Tool Count4/5

Three tools is minimal but sufficient for the focused domain of A-share annual financial analysis. The count feels well-scoped without being overly thin.

Completeness4/5

The tools cover core workflows: data retrieval, internal consistency checks, and peer comparison. Minor gaps like quarterly data or individual ratio lookups exist, but the surface is largely complete for annual report analysis.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    MCP server that wraps SFC financial data API into 32 tools for comprehensive A-share market data, including real-time quotes, rankings, limit-up statistics, news, themes, financials, charts, research reports, and watchlists.
    -
  • A
    license
    A
    quality
    C
    maintenance
    A-share market data MCP server via baostock. Full-stack coverage: K-line, financials, DCF/DDM/PEG valuation, 11 technical indicators with proper split-day volume handling (OBV/MFI on raw bars), CN-style KDJ (J=3K-2D), risk metrics (Beta/Sharpe/MaxDD with stock-suspension-aware aligned returns), and PBoC macro data.
    25
    11
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    MCP server to fetch Vietnamese corporate financial reports (balance sheet, income statement, cash flow) from cafef.vn using public API, no PDF or OCR needed.
    3
    4 npm
    1
    MIT