Nee*_*esh 3 python volatility quantitative-finance quantlib pandas
我正在寻找一个库,我可以用它来更快地计算 Python 中的隐含波动率。我有关于 1+ 百万行的期权数据,我想计算隐含波动率。我可以计算IV的最快方法是什么。我曾尝试使用 py_vollib,但它不支持矢量化。大约需要 5 分钟。计算。是否有任何其他库可以帮助加快计算速度。人们在每秒有数百万行的实时波动率计算中使用什么?
Dav*_*rte 13
你必须意识到隐含波动率计算的计算成本很高,如果你想要实时数字,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
Run Code Online (Sandbox Code Playgroud)
计算单个值足够快
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))
Run Code Online (Sandbox Code Playgroud)
隐含交易量:25.00%
市场价格=35.94
型号价格 = 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))
Run Code Online (Sandbox Code Playgroud)
挂壁时间:10.5 秒
小智 6
如果您将所有对norm.cdf()-method 的调用更改为ndtr(),您将获得 2.4 倍的性能提升。
如果您将norm.pdf()-method更改为norm._pdf(),您将获得另一个(巨大的)增加。
实施这两项更改后,上面的示例在我的机器上从17.7 [s]下到下0.99 [s]。
您将失去错误检查等功能,但在这种情况下,您可能不需要所有这些。
参见:https : //github.com/scipy/scipy/issues/1914
ndtr() 在 scipy.special