Skip to main content
Glama
ashare-mcp

ashare-mcp

by lolifamily

A-Share MCP Server

A-Share (中国A股) 市场数据 MCP 服务器,基于 baostock 数据源。

Vibe Coded -- 本项目由 AI 辅助编写 (vibe coding),代码质量和计算公式未经严格审计。 估值模型 (DCF / DDM / PEG)、技术指标、风险指标等涉及的数学公式可能存在错误, 产出的数字仅供学习参考,请勿作为任何投资决策的依据。 如果你发现了 bug,欢迎提 issue 或 PR。


功能概览

分类

工具

行情数据

K线、快照、复权因子、股票列表、行业分类、交易日历、分红

财务数据

利润、增长、资产负债、现金流、杜邦分析、营运能力

财务报表 (akshare 可选)

资产负债表、利润表、现金流量表 (绝对值全科目)、净负债

指数成分

沪深300、上证50、中证500

宏观数据

货币供应量 (M0/M1/M2)、存贷款利率、存款准备金率

技术分析

MACD、RSI、KDJ、BOLL、WR、CCI、ATR、ADX、OBV、MFI、均线 (SMA/EMA)

估值分析

PE/PB/PS 历史分位、行业对比、DCF、DDM、PEG

风险指标

Beta、Sharpe、最大回撤、波动率、信息比率

Related MCP server: ashare-mcp

快速开始

需要 Python >= 3.12 和 uv。

# 克隆
git clone <repo-url>
cd ashare-mcp

# 安装依赖
uv sync

# 启动 (stdio 模式,供 MCP 客户端对接)
uv run python -m ashare_mcp

# 或 HTTP 模式
uv run python -m ashare_mcp --transport http --port 3000

可选: akshare 扩展

# 安装 akshare 可选依赖后多出 2 个工具 + DCF 自动改用真实现金流/Capex/净负债
uv sync --extra akshare

安装后:

  • 新增 get_financial_statement (参数 statement: balance/income/cash_flow) 和 get_net_debt 工具 (数据源: 东方财富)

  • calculate_dcf_valuation 自动改用真实经营现金流 (NETCASH_OPERATE) 和 Capex (CONSTRUCT_LONG_ASSET),net_debt 自动从资产负债表计算;capex_to_ocf_ratio 仍需提供,作为 akshare 运行时失败/未安装时的回退估算

  • data_provenance 字段如实标注数据来源

  • 不安装则行为与之前完全一致

注意事项

  • 数据来源为 baostock 免费接口,无需注册、无需 API Key

  • baostock 仅提供 A 股历史数据,不提供实时行情

  • 技术指标需要足够的历史数据做 warmup(如 MACD 至少需要 33 个交易日),窗口过短会返回 null

  • 复权因子仅在除权除息日存在记录,非除权日期查询会返回空

  • DCF 中的 OCF 是由 MBRevenue * CFOToOR 推算的(约 2% 精度),Capex 需调用者自行提供;安装 akshare 后自动改用真实数据

  • DDM 的股利 CAGR 仅上限 clamp 到 20%(防过度外推),负 CAGR 透传

  • akshare 数据源走东方财富网页接口,有反爬/限频,不保证永久稳定

Credits

Available Tools

25 tools
calculate_dcf_valuationA

Simplified DCF valuation. OCF derived as MBRevenue * CFOToOR (~2% precision).

FCF = OCF * (1 - capex_to_ocf_ratio). Caller must supply capex_to_ocf_ratio because baostock provides no Capex data.

Enterprise value (EV) is always returned. To derive equity value and per-share intrinsic value, caller must provide net_debt, which baostock does NOT publish — it must come from the balance sheet (interest-bearing debt minus cash & equivalents). Without it, only EV is returned and the caller can compute equity = ev - (their own net_debt).

When akshare is installed and reachable, real operating cash flow (NETCASH_OPERATE) and real capex (CONSTRUCT_LONG_ASSET) are used automatically (capex_to_ocf_ratio is then ignored), and net_debt is computed from the balance sheet if not provided. If akshare is absent or fails at runtime (rate-limit, anti-scrape), the calculation falls back to baostock estimation using capex_to_ocf_ratio. data_provenance indicates which path.

Uses a fixed 5-year FCF history, degrading gracefully to as few as 2 years when reports are missing.

forecast_growth clamps fcf_cagr to growth_clamp_bounds ([-5%, 15%]); growth_clamped reports which bound (if any) was hit. Read it before using forecast_growth -- a raw CAGR outside the band was silently overridden.

intermediates.fcf_quality reports negative_years / sign_changes / min / max on the historical FCF series; fcf_cagr is endpoint-anchored and does not reflect intra-period volatility.

Args: code: Stock code. discount_rate: WACC / discount rate, e.g. 0.10. terminal_growth_rate: Perpetual growth rate, e.g. 0.025. capex_to_ocf_ratio: Capex as a fraction of OCF. Always required, but used only on the baostock fallback path; ignored when akshare's real capex is available. net_debt: Interest-bearing debt minus cash & equivalents (CNY). Negative = net cash position. Required for per-share valuation. forecast_years: Projection period (must be in [1, 20]).

Inputs: code (required), discount_rate (required), capex_to_ocf_ratio (required), terminal_growth_rate (required), +2 more.

calculate_ddm_valuationA

DDM (Dividend Discount Model) valuation.

Uses dividCashPsBeforeTax from baostock. Auto-sums semicolon-separated multi-payouts. Current price from latest K-line close. Excludes the current calendar year, whose dividend bucket is usually incomplete mid-year. Buckets are by announcement year, so a prior fiscal year's final payout and the next year's interim can land in the same bucket, distorting dividend_cagr.

forecast_growth caps dividend_cagr at growth_clamp_bounds.max (20%); negative CAGR passes through unchanged. growth_clamped is "exceeded_max" if the cap fired, else null.

Args: code: Stock code. discount_rate: Required rate of return, e.g. 0.10. terminal_growth_rate: Perpetual growth rate, e.g. 0.025. years_back: Years of dividend history to use. forecast_years: Projection period (must be in [1, 20]).

Inputs: code (required), discount_rate (required), terminal_growth_rate (required), years_back, +1 more.

calculate_peg_ratioA

Calculate PEG = current PE_TTM / G, with G the latest published YoY net profit growth.

PE is the latest available quote; G is the most recently disclosed YoY growth, returned as growth_period (statDate) and growth_period_type (Q1/H1/9M/FY). baostock's YOYNI is a ratio (0.1858 = +18.58% YoY); PEG uses the percent number (18.58).

PEG is undefined and returns peg=None when:

  • PE == 0 (no TTM earnings data: index / non-equity, not loss-making)

  • PE < 0 (loss-making company; PE has no valuation meaning)

  • no growth report has been published yet (fresh IPO / data delay)

  • YoY growth <= 0 (PEG is a growth-stock metric; declining earnings yield a negative or nonsensical value that LLMs would misread as cheap)

Args: code: Stock code.

Inputs: code (required).

calculate_risk_metricsA

Calculate risk metrics: beta, Sharpe, max drawdown, volatility, correlation.

Args: code: Stock code. benchmark_code: Benchmark index, default 'sh.000300' (CSI 300). lookback_days: Calendar days to look back. 365 ≈ 1 year, 730 ≈ 2 years. Must yield >= 30 trading-day bars (~45+ calendar days, more if the span crosses a long holiday) or the call is rejected. ~245 calendar days ≈ 1 trading year (CN A-share). risk_free_rate: Annualized risk-free rate for Sharpe ratio. Default ~3% (approximate CN 10Y bond yield); override for non-CN markets.

Inputs: code (required), lookback_days, benchmark_code, risk_free_rate.

compare_industry_valuationA

Compare a stock's valuation (PE/PB/PS) against its industry peers.

Behavior contract:

  • Raises NoDataFoundError if code is absent from the industry table for date, has no industry classification (delisted / legacy stock), or has no K-line in the lookback window — it will not return a result without the target.

  • Peers whose K-line is missing are listed in peer_coverage.skipped with the reason. Industry statistics exclude the target itself and use POSITIVE values only; the center stat is trimmed_mean (10% per tail, >=1 each side), not a raw mean. industry_stats[metric].count reports peers per statistic.

Args: code: Target stock code. date: Comparison date 'YYYY-MM-DD'. Defaults to latest.

Inputs: code (required), date.

get_adjust_factor_dataA

Fetch adjustment factor data for calculating adjusted prices.

Factors exist only on ex-div / ex-rights dates; a window with none returns an empty list.

Args: code: Stock code. start_date: 'YYYY-MM-DD'. end_date: 'YYYY-MM-DD'.

Inputs: code (required), end_date (required), start_date (required).

get_all_stockA

Search stocks by name. Returns matching code, code_name, and tradeStatus.

Args: query: Search keyword matched against code_name (substring, case-insensitive). An empty string matches every row and returns the full market (~5000+ stocks, ~1 MB). date: Date 'YYYY-MM-DD'. Defaults to the latest trading date.

Inputs: query (required), date.

get_benchmark_rate_dataA

Fetch PBoC benchmark deposit or loan rates within a date range.

rate_type:

  • 'deposit': benchmark deposit rates — demand plus fixed-term 3-month .. 5-year.

  • 'loan': benchmark loan rates — 6-month .. above-5-year, plus mortgage rates.

Args: rate_type: Which rate table to fetch. start_date: Optional 'YYYY-MM-DD'. end_date: Optional 'YYYY-MM-DD'.

Inputs: rate_type (required), end_date, start_date.

get_dividend_dataA

Fetch a year's dividends: annual cash total plus every payout's detail.

A year with several distributions has one entry per payout in payouts (full detail). annual_cash_per_share_pretax is their summed dividCashPsBeforeTax — the yearly total, so callers needn't add across rows. Within a single payout, semicolon-separated multi-values in the cash-dividend fields are already summed by the client.

annual_cash_per_share_pretax is None when the year had distributions but no cash (pure stock dividend / capital reserve conversion); read each payout's dividStocksPs / dividReserveToStockPs for those.

Args: code: Stock code. year: 4-digit year, e.g. '2023'. year_type: 'report' (announcement year) or 'operate' (ex-dividend year).

Returns: {code, year, annual_cash_per_share_pretax, payout_count, payouts}.

Inputs: code (required), year (required), year_type.

get_financial_indicatorsA

Fetch a quarterly financial report; report selects which statement.

baostock splits quarterly fundamentals across six statements, each with a distinct field set. All values are cumulative-from-year-start: quarter=1 is 3-month, 2 is H1 (6-month), 3 is 9-month, 4 is FY (12-month).

report:

  • 'profit': profitability — roeAvg, npMargin, gpMargin, netProfit, epsTTM, MBRevenue, totalShare.

  • 'operation': turnover ratios — NRTurnRatio, INVTurnRatio, CATurnRatio, AssetTurnRatio (and matching *Days).

  • 'growth': YoY growth rates — YOYNI, YOYEPSBasic, YOYEquity, YOYAsset, YOYPNI.

  • 'balance': balance-sheet ratios — currentRatio, quickRatio, liabilityToAsset, assetToEquity. liabilityToAsset is rederived as 1 - 1/assetToEquity to work around stale upstream values (falls back to the raw value only when assetToEquity is null or zero).

  • 'cash_flow': cash-flow ratios — CFOToOR, CFOToNP, CFOToGr, CAToAsset.

  • 'dupont': DuPont ROE decomposition — dupontROE, dupontAssetTurn, dupontNitogr, dupontTaxBurden, dupontEbittogr.

Args: code: Stock code, e.g. 'sh.600519'. report: Which statement to fetch (see above). year: 4-digit year, e.g. '2024'. quarter: 1, 2, 3, or 4.

Inputs: code (required), year (required), report (required), quarter (required).

get_financial_statementA

Fetch a full financial statement (all periods, all columns) from EastMoney via akshare.

statement selects which one (each is a separate EastMoney endpoint — one fetch per call, so request only the statement you need):

  • "balance" 资产负债表 — point-in-time snapshot per report date.

  • "income" 利润表 — key fields OPERATE_INCOME, NETPROFIT, ...

  • "cash_flow" 现金流量表 — key fields NETCASH_OPERATE (operating cash flow), CONSTRUCT_LONG_ASSET (capex).

Returns raw EastMoney field names (English uppercase keys), rows ordered most-recent-first (newest period at index 0). Columns entirely empty across the returned periods are dropped.

IMPORTANT — for "income" and "cash_flow", quarterly values are cumulative YTD (year-to-date), not single-quarter:

  • Q1 (一季报) = 3 months

  • H1 (半年报) = 6 months

  • Q3 (三季报) = 9 months

  • FY (年报) = 12 months Inspect REPORT_DATE_NAME before comparing across periods. To get a single quarter, subtract the previous cumulative period (e.g. Q3_single = Q3 - H1). The balance sheet is a snapshot, so this does not apply to it.

Args: code: Stock code in baostock format, e.g. 'sh.600519'. statement: Which statement — "balance", "income", or "cash_flow". periods: How many most-recent report periods to return (default 8 ≈ 2 years of quarterly filings). Raise only when you need older periods — the full history is large.

Inputs: code (required), statement (required), periods.

get_historical_k_dataA

Fetch historical K-line (OHLCV + valuation) data for a Chinese A-share stock.

Args: code: Stock code in baostock format, e.g. 'sh.600000', 'sz.000001'. start_date: Start date 'YYYY-MM-DD'. end_date: End date 'YYYY-MM-DD'. frequency: 'd' daily, 'w' weekly, 'm' monthly, '5'/'15'/'30'/'60' minutes. adjust_flag: '1' backward/后复权, '2' forward/前复权, '3' unadjusted/不复权 (default '3'). fields: Comma-separated field list. Defaults to all standard fields.

Inputs: code (required), end_date (required), start_date (required), fields, +2 more.

get_index_constituentsA

Fetch constituent stocks of a major A-share index.

index:

  • 'sz50': SSE 50 (上证50).

  • 'hs300': CSI 300 (沪深300).

  • 'zz500': CSI 500 (中证500).

Args: index: Which index's constituents to fetch. date: Optional date 'YYYY-MM-DD'. Defaults to latest.

Inputs: index (required), date.

get_latest_trading_dateA

Most recent trading date with K-line data published. Returns 'YYYY-MM-DD'.

Probes CSI 300 (sh.000300) directly and returns the date of its latest available daily bar. This is the safe anchor date for follow-up K-line queries — guaranteed to have data, regardless of wall-clock time. On a trading day before market close, today's bar is not yet published, so this returns the previous trading date.

Inputs: no named parameters.

get_money_supply_dataA

Fetch money supply data (M0, M1, M2) at monthly or yearly frequency.

freq:

  • 'month': monthly series — m0Month/m1Month/m2Month plus YOY and ChainRelative. Dates are 'YYYY-MM'.

  • 'year': year-end balances — m0Year/m1Year/m2Year plus YearYOY. Dates are 'YYYY'.

Args: freq: 'month' for the monthly series, 'year' for year-end balances. start_date: Optional. Format matches freq: 'YYYY-MM' (month) or 'YYYY' (year). end_date: Optional, same format as start_date.

Inputs: freq (required), end_date, start_date.

get_moving_averagesA

Calculate SMA and EMA for multiple periods over the requested date range.

Returns one row per trading day in [start_date, end_date]. Warmup is auto-prefetched, so values inside the range are not null from warmup. A period exceeding the stock's available history yields present-but-all-null SMA_/EMA_ columns, so a requested period never silently vanishes.

Args: code: Stock code. start_date: 'YYYY-MM-DD'. end_date: 'YYYY-MM-DD'. periods: Period list (each must be >= 1), e.g. [5,10,20,50,120,250]. Defaults to common set.

Inputs: code (required), end_date (required), start_date (required), periods.

get_net_debtA

Compute net debt from the latest balance sheet (conservative upper bound).

net_debt = SHORT_LOAN + LONG_LOAN + BOND_PAYABLE + NONCURRENT_LIAB_1YEAR - MONETARYFUNDS

NONCURRENT_LIAB_1YEAR is a CN-GAAP aggregate bucket containing both long-term-debt current portion (interest-bearing) and lease-liability / long-payable current portions (not interest-bearing); the breakdown is not exposed by EastMoney. For lease-heavy or zero-leverage firms the returned net_debt is overstated by the non-interest portion of this bucket.

Data source: EastMoney via akshare. Returns net_debt value, component breakdown, and the report date of the balance sheet used.

Args: code: Stock code in baostock format, e.g. 'sh.600519'.

Inputs: code (required).

get_performance_reportA

Fetch performance express (业绩快报) or forecast (业绩预告) reports.

kind:

  • 'express': performance express reports — absolute performanceExpressTotalAsset / NetAsset / EPSDiluted / ROEWa / GRYOY for companies that file them ahead of the full report.

  • 'forecast': performance forecast reports — profitForcastChgPctUp / profitForcastChgPctDwn and the forecast type.

Args: code: Stock code. kind: 'express' for filed express reports, 'forecast' for guidance. start_date: 'YYYY-MM-DD'. end_date: 'YYYY-MM-DD'.

Inputs: code (required), kind (required), end_date (required), start_date (required).

get_required_reserve_ratio_dataB

Fetch required reserve ratio data.

Args: start_date: Optional 'YYYY-MM-DD'. end_date: Optional 'YYYY-MM-DD'. year_type: '0' announcement date (default), '1' effective date.

Inputs: end_date, year_type, start_date.

get_stock_basic_infoB

Fetch basic info: code, code_name, ipoDate, outDate, type, status.

Args: code: Stock code, e.g. 'sh.600519'.

Inputs: code (required).

get_stock_industryA

Fetch industry classification data.

Args: code: Stock code, e.g. 'sh.600519'. date: Optional date 'YYYY-MM-DD'. Defaults to latest.

Inputs: code (required), date.

get_stock_snapshotA

One-call snapshot: latest price, valuation, industry, total shares, net profit.

Combines data from K-line, stock_industry, and profit_data.

Designed for individual stocks. An index (sh.000300, etc.) has K-line + valuation but no industry / basic / profit rows; those fields come back null instead of aborting the call, so price + PE/PB/PS are still returned.

Profit fields (net_profit, revenue) come from the most recently published report, so they may be Q1, H1, 9M, or FY depending on the calendar. Always inspect profit_period_type ('Q1'/'H1'/'9M'/'FY') and profit_period_months (3/6/9/12) before comparing across companies: baostock reports these cumulative-from-year-start, so Q1's net_profit is 3 months, NOT comparable to FY's 12. To annualize, multiply Q1 by 4, H1 by 2.

baostock fills MBRevenue only on H1 / FY reports, so revenue is null when profit_period_type is 'Q1' or '9M'.

Args: code: Stock code.

Inputs: code (required).

get_technical_indicatorsA

Calculate technical indicators for a stock.

Trend/momentum indicators use forward-adjusted prices. Volume indicators (OBV, MFI) transparently fetch a second pass with raw bars because baostock does not split-adjust volume — mixing forward-adjusted price with raw volume would distort money-flow on split / bonus-issue days. Volume indicators thus cost one extra network round-trip when requested.

Returns one row per trading day in [start_date, end_date]. Warmup is auto-prefetched, so values inside the range are not null from warmup.

Args: code: Stock code. start_date: 'YYYY-MM-DD'. end_date: 'YYYY-MM-DD'. indicators: List from ['MACD','RSI','KDJ','BOLL','WR','STOCH','CCI','ATR','ADX','OBV','MFI']. Defaults to all.

Inputs: code (required), end_date (required), start_date (required), indicators.

get_trade_datesA

Fetch trading calendar. Each row has calendar_date and is_trading_day ('1'/'0').

Args: start_date: Optional 'YYYY-MM-DD'. end_date: Optional 'YYYY-MM-DD'.

Inputs: end_date, start_date.

get_valuation_metricsA

Fetch valuation metrics (PE/PB/PS/PCF) history and current snapshot.

Each metric in metrics independently reports current and as_of (the date of its last valid observation), since close and PE/PB/PS can be missing on different days. period.last_trading_date reports the last K-line bar in the window, separate from any metric's as_of.

Each non-close metric also reports positive_mean/positive_median/ positive_min/positive_max plus percentile_pct (0-100 rank of current: a fresh low ~0.4, an all-time high ~100), computed over POSITIVE values only. sample_size is the positive-observation count; percentile_pct is null when current is non-positive.

Args: code: Stock code. start_date: Optional, defaults to 1 year ago. end_date: Optional, defaults to today.

Inputs: code (required), end_date, start_date.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 25 tools

    Disambiguation4/5

    Most tools have clearly distinct purposes, with only minor potential overlap between get_financial_indicators and get_financial_statement. Descriptions are detailed enough to differentiate them, and no two tools appear to do the same thing.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern using snake_case, either get_* or calculate_*. There is no mixing of conventions or camelCase, making the naming predictable and clear.

    Tool Count4/5

    25 tools is on the high side but still reasonable for a comprehensive Chinese A-share analysis server. The breadth of coverage (fundamentals, technicals, macro) justifies the count, though a slight reduction could improve focus.

    Completeness4/5

    The tool set covers a wide range of essential functionalities for stock analysis, including valuation, financials, technicals, and macro data. Minor gaps exist (e.g., options, sentiment), but the core workflows are well-supported.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      D
      maintenance
      Professional financial data MCP server integrating Tushare API, providing real-time financial data and technical indicators analysis for stocks, indices, funds, bonds, and cryptocurrencies across multiple markets (A-share, US, HK, crypto).
      18
      MIT
    • F
      license
      B
      quality
      D
      maintenance
      An MCP server that exposes all 23 baostock data endpoints as tools, including K-line, quarterly financials, performance reports, dividends, industry classification, index constituents, and macro series.
      24
      3
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      基于通达信行情服务器的 MCP Server,为 AI 助手提供实时 A 股、期货、港股等行情数据及技术指标。
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      An MCP server providing A-share market data tools (daily OHLCV, real-time quotes, financials, northbound capital flow, sector lists) with zero dependencies, also serving as a template for building custom MCP servers.
      2
      MIT