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 클라이언트)가 "핑안은행 2024년 연례 보고서는 어때?"라는 질문 한마디로 구조화된 재무상태표 / 손익계산서 / 현금흐름표를 즉시 가져올 수 있게 합니다. 필드는 엄선되었고, 단위는 명확하며, 캐싱에 최적화되어 있습니다.

데이터 소스는 동방재부(East Money)이며, akshare를 통해 제공됩니다. 모두 무료이며 토큰이 필요하지 않습니다.


왜 다시 만들었는가

GitHub의 "금융 LLM" 프로젝트 대부분은 트레이딩 에이전트SEC 10-K RAG에 집중되어 있습니다. 전자는 동질화가 심하고, 후자는 미국 주식만 서비스합니다. A주 + 중국어 + MCP 프로토콜 계층의 조합은 거의 공백 상태입니다.

ashare-mcp의 포지셔닝은 매우 좁습니다: A주 재무제표라는 한 가지 일만 수행하며, 어떤 LLM 클라이언트든 10초 안에 연결할 수 있도록 만드는 것입니다. 주가를 예측하거나, 연구 보고서를 작성하거나, 대신 의사결정을 내리지 않습니다. 단지 데이터를 동방재부에서 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을 재시작하면 바로 질문할 수 있습니다:

핑안은행 2024년 연례 보고서를 봐줘. 총자산, 총부채, 순이익, 영업현금흐름이 각각 얼마야?

도구 목록

도구

입력

출력

get_three_statements

stock_code, year

연례 보고서 3대 재무제표(엄선된 ~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 > 10억이면 은행 공식, TOTAL_OPERATE_INCOME + TOTAL_OPERATE_COST가 있으면 일반 기업 공식, 그 외는 skipped(보험 등은 현재 미지원)

허용 오차: 앞 3개는 1만 위안(단일 항목 반올림), 4번째는 1000만 위안(다항목 합산 반올림 누적). 필드 누락이나 산업 식별 불가 시 해당 항목은 skipped 처리되며 다른 검증에는 영향을 주지 않습니다. 실측 결과 3개 산업(은행 / 백주 / 배터리) 4개 기업의 2024년 연례 보고서 모두 4/4 통과.

lru cache 연동: get_three_statements 호출 후 cross_check_balance를 호출하면, 후자는 < 1ms 만에 응답(동일 주식 데이터가 이미 메모리에 있음).

compare_peers 기본 metrics: 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 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

핵심 설계:

  • 필드명은 동방재부 원문 영어 유지(TOTAL_ASSETS / LOAN_ADVANCE / NETPROFIT). LLM이 직접 이해할 수 있으며, 은행 / 일반 기업 / 보험 등 서로 다른 산업의 필드가 모두 동일한 딕셔너리에 있어 산업 판단을 별도로 할 필요가 없음.

  • 프로세스 메모리 캐싱으로 "동일 기업 다년도 비교" 비용을 거의 제로화 — 콜드 스타트 시 전체 데이터를 가져오고, 이후 연도 전환은 < 1ms.

  • 로그는 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

분기 데이터 + 전년 동기/전 분기 대비 파생 지표

대기

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())])"

데이터 고지

  • 데이터 소스: 동방재부, akshare를 통해 제공.

  • 데이터 지연, 구경, 정확성은 동방재부를 기준으로 하며, 투자 권유가 아님.

  • 교육 및 연구 목적으로만 사용 가능.

라이선스

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