{"record":{"id":"911a1b0545517e6b","repo":"ZhuLinsen/daily_stock_analysis","slug":"yahoo-finance-stock-code","errorCode":null,"errorMessage":"Yahoo Finance 未查询到 {stock_code} 的数据","messagePattern":"Yahoo Finance 未查询到 (.+?) 的数据","errorType":"exception","errorClass":"DataFetchError","httpStatus":null,"severity":"error","filePath":"data_provider/yfinance_fetcher.py","lineNumber":227,"sourceCode":"            # 使用 yfinance 下载数据\n            df = yf.download(\n                tickers=yf_code,\n                start=start_date,\n                end=end_date,\n                progress=False,  # 禁止进度条\n                auto_adjust=True,  # 自动调整价格（复权）\n                multi_level_index=True\n            )\n\n            # 筛选出 yf_code 的列, 避免多只股票数据混淆\n            if isinstance(df.columns, pd.MultiIndex) and len(df.columns) > 1:\n                ticker_level = df.columns.get_level_values(1)\n                mask = ticker_level == yf_code\n                if mask.any():\n                    df = df.loc[:, mask].copy()\n\n            if df.empty:\n                raise DataFetchError(f\"Yahoo Finance 未查询到 {stock_code} 的数据\")\n\n            return df\n\n        except Exception as e:\n            if isinstance(e, DataFetchError):\n                raise\n            raise DataFetchError(f\"Yahoo Finance 获取数据失败: {e}\") from e\n\n    def _normalize_data(self, df: pd.DataFrame, stock_code: str) -> pd.DataFrame:\n        \"\"\"\n        标准化 Yahoo Finance 数据\n\n        yfinance 返回的列名：\n        Open, High, Low, Close, Volume（索引是日期）\n\n        注意：新版 yfinance 返回 MultiIndex 列名，如 ('Close', 'AMD')\n        需要先扁平化列名再进行处理\n","sourceCodeStart":209,"sourceCodeEnd":245,"githubUrl":"https://github.com/ZhuLinsen/daily_stock_analysis/blob/5159bd72e8373d215492dff122acc9d389e219c9/data_provider/yfinance_fetcher.py#L209-L245","documentation":"YfinanceFetcher downloaded successfully but the resulting DataFrame is empty after column filtering, so the symbol simply has no data on Yahoo Finance. Common with delisted/renamed tickers, unsupported exchanges, or yf_code conversions this repo does for A/HK shares (e.g. 600519 -> 600519.SS, 00700 -> 0700.HK) that Yahoo does not recognize.","triggerScenarios":"yf.download returns an empty frame for the ticker (bad symbol, delisted, no trading data in the requested window), or the MultiIndex filter drops all columns because the level-1 ticker string does not match yf_code exactly (case or suffix mismatch).","commonSituations":"Typo'd or delisted US ticker; A-share code converted to the wrong suffix (.SS vs .SZ); HK code format mismatch with Yahoo's 4-digit .HK convention; requesting a date range with no sessions; yfinance version change altering the column layout so the mask filters everything out.","solutions":["Verify the symbol on finance.yahoo.com exactly as converted (print yf_code before the call).","Check the requested date range actually contains trading sessions for that market.","If the MultiIndex filter emptied the frame, inspect df.columns — a yfinance upgrade may have changed level ordering; adjust the mask or pin the yfinance version.","Route to another fetcher (Tushare for A-shares, Akshare) via the fallback chain when Yahoo has no coverage."],"exampleFix":"# before\ndf = yf.download('0700.HK', ...)  # wrong digit count for HK -> empty\n\n# after\ndf = yf.download('0700.HK'.lstrip('0').zfill(4) + '.HK', ...)  # ensure 4-digit HK code","handlingStrategy":"validation","validationCode":"import yfinance as yf\n\nt = yf.Ticker(yf_code)\ninfo_keys = set()\ntry:\n    info_keys = set(t.fast_info.keys())\nexcept Exception:\n    pass\nhas_data = bool(info_keys) or not t.history(period=\"5d\").empty\nif not has_data:\n    raise ValueError(f\"Yahoo has no data for {yf_code}; check the symbol\")","typeGuard":"def yahoo_symbol_ok(yf_code: str) -> bool:\n    import yfinance as yf\n    try:\n        return not yf.Ticker(yf_code).history(period=\"5d\").empty\n    except Exception:\n        return False","tryCatchPattern":"try:\n    df = yfinance_fetcher.fetch_stock_data(code)\nexcept DataFetchError as e:\n    if \"未查询到\" in str(e):\n        df = akshare_fetcher.fetch_stock_data(code)  # symbol not on Yahoo\n    else:\n        raise","preventionTips":["Verify converted Yahoo symbols (A-share .SS/.SZ, HK 4-digit .HK) against finance.yahoo.com before batch runs.","Keep a symbol-validation step in watchlist ingestion to catch typos/delistings early.","Treat empty-result and fetch-failure DataFetchErrors differently in fallback logic."],"tags":["yfinance","symbol","empty-data","data-provider"],"backgroundTag":null,"analyzedSha":"5159bd72e8373d215492dff122acc9d389e219c9","analyzedAt":"2026-08-15T01:59:36.292Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}