安全 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 = 14movav = stratforge::RsiMovAv::Smoothed(Simple,Exponential)safehigh = 100.0safelow = 50.0lookback = 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
