hsliuping/TradingAgents-CN · error · ValueError

DataFrame缺少必要列: {missing}, 现有列: {list(df.columns)[:10]}...

Error message

DataFrame缺少必要列: {missing}, 现有列: {list(df.columns)[:10]}...

What it means

_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.

Source

Thrown at tradingagents/tools/analysis/indicators.py:22

from typing import Any, Dict, Iterable, List, Optional

import numpy as np
import pandas as pd


@dataclass(frozen=True)
class IndicatorSpec:
    name: str
    params: Optional[Dict[str, Any]] = None


SUPPORTED = {"ma", "ema", "macd", "rsi", "boll", "atr", "kdj"}


def _require_cols(df: pd.DataFrame, cols: Iterable[str]):
    missing = [c for c in cols if c not in df.columns]
    if missing:
        raise ValueError(f"DataFrame缺少必要列: {missing}, 现有列: {list(df.columns)[:10]}...")


def ma(close: pd.Series, n: int, min_periods: int = None) -> pd.Series:
    """
    计算移动平均线(Moving Average)

    Args:
        close: 收盘价序列
        n: 周期
        min_periods: 最小周期数,默认为1(允许前期数据不足时也计算)

    Returns:
        移动平均线序列
    """
    if min_periods is None:
        min_periods = 1  # 默认为1,与现有代码保持一致
    return close.rolling(window=int(n), min_periods=min_periods).mean()

View on GitHub (pinned to 74783e8817)

Solutions

  1. Rename the DataFrame columns to the lowercase OHLC convention expected by the library: df.rename(columns={'Close':'close','High':'high','Low':'low'}, inplace=True).
  2. Check df.columns before calling compute_indicator; the error message itself lists existing columns to spot naming mismatches.
  3. Ensure your data loader (e.g. get_hk_stock_data_akshare) normalizes to the expected schema before indicator computation.

Example fix

# before
out = compute_indicator(df, "rsi", n=14)  # df has 'Close' not 'close'

# after
df = df.rename(columns={"Close": "close", "High": "high", "Low": "low", "Open": "open"})
out = compute_indicator(df, "rsi", n=14)
Defensive patterns

Strategy: validation

Validate before calling

REQUIRED = {"ma": ["close"], "rsi": ["close"], "macd": ["close"], "boll": ["close"], "atr": ["high","low","close"], "kdj": ["high","low","close"], "ema": ["close"]}

def ensure_ohlcv(df, name):
    missing = [c for c in REQUIRED[name] if c not in df.columns]
    if missing:
        raise ValueError(f"{name} needs {missing}; got {list(df.columns)}")

df = df.rename(columns=str.lower)
ensure_ohlcv(df, "kdj")
out = compute_indicator(df, "kdj")

Type guard

def has_ohlcv(df: pd.DataFrame, cols=("open","high","low","close")) -> bool:
    """True if df has standard lowercase OHLC columns."""
    return all(c in df.columns for c in cols)

Try / catch

try:
    out = compute_indicator(df, name, **params)
except ValueError as e:
    if "缺少必要列" in str(e):
        df = normalize_columns(df)  # rename Close/收盘 etc.
        out = compute_indicator(df, name, **params)
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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).

Related errors


AI-assisted analysis of hsliuping/TradingAgents-CN@74783e8817 (2026-08-28). Data as JSON: /api/errors/d64a077b0810fbf3. Report an issue: GitHub.