Monte Carlo Probability Forecaster

OlympusCipher · study · 349 行 · 点赞 103 · 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/
// © OlympusCipher
 
//  ◇━━━━━━━━━━━━━━━━━━  C R E A T E D    B Y  ━━━━━━━━━━━━━━━━━━◇
//
//     ████   ██      ██  ██  ██      ██  █████   ██  ██   █████
//    ██  ██  ██      ██  ██  ███    ███  ██  ██  ██  ██  ██
//    ██  ██  ██       ████   ████  ████  ██  ██  ██  ██  ██
//    ██  ██  ██        ██    ██ ████ ██  █████   ██  ██   ████
//    ██  ██  ██        ██    ██  ██  ██  ██      ██  ██      ██
//    ██  ██  ██        ██    ██      ██  ██      ██  ██      ██
//     ████   ██████    ██    ██      ██  ██       ████   █████
//
//           █████  ██████  █████   ██  ██  ██████  █████
//          ██        ██    ██  ██  ██  ██  ██      ██  ██
//          ██        ██    ██  ██  ██  ██  ██      ██  ██
//          ██        ██    █████   ██████  █████   █████
//          ██        ██    ██      ██  ██  ██      ██  ██
//          ██        ██    ██      ██  ██  ██      ██  ██
//           █████  ██████  ██      ██  ██  ██████  ██  ██
//
//  ◇━━━━━━━━━━━━ Ω  O L Y M P U S    C I P H E R  Ω ━━━━━━━━━━━━◇
 
 
// Monte Carlo Probability Forecast
 
//@version=6
indicator("Monte Carlo Probability Forecast", shorttitle = "MC Prob", overlay = true,
     max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500, max_polylines_count = 100)
 
// ═════════════════════════ INPUTS ═════════════════════════
G_SIM = "Simulation"
rngSeed   = input.int   (10,          "Random Seed",                minval = 0,                                   group = G_SIM,
     tooltip = "Same seed = repeatable results. Change it to draw a different random sample.")
retModel  = input.string("Gaussian", "Return Model",               options = ["Gaussian", "Historical Resample"], group = G_SIM,
     tooltip = "Gaussian: returns drawn from a normal distribution using recent mean and volatility.\nHistorical Resample: returns picked at random from actual recent returns (keeps fat tails).")
pathCount = input.int   (2000,        "Number of Paths",            minval = 100, maxval = 2000, step = 100,      group = G_SIM,
     tooltip = "More paths = smoother probabilities but heavier. Automatically reduced if Paths × Horizon is too large.")
horizon   = input.int   (40,         "Forecast Horizon (bars)",    minval = 5,   maxval = 300,  step = 5,        group = G_SIM)
lookback  = input.int   (200,        "Return Sample (bars)",       minval = 20,  maxval = 5000, step = 10,       group = G_SIM,
     tooltip = "Number of recent bars used to measure returns and volatility.")
keepDrift = input.bool  (true,       "Keep Average Trend (Drift)",                                               group = G_SIM,
     tooltip = "Off = zero trend, volatility only.")
tickMode  = input.bool  (false,      "Update on Every Tick",                                                     group = G_SIM,
     tooltip = "Off (recommended): built from closed candles only and stays fixed until the next candle closes.")
 
G_DIST = "Probability Distribution"
zoneCount = input.int (30,   "Price Zones",                 minval = 4,  maxval = 40,  group = G_DIST)
histWidth = input.int (40,   "Histogram Width (bars)",      minval = 10, maxval = 150, group = G_DIST)
showHist  = input.bool(true, "Show Probability Histogram",                             group = G_DIST)
showHeat  = input.bool(true, "Show Heat Zones",                                        group = G_DIST)
showCone  = input.bool(true, "Show Percentile Cone",                                   group = G_DIST)
drawPaths = input.int (20,   "Paths to Display",            minval = 0,  maxval = 80,  group = G_DIST,
     tooltip = "Visual only. Every path is always used for the probabilities.")
 
G_TGT = "Targets"
upTgtPct  = input.float(2.0, "Upside Target %",             minval = 0, maxval = 1000, step = 0.25, group = G_TGT)
dnTgtPct  = input.float(2.0, "Downside Target %",           minval = 0, maxval = 99,   step = 0.25, group = G_TGT)
userLevel = input.float(0.0, "Custom Level (0 = off)",      minval = 0,                             group = G_TGT)
 
G_STY = "Style"
cLow      = input.color(color.new(#f5433a, 65), "Low Probability",  group = G_STY)
cHigh     = input.color(color.new(#3ebec9, 0),  "High Probability", group = G_STY)
cUp       = input.color(#4caf50,                "Bullish",          group = G_STY)
cDown     = input.color(#f44336,                "Bearish",          group = G_STY)
cMedian   = input.color(#e0e0e0,                "Median",           group = G_STY)
cBand     = input.color(#26c6da,                "Percentile Bands", group = G_STY)
tablePos  = input.string("Top Right", "Panel Position",  options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G_STY)
panelSize = input.string("Small",       "Panel Text Size", options = ["Small", "Normal", "Large", "Huge"],                    group = G_STY)
 
// ═════════════════════════ WORK LIMIT ═════════════════════════
WORK_LIMIT = 300000
runPaths   = math.max(100, math.min(pathCount, int(WORK_LIMIT / horizon)))
isReduced  = runPaths < pathCount
 
// ═════════════════════════ RETURN SAMPLE ═════════════════════════
var array<float> logRets = array.new_float()
lr = math.log(close / close[1])
if not na(lr)
    logRets.push(lr)
    if logRets.size() > lookback
        logRets.shift()
 
sampleN   = logRets.size()
meanRet   = sampleN > 1 ? logRets.avg() : 0.0
driftRet  = keepDrift ? meanRet : 0.0
volRet    = sampleN > 1 ? logRets.stdev(false) : 0.0
upTarget  = close * (1 + upTgtPct / 100)
dnTarget  = close * (1 - dnTgtPct / 100)
shownN    = math.min(drawPaths, runPaths)
 
// ═════════════════════════ STORAGE ═════════════════════════
snapCount = math.min(horizon, 25)                     // snapshots stored per path
 
var array<int> snapBars = array.new_int()
if snapBars.size() == 0
    for j = 1 to snapCount
        snapBars.push(int(math.round(float(j * horizon) / snapCount)))
 
var array<int>      touchCnt = array.new_int(3, 0)    // 0 upside, 1 downside, 2 custom
var array<box>      gBoxes   = array.new<box>()
var array<label>    gLabels  = array.new<label>()
var array<line>     gLines   = array.new<line>()
var array<polyline> gPolys   = array.new<polyline>()
 
// ═════════════════════════ FUNCTIONS ═════════════════════════
stdNormal() =>
    a = math.random(1e-10, 1.0, rngSeed)
    b = math.random(0.0,   1.0, rngSeed)
    math.sqrt(-2.0 * math.log(a)) * math.cos(2.0 * math.pi * b)
 
nextReturn() =>
    float out = 0.0
    if retModel == "Gaussian"
        out := driftRet + volRet * stdNormal()
    else
        pick = math.min(int(math.random(0, sampleN, rngSeed)), sampleN - 1)
        out := logRets.get(pick) - (keepDrift ? 0.0 : meanRet)
    out
 
wipeDrawings() =>
    while gBoxes.size() > 0
        gBoxes.pop().delete()
    while gLabels.size() > 0
        gLabels.pop().delete()
    while gLines.size() > 0
        gLines.pop().delete()
    while gPolys.size() > 0
        gPolys.pop().delete()
 
fmtPct(float v)   => str.tostring(v, "0.0") + "%"
fmtPrice(float v) => str.tostring(v, format.mintick)
 
// Simulates one batch of paths (20 batches total keep each loop light)
runBatch(int batch, matrix<float> store) =>
    perBatch = int(math.ceil(runPaths / 20.0))
    first    = batch * perBatch
    last     = math.min(runPaths, (batch + 1) * perBatch) - 1
    if first <= last
        for pathId = first to last
            price   = close
            snap    = 0
            hitUp   = false
            hitDn   = false
            hitUser = false
            visible = pathId < shownN
            line_   = array.new<chart.point>()
            if visible
                line_.push(chart.point.from_index(bar_index, close))
            for step = 1 to horizon
                price *= math.exp(nextReturn())
                if price >= upTarget
                    hitUp := true
                if price <= dnTarget
                    hitDn := true
                if userLevel > 0
                    if (close <= userLevel and price >= userLevel) or (close > userLevel and price <= userLevel)
                        hitUser := true
                if visible
                    line_.push(chart.point.from_index(bar_index + step, price))
                if snap < snapCount
                    if step == snapBars.get(snap)
                        store.set(snap, pathId, price)
                        snap += 1
            if hitUp
                touchCnt.set(0, touchCnt.get(0) + 1)
            if hitDn
                touchCnt.set(1, touchCnt.get(1) + 1)
            if hitUser
                touchCnt.set(2, touchCnt.get(2) + 1)
            if visible
                gPolys.push(polyline.new(line_, line_color = color.new(price >= close ? cUp : cDown, 82)))
    true
 
panelPos = switch tablePos
    "Top Right"   => position.top_right
    "Top Left"    => position.top_left
    "Bottom Left" => position.bottom_left
    => position.bottom_right
 
txtSize = switch panelSize
    "Small" => size.small
    "Large" => size.large
    "Huge"  => size.huge
    => size.normal
 
titleSize = switch panelSize
    "Small" => size.normal
    "Large" => size.huge
    "Huge"  => size.huge
    => size.large
 
var table panel = table.new(panelPos, 2, 22, bgcolor = #11141c, border_color = #2a2e39,
     frame_color = #2a2e39, border_width = 1, frame_width = 2)
 
putRow(int r, string key, string val, color valCol) =>
    panel.cell(0, r, key, text_color = #b2b5be, text_size = txtSize, text_halign = text.align_left)
    panel.cell(1, r, val, text_color = valCol,  text_size = txtSize, text_halign = text.align_right)
 
// ═════════════════════════ TRIGGER ═════════════════════════
doRun = tickMode ? barstate.islast : (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
 
if barstate.islast and sampleN < 20
    panel.cell(0, 0, "MC Prob: waiting for data (" + str.tostring(sampleN) + "/20 bars)", text_color = color.orange, text_size = txtSize)
 
// ═════════════════════════ MAIN ═════════════════════════
if doRun and sampleN >= 20
    wipeDrawings()
    touchCnt.fill(0)
    store = matrix.new<float>(snapCount, runPaths, close)
 
    runBatch(0, store)
    runBatch(1, store)
    runBatch(2, store)
    runBatch(3, store)
    runBatch(4, store)
    runBatch(5, store)
    runBatch(6, store)
    runBatch(7, store)
    runBatch(8, store)
    runBatch(9, store)
    runBatch(10, store)
    runBatch(11, store)
    runBatch(12, store)
    runBatch(13, store)
    runBatch(14, store)
    runBatch(15, store)
    runBatch(16, store)
    runBatch(17, store)
    runBatch(18, store)
    runBatch(19, store)
 
    // ── Percentile cone ──
    qLevels = array.from(5.0, 25.0, 50.0, 75.0, 95.0)
    qMat    = matrix.new<float>(5, snapCount, close)
    for j = 0 to snapCount - 1
        snapRow = store.row(j)
        for q = 0 to 4
            qMat.set(q, j, snapRow.percentile_linear_interpolation(qLevels.get(q)))
 
    if showCone
        for q = 0 to 4
            conePts = array.new<chart.point>()
            conePts.push(chart.point.from_index(bar_index, close))
            for j = 0 to snapCount - 1
                conePts.push(chart.point.from_index(bar_index + snapBars.get(j), qMat.get(q, j)))
            isMid  = q == 2
            qColor = isMid ? cMedian : color.new(cBand, (q == 0 or q == 4) ? 45 : 0)
            gPolys.push(polyline.new(conePts, line_color = qColor, line_width = isMid ? 2 : 1,
                 line_style = isMid ? line.style_solid : line.style_dashed))
 
    // ── Clustering of final prices ──
    finals  = store.row(snapCount - 1)
    zoneLo  = finals.percentile_linear_interpolation(0.5)
    zoneHi  = finals.percentile_linear_interpolation(99.5)
    minStep = math.max(syminfo.mintick, close * 0.0001)
    if zoneHi - zoneLo < minStep * zoneCount
        center = (zoneHi + zoneLo) / 2
        zoneLo := center - minStep * zoneCount / 2
        zoneHi := center + minStep * zoneCount / 2
    zoneH   = (zoneHi - zoneLo) / zoneCount
    zoneCnt = array.new_int(zoneCount, 0)
    upEnd   = 0
    aboveUp = 0
    belowDn = 0
    aboveU  = 0
    total   = 0.0
    for fp in finals
        z = math.max(0, math.min(zoneCount - 1, int(math.floor((fp - zoneLo) / zoneH))))
        zoneCnt.set(z, zoneCnt.get(z) + 1)
        if fp > close
            upEnd += 1
        if fp >= upTarget
            aboveUp += 1
        if fp <= dnTarget
            belowDn += 1
        if userLevel > 0 and fp >= userLevel
            aboveU += 1
        total += fp
 
    peakCnt = 1
    peakZ   = 0
    for z = 0 to zoneCount - 1
        if zoneCnt.get(z) > peakCnt
            peakCnt := zoneCnt.get(z)
            peakZ   := z
 
    histX = bar_index + horizon + 3
 
    for z = 0 to zoneCount - 1
        cnt    = zoneCnt.get(z)
        zBot   = zoneLo + z * zoneH
        zTop   = zBot + zoneH
        zProb  = 100.0 * cnt / runPaths
        zColor = color.from_gradient(cnt, 0, peakCnt, cLow, cHigh)
        isPeak = z == peakZ
 
        if showHeat and cnt > 0
            gBoxes.push(box.new(bar_index, zTop, bar_index + horizon, zBot, border_color = color.new(zColor, 100),
                 bgcolor = color.new(zColor, 100 - math.round(55.0 * cnt / peakCnt))))
 
        if showHist
            barLen = math.max(1, int(math.round(float(histWidth) * cnt / peakCnt)))
            gBoxes.push(box.new(histX, zTop, histX + barLen, zBot, border_color = isPeak ? cHigh : color.new(zColor, 30),
                 border_width = isPeak ? 2 : 1, bgcolor = zColor))
            zText = fmtPct(zProb) + "  " + fmtPrice(zBot) + " – " + fmtPrice(zTop) + (isPeak ? "  ◀ most likely" : "")
            gLabels.push(label.new(histX + barLen + 1, (zTop + zBot) / 2, zText, style = label.style_label_left,
                 color = #00000000, textcolor = isPeak ? cHigh : chart.fg_color, size = size.small))
 
    // ── Reference and target lines ──
    gLines.push(line.new(bar_index, close,    bar_index + horizon, close,    color = color.gray, style = line.style_dotted))
    gLines.push(line.new(bar_index, upTarget, bar_index + horizon, upTarget, color = cUp,        style = line.style_dashed))
    gLines.push(line.new(bar_index, dnTarget, bar_index + horizon, dnTarget, color = cDown,      style = line.style_dashed))
    if userLevel > 0
        gLines.push(line.new(bar_index, userLevel, bar_index + horizon, userLevel, color = color.yellow, style = line.style_dashed))
 
    gLabels.push(label.new(bar_index, high, "MC: " + str.tostring(runPaths) + " paths", style = label.style_label_down,
         color = #11141c, textcolor = color.white, size = size.small))
 
    // ── Panel ──
    q025 = finals.percentile_linear_interpolation(2.5)
    q10  = finals.percentile_linear_interpolation(10)
    q90  = finals.percentile_linear_interpolation(90)
    q975 = finals.percentile_linear_interpolation(97.5)
    pBot = zoneLo + peakZ * zoneH
 
    panel.cell(0, 0, "Monte Carlo",          text_color = color.white, text_size = titleSize, text_halign = text.align_left,  bgcolor = #1c2030)
    panel.cell(1, 0, "Probability Forecast", text_color = cHigh,       text_size = titleSize, text_halign = text.align_right, bgcolor = #1c2030)
    putRow(1,  "Paths × Horizon",      str.tostring(runPaths) + " × " + str.tostring(horizon) + (isReduced ? " (reduced)" : ""), isReduced ? color.orange : color.white)
    putRow(2,  "Model",                retModel + (keepDrift ? " + drift" : " (no drift)"), color.white)
    putRow(3,  "Start price",          fmtPrice(close), color.white)
    putRow(4,  "Median outcome",       fmtPrice(qMat.get(2, snapCount - 1)), color.white)
    putRow(5,  "Average outcome",      fmtPrice(total / runPaths), color.white)
    putRow(6,  "P(end higher)",        fmtPct(100.0 * upEnd / runPaths), cUp)
    putRow(7,  "P(end lower)",         fmtPct(100.0 * (runPaths - upEnd) / runPaths), cDown)
    putRow(8,  "50% range",            fmtPrice(qMat.get(1, snapCount - 1)) + " – " + fmtPrice(qMat.get(3, snapCount - 1)), color.white)
    putRow(9,  "80% range",            fmtPrice(q10) + " – " + fmtPrice(q90), color.white)
    putRow(10, "95% range",            fmtPrice(q025) + " – " + fmtPrice(q975), color.white)
    putRow(11, "Most likely zone",     fmtPrice(pBot) + " – " + fmtPrice(pBot + zoneH) + " (" + fmtPct(100.0 * peakCnt / runPaths) + ")", cHigh)
    putRow(12, "▲ Target",             fmtPrice(upTarget) + " (+" + str.tostring(upTgtPct) + "%)", cUp)
    putRow(13, "P(end ≥ ▲)",           fmtPct(100.0 * aboveUp / runPaths), cUp)
    putRow(14, "P(touch ▲)",           fmtPct(100.0 * touchCnt.get(0) / runPaths), cUp)
    putRow(15, "▼ Target",             fmtPrice(dnTarget) + " (−" + str.tostring(dnTgtPct) + "%)", cDown)
    putRow(16, "P(end ≤ ▼)",           fmtPct(100.0 * belowDn / runPaths), cDown)
    putRow(17, "P(touch ▼)",           fmtPct(100.0 * touchCnt.get(1) / runPaths), cDown)
    if userLevel > 0
        putRow(18, "Custom level",     fmtPrice(userLevel), color.yellow)
        putRow(19, "P(end ≥ level)",   fmtPct(100.0 * aboveU / runPaths), color.yellow)
        putRow(20, "P(touch level)",   fmtPct(100.0 * touchCnt.get(2) / runPaths), color.yellow)

← 返回列表