Correlation Coefficient

SoCallMeDeaconBlues · study · 258 行 · 点赞 8 · 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/
// © SoCallMeDeaconBlues
//@version=6
indicator("Correlation Coefficient", shorttitle = "Corr", overlay = false, precision = 3, max_bars_back = 5000)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: where each series comes from
// ─────────────────────────────────────────────────────────────────────────────
grpA  = "Series A"
modeA = input.string("Chart source", "Take from", options = ["Chart source", "Symbol"], group = grpA,
     tooltip = "Chart source: pick a price field or any plot already on the chart.\nSymbol: type a ticker; the script fetches its close on the chart's timeframe.")
srcAIn = input.source(close, "Chart source", group = grpA, active = modeA == "Chart source")
symA   = input.symbol("CME_MINI:ES1!", "Symbol", group = grpA, active = modeA == "Symbol")
 
grpB  = "Series B"
modeB = input.string("Symbol", "Take from", options = ["Chart source", "Symbol"], group = grpB,
     tooltip = "Chart source: pick a price field or any plot already on the chart.\nSymbol: type a ticker; the script fetches its close on the chart's timeframe.")
srcBIn = input.source(close, "Chart source", group = grpB, active = modeB == "Chart source")
symB   = input.symbol("NYMEX:CL1!", "Symbol", group = grpB, active = modeB == "Symbol")
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: calculation
// ─────────────────────────────────────────────────────────────────────────────
grpC = "Calculation"
transform = input.string("Log returns", "Transform", options = ["Log returns", "Returns %", "Change (difference)", "Levels"], group = grpC,
     tooltip = "Correlating raw price levels gives inflated, often spurious values on trending markets. Log returns is the standard choice for prices; use Change (difference) for oscillators that can be zero or negative.")
gapMode = input.string("Align on common bars", "Missing data", options = ["Align on common bars", "Stop if gap in lookback", "Stop if gap anywhere"], group = grpC,
     tooltip = "What to do when one series has a value and the other doesn't (session breaks, holidays, minutes with no trades).\n\nAlign on common bars: use only bars where both series have a value, and measure each change from the last such bar, so a move made while one market was closed is paired with the other market's move over the same stretch.\nStop if gap in lookback: halt with an error if any closed bar in the current window has a mismatch.\nStop if gap anywhere: halt on the first mismatched closed bar anywhere in chart history.\n\nThe still-forming live bar is never checked by the stop modes, since the slower symbol may simply not have ticked yet.")
gapFix = input.string("Scale", "Session-gap bars", options = ["Scale", "Drop", "Off"], group = grpC,
     tooltip = "A session-gap bar is the first common bar after more than one bar's worth of clock time has passed (e.g. a stock's opening bar, which carries the whole overnight gap). One such bar can swing the correlation hard and take a long time to fade.\n\nScale: divide both changes on that bar by the square root of the number of bars of time it covers, so an overnight gap counts about as much as one normal bar. Direction is kept.\nDrop: leave gap bars out of the calculation entirely.\nOff: use them as-is.\n\nBars inside continuous trading are never touched. Ignored when Transform is Levels.")
method = input.string("Pearson", "Method", options = ["Pearson", "Spearman", "EWMA Pearson"], group = grpC,
     tooltip = "Pearson: linear, rolling window.\nSpearman: rank-based (monotonic, robust to outliers), rolling window.\nEWMA Pearson: exponentially weighted, recent bars count more; Lookback sets the span.")
len = input.int(50, "Lookback (common bars)", minval = 3, maxval = 1000, group = grpC,
     tooltip = "Number of bars where both series have a value. Gaps are skipped, so on a chart with session breaks the window can span more chart bars than this.")
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: visuals
// ─────────────────────────────────────────────────────────────────────────────
grpV = "Visuals"
posCol     = input.color(color.rgb(0, 200, 83), "Positive color", group = grpV)
negCol     = input.color(color.rgb(255, 61, 61), "Negative color", group = grpV)
maxTransp  = input.int(85, "Transparency at 0", minval = 0, maxval = 100, group = grpV)
minTransp  = input.int(0, "Transparency at ±1", minval = 0, maxval = 100, group = grpV)
lineW      = input.int(2, "Line width", minval = 1, maxval = 5, group = grpV)
showFill   = input.bool(true, "Fill to zero", group = grpV)
fillExtra  = input.int(10, "Extra fill transparency", minval = 0, maxval = 100, group = grpV)
showLevels = input.bool(true, "Show ±0.5 guides", group = grpV)
showSolid  = input.bool(true, "Show solid line", group = grpV, inline = "solid",
     tooltip = "A plain, fully opaque line drawn on top of the color-coded one, so the value stays readable even when the correlation is near zero and the colored line fades out.")
solidCol   = input.color(color.rgb(41, 98, 255), "", group = grpV, inline = "solid")
solidW     = input.int(1, "Width", minval = 1, maxval = 5, group = grpV, inline = "solid")
 
// ─────────────────────────────────────────────────────────────────────────────
// Series
// ─────────────────────────────────────────────────────────────────────────────
// gaps_on: a bar where the requested symbol didn't trade comes back as na
// (the same way an on-chart overlay behaves) instead of repeating the last price.
float secA = request.security(symA, timeframe.period, close, gaps = barmerge.gaps_on)
float secB = request.security(symB, timeframe.period, close, gaps = barmerge.gaps_on)
 
float srcA = modeA == "Symbol" ? secA : srcAIn
float srcB = modeB == "Symbol" ? secB : srcBIn
 
bool hasA     = not na(srcA)
bool hasB     = not na(srcB)
bool both     = hasA and hasB
bool mismatch = hasA != hasB
 
// ─────────────────────────────────────────────────────────────────────────────
// Guards
// ─────────────────────────────────────────────────────────────────────────────
mismatchMsg(int t) =>
    "Series A and B don't line up: one of them has no value on the bar at " +
     str.format_time(t, "yyyy-MM-dd HH:mm", syminfo.timezone) +
     ". Pick two series that trade the same hours, or set \"Missing data\" to \"Align on common bars\"."
 
if gapMode == "Stop if gap anywhere" and mismatch and barstate.isconfirmed
    runtime.error(mismatchMsg(time))
 
if gapMode == "Stop if gap in lookback" and barstate.islast
    int startOff = barstate.isconfirmed ? 0 : 1      // skip the still-forming live bar
    for i = startOff to len                          // len changes need len + 1 prices
        if mismatch[i]
            runtime.error(mismatchMsg(time[i]))
 
// Same series on both sides (e.g. both left on the chart's close).
if barstate.islast
    bool allSame = true
    int  seen    = 0
    for i = 0 to len
        if not na(srcA[i]) and not na(srcB[i])
            seen += 1
            if srcA[i] != srcB[i]
                allSame := false
                break
    if allSame and seen > 1
        runtime.error("Series A and Series B are the same series. Open the settings and point Series B at the other symbol.")
 
// ─────────────────────────────────────────────────────────────────────────────
// Aligned transform: each change is measured from the last bar where BOTH
// series had a value, so the two changes always cover the same stretch of time.
// ─────────────────────────────────────────────────────────────────────────────
change(float x, float prev) =>
    switch transform
        "Log returns"         => x > 0 and prev > 0 ? math.log(x / prev) : na
        "Returns %"           => prev != 0 ? (x / prev - 1.0) * 100.0 : na
        "Change (difference)" => x - prev
        => x
 
// Session-gap handling: how many bars' worth of clock time this change covers.
float barMs = timeframe.in_seconds(timeframe.period) * 1000.0
 
var float lastA = na
var float lastB = na
var int   lastT = na
float a = na
float b = na
if both
    if not na(lastA)
        a := change(srcA, lastA)
        b := change(srcB, lastB)
        if transform != "Levels" and gapFix != "Off" and barMs > 0
            float elapsed = (time - lastT) / barMs
            if elapsed > 1.5
                if gapFix == "Drop"
                    a := na
                    b := na
                else
                    float sc = math.sqrt(elapsed)
                    a := a / sc
                    b := b / sc
    lastA := srcA
    lastB := srcB
    lastT := time
 
// ── Indexed to 100 at the start of the lookback window (Data Window only) ────
// Correlation is scale-invariant, so this does not change the result.
float ancA = srcA[len]
float ancB = srcB[len]
float idxA = not na(ancA) and ancA != 0 ? 100.0 * srcA / ancA : na
float idxB = not na(ancB) and ancB != 0 ? 100.0 * srcB / ancB : na
 
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
pearson(array<float> x, array<float> y) =>
    int   n = x.size()
    float r = na
    if n >= 3
        float mx  = x.avg()
        float my  = y.avg()
        float sxy = 0.0
        float sxx = 0.0
        float syy = 0.0
        for i = 0 to n - 1
            float dx = x.get(i) - mx
            float dy = y.get(i) - my
            sxy += dx * dy
            sxx += dx * dx
            syy += dy * dy
        float den = math.sqrt(sxx * syy)
        r := den > 0 ? sxy / den : na
    r
 
// Fractional ranks (ties get the average rank), for Spearman.
rankArr(array<float> v) =>
    int n         = v.size()
    array<int> ix = v.sort_indices(order.ascending)
    array<float> ranks = array.new_float(n, 0.0)
    int i = 0
    while i < n
        int j = i
        while j + 1 < n and v.get(ix.get(j + 1)) == v.get(ix.get(i))
            j += 1
        float avgRank = (i + j) / 2.0 + 1.0
        for k = i to j
            ranks.set(ix.get(k), avgRank)
        i := j + 1
    ranks
 
// ─────────────────────────────────────────────────────────────────────────────
// Correlation
// ─────────────────────────────────────────────────────────────────────────────
// Rolling Pearson / Spearman over the last `len` common bars.
float rRoll = na
if method != "EWMA Pearson"
    xs = array.new_float()
    ys = array.new_float()
    int maxScan = math.min(4999, len * 4)
    for i = 0 to maxScan
        float xa = a[i]
        float yb = b[i]
        if not na(xa) and not na(yb)
            xs.push(xa)
            ys.push(yb)
            if xs.size() >= len
                break
    if xs.size() >= len
        rRoll := method == "Pearson" ? pearson(xs, ys) : pearson(rankArr(xs), rankArr(ys))
 
// EWMA Pearson (runs every bar so its state stays continuous).
float alpha = 2.0 / (len + 1)
var float emA  = na
var float emB  = na
var float evA  = 0.0
var float evB  = 0.0
var float ecAB = 0.0
var int   ewN  = 0
if not na(a) and not na(b)
    if na(emA)
        emA := a
        emB := b
    else
        float dA = a - emA
        float dB = b - emB
        emA  += alpha * dA
        emB  += alpha * dB
        evA  := (1 - alpha) * (evA  + alpha * dA * dA)
        evB  := (1 - alpha) * (evB  + alpha * dB * dB)
        ecAB := (1 - alpha) * (ecAB + alpha * dA * dB)
    ewN += 1
float rEW = ewN >= len and evA > 0 and evB > 0 ? ecAB / math.sqrt(evA * evB) : na
 
float r = method == "EWMA Pearson" ? rEW : rRoll
r := math.max(-1.0, math.min(1.0, r))
 
// ─────────────────────────────────────────────────────────────────────────────
// Color: hue by sign, opacity by distance from zero
// ─────────────────────────────────────────────────────────────────────────────
float mag     = math.abs(r)
float tr      = maxTransp - (maxTransp - minTransp) * mag
color base    = r >= 0 ? posCol : negCol
color lineCol = na(r) ? na : color.new(base, tr)
color fillCol = na(r) or not showFill ? na : color.new(base, math.min(100.0, tr + fillExtra))
 
// ─────────────────────────────────────────────────────────────────────────────
// Plots
// ─────────────────────────────────────────────────────────────────────────────
hline( 1.0, "Upper bound", color = color.new(color.gray, 100))   // invisible, pins scale to ±1
hline(-1.0, "Lower bound", color = color.new(color.gray, 100))
hline( 0.0, "Zero", color = color.new(color.gray, 40), linestyle = hline.style_solid)
hline( 0.5, "+0.5", color = color.new(color.gray, 70), linestyle = hline.style_dotted, display = showLevels ? display.all : display.none)
hline(-0.5, "-0.5", color = color.new(color.gray, 70), linestyle = hline.style_dotted, display = showLevels ? display.all : display.none)
 
rPlot = plot(r, "Correlation", color = lineCol, linewidth = lineW)
zPlot = plot(0, "Zero ref", color = na, display = display.none, editable = false)
fill(rPlot, zPlot, color = fillCol, title = "Fill")
plot(r, "Correlation (solid)", color = solidCol, linewidth = solidW, display = showSolid ? display.all : display.none)
 
// Data Window only: not drawn in the pane, so they don't wreck the ±1 scale.
plot(idxA, "Series A indexed (100 = window start)", color = color.gray, display = display.data_window)
plot(idxB, "Series B indexed (100 = window start)", color = color.gray, display = display.data_window)
 
// ─────────────────────────────────────────────────────────────────────────────
// Alerts
// ─────────────────────────────────────────────────────────────────────────────
alertcondition(ta.crossover(r, 0),  "Correlation turned positive", "Correlation crossed above 0")
alertcondition(ta.crossunder(r, 0), "Correlation turned negative", "Correlation crossed below 0")

← 返回列表