Implied and Historical Volatility v4
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Aziz_PactionTrader

//@version=4
study("Implied and Historical Volatility v4", overlay=false)

// Define pi
pi = 3.14159265359

// Input variables
strike_price = input(title="Strike Price", type=input.float, defval=100)
time_to_expiry = input(title="Time to Expiry (days)", type=input.integer, defval=30)
historical_volatility_length = input(title="Historical Volatility Length (days)", type=input.integer, defval=30)

// Get current market price of the stock
stock_price = security(syminfo.tickerid, timeframe.period, close)

// Get price and yield of Indian 10-year government bond
bond_price = security("IN10", timeframe.period, close)
bond_face_value = 100
bond_coupon_rate = 10.18
bond_years_to_maturity = 10
bond_interest_rate = (bond_coupon_rate * bond_face_value / bond_price) + ((bond_face_value - bond_price) / bond_years_to_maturity / bond_price) * 100

// Standard normal distribution function
std_norm_dist(x) =>
    exp(-0.5 * pow(x, 2)) / sqrt(2 * pi)

// Implied volatility calculation using bisection method and Black 76 model
option_price = input(title="Option Price", type=input.float, defval=5)
tolerance = 0.0001
max_iterations = 100
a = 0.01
b = 5.00
c = (a + b) / 2
//i = 0
for i = 0 to max_iterations
    d1 = (log(stock_price/strike_price) + (bond_interest_rate/100 - pow(c, 2)/2)*time_to_expiry/365) / (c * sqrt(time_to_expiry/365))
    d2 = d1 - c * sqrt(time_to_expiry/365)
    n_d1 = std_norm_dist(d1)
    n_d2 = std_norm_dist(d2)
    call_price = stock_price * n_d1 - strike_price * exp(-bond_interest_rate/100 * time_to_expiry/365) * n_d2
    put_price = strike_price * exp(-bond_interest_rate/100 * time_to_expiry/365) * (1 - n_d2) - stock_price * (1 - n_d1)
    if (abs(put_price - option_price) < tolerance)
        break
    if (put_price < option_price)
        a := c
    else
        b := c
    c := (a + b) / 2

implied_volatility = c

// Plot change in implied volatility
implied_change = change(implied_volatility)
plot(implied_change, title="Change in Implied Volatility", color=color.orange, linewidth=2, style=plot.style_line)
plotchar(implied_volatility, title="implied_volatility", char="", color=color.orange, location=location.top)

// Calculate daily returns of the stock
daily_returns = log(close / close[1])

// Calculate historical volatility
historical_volatility = stdev(daily_returns, historical_volatility_length) * sqrt(252)

// Plot change in historical volatility
historical_change = change(historical_volatility)
plot(historical_change, title="Change in Historical Volatility", color=color.blue, linewidth=2, style=plot.style_line)
plotchar(historical_volatility, title="istorical_volatilitylity", char="", color=color.blue, location=location.top)


