Skip to main content
Glama
24mlight

A-Share MCP Server

get_stock_analysis

Generate data-driven stock analysis reports for A-share stocks using fundamental, technical, or comprehensive analysis methods to inform investment decisions.

Instructions

    提供基于数据的股票分析报告,而非投资建议。

    Args:
        code: 股票代码,如'sh.600000'
        analysis_type: 'fundamental'|'technical'|'comprehensive'
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
analysis_typeNofundamental

Implementation Reference

  • The primary handler function for the 'get_stock_analysis' tool. It is decorated with @app.tool() for registration and implements the tool logic by logging the call and delegating to the use case layer via run_tool_with_handling.
    def get_stock_analysis(code: str, analysis_type: str = "fundamental") -> str:
        """
        提供基于数据的股票分析报告,而非投资建议。
    
        Args:
            code: 股票代码,如'sh.600000'
            analysis_type: 'fundamental'|'technical'|'comprehensive'
        """
        logger.info(f"Tool 'get_stock_analysis' called for {code}, type={analysis_type}")
        return run_tool_with_handling(
            lambda: build_stock_analysis_report(active_data_source, code=code, analysis_type=analysis_type),
            context=f"get_stock_analysis:{code}:{analysis_type}",
        )
  • The registration function that defines and registers the get_stock_analysis tool using the @app.tool() decorator within the FastMCP app.
    def register_analysis_tools(app: FastMCP, active_data_source: FinancialDataSource):
        """Register analysis tools."""
    
        @app.tool()
        def get_stock_analysis(code: str, analysis_type: str = "fundamental") -> str:
            """
            提供基于数据的股票分析报告,而非投资建议。
    
            Args:
                code: 股票代码,如'sh.600000'
                analysis_type: 'fundamental'|'technical'|'comprehensive'
            """
            logger.info(f"Tool 'get_stock_analysis' called for {code}, type={analysis_type}")
            return run_tool_with_handling(
                lambda: build_stock_analysis_report(active_data_source, code=code, analysis_type=analysis_type),
                context=f"get_stock_analysis:{code}:{analysis_type}",
            )
  • mcp_server.py:57-57 (registration)
    Top-level invocation of the analysis tools registration during server initialization, which includes registering the get_stock_analysis tool.
    register_analysis_tools(app, active_data_source)
  • Supporting helper function that implements the core stock analysis report generation logic, fetching basic info, fundamental, and technical data from the data source and formatting into a markdown report.
    def build_stock_analysis_report(data_source: FinancialDataSource, *, code: str, analysis_type: str) -> str:
        basic_info = data_source.get_stock_basic_info(code=code)
    
        # Fundamental data
        if analysis_type in ["fundamental", "comprehensive"]:
            recent_year = datetime.now().strftime("%Y")
            recent_quarter = (datetime.now().month - 1) // 3 + 1
            if recent_quarter < 1:
                recent_year = str(int(recent_year) - 1)
                recent_quarter = 4
    
            profit_data = data_source.get_profit_data(code=code, year=recent_year, quarter=recent_quarter)
            growth_data = data_source.get_growth_data(code=code, year=recent_year, quarter=recent_quarter)
            balance_data = data_source.get_balance_data(code=code, year=recent_year, quarter=recent_quarter)
            dupont_data = data_source.get_dupont_data(code=code, year=recent_year, quarter=recent_quarter)
        else:
            profit_data = growth_data = balance_data = dupont_data = None
    
        # Technical data
        if analysis_type in ["technical", "comprehensive"]:
            end_date = datetime.now().strftime("%Y-%m-%d")
            start_date = (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d")
            price_data = data_source.get_historical_k_data(code=code, start_date=start_date, end_date=end_date)
        else:
            price_data = None
    
        report = f"# {basic_info['code_name'].values[0] if not basic_info.empty else code} 数据分析报告\n\n"
        report += "## 免责声明\n本报告基于公开数据生成,仅供参考,不构成投资建议。投资决策需基于个人风险承受能力和研究。\n\n"
    
        # Basic info
        if not basic_info.empty:
            report += "## 公司基本信息\n"
            report += f"- 股票代码: {code}\n"
            report += f"- 股票名称: {basic_info['code_name'].values[0]}\n"
            report += f"- 所属行业: {basic_info['industry'].values[0] if 'industry' in basic_info.columns else '未知'}\n"
            report += f"- 上市日期: {basic_info['ipoDate'].values[0] if 'ipoDate' in basic_info.columns else '未知'}\n\n"
    
        if analysis_type in ["fundamental", "comprehensive"] and profit_data is not None and not profit_data.empty:
            report += f"## 基本面指标分析 ({recent_year}年第{recent_quarter}季度)\n\n"
            report += "### 盈利能力指标\n"
            if 'roeAvg' in profit_data.columns:
                report += f"- ROE(净资产收益率): {profit_data['roeAvg'].values[0]}%\n"
            if 'npMargin' in profit_data.columns:
                report += f"- 销售净利率: {profit_data['npMargin'].values[0]}%\n"
    
            if growth_data is not None and not growth_data.empty:
                report += "\n### 成长能力指标\n"
                if 'YOYEquity' in growth_data.columns:
                    report += f"- 净资产同比增长: {growth_data['YOYEquity'].values[0]}%\n"
                if 'YOYAsset' in growth_data.columns:
                    report += f"- 总资产同比增长: {growth_data['YOYAsset'].values[0]}%\n"
                if 'YOYNI' in growth_data.columns:
                    report += f"- 净利润同比增长: {growth_data['YOYNI'].values[0]}%\n"
    
            if balance_data is not None and not balance_data.empty:
                report += "\n### 偿债能力指标\n"
                if 'currentRatio' in balance_data.columns:
                    report += f"- 流动比率: {balance_data['currentRatio'].values[0]}\n"
                if 'assetLiabRatio' in balance_data.columns:
                    report += f"- 资产负债率: {balance_data['assetLiabRatio'].values[0]}%\n"
    
        if analysis_type in ["technical", "comprehensive"] and price_data is not None and not price_data.empty:
            report += "\n## 技术面简析(近180日)\n"
            latest_price = price_data['close'].iloc[-1]
            start_price = price_data['close'].iloc[0]
            price_change = ((latest_price - start_price) / start_price) * 100 if start_price else 0
            report += f"- 区间涨跌幅: {price_change:.2f}%\n"
            if 'close' in price_data.columns and price_data.shape[0] >= 20:
                ma20 = price_data['close'].astype(float).rolling(window=20).mean().iloc[-1]
                report += f"- 20日均线: {ma20:.2f}\n"
    
        return report
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions the tool provides 'data-based analysis reports' and distinguishes from investment advice, but lacks critical behavioral details: what format the reports are in, whether they're real-time or historical, if there are rate limits, authentication requirements, or data freshness. For a tool with no annotations, this is insufficient.

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 appropriately concise and well-structured: a clear purpose statement followed by an Args section with parameter explanations. No wasted sentences. However, the formatting with extra whitespace slightly reduces efficiency.

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

Completeness3/5

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

Given no annotations, no output schema, and 2 parameters with 0% schema coverage, the description is moderately complete. It covers the purpose and parameters adequately but lacks behavioral context (e.g., report format, limitations) and doesn't address the output, leaving gaps for a tool that generates analysis reports.

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?

Schema description coverage is 0%, so the description must compensate. It adds meaningful semantics: 'code' is explained as a stock code with an example ('sh.600000'), and 'analysis_type' is clarified with three specific options ('fundamental'|'technical'|'comprehensive') and a default. This goes beyond the bare schema, though it doesn't detail what each analysis type entails.

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

Purpose4/5

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

The description clearly states the tool's purpose: '提供基于数据的股票分析报告' (provide data-based stock analysis reports). It specifies the resource (stock analysis reports) and distinguishes from investment advice. However, it doesn't explicitly differentiate from sibling tools like get_fina_indicator or get_historical_k_data, which also provide stock-related data.

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

Usage Guidelines2/5

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

The description provides minimal usage guidance. It clarifies that the tool provides 'analysis reports, not investment advice,' which helps set expectations but doesn't specify when to use this tool versus the many sibling tools (e.g., get_fina_indicator for financial indicators, get_historical_k_data for price data). No explicit alternatives or exclusions are mentioned.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/24mlight/a-share-mcp-is-just-i-need'

If you have feedback or need assistance with the MCP directory API, please join our Discord server