get_dividend_data
Retrieve dividend data for specific A-share stocks by entering stock code, year, and year type. Access accurate dividend information for financial analysis and decision-making.
Instructions
Fetches dividend information for a given stock code and year.
Args:
code: The stock code in Baostock format (e.g., 'sh.600000', 'sz.000001').
year: The year to query (e.g., '2023').
year_type: Type of year. Valid options (from Baostock):
'report': Announcement year (预案公告年份)
'operate': Ex-dividend year (除权除息年份)
Defaults to 'report'.
Returns:
A Markdown formatted string containing the dividend data table,
or an error message.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes | ||
| year | Yes | ||
| year_type | No | report |
Implementation Reference
- src/tools/stock_market.py:156-205 (handler)The primary handler function for the 'get_dividend_data' tool. It performs input validation, calls the data source, handles errors, and formats the output as markdown or other formats.@app.tool() def get_dividend_data(code: str, year: str, year_type: str = "report", limit: int = 250, format: str = "markdown") -> str: """ Fetches dividend information for a given stock code and year. Args: code: The stock code in Baostock format (e.g., 'sh.600000', 'sz.000001'). year: The year to query (e.g., '2023'). year_type: Type of year. Valid options (from Baostock): 'report': Announcement year (预案公告年份) 'operate': Ex-dividend year (除权除息年份) Defaults to 'report'. Returns: Dividend records table. """ logger.info( f"Tool 'get_dividend_data' called for {code}, year={year}, year_type={year_type}") try: # Basic validation if year_type not in ['report', 'operate']: logger.warning(f"Invalid year_type requested: {year_type}") return f"Error: Invalid year_type '{year_type}'. Valid options are: 'report', 'operate'" if not year.isdigit() or len(year) != 4: logger.warning(f"Invalid year format requested: {year}") return f"Error: Invalid year '{year}'. Please provide a 4-digit year." df = active_data_source.get_dividend_data( code=code, year=year, year_type=year_type) logger.info( f"Successfully retrieved dividend data for {code}, year {year}.") meta = {"code": code, "year": year, "year_type": year_type} return format_table_output(df, format=format, max_rows=limit, meta=meta) except NoDataFoundError as e: logger.warning(f"NoDataFoundError for {code}, year {year}: {e}") return f"Error: {e}" except LoginError as e: logger.error(f"LoginError for {code}: {e}") return f"Error: Could not connect to data source. {e}" except DataSourceError as e: logger.error(f"DataSourceError for {code}: {e}") return f"Error: An error occurred while fetching data. {e}" except ValueError as e: logger.warning(f"ValueError processing request for {code}: {e}") return f"Error: Invalid input parameter. {e}" except Exception as e: logger.exception( f"Unexpected Exception processing get_dividend_data for {code}: {e}") return f"Error: An unexpected error occurred: {e}"
- src/baostock_data_source.py:325-368 (helper)Supporting method in BaostockDataSource class that implements the core data fetching logic using the Baostock query_dividend_data API.def get_dividend_data(self, code: str, year: str, year_type: str = "report") -> pd.DataFrame: """Fetches dividend information using Baostock.""" logger.info( f"Fetching dividend data for {code}, year={year}, year_type={year_type}") try: with baostock_login_context(): rs = bs.query_dividend_data( code=code, year=year, yearType=year_type) if rs.error_code != '0': logger.error( f"Baostock API error (Dividend) 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 dividend data found for {code} and year {year}. Baostock msg: {rs.error_msg}") else: raise DataSourceError( f"Baostock API error fetching dividend 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 dividend data found for {code}, year {year} (empty result set from Baostock).") raise NoDataFoundError( f"No dividend data found for {code}, year {year} (empty result set).") result_df = pd.DataFrame(data_list, columns=rs.fields) logger.info( f"Retrieved {len(result_df)} dividend records for {code}, year {year}.") return result_df except (LoginError, NoDataFoundError, DataSourceError, ValueError) as e: logger.warning( f"Caught known error fetching dividend data for {code}: {type(e).__name__}") raise e except Exception as e: logger.exception( f"Unexpected error fetching dividend data for {code}: {e}") raise DataSourceError( f"Unexpected error fetching dividend data for {code}: {e}")
- mcp_server.py:51-51 (registration)The call that registers the stock_market tools, including get_dividend_data, to the FastMCP app instance.register_stock_market_tools(app, active_data_source)
- src/tools/stock_market.py:15-15 (registration)The registration function that defines and registers the get_dividend_data tool (and others) using @app.tool() decorators.def register_stock_market_tools(app: FastMCP, active_data_source: FinancialDataSource):
- src/tools/stock_market.py:158-171 (schema)The docstring in the handler function that defines the input schema (parameters and descriptions) and output for the MCP tool.""" Fetches dividend information for a given stock code and year. Args: code: The stock code in Baostock format (e.g., 'sh.600000', 'sz.000001'). year: The year to query (e.g., '2023'). year_type: Type of year. Valid options (from Baostock): 'report': Announcement year (预案公告年份) 'operate': Ex-dividend year (除权除息年份) Defaults to 'report'. Returns: Dividend records table. """