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
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes | ||
| start_date | Yes | ||
| end_date | Yes | ||
| limit | No | ||
| format | No | markdown |
Implementation Reference
- src/tools/stock_market.py:140-165 (handler)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}", )
- src/use_cases/stock_market.py:82-94 (helper)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)
- src/data_source_interface.py:128-131 (schema)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
- src/baostock_data_source.py:369-411 (helper)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}")