Skip to main content
Glama
24mlight

A Share MCP

by 24mlight

get_adjust_factor_data

Fetch adjustment factor data for A-share stocks to calculate adjusted prices using Baostock's price change adjustment algorithm for specified date ranges.

Instructions

    Fetches adjustment factor data for a given stock code and date range.
    Uses Baostock's "涨跌幅复权算法" factors. Useful for calculating adjusted prices.

    Args:
        code: The stock code in Baostock format (e.g., 'sh.600000', 'sz.000001').
        start_date: Start date in 'YYYY-MM-DD' format.
        end_date: End date in 'YYYY-MM-DD' format.

    Returns:
        Adjustment factors table.
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
start_dateYes
end_dateYes
limitNo
formatNomarkdown

Implementation Reference

  • Primary handler function for the MCP tool 'get_adjust_factor_data'. Decorated with @app.tool() for automatic registration and schema inference. Handles logging, delegates to use case via run_tool_with_handling for shared error handling and formatting.
    @app.tool()
    def get_adjust_factor_data(code: str, start_date: str, end_date: str, limit: int = 250, format: str = "markdown") -> str:
        """
        Fetches adjustment factor data for a given stock code and date range.
        Uses Baostock's "涨跌幅复权算法" factors. Useful for calculating adjusted prices.
    
        Args:
            code: The stock code in Baostock format (e.g., 'sh.600000', 'sz.000001').
            start_date: Start date in 'YYYY-MM-DD' format.
            end_date: End date in 'YYYY-MM-DD' format.
    
        Returns:
            Adjustment factors table.
        """
        logger.info(f"Tool 'get_adjust_factor_data' called for {code} ({start_date} to {end_date})")
        return run_tool_with_handling(
            lambda: fetch_adjust_factor_data(
                active_data_source,
                code=code,
                start_date=start_date,
                end_date=end_date,
                limit=limit,
                format=format,
            ),
            context=f"get_adjust_factor_data:{code}",
        )
  • mcp_server.py:51-51 (registration)
    Explicit call to register the stock market tools, including 'get_adjust_factor_data', on the FastMCP app instance with the active data source.
    register_stock_market_tools(app, active_data_source)
  • Use case orchestrator that fetches raw data from the data source, applies output format validation and table formatting with row limits.
    def fetch_adjust_factor_data(
        data_source: FinancialDataSource,
        *,
        code: str,
        start_date: str,
        end_date: str,
        limit: int = 250,
        format: str = "markdown",
    ) -> str:
        validate_output_format(format)
        df = data_source.get_adjust_factor_data(code=code, start_date=start_date, end_date=end_date)
        meta = {"code": code, "start_date": start_date, "end_date": end_date}
        return format_table_output(df, format=format, max_rows=limit, meta=meta)
  • Abstract method in the FinancialDataSource interface defining the contract for fetching adjustment factor data.
    @abstractmethod
    def get_adjust_factor_data(self, code: str, start_date: str, end_date: str) -> pd.DataFrame:
        """Fetches adjustment factor data used for price adjustments."""
        pass
  • Concrete implementation in BaostockDataSource that queries the Baostock API via bs.query_adjust_factor, handles login, pagination, errors, and returns a pandas DataFrame.
    def get_adjust_factor_data(self, code: str, start_date: str, end_date: str) -> pd.DataFrame:
        """Fetches adjustment factor data using Baostock."""
        logger.info(
            f"Fetching adjustment factor data for {code} ({start_date} to {end_date})")
        try:
            with baostock_login_context():
                rs = bs.query_adjust_factor(
                    code=code, start_date=start_date, end_date=end_date)
    
                if rs.error_code != '0':
                    logger.error(
                        f"Baostock API error (Adjust Factor) for {code}: {rs.error_msg} (code: {rs.error_code})")
                    if "no record found" in rs.error_msg.lower() or rs.error_code == '10002':
                        raise NoDataFoundError(
                            f"No adjustment factor data found for {code} in the specified range. Baostock msg: {rs.error_msg}")
                    else:
                        raise DataSourceError(
                            f"Baostock API error fetching adjust factor data: {rs.error_msg} (code: {rs.error_code})")
    
                data_list = []
                while rs.next():
                    data_list.append(rs.get_row_data())
    
                if not data_list:
                    logger.warning(
                        f"No adjustment factor data found for {code} in range (empty result set from Baostock).")
                    raise NoDataFoundError(
                        f"No adjustment factor data found for {code} in the specified range (empty result set).")
    
                result_df = pd.DataFrame(data_list, columns=rs.fields)
                logger.info(
                    f"Retrieved {len(result_df)} adjustment factor records for {code}.")
                return result_df
    
        except (LoginError, NoDataFoundError, DataSourceError, ValueError) as e:
            logger.warning(
                f"Caught known error fetching adjust factor data for {code}: {type(e).__name__}")
            raise e
        except Exception as e:
            logger.exception(
                f"Unexpected error fetching adjust factor data for {code}: {e}")
            raise DataSourceError(
                f"Unexpected error fetching adjust factor data for {code}: {e}")
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It mentions the data source and general use case but fails to disclose critical behavioral traits such as rate limits, authentication needs, error handling, or the structure of the returned 'Adjustment factors table.' This is a significant gap for a data-fetching tool with no annotation coverage.

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 sized and front-loaded, with the core purpose stated first. The Args and Returns sections are structured for clarity, though the inclusion of parameter details in the description (while helpful) slightly reduces conciseness. Every sentence earns its place, but minor trimming could improve efficiency.

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

Completeness2/5

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

Given the complexity (5 parameters, no annotations, no output schema), the description is incomplete. It covers the purpose and some parameters but lacks details on behavioral aspects (e.g., rate limits, errors) and the output structure. Without an output schema, the description should explain return values more thoroughly, but it only vaguely mentions 'Adjustment factors table.'

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 provides clear semantics for 3 parameters (code, start_date, end_date) with examples and format details, which adds substantial value beyond the schema. However, it omits the 'limit' and 'format' parameters, leaving them undocumented. Since 3 out of 5 parameters are well-explained, this is above baseline but not perfect.

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 tool's purpose with specific verb ('Fetches') and resource ('adjustment factor data'), and distinguishes it from siblings by mentioning the specific data source ('Baostock's "涨跌幅复权算法" factors') and use case ('Useful for calculating adjusted prices'). This differentiates it from other data-fetching tools like get_historical_k_data or get_dividend_data.

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 implies usage context through 'Useful for calculating adjusted prices,' which suggests when this tool might be appropriate. However, it lacks explicit guidance on when to use this tool versus alternatives (e.g., other financial data tools in the sibling list) or any prerequisites or exclusions, leaving some ambiguity for the agent.

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