Inverse Fisher RSI [RC Tools]

RC-Tools · study · 245 行 · 点赞 27 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RAC97
 
//@version=6
indicator("Inverse Fisher RSI [RC Tools]", shorttitle="RCT IFT RSI", overlay=false, precision=2)
 
// ─────────────────────────────────────────────────────────────────────────────
// ABOUT
// ─────────────────────────────────────────────────────────────────────────────
// Inverse Fisher Transform of RSI — John Ehlers ("The Inverse Fisher
// Transform," Technical Analysis of Stocks & Commodities, 2004). The RSI is
// J. Welles Wilder's. A public, well-documented technique. Independent
// implementation, built from the public method description.
//
// Method:
//   1. Compute a short RSI.
//   2. Rescale it around zero (RSI - 50, times a scaling factor).
//   3. Smooth it with a moving average (a WMA in Ehlers' original; any
//      moving average type can be selected here).
//   4. Apply the INVERSE Fisher Transform: (e^(2x) - 1) / (e^(2x) + 1).
//
// The Fisher Transform stretches a bell-curve-shaped series so its turning
// points stand out. The INVERSE does the opposite: it squashes the values
// toward -1 and +1, so the oscillator spends most of its time clearly "in" or
// "out" of the extreme zones instead of hovering ambiguously in between.
// That makes fixed thresholds (here +/-0.5) far more meaningful than they are
// on a plain RSI.
//
// Zone and signal classification updates ONLY on confirmed bar close, so
// nothing here repaints.
// ─────────────────────────────────────────────────────────────────────────────
 
 
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
float src = input.source(close, "Source", group="Inverse Fisher RSI")
int rsiLen = input.int(5, "RSI Length", minval=2, maxval=50, group="Inverse Fisher RSI",
     tooltip="Lookback of the underlying RSI. Ehlers' classical default: 5 (a deliberately fast RSI; the smoothing below calms it).")
int smoothLen = input.int(9, "Smoothing Length", minval=1, maxval=50, group="Inverse Fisher RSI",
     tooltip="Length of the smoothing applied before the inverse Fisher transform. Ehlers' classical default: 9 (with a WMA). 1 = no smoothing.")
string maType = input.string("WMA", "Smoothing Type", options=["WMA", "SMA", "EMA", "RMA", "HMA", "DEMA", "TEMA", "ALMA", "Super Smoother"], group="Inverse Fisher RSI",
     tooltip="Moving-average family used to smooth the rescaled RSI. WMA is Ehlers' original. EMA/DEMA/TEMA/HMA react faster (more signals, less lag); SMA/RMA/Super Smoother are slower and calmer. ALMA uses offset 0.85, sigma 6.")
float scale = input.float(0.1, "Scaling Factor", minval=0.02, maxval=0.5, step=0.01, group="Inverse Fisher RSI",
     tooltip="Multiplies (RSI - 50) before smoothing. Higher = the transform saturates toward +/-1 more easily (more time in the extreme zones). Ehlers' classical default: 0.1.")
float thresh = input.float(0.5, "Signal Threshold", minval=0.1, maxval=0.95, step=0.05, group="Inverse Fisher RSI",
     tooltip="Zone boundary, both sides. A BULLISH TURN is the oscillator rising back above -threshold; a BEARISH TURN is it falling back below +threshold. Ehlers' classical default: 0.5.")
 
bool showSignalsMain = input.bool(true, "Show Signal Markers on Main Chart", group="Display",
     tooltip="Uses force_overlay to draw the turn markers on the price chart as well as in the oscillator pane.")
bool paintPane = input.bool(true, "Paint Pane Background", group="Display")
bool paintMainChart = input.bool(false, "Paint Main Chart Background", group="Display")
 
bool   showTable = input.bool(true, "Show Stats Table", group="Table")
string tablePos  = input.string("Top Right", "Table Position", options=["Top Right","Top Left","Bottom Right","Bottom Left"], group="Table")
 
color colUpperExt = input.color(color.new(color.lime, 60), "Upper Extreme", group="Colours")
color colPositive = input.color(color.new(color.lime, 88), "Positive",      group="Colours")
color colNegative = input.color(color.new(color.red,  88), "Negative",      group="Colours")
color colLowerExt = input.color(color.new(color.red,  60), "Lower Extreme", group="Colours")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// INVERSE FISHER TRANSFORM OF RSI
// ─────────────────────────────────────────────────────────────────────────────
float rsiVal = ta.rsi(src, rsiLen)
float v1     = scale * (rsiVal - 50.0)
 
// ── Smoothing: every candidate is computed each bar (keeps ta.* calls
//    consistent), then the selected one is used. Length is floored at 2 so
//    HMA and the others are always valid; Smoothing Length 1 bypasses them.
int   sLen = math.max(smoothLen, 2)
float mWma = ta.wma(v1, sLen)
float mSma = ta.sma(v1, sLen)
float mEma = ta.ema(v1, sLen)
float mRma = ta.rma(v1, sLen)
float mHma = ta.hma(v1, sLen)
float eA   = ta.ema(v1, sLen)
float eB   = ta.ema(eA, sLen)
float eC   = ta.ema(eB, sLen)
float mDema = 2.0 * eA - eB
float mTema = 3.0 * (eA - eB) + eC
float mAlma = ta.alma(v1, sLen, 0.85, 6.0)
 
// Ehlers two-pole Super Smoother (v1 is centred on zero, so a zero seed is safe)
float ssG  = math.exp(-1.414 * math.pi / sLen)
float ssC2 = 2.0 * ssG * math.cos(1.414 * math.pi / sLen)
float ssC3 = -ssG * ssG
float ssC1 = 1.0 - ssC2 - ssC3
var float mSs = 0.0
mSs := ssC1 * (v1 + nz(v1[1], v1)) / 2.0 + ssC2 * nz(mSs[1]) + ssC3 * nz(mSs[2])
 
float vSel = switch maType
    "WMA"            => mWma
    "SMA"            => mSma
    "EMA"            => mEma
    "RMA"            => mRma
    "HMA"            => mHma
    "DEMA"           => mDema
    "TEMA"           => mTema
    "ALMA"           => mAlma
    "Super Smoother" => mSs
    => mWma
float v2     = smoothLen > 1 ? vSel : v1
float e2x    = math.exp(2.0 * v2)
float ift    = (e2x - 1.0) / (e2x + 1.0)
 
// RSI is a recursive (RMA) calculation; give it time to settle.
bool warmedUp = bar_index >= rsiLen * 3 + smoothLen and not na(ift)
 
 
// ─────────────────────────────────────────────────────────────────────────────
// CONFIRMED-CLOSE-ONLY STATE AND SIGNALS (non-repainting)
// Zone codes: 0 = Upper Extreme (>= +thresh), 1 = Positive (0 to +thresh),
//             2 = Negative (-thresh to 0),   3 = Lower Extreme (<= -thresh),
//             4 = Warming up
// ─────────────────────────────────────────────────────────────────────────────
var float dispIft  = na
var float dispRsi  = na
var float prevIft  = na
var int   lastSigDir = 0       // +1 bullish turn, -1 bearish turn
var int   barsSinceSig = na
 
bool bullTurn = false
bool bearTurn = false
 
if barstate.isconfirmed
    dispIft := warmedUp ? ift : na
    dispRsi := warmedUp ? rsiVal : na
    if not na(dispIft) and not na(prevIft)
        bullTurn := prevIft <= -thresh and dispIft > -thresh
        bearTurn := prevIft >= thresh and dispIft < thresh
    prevIft := dispIft
    if bullTurn
        lastSigDir := 1
        barsSinceSig := 0
    else if bearTurn
        lastSigDir := -1
        barsSinceSig := 0
    else if lastSigDir != 0
        barsSinceSig := nz(barsSinceSig) + 1
 
zoneOf(v) =>
    na(v) ? 4 :
     v >=  thresh ? 0 :
     v >=  0.0    ? 1 :
     v >  -thresh ? 2 : 3
 
zoneName(z) =>
    z == 0 ? "Upper Extreme" :
     z == 1 ? "Positive" :
     z == 2 ? "Negative" :
     z == 3 ? "Lower Extreme" : "Warming up…"
 
zoneColor(z) =>
    z == 0 ? colUpperExt :
     z == 1 ? colPositive :
     z == 2 ? colNegative :
     z == 3 ? colLowerExt : na
 
int currentZone = zoneOf(dispIft)
 
// ── Zone streak ───────────────────────────────────────────────────────────────
var int lastZone = na
var int streak   = 0
if barstate.isconfirmed
    if currentZone == lastZone
        streak := streak + 1
    else
        streak := 1
        lastZone := currentZone
 
 
// ─────────────────────────────────────────────────────────────────────────────
// PLOTS
// ─────────────────────────────────────────────────────────────────────────────
plot(dispIft, "Inverse Fisher RSI", color=color.new(color.yellow, 0), linewidth=2)
hUp   = hline(thresh,  "Upper Threshold", color=color.new(color.lime, 30), linestyle=hline.style_dashed)
hDn   = hline(-thresh, "Lower Threshold", color=color.new(color.red,  30), linestyle=hline.style_dashed)
hline(0, "Zero", color=color.gray, linestyle=hline.style_solid)
hline(1,  "+1", color=color.new(color.gray, 75), linestyle=hline.style_dotted)
hline(-1, "-1", color=color.new(color.gray, 75), linestyle=hline.style_dotted)
fill(hUp, hDn, color=color.new(color.gray, 94), title="Neutral Band")
 
plotshape(bullTurn, "Bullish Turn", style=shape.triangleup,   location=location.bottom, color=color.lime, size=size.tiny)
plotshape(bearTurn, "Bearish Turn", style=shape.triangledown, location=location.top,    color=color.red,  size=size.tiny)
plotshape(showSignalsMain and bullTurn, "Bullish Turn (main chart)", style=shape.triangleup,   location=location.belowbar, color=color.lime, size=size.tiny, force_overlay=true)
plotshape(showSignalsMain and bearTurn, "Bearish Turn (main chart)", style=shape.triangledown, location=location.abovebar, color=color.red,  size=size.tiny, force_overlay=true)
 
bgcolor(paintPane and warmedUp ? zoneColor(currentZone) : na, title="Zone Background (pane)")
bgcolor(paintMainChart and warmedUp ? zoneColor(currentZone) : na, force_overlay=true, title="Zone Background (main chart)")
 
alertcondition(bullTurn, "RC IFT RSI - Bullish Turn", "Inverse Fisher RSI crossed back above the lower threshold (confirmed bar close).")
alertcondition(bearTurn, "RC IFT RSI - Bearish Turn", "Inverse Fisher RSI crossed back below the upper threshold (confirmed bar close).")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// STATS TABLE
// ─────────────────────────────────────────────────────────────────────────────
getPosition(p) =>
    p == "Top Left"     ? position.top_left :
     p == "Bottom Right" ? position.bottom_right :
     p == "Bottom Left"  ? position.bottom_left : position.top_right
 
if showTable and barstate.islast
    var table t = table.new(getPosition(tablePos), 2, 6,
         bgcolor=color.new(color.black, 15), border_width=1, border_color=color.gray,
         frame_color=color.gray, frame_width=1)
 
    table.cell(t, 0, 0, "Inverse Fisher RSI", text_color=color.white, text_size=size.small, bgcolor=color.new(color.black, 0))
    table.cell(t, 1, 0, "", bgcolor=color.new(color.black, 0))
 
    table.cell(t, 0, 1, "Zone", text_color=color.white, text_size=size.small)
    table.cell(t, 1, 1, warmedUp ? zoneName(currentZone) : "Warming up…", text_color=warmedUp ? color.new(zoneColor(currentZone), 0) : color.gray, text_size=size.small)
 
    table.cell(t, 0, 2, "In zone for", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 2, warmedUp ? str.tostring(streak) + " bars" : "—", text_color=color.gray, text_size=size.small)
 
    table.cell(t, 0, 3, "Reading", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 3, not na(dispIft) ? str.tostring(dispIft, "#.00") : "—", text_color=color.gray, text_size=size.small)
 
    table.cell(t, 0, 4, "Underlying RSI", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 4, not na(dispRsi) ? str.tostring(dispRsi, "#.0") : "—", text_color=color.gray, text_size=size.small)
 
    string lastTxt = lastSigDir == 0 ? "None yet" : (lastSigDir == 1 ? "Bullish turn, " : "Bearish turn, ") + str.tostring(nz(barsSinceSig)) + " bars ago"
    table.cell(t, 0, 5, "Last signal", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 5, lastTxt, text_color=lastSigDir == 1 ? color.lime : lastSigDir == -1 ? color.red : color.gray, text_size=size.small)
 
 
// ─────────────────────────────────────────────────────────────────────────────
// LIMITATIONS (see published description for the full-length version)
// ─────────────────────────────────────────────────────────────────────────────
// - It is a bounded oscillator that SATURATES near +/-1. In a strong trend it
//   can sit in an extreme zone for a long time; an extreme reading is not a
//   reversal forecast.
// - The smoothing adds lag, and the threshold-cross "turn" signals fire after
//   the turn is already under way, never before.
// - Threshold crossings can whip back and forth in choppy, range-bound
//   markets, producing clusters of signals that do not follow through.
// - Defaults (RSI 5, WMA 9, scale 0.1, threshold 0.5) are Ehlers' published
//   starting points, not tuned values for any particular asset.
// - Because the transform compresses extremes, it tells you WHICH zone price
//   momentum is in, not HOW far it is stretched beyond it.
// - Zones and signals update on confirmed bar close only. Nothing repaints.
// ─────────────────────────────────────────────────────────────────────────────

← 返回列表