{"record":{"id":"fb4e7f4e0fc77088","repo":"hsliuping/TradingAgents-CN","slug":"rsi-method-ema-sma-china","errorCode":null,"errorMessage":"不支持的RSI计算方法: {method}，支持的方法: 'ema', 'sma', 'china'","messagePattern":"不支持的RSI计算方法: (.+?)，支持的方法: 'ema', 'sma', 'china'","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"tradingagents/tools/analysis/indicators.py","lineNumber":117,"sourceCode":"    gain = delta.where(delta > 0, 0)\n    loss = -delta.where(delta < 0, 0)\n\n    if method == 'ema':\n        # 国际标准：Wilder's指数移动平均\n        avg_gain = gain.ewm(alpha=1 / float(n), adjust=False).mean()\n        avg_loss = loss.ewm(alpha=1 / float(n), adjust=False).mean()\n    elif method == 'sma':\n        # 简单移动平均\n        avg_gain = gain.rolling(window=int(n), min_periods=1).mean()\n        avg_loss = loss.rolling(window=int(n), min_periods=1).mean()\n    elif method == 'china':\n        # 中国式SMA：同花顺/通达信风格\n        # SMA(X, N, 1) = ewm(com=N-1, adjust=True).mean()\n        # 参考：https://blog.csdn.net/u011218867/article/details/117427927\n        avg_gain = gain.ewm(com=int(n) - 1, adjust=True).mean()\n        avg_loss = loss.ewm(com=int(n) - 1, adjust=True).mean()\n    else:\n        raise ValueError(f\"不支持的RSI计算方法: {method}，支持的方法: 'ema', 'sma', 'china'\")\n\n    rs = avg_gain / (avg_loss.replace(0, np.nan))\n    rsi_val = 100 - (100 / (1 + rs))\n    return rsi_val\n\n\ndef boll(close: pd.Series, n: int = 20, k: float = 2.0, min_periods: int = None) -> pd.DataFrame:\n    \"\"\"\n    计算布林带指标（Bollinger Bands）\n\n    Args:\n        close: 收盘价序列\n        n: 周期，默认20\n        k: 标准差倍数，默认2.0\n        min_periods: 最小周期数，默认为1（允许前期数据不足时也计算）\n\n    Returns:\n        包含 boll_mid, boll_upper, boll_lower 的 DataFrame","sourceCodeStart":99,"sourceCodeEnd":135,"githubUrl":"https://github.com/hsliuping/TradingAgents-CN/blob/74783e8817d6cf6de29867880631cc555153f36b/tradingagents/tools/analysis/indicators.py#L99-L135","documentation":"The rsi function supports exactly three computation methods: 'ema' (exponential smoothing), 'sma' (simple moving average of gains/losses), and 'china' (同花顺/通达信-style SMA(X,N,1) via ewm(com=n-1, adjust=True)). Passing any other method string reaches the final else branch and raises this ValueError. The method parameter exists because different charting platforms produce visibly different RSI values.","triggerScenarios":"Calling rsi(close, n, method='wilder'), method='Wilder', method='EMA' (case-sensitive), or compute_indicator(df, 'rsi', method='wma'). Also passing method=None explicitly if the default handling doesn't catch it before the else.","commonSituations":"Porting code from other libraries where the Wilder/smoothing method is named differently ('rma', 'wilder', 'cutler'); case mismatches; typos like 'cn' or 'zh' instead of 'china'; assuming TradingView/TA-Lib naming applies here.","solutions":["Use one of the exact strings 'ema', 'sma', or 'china' (lowercase).","If you want Wilder's RSI (TA-Lib default), note this library's 'china' method uses ewm(com=n-1) which is equivalent to Wilder smoothing — use that.","If a genuinely different smoothing is needed, compute it manually with pandas ewm rather than passing an unsupported method string."],"exampleFix":"# before\nrsi_val = rsi(df[\"close\"], n=14, method=\"wilder\")\n\n# after\nrsi_val = rsi(df[\"close\"], n=14, method=\"china\")  # ewm(com=n-1) == Wilder-style smoothing","handlingStrategy":"validation","validationCode":"VALID_RSI_METHODS = {\"ema\", \"sma\", \"china\"}\nmethod = (method or \"ema\").lower()\nif method not in VALID_RSI_METHODS:\n    method = \"china\"  # or raise your own config error\nrsi_val = rsi(df[\"close\"], n=14, method=method)","typeGuard":"def is_valid_rsi_method(m: str) -> bool:\n    \"\"\"Narrow to the library's supported RSI methods.\"\"\"\n    return isinstance(m, str) and m in {\"ema\", \"sma\", \"china\"}","tryCatchPattern":"try:\n    rsi_val = rsi(close, n, method=method)\nexcept ValueError as e:\n    if \"不支持的RSI计算方法\" in str(e):\n        rsi_val = rsi(close, n, method=\"china\")  # sensible default\n    else:\n        raise","preventionTips":["Whitelist method strings from user/config input against {'ema','sma','china'}.","Remember 'china' == Wilder-style smoothing via ewm(com=n-1) if porting TA-Lib code.","Method strings are case-sensitive; lowercase before passing."],"tags":["rsi","indicators","parameter-validation","ta","pandas"],"backgroundTag":"invalid-enum-argument","analyzedSha":"74783e8817d6cf6de29867880631cc555153f36b","analyzedAt":"2026-08-28T11:39:07.729Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}