Skip to main content
Glama
24mlight

A-Share MCP Server

get_adjust_factor_data

Fetches adjustment factor data for A-share stocks to calculate accurate historical prices by applying Baostock's price adjustment algorithms 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

  • The MCP tool handler function for 'get_adjust_factor_data'. Decorated with @app.tool() for automatic registration. Handles input, logging, error handling via run_tool_with_handling, and delegates to the use case fetch function.
    @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}",
        )
  • Use case helper function that fetches adjustment factor data from the data source, adds metadata, and formats the output table.
    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)
  • Interface definition specifying the method signature and documentation for the data source's get_adjust_factor_data method, serving as schema for the underlying data fetch.
    @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 class that queries the Baostock API for adjustment factor data, handles errors, and returns a 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}")
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses the data source (Baostock) and algorithm type ('涨跌幅复权算法'), but doesn't mention behavioral aspects like rate limits, authentication requirements, error conditions, or pagination behavior. The description is accurate about what it does but lacks operational context that would help an agent use it effectively.

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 purpose statement, context, and parameter documentation. Every sentence adds value, though the Args/Returns formatting could be more integrated. It's appropriately sized for a data-fetching tool with multiple parameters.

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?

For a tool with 5 parameters (3 required), no annotations, and no output schema, the description provides adequate purpose and core parameter documentation but lacks details about optional parameters, return format specifics, error handling, and operational constraints. It's minimally viable but has clear gaps given the tool's complexity.

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 documents 3 required parameters (code, start_date, end_date) with format examples and purpose, but doesn't mention the 2 optional parameters (limit, format) from the schema. The description adds meaningful semantics for the core parameters but leaves the optional ones undocumented.

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 'fetches adjustment factor data for a given stock code and date range', specifying both the verb ('fetches') and resource ('adjustment factor data'). It distinguishes from siblings by mentioning the specific data source (Baostock's '涨跌幅复权算法' factors) and purpose (calculating adjusted prices), which none of the other tools appear to handle.

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 by stating it's 'useful for calculating adjusted prices', but doesn't explicitly guide when to use this tool versus alternatives like get_historical_k_data or get_stock_basic_info. No exclusions or prerequisites are mentioned, leaving usage decisions to inference based on the stated purpose.

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