Indicador Coeficiente de correlación BTCUSD/SPX
//@version=6
indicator(«Correlación BTC/SPX — Leyguarda», overlay=false)
// ── Inputs ──────────────────────────────────────────────
symBtc = input.symbol(«BITSTAMP:BTCUSD», «Símbolo BTC»)
symSpx = input.symbol(«TVC:SPX», «Símbolo SPX»)
len = input.int(30, «Periodo correlación», minval=5)
useLog = input.bool(true, «Usar retornos logarítmicos (recomendado)»)
smoothLen= input.int(5, «Suavizado (1 = sin suavizar)», minval=1)
hiTh = input.float(0.5, «Umbral correlación alta», step=0.05)
loTh = input.float(-0.3, «Umbral correlación inversa», step=0.05)
// ── Datos ───────────────────────────────────────────────
btcClose = request.security(symBtc, timeframe.period, close)
spxClose = request.security(symSpx, timeframe.period, close)
btcRet = useLog ? math.log(btcClose / btcClose[1]) : ta.change(btcClose)
spxRet = useLog ? math.log(spxClose / spxClose[1]) : ta.change(spxClose)
// ── Correlación ─────────────────────────────────────────
corrRaw = ta.correlation(btcRet, spxRet, len)
corr = smoothLen > 1 ? ta.sma(corrRaw, smoothLen) : corrRaw
// ── Régimen ─────────────────────────────────────────────
regimen = corr >= hiTh ? 1 : corr <= loTh ? -1 : 0
colCorr = regimen == 1 ? color.new(#C9961A, 0) :
regimen == -1 ? color.new(#E0506A, 0) :
color.new(#8A8A8A, 0)
// ── Plot ────────────────────────────────────────────────
plot(corr, «Correlación», color=colCorr, linewidth=2)
plot(corrRaw, «Correlación sin suavizar», color=color.new(color.gray, 70))
hline(1, «Máx», color=color.new(color.gray, 60))
hline(0, «Cero», color=color.new(color.gray, 30), linestyle=hline.style_solid)
hline(-1, «Mín», color=color.new(color.gray, 60))
bandHi = hline(hiTh, «Umbral alto», color=color.new(#C9961A, 60))
bandLo = hline(loTh, «Umbral inverso», color=color.new(#E0506A, 60))
fill(bandHi, bandLo, color=color.new(color.gray, 92))
// ── Tabla de estado ─────────────────────────────────────
var table t = table.new(position.top_right, 1, 2)
if barstate.islast
txt = regimen == 1 ? «RISK-ON: BTC acoplado a SPX» :
regimen == -1 ? «INVERSA: BTC contra SPX» :
«DESACOPLADO / neutral»
table.cell(t, 0, 0, str.format(«ρ({0}) = {1}», len, str.tostring(corr, «#.##»)), text_color=color.white, bgcolor=color.new(#1A1A1A, 0))
table.cell(t, 0, 1, txt, text_color=colCorr, bgcolor=color.new(#1A1A1A, 0))
