get_stock_a_code_name
Retrieve A-share stock codes and names from Chinese stock markets (Shanghai, Shenzhen, Beijing) with flexible output formats including JSON, CSV, and XML.
Instructions
获取沪深京 A 股股票代码和股票简称数据
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| output_format | No | 输出数据格式: json, csv, xml, excel, markdown, html。默认: markdown | markdown |
Implementation Reference
- src/china_stock_mcp/server.py:911-926 (handler)Main handler function for the 'get_stock_a_code_name' tool. Fetches A-share stock codes and names using akshare, caches the result, formats output as specified.def get_stock_a_code_name( output_format: Annotated[ Literal["json", "csv", "xml", "excel", "markdown", "html"], Field(description="输出数据格式: json, csv, xml, excel, markdown, html。默认: markdown"), ] = "markdown" ) -> str: """获取沪深京 A 股股票代码和股票简称数据.""" @cached_data_fetch() def get_stock_a_code_name_fetch() -> pd.DataFrame: return ak.stock_info_a_code_name() df = get_stock_a_code_name_fetch() if df.empty: df = pd.DataFrame() return _format_dataframe_output(df, output_format)
- src/china_stock_mcp/server.py:908-910 (registration)Registration of the 'get_stock_a_code_name' tool using @mcp.tool decorator.@mcp.tool( name="get_stock_a_code_name", description="获取沪深京 A 股股票代码和股票简称数据" )
- Cached helper function that fetches the stock data from ak.stock_info_a_code_name().@cached_data_fetch() def get_stock_a_code_name_fetch() -> pd.DataFrame: return ak.stock_info_a_code_name()
- src/china_stock_mcp/server.py:89-117 (helper)General helper function to format DataFrame output in various formats (json, csv, etc.), used by the tool.def _format_dataframe_output( df: pd.DataFrame, output_format: Literal["json", "csv", "xml", "excel", "markdown", "html"], ) -> str: """ 根据指定的格式格式化 DataFrame 输出。 """ if df.empty: return json.dumps([]) if output_format == "json": return df.to_json(orient="records", force_ascii=False) elif output_format == "csv": return df.to_csv(index=False) elif output_format == "xml": return df.to_xml(index=False) elif output_format == "excel": # 使用 BytesIO 将 Excel 写入内存 output = io.BytesIO() df.to_excel(output, index=False, engine='openpyxl') # 返回 base64 编码的二进制数据,或者直接返回字节流 # 为了兼容性,这里尝试返回 utf-8 编码的字符串,但对于二进制文件,通常直接传输字节流更合适 return output.getvalue().decode("utf-8", errors="ignore") elif output_format == "markdown": return df.to_markdown(index=False) elif output_format == "html": return df.to_html(index=False) else: return df.to_json(orient="records", force_ascii=False)