Indicator · Pine Script v5 · On the chart

Advanced Option Price Estimator

by jawauntb

Advanced Option Price Estimator applies the Black-Scholes model to estimate call and put option prices directly on the main price chart.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code71
Settings2inputs
LicenceGPL-3.0
Last update2 years ago22 May 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

71 lines of Pine Script v5 from option-price-estimator.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

option-price-estimator.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jawauntb

//@version=5
indicator("Advanced Option Price Estimator", overlay=true)

// Inputs
riskFreeRate = request.security("RFR:TICKER", "D", close) // Assuming a ticker for risk-free rate
daysToExpiration = input.int(30, "Days to Expiration", step=1)
volatilityPeriod = input.int(20, "Volatility Period", step=1)

// Get the current price of the ticker
tickerPrice = close

// Function to fetch current market price of an option (placeholder)
getMarketOptionPrice(callPut, strike, expiration) => na // Implement actual fetching logic

// Function to calculate the PDF of the standard normal distribution
norm_pdf(x) =>
    (1 / sqrt(2 * pi)) * exp(-x * x / 2)

// Vega calculation using Black-Scholes components
calculateVega(s, k, t, r, v) =>
    d1 = (log(s / k) + (r + v * v / 2) * t) / (v * sqrt(t))
    s * sqrt(t) * norm_pdf(d1)

// Example usage in the Newton-Raphson method for implied volatility calculation
calculateImpliedVolatility(s, k, t, r, marketPrice, isCall) =>
    sigma = 0.20 // Initial guess for implied volatility
    for i = 0 to 100
        price = bsm(s, k, t, r, sigma, isCall)
        vega = calculateVega(s, k, t, r, sigma) // Vega calculation
        diff = marketPrice - price
        if abs(diff) < 0.0001
            break
        sigma := sigma + diff / vega
    sigma


// Function to calculate the BSM option price
bsm(s, k, t, r, v, isCall) =>
    d1 = (log(s / k) + (r + v * v / 2) * t) / (v * sqrt(t))
    d2 = d1 - v * sqrt(t)
    callPrice = s * norm_cdf(d1) - k * exp(-r * t) * norm_cdf(d2)
    putPrice = k * exp(-r * t) * norm_cdf(-d2) - s * norm_cdf(-d1)
    isCall ? callPrice : putPrice

// Calculate the time to expiration in years
timeToExpiration = daysToExpiration / 365

// Calculate the strike prices at 1.5% increments
increment = tickerPrice * 0.015
strikePrice = tickerPrice - (tickerPrice % increment)
maxStrikes = 20

// Graphical representation using plot shapes instead of labels
for i = 0 to maxStrikes
    callStrike = strikePrice + i * increment
    putStrike = strikePrice - i * increment

    marketPriceCall = getMarketOptionPrice("call", callStrike, timeToExpiration)
    marketPricePut = getMarketOptionPrice("put", putStrike, timeToExpiration)

    impliedVolatilityCall = calculateImpliedVolatility(tickerPrice, callStrike, timeToExpiration, riskFreeRate, marketPriceCall, true)
    impliedVolatilityPut = calculateImpliedVolatility(tickerPrice, putStrike, timeToExpiration, riskFreeRate, marketPricePut, false)

    callPrice = bsm(tickerPrice, callStrike, timeToExpiration, riskFreeRate, impliedVolatilityCall, true)
    putPrice = bsm(tickerPrice, putStrike, timeToExpiration, riskFreeRate, impliedVolatilityPut, false)

    plotshape(series=callPrice, location=location.absolute, color=color.green, style=shape.triangledown, title="Call Price")
    plotshape(series=putPrice, location=location.absolute, color=color.red, style=shape.triangleup, title="Put Price")

Overview

Advanced Option Price Estimator uses standard normal distribution functions and Newton-Raphson iterations to calculate implied volatility across calculated strike prices. Dynamic strike levels are generated at percentage increments relative to the underlying asset's current price. Users can adjust the days to expiration and volatility evaluation period via inputs. Note that real-time market option price fetching uses placeholder logic in this script.

Details

Published by

jawauntb on GitHub

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Volatility & bands

Markets

Stocks, Indices

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Days to Expirationint30daysToExpiration
Volatility Periodint20volatilityPeriod
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Chandelier Exit

by everget
948 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 10 days ago · GPL-3.0 GitHub repository of Chandelier Exit

ICT Liquidity Void Fill

by ArunKBhaskar
575 stars

This overlay indicator marks ICT liquidity void fills on the price chart and can show long and short signals. It places a Fibonacci level inside a displacement candle, defaulting to the midpoint, and draws lines in a chosen style. Optional filters limit the fi

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Liquidity Void Fill

This indicator plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of NVDA Trend Ribbon

Algo AVT

by ricardosantos79
261 stars

This indicator calculates an outlier-filtered moving average based on statistical filtering concepts. It stores close prices in a rolling array over a user-defined length, calculates the mean and standard deviation, and excludes values falling within a specifi

Indicator v4 Moving averagesVolatility & bands
Updated 4 years ago · None stated GitHub repository of Algo AVT

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers