normalize_stock_code
Convert stock codes to Baostock format for consistent data processing in A-share market analysis.
Instructions
Normalize a stock code to Baostock format.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes |
Implementation Reference
- src/tools/helpers.py:18-25 (handler)The MCP tool handler for 'normalize_stock_code', decorated with @app.tool(). It logs the input and delegates to the normalization logic via run_tool_with_handling for error handling.
@app.tool() def normalize_stock_code(code: str) -> str: """Normalize a stock code to Baostock format.""" logger.info("Tool 'normalize_stock_code' called with input=%s", code) return run_tool_with_handling( lambda: normalize_stock_code_logic(code), context="normalize_stock_code", ) - src/use_cases/helpers.py:7-27 (helper)Core implementation logic for normalizing stock codes using regex patterns to match various formats (sh/sz prefix/suffix, numeric only) and convert to Baostock 'ex.num' format.
def normalize_stock_code_logic(code: str) -> str: validate_non_empty_str(code, "code") raw = code.strip() m = re.fullmatch(r"(?i)(sh|sz)[.]?(\d{6})", raw) if m: ex, num = m.group(1).lower(), m.group(2) return f"{ex}.{num}" m2 = re.fullmatch(r"(\d{6})[.]?(?i:(sh|sz))", raw) if m2: num, ex = m2.group(1), m2.group(2).lower() return f"{ex}.{num}" m3 = re.fullmatch(r"(\d{6})", raw) if m3: num = m3.group(1) ex = "sh" if num.startswith("6") else "sz" return f"{ex}.{num}" raise ValueError("Unsupported code format. Examples: 'sh.600000', '600000', '000001.SZ'.") - mcp_server.py:58-58 (registration)Top-level registration call to register_helpers_tools(app), which defines and registers the normalize_stock_code tool among helpers.
register_helpers_tools(app) - mcp_server.py:20-20 (registration)Import of the register_helpers_tools function used to register helper tools including normalize_stock_code.
from src.tools.helpers import register_helpers_tools