Inverse Volatility Allocation | NickJoan

Nick_Joan · study · 145 行 · 点赞 3 · 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/
// © Nick_Joan
 
//@version=6
indicator(title = "Inverse Volatility Allocation | NickJoan", format = format.percent, overlay = false)
 
// ─── Inputs ───────────────────────────────────────────────────────────────────
lookback   = input.int(180, "Volatility Lookback (bars)", minval = 2, group = "CALCULATION")
annualType = input.string("Crypto (√365)", "Annualization", options = ["None", "Crypto (√365)", "Traditional (√252)"], group = "CALCULATION", tooltip = "Crypto trades every day (365). Traditional markets such as stocks and indices trade about 252 days per year. Choose None for raw per-bar volatility.")
 
numAssetsStr = input.string("5", "Number of Assets", options = ["2", "3", "4", "5", "6", "7", "8", "9", "10"], group = "ASSETS", tooltip = "Only the first N assets below are included in the calculation.")
numAssets    = int(str.tonumber(numAssetsStr))
 
symbol1  = input.symbol("INDEX:BTCUSD", "Asset 1", group = "ASSETS")
symbol2  = input.symbol("INDEX:ETHUSD", "Asset 2", group = "ASSETS")
symbol3  = input.symbol("COINBASE:SOLUSD", "Asset 3", group = "ASSETS")
symbol4  = input.symbol("COINBASE:ADAUSD", "Asset 4", group = "ASSETS")
symbol5  = input.symbol("BITSTAMP:XRPUSD", "Asset 5", group = "ASSETS")
symbol6  = input.symbol("COINBASE:DOGEUSD", "Asset 6", group = "ASSETS")
symbol7  = input.symbol("COINBASE:AVAXUSD", "Asset 7", group = "ASSETS")
symbol8  = input.symbol("COINBASE:LINKUSD", "Asset 8", group = "ASSETS")
symbol9  = input.symbol("COINBASE:DOTUSD", "Asset 9", group = "ASSETS")
symbol10 = input.symbol("COINBASE:LTCUSD", "Asset 10", group = "ASSETS")
 
tablePos  = input.string("Middle Center", "Table Position", options = ["Top Right", "Middle Right", "Bottom Right", "Top Center", "Middle Center", "Bottom Center", "Top Left", "Middle Left", "Bottom Left"], group = "TABLE")
tableSize = input.string("Large", "Table Text Size", options = ["Small", "Normal", "Large", "Huge"], group = "TABLE")
 
// ─── Annualization Factor ─────────────────────────────────────────────────────
annualFactor = switch annualType
    "Crypto (√365)" => math.sqrt(365)
    "Traditional (√252)" => math.sqrt(252)
    => 1.0
 
// ─── Volatility Function ──────────────────────────────────────────────────────
calcVolatility() =>
    ta.stdev(math.log(close / close[1]), lookback)
 
// Inactive assets reuse Asset 1 so they share its request and add no extra load
activeSymbol(int n, string sym) =>
    n <= numAssets ? sym : symbol1
 
// Shows the ticker without the exchange prefix
tickerOf(string s) =>
    string[] parts = str.split(s, ":")
    array.size(parts) > 1 ? array.get(parts, 1) : s
 
// ─── Data Requests (static calls) ─────────────────────────────────────────────
rawVol1  = request.security(activeSymbol(1, symbol1), timeframe.period, calcVolatility())
rawVol2  = request.security(activeSymbol(2, symbol2), timeframe.period, calcVolatility())
rawVol3  = request.security(activeSymbol(3, symbol3), timeframe.period, calcVolatility())
rawVol4  = request.security(activeSymbol(4, symbol4), timeframe.period, calcVolatility())
rawVol5  = request.security(activeSymbol(5, symbol5), timeframe.period, calcVolatility())
rawVol6  = request.security(activeSymbol(6, symbol6), timeframe.period, calcVolatility())
rawVol7  = request.security(activeSymbol(7, symbol7), timeframe.period, calcVolatility())
rawVol8  = request.security(activeSymbol(8, symbol8), timeframe.period, calcVolatility())
rawVol9  = request.security(activeSymbol(9, symbol9), timeframe.period, calcVolatility())
rawVol10 = request.security(activeSymbol(10, symbol10), timeframe.period, calcVolatility())
 
// ─── Table Settings ───────────────────────────────────────────────────────────
tablePosition = switch tablePos
    "Top Right" => position.top_right
    "Middle Right" => position.middle_right
    "Bottom Right" => position.bottom_right
    "Top Center" => position.top_center
    "Middle Center" => position.middle_center
    "Bottom Center" => position.bottom_center
    "Top Left" => position.top_left
    "Middle Left" => position.middle_left
    "Bottom Left" => position.bottom_left
    => position.middle_center
 
txtSize = switch tableSize
    "Small" => size.small
    "Normal" => size.normal
    "Large" => size.large
    "Huge" => size.huge
    => size.large
 
// ─── Table Colors ─────────────────────────────────────────────────────────────
titleBg   = color.rgb(19, 23, 34)
headerBg  = color.rgb(42, 46, 57)
rowBg     = color.rgb(30, 34, 45)
rowAltBg  = color.rgb(36, 40, 52)
footerBg  = color.rgb(42, 46, 57)
textMain  = color.rgb(209, 212, 220)
textMuted = color.rgb(131, 137, 150)
frameCol  = color.rgb(67, 70, 81)
 
// ─── Allocation Table (last bar only) ─────────────────────────────────────────
var table allocationTable = na
 
if barstate.islast
    string[] assets = array.from(symbol1, symbol2, symbol3, symbol4, symbol5, symbol6, symbol7, symbol8, symbol9, symbol10)
    float[] rawVols = array.from(rawVol1, rawVol2, rawVol3, rawVol4, rawVol5, rawVol6, rawVol7, rawVol8, rawVol9, rawVol10)
 
    float[] volatilities = array.new_float()
    float[] inverseVols = array.new_float()
    float totalInverseVol = 0.0
 
    for i = 0 to numAssets - 1
        float raw = array.get(rawVols, i)
        float vol = (not na(raw) and raw > 0) ? raw * annualFactor * 100 : na
        float inv = na(vol) ? 0.0 : 1 / vol
        array.push(volatilities, vol)
        array.push(inverseVols, inv)
        totalInverseVol += inv
 
    if not na(allocationTable)
        table.delete(allocationTable)
 
    allocationTable := table.new(tablePosition, 4, numAssets + 3,
         bgcolor = rowBg,
         frame_color = frameCol,
         frame_width = 1,
         border_color = frameCol,
         border_width = 0)
 
    // Title row
    table.cell(allocationTable, 0, 0, "INVERSE VOLATILITY ALLOCATION  |  " + str.tostring(lookback) + " BAR LOOKBACK",
         text_color = color.white, text_size = txtSize, text_halign = text.align_center, bgcolor = titleBg)
    table.merge_cells(allocationTable, 0, 0, 3, 0)
 
    // Header row
    table.cell(allocationTable, 0, 1, " ASSET ", text_color = textMuted, text_size = txtSize, text_halign = text.align_center, bgcolor = headerBg)
    table.cell(allocationTable, 1, 1, " VOLATILITY ", text_color = textMuted, text_size = txtSize, text_halign = text.align_center, bgcolor = headerBg)
    table.cell(allocationTable, 2, 1, " INVERSE VOL ", text_color = textMuted, text_size = txtSize, text_halign = text.align_center, bgcolor = headerBg)
    table.cell(allocationTable, 3, 1, " ALLOCATION ", text_color = textMuted, text_size = txtSize, text_halign = text.align_center, bgcolor = headerBg)
 
    // Asset rows
    for i = 0 to numAssets - 1
        float volatility = array.get(volatilities, i)
        float inverseVol = array.get(inverseVols, i)
        float allocation = totalInverseVol > 0 ? inverseVol / totalInverseVol * 100 : 0
        color bg = i % 2 == 0 ? rowBg : rowAltBg
 
        table.cell(allocationTable, 0, i + 2, " " + tickerOf(array.get(assets, i)) + " ", text_color = textMain, text_size = txtSize, text_halign = text.align_center, bgcolor = bg)
        table.cell(allocationTable, 1, i + 2, na(volatility) ? "N/A" : str.tostring(volatility, "#.##") + "%", text_color = textMain, text_size = txtSize, text_halign = text.align_center, bgcolor = bg)
        table.cell(allocationTable, 2, i + 2, na(volatility) ? "N/A" : str.tostring(inverseVol, "#.####"), text_color = textMain, text_size = txtSize, text_halign = text.align_center, bgcolor = bg)
        table.cell(allocationTable, 3, i + 2, str.tostring(allocation, "#.##") + "%", text_color = color.white, text_size = txtSize, text_halign = text.align_center, bgcolor = bg)
 
    // Footer row
    table.cell(allocationTable, 0, numAssets + 2, " TOTAL ", text_color = textMuted, text_size = txtSize, text_halign = text.align_center, bgcolor = footerBg)
    table.cell(allocationTable, 1, numAssets + 2, "", bgcolor = footerBg)
    table.cell(allocationTable, 2, numAssets + 2, "", bgcolor = footerBg)
    table.cell(allocationTable, 3, numAssets + 2, totalInverseVol > 0 ? "100%" : "N/A", text_color = color.white, text_size = txtSize, text_halign = text.align_center, bgcolor = footerBg)

← 返回列表