安全 RSI (RSI_SAFE)

已核验的 StratForge C++23 API、计算与预热行为。

Route: /indicators/rsi_safe/

安全除法处理平均损失为零的情况,不检测价格与 RSI 的背离。默认安全值下输出为 0–100 的 RSI 数值,不是收益百分比。

change = close[t] - close[t - lookback]

gain = max(change, 0); loss = max(-change, 0)

average[t] = (average[t - 1] * (period - 1) + value[t]) / period

RS = average_gain / average_loss; RSI = 100 - 100 / (1 + RS)

参数

  • period = 14
  • movav = stratforge::RsiMovAv::Smoothed (Simple, Exponential)
  • safehigh = 100.0
  • safelow = 50.0
  • lookback = 1

RSI_Safe: safediv = true; RSI: safediv = false. upperband / lowerband: 70 / 30 — 图表阈值,不是构造函数参数。

计算示例

period = 3、lookback = 1,收盘价 [10, 11, 10, 11, 13] 的变化为 [1, -1, 1, 2]。初始平均上涨为 2/3、平均下跌为 1/3,第 4 根 RSI = 66.666667。第 5 根平滑平均上涨为 10/9、下跌为 2/9,RSI = 83.333333。前三根输出 NaN;预热长度为 period + lookback,默认 15 根。

默认安全值下:只有上涨、无下跌时为 100;只有下跌、无上涨时为 0;全平盘(0/0)为 50。这些分支只在预热后适用。自定义 safehigh/safelow 指定零分母结果,是 RSI 数值,不是分母修正量。

使用有限价格及正数周期和回看长度。此版本把零周期或零回看长度归一为 1,不校验自定义安全值,也不保证非有限价格的输出有意义。示例计算不是交易信号或收益证据。

C++23 API — StratForge

#include <stratforge/indicators/rsi.hpp>
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>

int main() {
    stratforge::Line<double> close, rising, falling, flat;
    stratforge::RSI_Safe rsi(close, 3);
    stratforge::RSI_Safe up(rising, 3), down(falling, 3), neutral(flat, 3);
    assert(rsi.minimum_period() == 4);
    std::cout << std::fixed << std::setprecision(6);
    for (double price : {10.0, 11.0, 10.0, 11.0, 13.0}) {
        close.forward(price);
        rsi.next();
        if (close.size() < 4) assert(std::isnan(rsi[0]));
        else std::cout << rsi[0] << " ";
    }
    assert(std::abs(rsi.line()[-1] - 66.666666667) < 1e-9);
    assert(std::abs(rsi[0] - 83.333333333) < 1e-9);
    for (int i = 0; i < 4; ++i) {
        rising.forward(10.0 + i);
        falling.forward(10.0 - i);
        flat.forward(10.0);
        up.next();
        down.next();
        neutral.next();
    }
    assert(up[0] == 100.0 && down[0] == 0.0 && neutral[0] == 50.0);
    std::cout << up[0] << " " << down[0] << " " << neutral[0] << "\n";
}

复现

StratForge d25404dcf2c3842ba304ddc60ac19cfec1f8aa37 (2026-08-28); GCC 14, C++23; scalar build, no xsimd dependency.

git clone https://github.com/StratCraftsAI/StratForge.git StratForge
git -C StratForge checkout --detach d25404dcf2c3842ba304ddc60ac19cfec1f8aa37
g++-14 -std=c++23 -O2 -Wall -Wextra -pedantic -IStratForge/include example.cpp -o example
./example

example.cpp: C++23 API. stdout:

66.666667 83.333333 100.000000 0.000000 50.000000

来源