For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
ThinkorSwim Imp_Vol Function
-
I am having issues on matching the output on Ameritrade's ThinkorSwim Imp_Vol function. They use a reverse calculate based on the marks of the options, based off the Bjerksund-Stensland model.
This is what I have right now and I would appreciate any help on it.
def implied_volatility_put(underlying_price, exercise_price, time_in_years, risk_free_rate, option_price):
high = 5
low = 0while (high - low) > 0.0001: if bjerksund_stensland_put(underlying_price, exercise_price, time_in_years, risk_free_rate, (high + low) / 2) > option_price: high = (high + low) / 2 else: low = (high + low) / 2 return (high + low) / 2
def bjerksund_stensland_put(underlying_price, exercise_price, time_in_years, risk_free_rate, volatility):
div = 1E-08
z = -1
rr = div
dd = rr
dd2 = 2 * dd - rr
asset_new = underlying_price
underlying_price = exercise_price
exercise_price = asset_newdt = volatility * sqrt(time_in_years) drift = risk_free_rate - div v2 = volatility**2 b1 = sqrt((z * drift / v2 - 0.5)**2 + 2 * rr / v2) beta = (1 / 2 - z * drift / v2) + b1 binfinity = beta / (beta - 1) * exercise_price bb = max(exercise_price, rr / dd2 * exercise_price) ht = -(z * drift * time_in_years + 2 * dt) * bb / (binfinity - bb) i = bb + (binfinity - bb) * (1 - exp(ht)) if underlying_price < i and beta < 100: # To avoid overflow alpha = (i - exercise_price) * i**(-beta) return alpha * underlying_price**beta - alpha * phi(underlying_price, time_in_years, beta, i, i, rr, z * drift, volatility) + phi(underlying_price, time_in_years, 1, i, i, rr, z * drift, volatility) - phi(underlying_price, time_in_years, 1, exercise_price, i, rr, z * drift, volatility) - exercise_price * phi(underlying_price, time_in_years, 0, i, i, rr, z * drift, volatility) + exercise_price * phi(underlying_price, time_in_years, 0, exercise_price, i, rr, z * drift, volatility) return underlying_price - exercise_price
Parameters
underlying_price: Price of underlying asset
exercise_price: Exercise price of the option
time_in_years: Time to expiration in years (ie. 33 days to expiration is 33/365)
risk_free_rate: Risk free rate (ie. 2% is 0.02)
volatility: Volatility percentage (ie. 30% volatility is 0.30)
-
Here's the code I previously posted to do exactly that: