Relative Strength Line v1.3

TalentedInvestor · study · 222 行 · 点赞 10 · TradingView 原页

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

Pine Script

//@version=6
// RSLine v1.3 - Relative performance against a selected benchmark.
// RS = display scale * (stock closing price / benchmark closing price).
// A rising line means stronger relative performance; a falling line means weaker
// relative performance. Prices use the selected currency basis.
// Yellow and white averages default to 21 and 50 selected RS periods.
// Green shading: RS at or above its yellow average. Red shading: RS below it.
// Green dots: RS and stock price both exceed their preceding lookback highs.
// Pink/purple dots: RS exceeds its high while price has yet to exceed its own.
// The default high window is 12 approximate trading months.
// All calculations use the selected RS timeframe before chart mapping.
// The live line can change during an open period. Dots require source and chart
// close. Different market sessions can update asynchronously.
// Coarser charts sample the line once per candle and summarize source dots.
 
indicator("RSLine v1.3", shorttitle = "RSLine", overlay = false, precision = 2, max_bars_back = 2000, dynamic_requests = true)
 
gTimeframe = "RS timeframe"
rsTimeframeChoice = input.string("Chart", "Calculate RS using", options = ["Chart", "Daily", "Weekly", "Monthly"], group = gTimeframe,
     tooltip = "Choose the RS calculation independently of your price chart. Weekly on Daily uses weekly prices, 21/50-week averages and weekly dots. Chart follows your chart interval. A lower RS timeframe is summarized within each chart candle.")
string rsTimeframe = switch rsTimeframeChoice
    "Daily" => "1D"
    "Weekly" => "1W"
    "Monthly" => "1M"
    => timeframe.period
 
gComparison = "Benchmark"
benchmarkChoice = input.string("QQQ", "Benchmark", options = ["QQQ", "SPY", "SOXX", "Custom"], group = gComparison, display = display.none,
     tooltip = "Choose QQQ, SPY or SOXX. Select Custom to use the symbol field below.")
customBenchmark = input.symbol("NASDAQ:QQQ", "Custom benchmark (select Custom above)", group = gComparison, display = display.none,
     tooltip = "Click this field and search for any benchmark, such as QQQ, SOXX, SPY or an exchange-qualified symbol. This field is used when Benchmark is Custom.")
string benchmark = switch benchmarkChoice
    "QQQ" => "NASDAQ:QQQ"
    "SPY" => "AMEX:SPY"
    "SOXX" => "NASDAQ:SOXX"
    => customBenchmark
currencyBasis = input.string("USD", "Currency basis", options = ["USD", "Local prices"], group = gComparison, display = display.none,
     tooltip = "USD expresses both price series in USD using TradingView's prior daily FX conversion. Local prices compares each listing's own price performance and omits FX changes.")
scaleFactor = input.float(1000.0, "Vertical scale multiplier", minval = 0.000001, group = gComparison, display = display.none,
     tooltip = "A constant multiplier changes the axis numbers while preserving the line's shape, relative returns and signals.")
 
gAverages = "Moving averages"
fastLength = input.int(21, "Yellow MA length (RS periods)", minval = 1, maxval = 500, group = gAverages, display = display.none)
fastType = input.string("SMA", "Yellow MA type", options = ["SMA", "EMA"], group = gAverages, display = display.none)
slowLength = input.int(50, "White MA length (RS periods)", minval = 1, maxval = 500, group = gAverages, display = display.none)
slowType = input.string("SMA", "White MA type", options = ["SMA", "EMA"], group = gAverages, display = display.none)
showSlow = input.bool(true, "Show white moving average", group = gAverages, display = display.none)
 
gHighs = "New-high dots"
showDots = input.bool(true, "Show green and pink dots", group = gHighs, display = display.none)
highMonths = input.int(12, "New-high lookback (months)", minval = 1, maxval = 36, group = gHighs, display = display.none,
     tooltip = "A full window is required. Twelve months uses approximately 252 Daily, 52 Weekly or 12 Monthly RS periods. Shorten the window for recent listings.")
priceHighBasis = input.string("High", "Compare price highs using", options = ["High", "Close"], group = gHighs, display = display.none,
     tooltip = "Price highs use native-currency standard prices in the selected RS timeframe. Pink means RS exceeds its preceding lookback high while price has yet to exceed its own preceding high.")
 
gStyle = "Appearance"
upColor = input.color(#32BF6D, "RS above yellow MA", group = gStyle, display = display.none)
downColor = input.color(#A65050, "RS below yellow MA", group = gStyle, display = display.none)
fastColor = input.color(#C6A65D, "Yellow MA", group = gStyle, display = display.none)
slowColor = input.color(#ECECEC, "White MA", group = gStyle, display = display.none)
greenDotColor = input.color(#28D56B, "RS and price new-high dot", group = gStyle, display = display.none)
pinkDotColor = input.color(#ED50A5, "RS high before price dot", group = gStyle, display = display.none)
showCloud = input.bool(true, "Show green/red cloud", group = gStyle, display = display.none)
cloudTransparency = input.int(82, "Cloud transparency", minval = 0, maxval = 100, group = gStyle, display = display.none)
showTable = input.bool(false, "Show relative-return table", group = gStyle, display = display.none)
showNotices = input.bool(true, "Show data notices", group = gStyle, display = display.none)
 
movingAverage(float source, int length, string kind) =>
    float simpleAverage = ta.sma(source, length)
    float exponentialAverage = ta.ema(source, length)
    kind == "EMA" ? exponentialAverage : simpleAverage
 
relativeReturn(float source, int months, float barsInMonth) =>
    float requestedBars = months * barsInMonth
    int offset = math.max(1, int(math.round(requestedBars)))
    float previous = source[offset]
    requestedBars >= 1 and not na(source) and not na(previous) and previous > 0 ? 100.0 * (source / previous - 1.0) : na
 
returnText(float value) =>
    na(value) ? "—" : (value > 0 ? "+" : "") + str.tostring(value, "0.0") + "%"
 
returnColor(float value, color positive, color negative) =>
    na(value) or value == 0 ? chart.fg_color : value > 0 ? positive : negative
 
bool supportedChart = chart.is_standard and (timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly)
bool lowerRS = timeframe.in_seconds(rsTimeframe) < timeframe.in_seconds()
string requestedCurrency = currencyBasis == "USD" ? currency.USD : currency.NONE
string stockSymbol = ticker.standard(syminfo.tickerid)
 
// Outer requests establish the selected stock/timeframe context. The two nested
// price requests inherit that timeframe through "". Convert only their prices;
// the outer request leaves the ratio, returns and averages dimensionless.
sourceMetrics() =>
    float barsPerMonth = timeframe.isdaily ? 21.0 / timeframe.multiplier : timeframe.isweekly ? 52.0 / (12.0 * timeframe.multiplier) : timeframe.ismonthly ? 1.0 / timeframe.multiplier : 0.0
    int highBars = math.max(1, int(math.round(highMonths * barsPerMonth)))
    [stockPrice, stockCloseTime] = request.security(stockSymbol, "", [close, time_close],
         gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true, currency = requestedCurrency)
    [benchmarkPrice, benchmarkCloseTime] = request.security(benchmark, "", [close, time_close],
         gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true, currency = requestedCurrency)
    float sourceRS = not na(stockPrice) and not na(benchmarkPrice) and stockPrice > 0 and benchmarkPrice > 0 ? scaleFactor * (stockPrice / benchmarkPrice) : na
    float fast = movingAverage(sourceRS, fastLength, fastType)
    float slow = movingAverage(sourceRS, slowLength, slowType)
    float priorRSHigh = ta.highest(sourceRS[1], highBars)
    float price = priceHighBasis == "High" ? high : close
    float priorPriceHigh = ta.highest(price[1], highBars)
    float validObservations = math.sum(not na(sourceRS) ? 1.0 : 0.0, highBars + 1)
    bool windowReady = highMonths * barsPerMonth >= 1 and not na(sourceRS[highBars]) and not na(price[highBars]) and validObservations == highBars + 1
    bool rsNewHigh = windowReady and sourceRS > priorRSHigh
    bool priceNewHigh = not na(price) and not na(priorPriceHigh) and price > priorPriceHigh
    bool green = rsNewHigh and priceNewHigh
    bool pink = rsNewHigh and not priceNewHigh
    bool crossAbove = ta.crossover(sourceRS, fast)
    bool crossBelow = ta.crossunder(sourceRS, fast)
    float relative1M = relativeReturn(sourceRS, 1, barsPerMonth)
    float relative3M = relativeReturn(sourceRS, 3, barsPerMonth)
    float relative6M = relativeReturn(sourceRS, 6, barsPerMonth)
    float relative9M = relativeReturn(sourceRS, 9, barsPerMonth)
    float relative12M = relativeReturn(sourceRS, 12, barsPerMonth)
    // Carry the preceding source signal across week/month boundaries. Its own
    // close timestamp determines which chart candle may confirm it.
    [sourceRS, fast, slow, stockCloseTime, benchmarkCloseTime, green, pink, crossAbove, crossBelow, relative1M, relative3M, relative6M, relative9M, relative12M, sourceRS[1], stockCloseTime[1], green[1], pink[1], crossAbove[1], crossBelow[1]]
 
// Statistics are computed before mapping, so weekly observations are never
// counted repeatedly as daily observations. lookahead_off avoids future values.
[sampleRS, sampleFast, sampleSlow, sourceCloseTime, benchmarkCloseTime, rawGreen, rawPink, rawCrossAbove, rawCrossBelow, relative1M, relative3M, relative6M, relative9M, relative12M, previousRS, previousCloseTime, previousGreen, previousPink, previousCrossAbove, previousCrossBelow] = request.security(stockSymbol, rsTimeframe, sourceMetrics(),
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true, currency = currency.NONE)
 
float rs = supportedChart ? sampleRS : na
float fastMA = supportedChart ? sampleFast : na
float slowMA = supportedChart ? sampleSlow : na
bool aboveFast = not na(rs) and not na(fastMA) and rs >= fastMA
color rsColor = na(fastMA) ? color.gray : aboveFast ? upColor : downColor
rsPlot = plot(rs, "RS", color = rsColor, linewidth = 2, style = plot.style_linebr)
fastPlot = plot(not na(rs) ? fastMA : na, "Fast MA", color = fastColor, linewidth = 1, style = plot.style_linebr)
plot(showSlow and not na(rs) ? slowMA : na, "Slow MA", color = slowColor, linewidth = 2, style = plot.style_linebr)
fill(rsPlot, fastPlot, color = showCloud and not na(rs) and not na(fastMA) ? color.new(aboveFast ? upColor : downColor, cloudTransparency) : na,
     title = "RS / fast MA cloud", fillgaps = false)
 
float greenMarker = na
float pinkMarker = na
bool crossAboveSignal = false
bool crossBelowSignal = false
bool lowerHistoryMissing = false
var int lastProcessedSourceClose = na
 
if supportedChart and lowerRS
    // All available lower-timeframe signals contribute to the enclosing chart
    // candle. Keep the most recent dot of each color, at its actual source RS.
    [rsBars, fastBars, slowBars, closeTimes, benchmarkTimes, greenBars, pinkBars, aboveBars, belowBars, r1Bars, r3Bars, r6Bars, r9Bars, r12Bars, previousRSBars, previousCloseTimes, previousGreenBars, previousPinkBars, previousAboveBars, previousBelowBars] = request.security_lower_tf(stockSymbol, rsTimeframe, sourceMetrics(),
         ignore_invalid_symbol = true, currency = currency.NONE)
    int count = array.size(rsBars)
    lowerHistoryMissing := count == 0
    if barstate.isconfirmed and count > 0
        int processedClose = time
        for i = 0 to count - 1
            // A week can open in one month and close in the next. Check the
            // predecessor first, then the current period, without duplicates.
            for candidate = 0 to 1
                bool predecessor = candidate == 0
                int sourceEnd = predecessor ? array.get(previousCloseTimes, i) : array.get(closeTimes, i)
                bool sourceClosed = not na(sourceEnd) and sourceEnd > processedClose and sourceEnd <= time_close and (not barstate.isrealtime or sourceEnd <= timenow)
                if sourceClosed
                    float dotRS = predecessor ? array.get(previousRSBars, i) : array.get(rsBars, i)
                    bool green = predecessor ? array.get(previousGreenBars, i) : array.get(greenBars, i)
                    bool pink = predecessor ? array.get(previousPinkBars, i) : array.get(pinkBars, i)
                    bool above = predecessor ? array.get(previousAboveBars, i) : array.get(aboveBars, i)
                    bool below = predecessor ? array.get(previousBelowBars, i) : array.get(belowBars, i)
                    if green
                        greenMarker := dotRS
                    if pink
                        pinkMarker := dotRS
                    crossAboveSignal := crossAboveSignal or above
                    crossBelowSignal := crossBelowSignal or below
                    processedClose := sourceEnd
else if supportedChart
    // Confirmation belongs to the source period as well as the chart bar.
    // Remember its close timestamp to avoid repeating a weekly dot all week.
    bool currentClosed = not na(sourceCloseTime) and sourceCloseTime <= time_close and (not barstate.isrealtime or sourceCloseTime <= timenow)
    int candidateClose = currentClosed ? sourceCloseTime : previousCloseTime
    bool sourceClosed = not na(candidateClose) and candidateClose > time and candidateClose <= time_close and (not barstate.isrealtime or candidateClose <= timenow)
    bool newClosedSource = sourceClosed and (na(lastProcessedSourceClose) or candidateClose > lastProcessedSourceClose)
    if barstate.isconfirmed and newClosedSource
        float dotRS = currentClosed ? rs : previousRS
        greenMarker := (currentClosed ? rawGreen : previousGreen) ? dotRS : na
        pinkMarker := (currentClosed ? rawPink : previousPink) ? dotRS : na
        crossAboveSignal := currentClosed ? rawCrossAbove : previousCrossAbove
        crossBelowSignal := currentClosed ? rawCrossBelow : previousCrossBelow
        lastProcessedSourceClose := candidateClose
 
bool greenSignal = not na(greenMarker)
bool pinkSignal = not na(pinkMarker)
plot(showDots ? greenMarker : na, "RS and price new high", color = greenDotColor, linewidth = 6, style = plot.style_circles, display = display.pane)
plot(showDots ? pinkMarker : na, "RS high before price", color = pinkDotColor, linewidth = 6, style = plot.style_circles, display = display.pane)
 
alertcondition(greenSignal, "RS and price new highs", "RSLine: {{ticker}} RS and price reached new lookback highs in the selected RS timeframe. Evaluated at chart-bar close ({{interval}}).")
alertcondition(pinkSignal, "RS high before price", "RSLine: {{ticker}} RS reached a new lookback high before price in the selected RS timeframe. Evaluated at chart-bar close ({{interval}}).")
alertcondition(crossAboveSignal, "RS crossed above yellow MA", "RSLine: {{ticker}} crossed above its fast RS average in the selected RS timeframe. Evaluated at chart-bar close ({{interval}}).")
alertcondition(crossBelowSignal, "RS crossed below yellow MA", "RSLine: {{ticker}} crossed below its fast RS average in the selected RS timeframe. Evaluated at chart-bar close ({{interval}}).")
 
var table returnsTable = table.new(position.bottom_right, 6, 2, border_width = 1)
var table noticeTable = table.new(position.top_left, 1, 1)
if barstate.islast
    if showTable and supportedChart
        array<string> headings = array.from("Rel %", "1M", "3M", "6M", "9M", "12M")
        array<float> values = array.from(relative1M, relative3M, relative6M, relative9M, relative12M)
        color cellBackground = color.new(chart.bg_color, 15)
        for column = 0 to 5
            table.cell(returnsTable, column, 0, array.get(headings, column), text_color = chart.fg_color,
                 text_size = size.tiny, bgcolor = cellBackground,
                 tooltip = "Change in stock/benchmark ratio over approximate trading-month windows in the selected RS timeframe.")
        table.cell(returnsTable, 0, 1, benchmark + " / " + rsTimeframe, text_color = chart.fg_color, text_size = size.tiny, bgcolor = cellBackground,
             tooltip = "This table shows the latest sampled RS period. The RS/MA status-line values follow the historical crosshair.")
        for column = 1 to 5
            float value = array.get(values, column - 1)
            table.cell(returnsTable, column, 1, returnText(value), text_color = returnColor(value, greenDotColor, pinkDotColor),
                 text_size = size.tiny, bgcolor = cellBackground)
    else
        table.clear(returnsTable, 0, 0, 5, 1)
 
    string notice = not supportedChart ? "RSLine: use standard Daily, Weekly or Monthly bars" : na(rs) ? "RSLine: price or currency-conversion data unavailable" : lowerHistoryMissing ? "RSLine: lower-timeframe signal history unavailable on this bar" : sourceCloseTime != benchmarkCloseTime ? "RSLine: latest available benchmark; session closing times differ" : ""
    table.cell(noticeTable, 0, 0, showNotices ? notice : "", text_color = chart.fg_color,
         text_size = size.tiny, bgcolor = color.new(chart.bg_color, str.length(notice) > 0 and showNotices ? 15 : 100))

← 返回列表