Python中隐含波动率的快速计算

Python中隐含波动率的快速计算,python,pandas,quantitative-finance,quantlib,volatility,Python,Pandas,Quantitative Finance,Quantlib,Volatility,我正在寻找一个库,我可以用它来更快地计算python中的隐含波动率。我有大约100多万行的期权数据,我想计算隐含波动率。我计算静脉输液的最快方法是什么。我尝试过使用py_vollib,但它不支持矢量化。计算大约需要5分钟。有没有其他库可以帮助加快计算速度。人们在实时波动率计算中使用的是什么?每秒有数百万行的数据 您必须意识到隐含波动率计算在计算上非常昂贵,如果您想要实时数字,python可能不是最佳解决方案 以下是您需要的功能示例: import numpy as np from scipy.s

我正在寻找一个库,我可以用它来更快地计算python中的隐含波动率。我有大约100多万行的期权数据,我想计算隐含波动率。我计算静脉输液的最快方法是什么。我尝试过使用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
隐含容量: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))

墙时间:10.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
隐含容量: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))

墙时间:10.5秒

如果将所有对
norm.cdf()
-method的调用更改为
ndtr()
,则性能将提高2.4倍

如果您将
norm.pdf()
-方法更改为
norm.\u pdf()
,您将获得另一个(巨大的)增长

实施这两项更改后,在我的机器上,上面的示例从
17.7[s]
下降到
0.99[s]

您将失去错误检查等,但在这种情况下,您可能不需要所有这些

见:


ndtr()
位于
scipy.special

中,如果将所有调用更改为
norm.cdf()
-方法为
ndtr()
,则性能将提高2.4倍

如果您将
norm.pdf()
-方法更改为
norm.\u pdf()
,您将获得另一个(巨大的)增长

实施这两项更改后,在我的机器上,上面的示例从
17.7[s]
下降到
0.99[s]

您将失去错误检查等,但在这种情况下,您可能不需要所有这些

见:


ndtr()
位于
scipy.special

最近,有一个矢量化版本的
py\u-vollib
可在上获得,它建立在
py\u-vollib
之上,使数千份期权合约的定价和计算速度更快。

最近,有一个矢量化版本的
py_-vollib
可在上获得,它建立在
py_-vollib
之上,使数千份期权合约的定价和计算速度大大加快

!pip install py_vollib
这将使希腊人与布莱克·斯科尔斯·普莱斯和第四次世界大战一同归来

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)
这将使希腊人和布莱克·斯科尔斯·普莱斯和四世一起回归

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
def goalseek(现货价格:浮动,
执行价格:浮动,
到期时间:浮动,
选项类型:str,
选项(价格:浮动):
波动率=2.5
上限范围=5.0
下限范围=0
MOE=0.0001#最小误差范围
最大值=100
iter=0
而iter选项价格:
tmp=波动性
波动率=(波动率+下限)/2
上限范围=tmp
elif价格<期权价格:
tmp=波动性
波动率=(波动率+上限)/2
下限=tmp
iter+=1
收益波动率

您可以使用二进制搜索快速查找隐含的卷

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
def goalseek(现货价格:浮动,
执行价格:浮动,
到期时间:浮动,
选项类型:str,
选项(价格:浮动):
波动率=2.5
上限范围=5.0
下限范围=0
MOE=0.0001#最小误差范围
最大值=100
iter=0
而iter选项价格:
tmp=波动性
波动率=(波动率+下限)/2
上限范围=tmp
elif价格<期权价格:
tmp=波动性
波动率=(波动率+上限)/2
下限=tmp
iter+=1
收益波动率

对于我们这些不是金融数学专家的人,你能定义隐含波动率函数吗?一些样本输入数据对我们这些不是金融数学专家的人也有帮助,你能定义隐含波动率函数吗?一些示例输入数据也会有帮助@David Duarte您是否有上述等式的
PUT
部分?现在我有一个方法
def bs_put(S,K,r,vol,T)-返回bs_调用(S,K,r,vol,T)-S+np。