Pine Script双序列输入RSI的计算实现逻辑解析
Great question! Let's clear up the confusion here first: the "dual-sequence input" you're noticing is actually a misinterpretation of Pine Script's rsi() function parameters. The second argument in the official implementation you shared is not a second price sequence—it's the period length for the RSI calculation (the same N value you'd use in traditional RSI formulas, like 14).
Let's break down the official code line by line to confirm:
pine_rsi(x, y) => u = max(x - x[1], 0) // upward change d = max(x[1] - x, 0) // downward change rs = rma(u, y) / rma(d, y) res = 100 - 100 / (1 + rs) res
Parameter Breakdown
x: This is the source sequence you want to calculate RSI for (e.g., closing prices, opening prices, or any other price/indicator series).y: This is the period length parameter (the number of bars used to smooth the up/down moves with the RMA).
Step-by-Step Logic
- Calculate Upward/Downward Moves:
ucaptures only positive price changes (if the current value inxis higher than the previous value, we take the difference; otherwise, we use 0).dcaptures only negative price changes (if the previous value inxis higher than the current, we take the difference; otherwise, 0).
- Smooth Moves with RMA:
rma(u, y)applies Pine Script's Recursive Moving Average (a variant of EMA) to the upward moves overybars.rma(d, y)does the same for downward moves.
- Compute Relative Strength (RS):
- RS is the ratio of the smoothed upward moves to the smoothed downward moves.
- Convert to RSI:
- The final formula transforms RS into the familiar 0-100 scale RSI value, identical to the traditional RSI calculation.
Why No "Second Sequence" Usage?
The confusion likely comes from parameter naming or a mix-up with custom RSI variants (some custom implementations might use two sequences for unique calculations). But the official Pine Script RSI implementation only uses one source sequence (x) and one period parameter (y)—there's no second sequence input here at all.
内容的提问来源于stack exchange,提问作者Ahmed Montasser

