Bitcoin Power Law - Polaris

Julian_Arcila · study · 155 行 · 点赞 33 · 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/
// © Julián Arcila · Tradeknowlogy · Polaris
//@version=6
indicator("Bitcoin · Ley de potencia con banda medida (Polaris)", shorttitle = "BTC Ley de potencia", overlay = true, max_polylines_count = 10, max_labels_count = 5)
 
// ── Entradas ──
inicio   = input.time(timestamp("18 Jul 2010 00:00 +0000"), "Usar datos desde", tooltip = "La serie arranca cuando el bitcoin empieza a cotizar con regularidad (julio de 2010). CRYPTO:BTCUSD (el índice de bitcoin de TradingView) llega hasta ahí; otros símbolos empiezan más tarde y la línea sale algo distinta.", group = "Línea y banda")
pLo      = input.float(2.0, "Borde inferior (percentil)", minval = 0.5, maxval = 25, step = 0.5, group = "Línea y banda")
pHi      = input.float(98.0, "Borde superior (percentil)", minval = 75, maxval = 99.5, step = 0.5, group = "Línea y banda")
anios    = input.int(2, "Proyectar la línea (años)", minval = 0, maxval = 10, group = "Línea y banda")
cLinea   = input.color(color.new(#f7a600, 0), "Color de la línea de hoy", group = "Línea y banda")
cBanda   = input.color(color.new(#4dd0e1, 0), "Color de la banda", group = "Línea y banda")
verPit   = input.bool(true, "Mostrar", tooltip = "Recalcula la recta en cada vela usando solo los datos hasta esa vela. Enseña cuánto se ha movido la línea con los años: la de hoy no es la que se veía entonces.", group = "Línea con lo que se sabía entonces")
cPit     = input.color(color.new(#9575cd, 0), "Color", group = "Línea con lo que se sabía entonces")
 
verTabla = input.bool(true, "Mostrar", group = "Resumen", inline = "t")
posTabla = input.string("Arriba a la derecha", "", options = ["Arriba a la derecha", "Arriba a la izquierda", "Arriba al centro", "Abajo a la derecha", "Abajo a la izquierda", "Abajo al centro", "En medio a la derecha", "En medio a la izquierda"], group = "Resumen", inline = "t")
tamTabla = input.string("Pequeño", "Tamaño del texto", options = ["Muy pequeño", "Pequeño", "Normal", "Grande"], group = "Resumen")
 
POS = switch posTabla
    "Arriba a la izquierda"   => position.top_left
    "Arriba al centro"        => position.top_center
    "Abajo a la derecha"      => position.bottom_right
    "Abajo a la izquierda"    => position.bottom_left
    "Abajo al centro"         => position.bottom_center
    "En medio a la derecha"   => position.middle_right
    "En medio a la izquierda" => position.middle_left
    => position.top_right
TAM = switch tamTabla
    "Muy pequeño" => size.tiny
    "Normal"      => size.normal
    "Grande"      => size.large
    => size.small
TAMT = switch tamTabla
    "Muy pequeño" => size.small
    "Normal"      => size.large
    "Grande"      => size.huge
    => size.normal
 
// ── Ajuste: log10(precio) = a + b·log10(días desde el bloque génesis, 3-ene-2009) ──
GEN    = timestamp("UTC", 2009, 1, 3, 0, 0)
DIA    = 86400000.0
// Fecha de la vela = su último día (en semanal, el domingo): así cuadra con el cierre que mide.
diasDe(t) => (t - GEN) / DIA + math.max(timeframe.in_seconds() / 86400.0 - 1.0, 0.0)
 
var float n = 0.0
var float sx = 0.0
var float sy = 0.0
var float sxx = 0.0
var float sxy = 0.0
var xs = array.new_float()
var ys = array.new_float()
var ts = array.new_int()
 
ok = time >= inicio and close > 0 and diasDe(time) > 0
if ok
    x = math.log10(diasDe(time))
    y = math.log10(close)
    n   += 1
    sx  += x
    sy  += y
    sxx += x * x
    sxy += x * y
    xs.push(x)
    ys.push(y)
    ts.push(time)
 
den = n * sxx - sx * sx
b   = n > 2 and den != 0 ? (n * sxy - sx * sy) / den : na
a   = n > 2 ? (sy - b * sx) / n : na
modeloPit = ok and n >= 104 ? math.pow(10, a + b * math.log10(diasDe(time))) : na   // 2 años de datos mínimo
 
plot(verPit ? modeloPit : na, "Línea con lo que se sabía entonces", color.new(cPit, 20), 1, plot.style_line)
 
// ── Última vela: la línea de hoy sobre toda la historia, la banda medida y el resumen ──
fmtP(v) => str.replace_all(str.tostring(math.round(v), "#,###"), ",", ".") + " $"
fmtX(v) => str.replace(str.tostring(v, "0.00"), ".", ",") + "×"
 
var float ratioHoy = na
var float pctHoy = na
var float modHoy = na
if barstate.islast and n > 104
    res = array.new_float()
    for i = 0 to int(n) - 1
        res.push(ys.get(i) - (a + b * xs.get(i)))
    lo = res.percentile_linear_interpolation(pLo)
    hi = res.percentile_linear_interpolation(pHi)
    rHoy = ys.get(int(n) - 1) - (a + b * xs.get(int(n) - 1))
    menos = 0
    for r in res
        menos += r < rHoy ? 1 : 0
    pctHoy   := 100.0 * menos / n
    modHoy   := math.pow(10, a + b * xs.get(int(n) - 1))
    ratioHoy := math.pow(10, rHoy)
 
    paso = math.max(1, int(math.ceil(n / 2500)))
    linea = array.new<chart.point>()
    sup   = array.new<chart.point>()
    inf   = array.new<chart.point>()
    for i = 0 to int(n) - 1 by paso
        f = a + b * xs.get(i)
        linea.push(chart.point.from_time(ts.get(i), math.pow(10, f)))
        sup.push(chart.point.from_time(ts.get(i), math.pow(10, f + hi)))
        inf.push(chart.point.from_time(ts.get(i), math.pow(10, f + lo)))
    // proyección: una semana cada punto
    tUlt = ts.get(int(n) - 1)
    semanas = anios * 52
    if semanas > 0
        for j = 1 to semanas
            t = tUlt + j * 7 * 86400000
            f = a + b * math.log10(diasDe(t))
            linea.push(chart.point.from_time(t, math.pow(10, f)))
            sup.push(chart.point.from_time(t, math.pow(10, f + hi)))
            inf.push(chart.point.from_time(t, math.pow(10, f + lo)))
    // banda rellena: borde superior hacia delante y el inferior de vuelta
    banda = array.copy(sup)
    for k = inf.size() - 1 to 0
        banda.push(inf.get(k))
    polyline.new(banda, false, true, xloc.bar_time, color.new(cBanda, 100), color.new(cBanda, 90))
    polyline.new(sup, false, false, xloc.bar_time, color.new(cBanda, 40), na, line.style_dotted, 1)
    polyline.new(inf, false, false, xloc.bar_time, color.new(cBanda, 40), na, line.style_dotted, 1)
    polyline.new(linea, false, false, xloc.bar_time, cLinea, na, line.style_solid, 2)
 
    if verTabla
        // Colores del tema del gráfico: se lee igual en claro y en oscuro
        cFondo = color.new(chart.bg_color, 5)
        cTexto = chart.fg_color
        cSuave = color.new(chart.fg_color, 35)
        cBorde = color.new(chart.fg_color, 85)
        claro  = (color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color)) / 3 > 128
        cDato  = claro ? #d35400 : cLinea   // naranja más oscuro sobre fondo claro
        var tb = table.new(POS, 2, 10, cFondo, cBorde, 1, cBorde, 1)
        primer = ts.get(0)
        filas = array.from("Precio frente a su línea", "Su línea hoy", "Banda (" + str.tostring(pHi - pLo, "#.#") + " % de las velas)", "Velas más abajo en su historia", "Exponente", "Datos")
        vals  = array.from(fmtX(ratioHoy), fmtP(modHoy), fmtP(modHoy * math.pow(10, lo)) + " – " + fmtP(modHoy * math.pow(10, hi)), str.tostring(math.round(pctHoy)) + " de cada 100", str.replace(str.tostring(b, "0.00"), ".", ","), str.format_time(primer, "MMM yyyy", "UTC") + " → hoy · " + str.tostring(n, "#") + " velas")
        table.cell(tb, 0, 0, "Ley de potencia del bitcoin", text_color = cTexto, text_size = TAMT, text_halign = text.align_left, text_formatting = text.format_bold)
        table.merge_cells(tb, 0, 0, 1, 0)
        for k = 0 to filas.size() - 1
            table.cell(tb, 0, k + 1, filas.get(k), text_color = cSuave, text_size = TAM, text_halign = text.align_left)
            table.cell(tb, 1, k + 1, vals.get(k), text_color = k == 0 ? cDato : cTexto, text_size = TAM, text_halign = text.align_right, text_formatting = k == 0 ? text.format_bold : text.format_none)
        // Leyenda con el color de cada trazo
        table.cell(tb, 0, 7, "━ Línea de hoy", text_color = cDato, text_size = TAM, text_halign = text.align_left)
        table.cell(tb, 1, 7, "┅ Banda (" + str.tostring(pHi - pLo, "#.#") + " %)", text_color = claro ? #00838f : cBanda, text_size = TAM, text_halign = text.align_right)
        if verPit
            table.cell(tb, 0, 8, "━ La línea con lo que se sabía entonces", text_color = claro ? #5e35b1 : cPit, text_size = TAM, text_halign = text.align_left)
            table.merge_cells(tb, 0, 8, 1, 8)
        if primer > timestamp("UTC", 2011, 12, 31, 0, 0)
            table.cell(tb, 0, 9, "⚠ Este símbolo empieza en " + str.format_time(primer, "yyyy", "UTC") + ": para la historia completa usa CRYPTO:BTCUSD", text_color = color.orange, text_size = size.tiny)
            table.merge_cells(tb, 0, 9, 1, 9)
 
// Valores en la ventana de datos (para comprobar las cifras)
plot(ratioHoy, "Precio ÷ línea (hoy)", display = display.data_window)
plot(pctHoy, "Percentil de hoy", display = display.data_window)
plot(modHoy, "Línea hoy", display = display.data_window)
plot(b, "Exponente", display = display.data_window)

← 返回列表