{"record":{"id":"d2617ccfb890594a","repo":"ZhuLinsen/daily_stock_analysis","slug":"code","errorCode":null,"errorMessage":"非法股票代码格式: {code}","messagePattern":"非法股票代码格式: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":400,"severity":"error","filePath":"src/services/backtest_service.py","lineNumber":431,"sourceCode":"        for analysis in candidates:\n            analysis_date = self._resolve_analysis_date(analysis)\n            if analysis_date is None:\n                continue\n            if analysis_date_from is not None and analysis_date < analysis_date_from:\n                continue\n            if analysis_date_to is not None and analysis_date > analysis_date_to:\n                continue\n            filtered.append(analysis)\n        return filtered\n\n    @staticmethod\n    def _normalize_code(code: Optional[str]) -> Optional[str]:\n        if not code:\n            return None\n\n        identity = resolve_daily_stock_identity(str(code).strip())\n        if identity is None:\n            raise ValueError(f\"非法股票代码格式: {code}\")\n        return identity.normalized_code\n\n    @staticmethod\n    def _normalize_summary_code(code: Optional[str]) -> Optional[str]:\n        if not code:\n            return None\n        raw_code = str(code).strip()\n        normalized = normalize_stock_code(raw_code)\n        backtest_normalized = normalize_backtest_code(raw_code)\n        if raw_code.upper().startswith(\"SS\") and backtest_normalized and backtest_normalized != normalized:\n            normalized = backtest_normalized\n        return canonical_stock_code(normalized or raw_code)\n\n    @staticmethod\n    def _normalize_code_for_display(code: Optional[str]) -> Optional[str]:\n        return BacktestService._normalize_code(code)\n\n    @staticmethod","sourceCodeStart":413,"sourceCodeEnd":449,"githubUrl":"https://github.com/ZhuLinsen/daily_stock_analysis/blob/5159bd72e8373d215492dff122acc9d389e219c9/src/services/backtest_service.py#L413-L449","documentation":"BacktestService._normalize_code resolves the stock code through resolve_daily_stock_identity; if that helper cannot recognize the code's format (A-share, HK, US conventions), it returns None and the service raises ValueError with the original input. This guards every backtest entry point (run, results, summaries, export) so only codes the daily-data layer can fetch are accepted.","triggerScenarios":"Calling any BacktestService method or /api/v1/backtest/* endpoint with code=\"12345\" (not 6 digits), \"60051X\", \"hk0700 \" style variants that resolve_daily_stock_identity rejects, random strings, or a code from another market convention the identity resolver does not support.","commonSituations":"Users pasting a stock name instead of a code, typos, mixing exchanges (e.g. \"00700\" without the hk prefix when the resolver requires it for HK), or test fixtures using placeholder codes like \"TEST\".","solutions":["Use the canonical code format the resolver expects: A-share \"600519\"/\"000001\", HK \"hk00700\", US \"AAPL\".","Verify the code resolves first: from src.utils.stock_code import resolve_daily_stock_identity; resolve_daily_stock_identity(\"hk00700\").","Pass code=None to query all stocks instead of an invalid sentinel like \"all\" or \"*\"."],"exampleFix":"# before\nservice.get_recent_evaluations(code=\"700.HK\")\n\n# after\nservice.get_recent_evaluations(code=\"hk00700\")","handlingStrategy":"validation","validationCode":"from src.utils.stock_code import resolve_daily_stock_identity\n\ndef isResolvableCode(code: str) -> bool:\n    return resolve_daily_stock_identity(code.strip()) is not None\n\nif code and not isResolvableCode(code):\n    return JSONResponse(status_code=400, content={\"error\": \"invalid_code\", \"message\": f\"unrecognized code: {code}\"})","typeGuard":"from typing import Optional\nfrom src.utils.stock_code import resolve_daily_stock_identity\n\ndef validBacktestCode(code: Optional[str]) -> bool:\n    if not code:\n        return True  # None means 'all stocks'\n    return resolve_daily_stock_identity(str(code).strip()) is not None","tryCatchPattern":"try:\n    service.run_backtest(code=code)\nexcept ValueError as exc:\n    if \"非法股票代码格式\" in str(exc):\n        return JSONResponse(status_code=400, content={\"error\": \"invalid_code\", \"message\": str(exc)})\n    raise","preventionTips":["Canonicalize codes client-side to A-share 6-digit, 'hk'+5-digit, or US ticker before calling.","Offer users a searchable code picker instead of free-text entry.","Centralize code normalization in one helper so every endpoint validates identically."],"tags":["backtest","stock-code","validation"],"backgroundTag":null,"analyzedSha":"5159bd72e8373d215492dff122acc9d389e219c9","analyzedAt":"2026-08-15T01:59:36.292Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}