Black-Scholes Options Panel

Ama7Choudhary · study · 378 行 · 点赞 22 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator("Black-Scholes Options Panel", "BS Panel", overlay = true, max_lines_count = 50, max_labels_count = 50)
 
// ───────── Option data ─────────
optPick   = input.symbol("", "Option contract (search)", group = "Option data", tooltip = "Search and pick ANY one option contract of the asset and expiry you want. The script reads the asset and expiry from it.")
stepIn    = input.float(0.0, "Strike step (0 = auto)", minval = 0.0, group = "Option data", tooltip = "Leave at 0 to detect the distance between strikes automatically, or type it (e.g. 50).")
ratePct   = input.float(6.5, "Interest rate (% a year)", minval = 0.0, step = 0.25, group = "Option data")
expHour   = input.int(15, "Expiry time: hour", minval = 0, maxval = 23, group = "Option data", tooltip = "Time of day the options expire, in the exchange's time zone. 15:30 for NSE.")
expMin    = input.int(30, "Expiry time: minute", minval = 0, maxval = 59, group = "Option data")
priceMode = input.string("Options-implied (recommended)", "Asset price used in the model", options = ["Options-implied (recommended)", "Chart price"], group = "Option data", tooltip = "Options-implied: the price the options themselves are assuming (from call price minus put price). Works on both the index and its futures chart.\nChart price: this chart's last price.")
strikesN  = input.int(7, "Strikes in the table", minval = 1, maxval = 11, step = 2, group = "Option data")
 
// ───────── What to show ─────────
showSummary = input.bool(true, "Summary (expected move, ranges, implied price)", group = "Show")
showCone    = input.bool(true, "Expected range cone on the chart", group = "Show")
showTable   = input.bool(true, "Greeks table", group = "Show")
showHelp    = input.bool(true, "Plain-language explanations under the table", group = "Show")
 
showPx    = input.bool(true,  "Option price", group = "Table columns")
showIV    = input.bool(true,  "IV (implied volatility)", group = "Table columns")
showDelta = input.bool(true,  "Delta", group = "Table columns")
showGamma = input.bool(true,  "Gamma", group = "Table columns")
showTheta = input.bool(true,  "Theta", group = "Table columns")
showVega  = input.bool(true,  "Vega", group = "Table columns")
showRho   = input.bool(false, "Rho", group = "Table columns")
 
tblPos  = input.string("top_right", "Panel position", options = ["top_left", "top_center", "top_right", "middle_left", "middle_right", "bottom_left", "bottom_center", "bottom_right"], group = "Look")
txtSize = input.string("small", "Text size", options = ["tiny", "small", "normal", "large"], group = "Look")
callCol = input.color(#f23645, "Call color", group = "Look")
putCol  = input.color(#089981, "Put color", group = "Look")
coneCol = input.color(#5b9cf6, "Range cone color", group = "Look")
 
// ───────── Read asset, expiry and strike from the picked contract ─────────
// TradingView option format: EXCHANGE:ROOT + YYMMDD + C/P + STRIKE, e.g. NSE:NIFTY261117C25000
string tail    = str.match(optPick, "[0-9]{6}[CP][0-9]+([.][0-9]+)?$")
bool   picked  = str.length(tail) > 7
string rootSym = picked ? str.substring(optPick, 0, str.length(optPick) - str.length(tail)) : ""
string expiry  = picked ? str.substring(tail, 0, 6) : ""
float  k0      = picked ? str.tonumber(str.substring(tail, 7)) : na
 
fmtStrike(float k) =>
    float r = math.round(k)
    math.abs(k - r) < 0.0000001 ? str.tostring(int(r)) : str.tostring(k)
 
optSym(float k, string side) =>
    rootSym + expiry + side + fmtStrike(k)
 
fmt(float x, string f) =>
    na(x) ? "–" : str.tostring(x, f)
 
// ───────── Black-Scholes maths ─────────
ncdf(float x) =>
    float a = math.abs(x)
    float t = 1.0 / (1.0 + 0.2316419 * a)
    float d = 0.3989422804 * math.exp(-a * a / 2.0)
    float p = d * t * (0.31938153 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))))
    x >= 0 ? 1.0 - p : p
 
npdf(float x) =>
    0.3989422804 * math.exp(-x * x / 2.0)
 
bsPrice(float S, float K, float T, float r, float v, bool isCall) =>
    float sq = math.sqrt(T)
    float d1 = (math.log(S / K) + (r + v * v / 2.0) * T) / (v * sq)
    float d2 = d1 - v * sq
    isCall ? S * ncdf(d1) - K * math.exp(-r * T) * ncdf(d2) : K * math.exp(-r * T) * ncdf(-d2) - S * ncdf(-d1)
 
// Implied volatility: the volatility that makes the formula's price equal the real option price
impliedVol(float price, float S, float K, float T, float r, bool isCall) =>
    float result = na
    if not na(price) and not na(S) and price > 0 and T > 0
        float disc      = math.exp(-r * T)
        float intrinsic = isCall ? math.max(S - K * disc, 0.0) : math.max(K * disc - S, 0.0)
        if price > intrinsic and price < bsPrice(S, K, T, r, 5.0, isCall)
            float lo = 0.0001
            float hi = 5.0
            for i = 0 to 39
                float mid = (lo + hi) / 2.0
                if bsPrice(S, K, T, r, mid, isCall) > price
                    hi := mid
                else
                    lo := mid
            result := (lo + hi) / 2.0
    result
 
greeks(float S, float K, float T, float r, float v, bool isCall) =>
    float sq    = math.sqrt(T)
    float d1    = (math.log(S / K) + (r + v * v / 2.0) * T) / (v * sq)
    float d2    = d1 - v * sq
    float disc  = math.exp(-r * T)
    float delta = isCall ? ncdf(d1) : ncdf(d1) - 1.0
    float gamma = npdf(d1) / (S * v * sq)
    float vega  = S * npdf(d1) * sq / 100.0
    float theta = isCall ? (-S * npdf(d1) * v / (2.0 * sq) - r * K * disc * ncdf(d2)) / 365.0 : (-S * npdf(d1) * v / (2.0 * sq) + r * K * disc * ncdf(-d2)) / 365.0
    float rho   = isCall ? K * T * disc * ncdf(d2) / 100.0 : -K * T * disc * ncdf(-d2) / 100.0
    [delta, gamma, theta, vega, rho]
 
// ───────── Panel helpers ─────────
var table tbl = table.new(tblPos, 13, 20, bgcolor = color.new(#0f1420, 5), border_color = color.new(color.gray, 75), border_width = 1, frame_color = color.new(color.gray, 50), frame_width = 1)
var table msg = table.new(position.bottom_right, 1, 1, bgcolor = color.new(color.black, 20), frame_color = color.new(color.gray, 50), frame_width = 1)
 
cell(int c, int r, string txt, color tc, color bg, string tip = "") =>
    table.cell(tbl, c, r, txt, text_color = tc, bgcolor = bg, text_size = txtSize, tooltip = tip)
 
wideRow(int r, int nCols, string txt, color tc, color bg) =>
    table.cell(tbl, 0, r, txt, text_color = tc, bgcolor = bg, text_size = txtSize, text_halign = text.align_left)
    if nCols > 1
        table.merge_cells(tbl, 0, r, nCols - 1, r)
 
colName(string key) =>
    switch key
        "cPx"    => "Price"
        "pPx"    => "Price"
        "cIV"    => "IV"
        "pIV"    => "IV"
        "cDelta" => "Delta"
        "pDelta" => "Delta"
        "cTheta" => "Theta"
        "pTheta" => "Theta"
        "cRho"   => "Rho"
        "pRho"   => "Rho"
        "gamma"  => "Gamma"
        "vega"   => "Vega"
        => "STRIKE"
 
colTip(string key) =>
    switch key
        "cPx"    => "Last traded price of the call option."
        "pPx"    => "Last traded price of the put option."
        "cIV"    => "Implied volatility: how big a yearly move the market is pricing in. Higher = more expensive options."
        "pIV"    => "Implied volatility: how big a yearly move the market is pricing in. Higher = more expensive options."
        "cDelta" => "How much the call price changes when the asset moves 1 point."
        "pDelta" => "How much the put price changes when the asset moves 1 point (negative: puts gain when the asset falls)."
        "cTheta" => "How much value the call loses each day just from time passing."
        "pTheta" => "How much value the put loses each day just from time passing."
        "cRho"   => "How much the call price changes when interest rates move 1%."
        "pRho"   => "How much the put price changes when interest rates move 1%."
        "gamma"  => "How fast delta changes when the asset moves 1 point. Same for calls and puts."
        "vega"   => "How much the option price changes when implied volatility moves 1%. Same for calls and puts."
        => "Strike price. The highlighted row is the strike closest to the current price."
 
// ───────── Main ─────────
var float stepUse = na
var float center  = na
var array<line>     dl  = array.new<line>()
var array<label>    dlb = array.new<label>()
var array<linefill> dlf = array.new<linefill>()
 
if barstate.islast
    while array.size(dlf) > 0
        linefill.delete(array.pop(dlf))
    while array.size(dl) > 0
        line.delete(array.pop(dl))
    while array.size(dlb) > 0
        label.delete(array.pop(dlb))
    table.cell(msg, 0, 0, "")
 
    if not picked
        table.cell(msg, 0, 0, "Black-Scholes Panel: open the settings and pick an option contract\nin the 'Option contract (search)' box.", text_color = color.orange, text_size = size.small)
    else
        // Strike step: typed, or detected by checking which neighbouring strike exists
        if na(stepUse)
            if stepIn > 0
                stepUse := stepIn
            else
                array<float> cands = array.from(1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 500.0)
                for i = 0 to array.size(cands) - 1
                    if na(stepUse)
                        float tPx = request.security(optSym(k0 + array.get(cands, i), "C"), "D", close, ignore_invalid_symbol = true)
                        if not na(tPx)
                            stepUse := array.get(cands, i)
 
        // Time to expiry in years
        int   yy    = int(str.tonumber(str.substring(expiry, 0, 2)))
        int   mm    = int(str.tonumber(str.substring(expiry, 2, 4)))
        int   dd    = int(str.tonumber(str.substring(expiry, 4, 6)))
        int   expTs = timestamp(syminfo.timezone, 2000 + yy, mm, dd, expHour, expMin)
        float T     = (expTs - timenow) / (365.0 * 86400000.0)
        float r     = ratePct / 100.0
 
        if na(stepUse)
            table.cell(msg, 0, 0, "Black-Scholes Panel: could not detect the strike step for " + rootSym + ".\nType it in the 'Strike step' box (e.g. 50).", text_color = color.orange, text_size = size.small)
        else if T <= 0
            table.cell(msg, 0, 0, "Black-Scholes Panel: this contract has expired.\nPick a contract from a later expiry.", text_color = color.orange, text_size = size.small)
        else
            if na(center)
                center := k0 + math.round((close - k0) / stepUse) * stepUse
 
            int   n    = strikesN
            int   ai   = int(math.floor(n / 2.0))
            float lowK = center - ai * stepUse
            array<float> K  = array.new<float>()
            array<float> CP = array.new<float>()
            array<float> PP = array.new<float>()
            int found = 0
            for i = 0 to n - 1
                float k   = lowK + i * stepUse
                float cPx = request.security(optSym(k, "C"), "D", close, ignore_invalid_symbol = true)
                float pPx = request.security(optSym(k, "P"), "D", close, ignore_invalid_symbol = true)
                array.push(K, k)
                array.push(CP, cPx)
                array.push(PP, pPx)
                if not na(cPx) or not na(pPx)
                    found += 1
 
            if found == 0
                table.cell(msg, 0, 0, "Black-Scholes Panel: no option prices found.\nTried: " + optSym(center, "C") + "\nThis chart should be the option's underlying (index or future).", text_color = color.orange, text_size = size.small)
            else
                // Asset price for the model: what the options imply (put-call parity), or the chart price
                float atmK     = array.get(K, ai)
                float aC       = array.get(CP, ai)
                float aP       = array.get(PP, ai)
                float implSpot = aC - aP + atmK * math.exp(-r * T)
                float implFwd  = atmK + (aC - aP) * math.exp(r * T)
                bool  useImpl  = priceMode != "Chart price" and not na(implSpot)
                float S        = useImpl ? implSpot : close
                float fwd      = S * math.exp(r * T)
 
                // ATM implied volatility and the expected ranges
                float ivC   = impliedVol(aC, S, atmK, T, r, true)
                float ivP   = impliedVol(aP, S, atmK, T, r, false)
                float atmIV = na(ivC) ? ivP : na(ivP) ? ivC : (ivC + ivP) / 2.0
                float sd    = atmIV * math.sqrt(T)
                float up1   = fwd * math.exp(sd)
                float dn1   = fwd * math.exp(-sd)
                float up2   = fwd * math.exp(2.0 * sd)
                float dn2   = fwd * math.exp(-2.0 * sd)
 
                // Columns of the Greeks table
                array<string> cols = array.new<string>()
                if showTable
                    if showRho
                        array.push(cols, "cRho")
                    if showTheta
                        array.push(cols, "cTheta")
                    if showDelta
                        array.push(cols, "cDelta")
                    if showIV
                        array.push(cols, "cIV")
                    if showPx
                        array.push(cols, "cPx")
                    array.push(cols, "K")
                    if showPx
                        array.push(cols, "pPx")
                    if showIV
                        array.push(cols, "pIV")
                    if showDelta
                        array.push(cols, "pDelta")
                    if showTheta
                        array.push(cols, "pTheta")
                    if showRho
                        array.push(cols, "pRho")
                    if showGamma
                        array.push(cols, "gamma")
                    if showVega
                        array.push(cols, "vega")
                int nCols = showTable ? array.size(cols) : 1
                int kCol  = showTable ? array.indexof(cols, "K") : 0
 
                color txtC  = color.white
                color dimC  = color.new(color.white, 30)
                color baseB = color.new(#0f1420, 5)
                color headB = color.new(#1c2333, 0)
                int row = 0
 
                // ── Summary ──
                if showSummary
                    string left = T * 365.0 >= 1.0 ? str.tostring(T * 365.0, "#.#") + " days left" : str.tostring(T * 365.0 * 24.0, "#.#") + " hours left"
                    wideRow(row, nCols, rootSym + "   ·   expiry " + str.format_time(expTs, "dd MMM yyyy", syminfo.timezone) + "   ·   " + left, txtC, headB)
                    row += 1
                    if na(atmIV)
                        wideRow(row, nCols, "Implied volatility not available (the at-the-money options have no usable price).", color.orange, baseB)
                        row += 1
                    else
                        wideRow(row, nCols, "Implied volatility: " + str.tostring(atmIV * 100.0, "#.#") + "% a year", txtC, baseB)
                        row += 1
                        wideRow(row, nCols, "Market is pricing a move of about ±" + str.tostring(S * sd, format.mintick) + "  (±" + str.tostring(sd * 100.0, "#.##") + "%) by expiry", txtC, baseB)
                        row += 1
                        wideRow(row, nCols, "Likely range (68%): " + str.tostring(dn1, format.mintick) + " to " + str.tostring(up1, format.mintick) + "     Wide range (95%): " + str.tostring(dn2, format.mintick) + " to " + str.tostring(up2, format.mintick), txtC, baseB)
                        row += 1
                    if not na(implFwd)
                        wideRow(row, nCols, "Options-implied price: " + str.tostring(implFwd, format.mintick) + "     Chart price: " + str.tostring(close, format.mintick) + "     Difference: " + str.tostring(implFwd - close, format.mintick), dimC, baseB)
                        row += 1
 
                // ── Greeks table ──
                if showTable
                    // Group header: CALLS | (strike) | PUTS | BOTH
                    if kCol > 0
                        cell(0, row, "CALLS", callCol, color.new(callCol, 80))
                        if kCol > 1
                            table.merge_cells(tbl, 0, row, kCol - 1, row)
                        cell(kCol + 1, row, "PUTS", putCol, color.new(putCol, 80))
                        if kCol > 1
                            table.merge_cells(tbl, kCol + 1, row, 2 * kCol, row)
                    cell(kCol, row, "", txtC, headB)
                    if nCols - 1 >= 2 * kCol + 1
                        cell(2 * kCol + 1, row, "BOTH", dimC, headB)
                        if nCols - 1 > 2 * kCol + 1
                            table.merge_cells(tbl, 2 * kCol + 1, row, nCols - 1, row)
                    row += 1
 
                    // Column names (hover a name for its meaning)
                    for [c, key] in cols
                        cell(c, row, colName(key), txtC, headB, colTip(key))
                    row += 1
 
                    // One row per strike
                    for i = 0 to n - 1
                        float k   = array.get(K, i)
                        float cPx = array.get(CP, i)
                        float pPx = array.get(PP, i)
                        float cIv = impliedVol(cPx, S, k, T, r, true)
                        float pIv = impliedVol(pPx, S, k, T, r, false)
                        [cD, cG, cT, cV, cR] = greeks(S, k, T, r, cIv, true)
                        [pD, pG, pT, pV, pR] = greeks(S, k, T, r, pIv, false)
                        float gam = na(cG) ? pG : cG
                        float veg = na(cV) ? pV : cV
                        bool isAtm = i == ai
                        for [c, key] in cols
                            string txt = switch key
                                "cPx"    => fmt(cPx, "#.##")
                                "pPx"    => fmt(pPx, "#.##")
                                "cIV"    => na(cIv) ? "–" : str.tostring(cIv * 100.0, "#.#") + "%"
                                "pIV"    => na(pIv) ? "–" : str.tostring(pIv * 100.0, "#.#") + "%"
                                "cDelta" => fmt(cD, "0.00")
                                "pDelta" => fmt(pD, "0.00")
                                "cTheta" => fmt(cT, "0.00")
                                "pTheta" => fmt(pT, "0.00")
                                "cRho"   => fmt(cR, "0.00")
                                "pRho"   => fmt(pR, "0.00")
                                "gamma"  => fmt(gam, "0.0000")
                                "vega"   => fmt(veg, "0.00")
                                => fmtStrike(k)
                            bool callSide = c < kCol
                            bool putSide  = c > kCol and c <= 2 * kCol
                            color bg = isAtm ? color.new(#f9a825, 78) : callSide and k < S ? color.new(callCol, 88) : putSide and k > S ? color.new(putCol, 88) : baseB
                            color tc = c == kCol ? txtC : callSide ? color.new(callCol, 0) : putSide ? color.new(putCol, 0) : dimC
                            cell(c, row, txt, isAtm ? txtC : tc, c == kCol and not isAtm ? headB : bg)
                        row += 1
 
                    // Plain-language explanations
                    if showHelp
                        string help = "Yellow row = strike closest to the current price.   Tinted cells = options already in the money."
                        if showIV
                            help += "\nIV: the yearly move the market is pricing in. Higher IV = more expensive options."
                        if showDelta
                            help += "\nDelta: option price change when the asset moves 1 point."
                        if showTheta
                            help += "\nTheta: value the option loses per day from time passing."
                        if showGamma
                            help += "\nGamma: how fast delta changes per 1 point move."
                        if showVega
                            help += "\nVega: option price change when IV moves 1%."
                        if showRho
                            help += "\nRho: option price change when interest rates move 1%."
                        wideRow(row, nCols, help, dimC, baseB)
                        row += 1
 
                // ── Expected range cone on the chart ──
                if showCone and not na(atmIV) and expTs > time
                    line lMid = line.new(time, S, expTs, fwd, xloc = xloc.bar_time, color = color.new(coneCol, 30), style = line.style_dotted)
                    line lU1  = line.new(time, S, expTs, up1, xloc = xloc.bar_time, color = coneCol, width = 2)
                    line lD1  = line.new(time, S, expTs, dn1, xloc = xloc.bar_time, color = coneCol, width = 2)
                    line lU2  = line.new(time, S, expTs, up2, xloc = xloc.bar_time, color = color.new(coneCol, 40), style = line.style_dashed)
                    line lD2  = line.new(time, S, expTs, dn2, xloc = xloc.bar_time, color = color.new(coneCol, 40), style = line.style_dashed)
                    array.push(dl, lMid)
                    array.push(dl, lU1)
                    array.push(dl, lD1)
                    array.push(dl, lU2)
                    array.push(dl, lD2)
                    array.push(dlf, linefill.new(lU1, lD1, color.new(coneCol, 85)))
                    array.push(dlf, linefill.new(lU2, lU1, color.new(coneCol, 93)))
                    array.push(dlf, linefill.new(lD1, lD2, color.new(coneCol, 93)))
                    array.push(dlb, label.new(expTs, up2, "Wide range high (95%)  " + str.tostring(up2, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color(na), textcolor = color.new(coneCol, 20), size = size.small))
                    array.push(dlb, label.new(expTs, up1, "Likely high (68%)  " + str.tostring(up1, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color(na), textcolor = coneCol, size = size.small))
                    array.push(dlb, label.new(expTs, fwd, "Options-implied price  " + str.tostring(fwd, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color(na), textcolor = color.new(coneCol, 30), size = size.small))
                    array.push(dlb, label.new(expTs, dn1, "Likely low (68%)  " + str.tostring(dn1, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color(na), textcolor = coneCol, size = size.small))
                    array.push(dlb, label.new(expTs, dn2, "Wide range low (95%)  " + str.tostring(dn2, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color(na), textcolor = color.new(coneCol, 20), size = size.small))

← 返回列表