Giter Site home page Giter Site logo

py_vollib's Introduction

About py_vollib

py_vollib is a python library for calculating option prices, implied volatility and greeks. At its core is Peter Jäckel's source code for LetsBeRational, an extremely fast and accurate algorithm for obtaining Black's implied volatility from option prices.

Building on this solid foundation, py_vollib provides functions to calculate option prices, implied volatility and greeks using Black, Black-Scholes, and Black-Scholes-Merton. py_vollib implements both analytical and numerical greeks for each of the three pricing formulae.

Comparison with vollib

Feature py_vollib vollib
Python Version Compatibility 2.7 and 3.x 2.7 only
Source Language Python C with Python SWIG Wrapper
Optional Dependencies Numba None
Core Dependency (automatically installed by pip) py_lets_be_rational lets_be_rational

Execution Speed

Except for the source languages of py_lets_be_rational and lets_be_rational, py_vollib and vollib are almost identical. Each is orders of magnitude faster than traditional implied volatility calculation libraries, thanks to the algorithms developed by Peter Jäckel. However, py_vollib, without Numba installed, is about an order of magnitude slower than vollib. Numba helps to mitigate this speed gap considerably.

Numba Dependency

Numba is an optional dependency of py_vollib . Because Numba installation can be tricky and OS-dependent, we decided to leave it up to each user to decide how and whether to install Numba. If Numba is present, execution speed will be faster. If not, the code will still run -- just slower.

Installing Numba

py_lets_be_rational optionally depends on numba which in turn depends on llvm-lite. llvm-lite wants LLVM 3.9 being installed. On Mac OSX, use the latest version of HomeBrew to install numba's dependencies as shown below:

brew install [email protected]
LLVM_CONFIG=/usr/local/opt/[email protected]/bin/llvm-config pip install llvmlite==0.16.0
pip install numba==0.31.0

For other operating systems, please refer to the llvm-lite and numba documentation.

About the reference Python implementation

py_vollib contains py_vollib.ref_python, a pure python version of the functions in py_vollib.*, except without any dependency on lets_be_rational or py_lets_be_rational. It is provided purely as a reference implementation for sanity checking. It is not recommended for serious use.

Dependencies

py_vollib is Python 2.7/Python 3.6 compatible. Its core dependency is py_lets_be_rational package, pure python implementation of Peter Jäckel's original C source code.

To install via pip, type the following:

pip install py_vollib

Installing py_vollib via pip will automatically install the necessary dependencies, except for pip, and Python.

Python, and pip must be installed prior to installing py_vollib.

About "Let's be Rational"

"Let's Be Rational" is a paper by Peter Jäckel showing "how Black's volatility can be implied from option prices with as little as two iterations to maximum attainable precision on standard (64 bit floating point) hardware for all possible inputs."

The paper is accompanied by the full C source code, which resides at www.jaeckel.org/LetsBeRational.7z.

Copyright © 2013-2014 Peter Jäckel.

Permission to use, copy, modify, and distribute this software is freely granted,
provided that this notice is preserved.

WARRANTY DISCLAIMER
The Software is provided "as is" without warranty of any kind, either express or implied,
including without limitation any implied warranties of condition, uninterrupted use,
merchantability, fitness for a particular purpose, or non-infringement.

Links

Development

Fork the GitHub repository. This will make it available under your username e.g. https://github.com/YOUR-USERNAME/py_vollib. Clone that repo on your computer, change the code as you wish. Commit and push it, and create a pull request. That's all.

Generate documentation

cd docs
sphinx-apidoc -f -o apidoc ../py_vollib
make html

py_vollib's People

Contributors

kaze avatar lbrichards avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

py_vollib's Issues

Importing py_vollib causes a MySQL import error in a Flask App

Hi everyone, I am trying to use this library to calculate IV and Greeks for an array of option prices and when I was developing on my local windows machine everything went smoothly but on trying to run the code on a Flask application that uses a MySQL connector to read price data, simply importing the py_vollib library causes the application to break with the following error:-

  File "*/.venv2/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module>
    from . import _mysql
ImportError: /lib64/libstdc++.so.6: cannot allocate memory in static TLS block

Joined by another exception here :-

  File "*/.venv2/lib/python3.6/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 167, in dbapi
    return __import__("MySQLdb")
  File "*/.venv2/lib/python3.6/site-packages/MySQLdb/__init__.py", line 24, in <module>
    version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined

SQLALchemy works fine on my Windows machine but not on this RedHat Linux instance that I am developing on. I would appreciate if you could provide any insight on the C level imports that occur when using this library that is probably causing this issue / conflict. As for me I'm a bit boggled on how to go about debugging it.

Very slow to run on SQL Server 2017

I am trying to run some calculations on SQL Server by sending the calculations to server from python scripts. When I try to run sample calculations on my local machine, it takes less than a second to run sample calculations. When I try to run it on the SQL server, however, it takes a long time. It seems like the server has trouble importing modules. Specifically, when I add this line to the code

from py_vollib.black_scholes.implied_volatility import implied_volatility as iv

the server will take forever to run the script, even if I never make any calls to iv.

When I check the packages in the server, all the required packages for py_vollib (including numba) are installed. Any idea as to what might be causing the problem?

Unable to update to latest version with pip

pip just says py_volliv is up to date (=1.0.2), but my code in site-packages folder is not equal to the code in master shown here (I'm specifically looking at black_scholes.implied_volatility exceptions: helpers/exceptions.py does not even exist in my downloaded version).

Is it possible that you forgot to increase the version in setup.py after some updates?

BelowIntrinsicValue exception for Deep in the money put

Hi,
I am using your package to calculate all the greeks and also the IV for deribit btc usd options. but I am facing issues with evaulating deep in the money puts or out of the money calls.
I am getting the exception : BelowIntrinsicValue. kindly help me how can I overcome this exception which is coming from the code lets_be_rational.py

Regards
Shubha

Incorrect Theta calculation

Theta calculation in analytical greeks of Black is incorrect. second_term should be 0.Developer confused 'q' which is annual dividend yield which should be 0 in this case with 'r' risk free return rate

Black Model's gamma gives a very low number?

I am getting a very low numbered gamma (power lesser than -50) in black models gamma. I don't know what I am doing wrong

spot=100
strike=150
days=7/365  
rate=4/100
sigma=17/100

from py_vollib.black.greeks.analytical import gamma

x=gamma("c",spot,strike,days,rate,sigma)
print(x)

x=gamma("p",spot,strike,days,rate,sigma)
print(x)

Feature Request: Second Order Greeks

Are there any plans to add functions to calculate other second order Greeks? Like Vanna, Vomma, Charm. Given the vectorized framework of py_vollib, these functions will be of great help. Thanks.

I am happy to work with someone on building this functionality as well. I have built these functions but do not have experience with vectorization.

ImportError: No module named '_testcapi'

using python from centos 7 ,
install python by yum install -y python35u .

get error :
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.5/site-packages/py_vollib/black_scholes/init.py", line 44, in
from py_vollib.black import undiscounted_black
File "/usr/lib/python3.5/site-packages/py_vollib/black/init.py", line 44, in
import py_lets_be_rational as lets_be_rational
File "/usr/lib/python3.5/site-packages/py_lets_be_rational/init.py", line 30, in
from py_lets_be_rational.lets_be_rational import black
File "/usr/lib/python3.5/site-packages/py_lets_be_rational/lets_be_rational.py", line 35, in
from py_lets_be_rational.exceptions import BelowIntrinsicException, AboveMaximumException
File "/usr/lib/python3.5/site-packages/py_lets_be_rational/exceptions.py", line 30, in
from py_lets_be_rational import constants
File "/usr/lib/python3.5/site-packages/py_lets_be_rational/constants.py", line 32, in
from _testcapi import DBL_MIN, DBL_MAX
ImportError: No module named '_testcapi'

It should not be included in a production library

In an uncompiled version, this file does not necessarily exist .
please fix this problem

NumbaDeprecationWarning

C:\Users\August\anaconda3\Lib\site-packages\py_lets_be_rational\numba_helper.py:10: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.
return jit(*jit_args, **jit_kwargs)(fun)

Has anyone looked into this?

Get Price from Vol

Hi guys, big fan of Vollib, I was wondering though is there a way to get say the options price from the implied vol? I basically now have my cubic spline going through the bid/ask mids but want to see in Price terms how under/over valued out of line strikes are.

Cheers

Strange values for rho

Followed the example in the docs but not getting the correct answer:

>>> import py_vollib.black.greeks.analytical as vollib
>>> S =49
>>> K=50
>>> r=.05
>>> t=.3846
>>> sigma=.2
>>> flag='c'
>>> rho = vollib.rho(flag,S,K,t,r,sigma)
>>> print (rho)
-0.00747053800596

From the docs, Example 17.7, page 368, Hull:

>>> S = 49
>>> K = 50 
>>> r = .05
>>> t = 0.3846
>>> sigma = 0.2
>>> flag = 'c'
>>> rho_calc = rho(flag, S, K, t, r, sigma)
>>> 0.089065740988

It's not even close. Using this in py3 conda env & all other greek values seem to be fine

Importing library in PyCharm Python Console raises ModuleNotFoundError

Hi guys,

I was trying the library out in the PyCharm IDE. Whenever I try to import libraries, it is throwing the ModuleNotFoundError for _testcapi. I did read in one of the closed issues that this is no longer an issue. But I could not find a working solution to the issue on my computer. I tried reinstalling the library multiple times. Any help would be much appreciated.

I am trying the library on Python 3.10 on Fedora box.

from py_vollib import black_scholes
Traceback (most recent call last):
File "/usr/lib64/python3.10/code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
File "/home/guruappa/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/222.4167.33/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/run/media/guruappa/programs/projects/trade_station/venv/lib/python3.10/site-packages/py_vollib/black_scholes/init.py", line 44, in
from py_vollib.black import undiscounted_black
File "/home/guruappa/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/222.4167.33/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/run/media/guruappa/programs/projects/trade_station/venv/lib/python3.10/site-packages/py_vollib/black/init.py", line 44, in
import py_lets_be_rational as lets_be_rational
File "/home/guruappa/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/222.4167.33/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/run/media/guruappa/programs/projects/trade_station/venv/lib/python3.10/site-packages/py_lets_be_rational/init.py", line 30, in
from py_lets_be_rational.lets_be_rational import black
File "/home/guruappa/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/222.4167.33/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/run/media/guruappa/programs/projects/trade_station/venv/lib/python3.10/site-packages/py_lets_be_rational/lets_be_rational.py", line 35, in
from py_lets_be_rational.exceptions import BelowIntrinsicException, AboveMaximumException
File "/home/guruappa/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/222.4167.33/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/run/media/guruappa/programs/projects/trade_station/venv/lib/python3.10/site-packages/py_lets_be_rational/exceptions.py", line 30, in
from py_lets_be_rational import constants
File "/home/guruappa/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/222.4167.33/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/run/media/guruappa/programs/projects/trade_station/venv/lib/python3.10/site-packages/py_lets_be_rational/constants.py", line 32, in
from _testcapi import DBL_MIN, DBL_MAX
File "/home/guruappa/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/222.4167.33/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named '_testcapi'

ModuleNotFoundError: No module named '_testcapi'

from py_vollib.black_scholes_merton import black_scholes_merton

raises

ModuleNotFoundError: No module named '_testcapi'

Python 3.11.7
py-vollib 1.0.1

Issue mentioned elsewhere:
#11
#20

Is this issue still a known problem with the pip package?

Multiple ZeroDivisionError error on Windows

I am using Winpython64bit Python3.5 distribution on my Windows10 64 bit pc. When I first ran function to find black implied volatility I got an error saying that

ImportError: No module named _testcapi

Apparently _testcapi is not a package which can be installed using pip. It comes pre-installed. Neverthless, I went to py_lets_be_rational\constants and removed the
from _testcapi import DBL_MIN, DBL_MAX
line and added the following:

DBL_MIN = sys.float_info.min
DBL_MAX = sys.float_info.max

The values captured by DBL_MIN and DBL_MAX are as follows:

import sys
DBL_MIN = sys.float_info.min
DBL_MAX = sys.float_info.max
DBL_MAX
Out[34]: 1.7976931348623157e+308
DBL_MIN
Out[35]: 2.2250738585072014e-308

After this the code was compiling and I could run the example mentioned in the documentation. It worked okay. Next, I tried to find the iv of an actual trading option on link:
https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=ACC&instrument=FUTSTK&type=-&strike=-&expiry=25MAY2017

I used the following and got the error:

import py_vollib.black.implied_volatility as biv
P = 30.70
F = 1685
K = 1680
r= .06
flag = "c"
biv.implied_volatility(P, F, K, r, 0.35, flag)
Traceback (most recent call last):

  File "<ipython-input-29-bcdbf833ce25>", line 1, in <module>
    biv.implied_volatility(P, F, K, r, 0.35, flag)

  File "D:\Filehistory Backup D\WinPython-64bit-3.5.2.2\python-3.5.2.amd64\lib\site-packages\py_vollib\black\implied_volatility.py", line 99, in implied_volatility_of_discounted_option_price
    binary_flag[flag]

  File "D:\Filehistory Backup D\WinPython-64bit-3.5.2.2\python-3.5.2.amd64\lib\site-packages\py_lets_be_rational\lets_be_rational.py", line 653, in implied_volatility_from_a_transformed_rational_guess
    price, F, K, T, q, implied_volatility_maximum_iterations)

  File "D:\Filehistory Backup D\WinPython-64bit-3.5.2.2\python-3.5.2.amd64\lib\site-packages\py_lets_be_rational\lets_be_rational.py", line 613, in implied_volatility_from_a_transformed_rational_guess_with_limited_iterations
    price / (sqrt(F) * sqrt(K)), x, q, N) / sqrt(T)

  File "D:\Filehistory Backup D\WinPython-64bit-3.5.2.2\python-3.5.2.amd64\lib\site-packages\py_lets_be_rational\lets_be_rational.py", line 388, in _unchecked_normalised_implied_volatility_from_a_transformed_rational_guess_with_limited_iterations
    s_l = s_c - b_c/v_c

ZeroDivisionError: float division by zero

I keep getting this error for almost all options. Then on my windows machine again, I tried calculating the implied vol using the py_vollib.ref_python modules and it worked. Next, I used another pc with linux and Anaconda python distribution and ran the original py_vollib.black.implied_volatility module and it worked well.

So, we have a situation where I am able to calculate options prices on linux distribution and on Windows 64bit platform using ref_python module but not through the recommended way on Windows 64 bit platform. Any suggestions? I want to use this package on a windows machine, would you recommend me using the ref_python modules in the interim? What could be the challenge?

Deep ITM European Options

Is this package available for computing European options' IV and Greeks???

Sometimes for deep ITM European options, the market price can be smaller than the intrinsic value. This raises the error:

py_lets_be_rational.exceptions.BelowIntrinsicException: The volatility is below the intrinsic value.

But such data do exist in practical trading

Zero strike price

Using K=0, leads to Error: "ZeroDivisionError: division by zero"

example:

from py_vollib.black_scholes import black_scholes
black_scholes('c',200,0,1,0.02,1.3)

What are 'b' and 'pricing function' arguments for numerical greeks

What are 'b' and 'pricing function' arguments for numerical greeks and how do you pass them as arguments? My understanding is you should be using numerical_delta() instead of analytical delta function for faster, but slightly less accurate results.

from py_vollib.helpers.numerical_greeks import delta as numerical_delta
from py_vollib.black_scholes.greeks.analytical import delta

S = 49
K = 50 
r = .05
t = 0.3846
sigma = 0.2
flag = 'c'

delta(flag, S, K, t, r, sigma)
numerical_delta(flag, S, K, t, r, sigma)

Results

>>> delta(flag, S, K, t, r, sigma)
0.5216016339715761
>>> numerical_delta(flag, S, K, t, r, sigma)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: delta() missing 2 required positional arguments: 'b' and 'pricing_function'

Dealing with deep in-the-money index option

I am trying to get the implied volatility of SP500 options under deep in-the-money condition.

It returns "below intrinsic value".

I am aware the traditional method of calculating implied volatility would fail when it is deep in the money, while jaeckel's method improves the calculation.

So, I wanna know if it is my code's problem or it is the problem with the data of deep strikes.

implied_volatility(1529.75, 4127.83, 2600, 133/252, 0.01, "c")

vectorization in py_vollib

i am looking to calculate implied volatility using black scholes formula for european options for around 1 million + rows. I have the data stored required data like stock price, strike, option price etc in a dataframe. I am looking for a process which i can use to get the implied volatility calculated for all the rows rather than me manually looping through each and every row of the dataframe and calling py_vollib implied volatility function. What would you recommend so that i can speed up this entire process?

Black-Scholes implied vol BelowIntrinsicError with negative risk-free rate

Trying to calculate the implied vol for Eurostoxx50 options and running into problems due to the negative risk-free rate in EUR:

from py_vollib.black_scholes.implied_volatility import implied_volatility
implied_volatility(price=107.35, S=3576.1, K=3575, t=0.139726, r=-0.618873, flag='p')

Any suggestions how to handle/overcome this?


BelowIntrinsicException Traceback (most recent call last)
in
1 from py_vollib.black_scholes.implied_volatility import implied_volatility
----> 2 implied_volatility(price=107.35, S=3576.1, K=3575, t=0.139726, r=-0.618873, flag='p')

~/miniconda3/lib/python3.8/site-packages/py_vollib/black_scholes/implied_volatility.py in implied_volatility(price, S, K, t, r, flag)
89 undiscounted_option_price = price / deflater
90 F = forward_price(S, t, r)
---> 91 sigma_calc = iv(undiscounted_option_price, F, K, t, binary_flag[flag])
92 if sigma_calc == FLOAT_MAX:
93 raise PriceIsAboveMaximum()

~/miniconda3/lib/python3.8/site-packages/py_lets_be_rational/lets_be_rational.py in implied_volatility_from_a_transformed_rational_guess(price, F, K, T, q)
650 :rtype: float
651 """
--> 652 return implied_volatility_from_a_transformed_rational_guess_with_limited_iterations(
653 price, F, K, T, q, implied_volatility_maximum_iterations)
654

~/miniconda3/lib/python3.8/site-packages/py_lets_be_rational/lets_be_rational.py in implied_volatility_from_a_transformed_rational_guess_with_limited_iterations(price, F, K, T, q, N)
601 intrinsic = fabs(max(K - F if q < 0 else F - K, 0.0))
602 if price < intrinsic:
--> 603 raise BelowIntrinsicException
604 max_price = K if q < 0 else F
605 if price >= max_price:

BelowIntrinsicException: The volatility is below the intrinsic value.

Strike from IV and delta

Options implied volatility data is often given in terms of delta of the contracts (and not their strike).
However, the option strike is required to price the option (using py_vollib.black_scholes).

Can strike be computed from iv and delta (along with other parameters) with py_vollib?

How to use this lib?

I manually installed this package on OSX (sudo python setup.py install), but after importing it I don't see any usefull methods or classes in there:

>>> import py_vollib
>>> dir(py_vollib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

I also checked out the docs but it only mentions things about installation and performance, nothing about how to actually use this lib.

Does anybody know how I can calculate an option price and get it's greeks using vollib?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.