[英]Fast Implied Volatility Calculation in Python
我正在尋找一個庫,我可以用它來更快地計算 python 中的隱含波動率。 我有大約 1+ 百萬行的期權數據,我想為其計算隱含波動率。 我可以計算IV的最快方法是什么。 我嘗試過使用 py_vollib,但它不支持矢量化。 大約需要5分鍾。 計算。 是否有任何其他庫可以幫助加快計算速度。 人們在每秒有數百萬行進入的實時波動率計算中使用什么?
您必須意識到隱含波動率計算的計算成本很高,如果您想要實時數字,python 可能不是最佳解決方案。
以下是您需要的功能示例:
import numpy as np
from scipy.stats import norm
N = norm.cdf
def bs_call(S, K, T, r, vol):
d1 = (np.log(S/K) + (r + 0.5*vol**2)*T) / (vol*np.sqrt(T))
d2 = d1 - vol * np.sqrt(T)
return S * norm.cdf(d1) - np.exp(-r * T) * K * norm.cdf(d2)
def bs_vega(S, K, T, r, sigma):
d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
return S * norm.pdf(d1) * np.sqrt(T)
def find_vol(target_value, S, K, T, r, *args):
MAX_ITERATIONS = 200
PRECISION = 1.0e-5
sigma = 0.5
for i in range(0, MAX_ITERATIONS):
price = bs_call(S, K, T, r, sigma)
vega = bs_vega(S, K, T, r, sigma)
diff = target_value - price # our root
if (abs(diff) < PRECISION):
return sigma
sigma = sigma + diff/vega # f(x) / f'(x)
return sigma # value wasn't found, return best guess so far
計算單個值足夠快
S = 100
K = 100
T = 11
r = 0.01
vol = 0.25
V_market = bs_call(S, K, T, r, vol)
implied_vol = find_vol(V_market, S, K, T, r)
print ('Implied vol: %.2f%%' % (implied_vol * 100))
print ('Market price = %.2f' % V_market)
print ('Model price = %.2f' % bs_call(S, K, T, r, implied_vol))
隱含成交量:25.00%
市場價格 = 35.94
Model 價格 = 35.94
但是如果你嘗試計算很多,你會意識到這需要一些時間......
%%time
size = 10000
S = np.random.randint(100, 200, size)
K = S * 1.25
T = np.ones(size)
R = np.random.randint(0, 3, size) / 100
vols = np.random.randint(15, 50, size) / 100
prices = bs_call(S, K, T, R, vols)
params = np.vstack((prices, S, K, T, R, vols))
vols = list(map(find_vol, *params))
掛壁時間:10.5 秒
如果將所有對norm.cdf()
-方法的調用更改為ndtr()
,您將獲得 2.4 倍的性能提升。
如果您將norm.pdf()
-方法更改為norm._pdf()
,您將獲得另一個(巨大的)增長。
實施這兩項更改后,上面的示例在我的機器上從 17.7 秒下降到 0.99 秒。
您將丟失錯誤檢查等,但在這種情況下,您可能不需要所有這些。
見: https://github.com/scipy/scipy/issues/1914
ndtr()
在scipy.special
最近, py_vollib
提供了py_vollib的矢量化版本,它建立在py_vollib
,可以更快地為數千種期權合約定價和計算希臘字母。
!pip install py_vollib
這將返回希臘人以及 black_scholes price 和 iv
import py_vollib
from py_vollib.black_scholes import black_scholes as bs
from py_vollib.black_scholes.implied_volatility import implied_volatility as iv
from py_vollib.black_scholes.greeks.analytical import delta
from py_vollib.black_scholes.greeks.analytical import gamma
from py_vollib.black_scholes.greeks.analytical import rho
from py_vollib.black_scholes.greeks.analytical import theta
from py_vollib.black_scholes.greeks.analytical import vega
import numpy as np
#py_vollib.black_scholes.implied_volatility(price, S, K, t, r, flag)
"""
price (float) – the Black-Scholes option price
S (float) – underlying asset price
sigma (float) – annualized standard deviation, or volatility
K (float) – strike price
t (float) – time to expiration in years
r (float) – risk-free interest rate
flag (str) – ‘c’ or ‘p’ for call or put.
"""
def greek_val(flag, S, K, t, r, sigma):
price = bs(flag, S, K, t, r, sigma)
imp_v = iv(price, S, K, t, r, flag)
delta_calc = delta(flag, S, K, t, r, sigma)
gamma_calc = gamma(flag, S, K, t, r, sigma)
rho_calc = rho(flag, S, K, t, r, sigma)
theta_calc = theta(flag, S, K, t, r, sigma)
vega_calc = vega(flag, S, K, t, r, sigma)
return np.array([ price, imp_v ,theta_calc, delta_calc ,rho_calc ,vega_calc ,gamma_calc])
S = 8400
K = 8600
sigma = 16
r = 0.07
t = 1
call=greek_val('c', S, K, t, r, sigma)
put=greek_val('p', S, K, t, r, sigma)
您可以使用二進制搜索快速找到隱含的 vol
def goalseek(spot_price: float,
strike_price: float,
time_to_maturity: float,
option_type: str,
option_price: float):
volatility = 2.5
upper_range = 5.0
lower_range = 0
MOE = 0.0001 # Minimum margin of error
max_iters = 100
iter = 0
while iter < max_iters: # Don't iterate too much
price = proposedPrice(spot_price=spot_price,
strike_price=strike_price,
time_to_maturity=time_to_maturity,
volatility=volatility,
option_type=option_type) # BS Model Pricing
if abs((price - option_price)/option_price) < MOE:
return volatility
if price > option_price:
tmp = volatility
volatility = (volatility + lower_range)/2
upper_range = tmp
elif price < option_price:
tmp = volatility
volatility = (volatility + upper_range)/2
lower_range = tmp
iter += 1
return volatility
請使用 py_vollib.black_scholes.greeks.numerical 而不是分析用於回測目的。 當期權執行價格在價內或價內以及非流動性合約時的分析拋出錯誤,在這種情況下,使用歷史波動率而不是隱含波動率來計算期權希臘。 嘗試:使用 iv 和 except:使用 hv
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.