{"record":{"id":"d64a077b0810fbf3","repo":"hsliuping/TradingAgents-CN","slug":"dataframe-missing-list-df-columns","errorCode":null,"errorMessage":"DataFrame缺少必要列: {missing}, 现有列: {list(df.columns)[:10]}...","messagePattern":"DataFrame缺少必要列: (.+?), 现有列: (.+?)\\.\\.\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"tradingagents/tools/analysis/indicators.py","lineNumber":22,"sourceCode":"from typing import Any, Dict, Iterable, List, Optional\n\nimport numpy as np\nimport pandas as pd\n\n\n@dataclass(frozen=True)\nclass IndicatorSpec:\n    name: str\n    params: Optional[Dict[str, Any]] = None\n\n\nSUPPORTED = {\"ma\", \"ema\", \"macd\", \"rsi\", \"boll\", \"atr\", \"kdj\"}\n\n\ndef _require_cols(df: pd.DataFrame, cols: Iterable[str]):\n    missing = [c for c in cols if c not in df.columns]\n    if missing:\n        raise ValueError(f\"DataFrame缺少必要列: {missing}, 现有列: {list(df.columns)[:10]}...\")\n\n\ndef ma(close: pd.Series, n: int, min_periods: int = None) -> pd.Series:\n    \"\"\"\n    计算移动平均线（Moving Average）\n\n    Args:\n        close: 收盘价序列\n        n: 周期\n        min_periods: 最小周期数，默认为1（允许前期数据不足时也计算）\n\n    Returns:\n        移动平均线序列\n    \"\"\"\n    if min_periods is None:\n        min_periods = 1  # 默认为1，与现有代码保持一致\n    return close.rolling(window=int(n), min_periods=min_periods).mean()\n","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/hsliuping/TradingAgents-CN/blob/74783e8817d6cf6de29867880631cc555153f36b/tradingagents/tools/analysis/indicators.py#L4-L40","documentation":"_require_cols is an internal guard used by compute_indicator and the individual indicator functions; it verifies that the input DataFrame contains the columns each indicator needs (e.g. 'close' for ma/rsi, 'high'/'low'/'close' for atr/kdj). If any required column is missing it raises ValueError listing the missing columns and up to 10 existing columns for diagnosis. It exists because pandas operations would otherwise fail later with confusing KeyError messages.","triggerScenarios":"Calling compute_indicator(df, 'macd', ...) on a DataFrame lacking a 'close' column, or computing 'kdj'/'atr'/'boll' on a DataFrame missing 'high' or 'low'. Also happens when columns are named differently ('Close', 'adj_close', '收盘价') due to un-normalized upstream data.","commonSituations":"Renaming columns after loading from akshare/tushare (Chinese column names like '收盘' not mapped to 'close'); passing OHLCV subsets that dropped volume/high/low for slimming; chaining data from a source with different capitalization (Close vs close).","solutions":["Rename the DataFrame columns to the lowercase OHLC convention expected by the library: df.rename(columns={'Close':'close','High':'high','Low':'low'}, inplace=True).","Check df.columns before calling compute_indicator; the error message itself lists existing columns to spot naming mismatches.","Ensure your data loader (e.g. get_hk_stock_data_akshare) normalizes to the expected schema before indicator computation."],"exampleFix":"# before\nout = compute_indicator(df, \"rsi\", n=14)  # df has 'Close' not 'close'\n\n# after\ndf = df.rename(columns={\"Close\": \"close\", \"High\": \"high\", \"Low\": \"low\", \"Open\": \"open\"})\nout = compute_indicator(df, \"rsi\", n=14)","handlingStrategy":"validation","validationCode":"REQUIRED = {\"ma\": [\"close\"], \"rsi\": [\"close\"], \"macd\": [\"close\"], \"boll\": [\"close\"], \"atr\": [\"high\",\"low\",\"close\"], \"kdj\": [\"high\",\"low\",\"close\"], \"ema\": [\"close\"]}\n\ndef ensure_ohlcv(df, name):\n    missing = [c for c in REQUIRED[name] if c not in df.columns]\n    if missing:\n        raise ValueError(f\"{name} needs {missing}; got {list(df.columns)}\")\n\ndf = df.rename(columns=str.lower)\nensure_ohlcv(df, \"kdj\")\nout = compute_indicator(df, \"kdj\")","typeGuard":"def has_ohlcv(df: pd.DataFrame, cols=(\"open\",\"high\",\"low\",\"close\")) -> bool:\n    \"\"\"True if df has standard lowercase OHLC columns.\"\"\"\n    return all(c in df.columns for c in cols)","tryCatchPattern":"try:\n    out = compute_indicator(df, name, **params)\nexcept ValueError as e:\n    if \"缺少必要列\" in str(e):\n        df = normalize_columns(df)  # rename Close/收盘 etc.\n        out = compute_indicator(df, name, **params)\n    else:\n        raise","preventionTips":["Normalize all loaded DataFrames to lowercase open/high/low/close/volume immediately after fetching.","Assert df.columns contains OHLC in loader functions, closest to the data source.","Keep one canonical rename map per data source (akshare/tushare) in a shared util."],"tags":["pandas","dataframe","indicators","column-mismatch","precondition"],"backgroundTag":"missing-dataframe-column","analyzedSha":"74783e8817d6cf6de29867880631cc555153f36b","analyzedAt":"2026-08-28T11:39:07.729Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}