Metadata-Version: 2.4
Name: py_vollib_vectorized
Version: 1.0.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Rust
Requires-Dist: vollib>=1.0.11
Requires-Dist: numba>=0.61
Requires-Dist: numpy
Requires-Dist: pandas
Requires-Dist: polars>=1.0 ; extra == 'polars'
Requires-Dist: pytest ; extra == 'test'
Requires-Dist: polars>=1.0 ; extra == 'test'
Provides-Extra: polars
Provides-Extra: test
License-File: LICENSE
License-File: py_vollib_vectorized/_lets_be_rational/LICENSE
Summary: A fast, vectorized approach to calculating Implied Volatility and Greeks using the Black, Black-Scholes and Black-Scholes-Merton pricing.
Keywords: options,implied volatility,greeks,black-scholes,pandas,polars,polars-extension
Author-email: Marc Demers <demers.marc@gmail.com>
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/marcdemers/py_vollib_vectorized/blob/main/CHANGELOG.md
Project-URL: Documentation, https://py-vollib-vectorized.readthedocs.io/en/latest
Project-URL: Homepage, https://github.com/marcdemers/py_vollib_vectorized
Project-URL: Issues, https://github.com/marcdemers/py_vollib_vectorized/issues

# py_vollib_vectorized


## Introduction

The `py_vollib_vectorized` package makes pricing thousands of option contracts and calculating greeks fast and effortless.
It is built on top of the `vollib` library, formerly named `py_vollib`.
Upon import, it will automatically patch the corresponding `vollib` functions so as to support vectorization.
The deprecated `py_vollib` import name refers to the same functions, so code that still imports `py_vollib` is patched too.
The patch changes `vollib` for the whole process; [it can be turned off](#using-vollib-without-the-patch).
Inputs can then be passed as floats, tuples, lists, `numpy.array`, or `pandas.Series`.
Automatic broadcasting is performed on the inputs.
Results returned as `pandas` objects have the index of the `pandas` inputs.

On top of vectorization, modifications to vollib include additional `numba` speedups; as such, `numba` is required.
These speedups make `py_vollib_vectorized` the fastest library for pricing option contracts.

The same prices, implied volatilities and greeks are also available as [Polars](https://pola.rs) expressions.
A compiled plugin evaluates them on DataFrames and LazyFrames, on one core or on all of them.

See the [documentation](https://py-vollib-vectorized.readthedocs.io/en/latest) for more details.

## Installation

    pip install py_vollib_vectorized

To use the Polars expressions, install Polars with it:

    pip install "py_vollib_vectorized[polars]"

## Requirements

* Written for Python 3.10+
* Requires vollib, numba, numpy, pandas
* Polars 1.0+ is optional, for the Polars expressions
* Wheels are available for Linux (x86-64, aarch64), macOS (Apple silicon, Intel) and Windows (x86-64). Installing from source on another platform takes a Rust toolchain.

## Code samples

The library can be used in three ways.
Upon import, it monkey-patches (i.e. replaces) the corresponding functions in `vollib`.

As a more versatile alternative, users that would prefer to work with a dedicated option pricing API can make use of the utility functions provided by the library.

Users of Polars can price the columns of their frames with expressions.

#### Patching `vollib`

```python
# The usual vollib syntax

import numpy as np
import pandas as pd

import vollib.black_scholes
flag = 'c'  # 'c' for call, 'p' for put
S = 100  # Underlying asset price
K = 90  # Strike
t = 0.5  # (Annualized) time-to-expiration
r = 0.01  # Interest free rate
iv = 0.2  # Implied Volatility

option_price = vollib.black_scholes.black_scholes(flag, S, K, t, r, iv)  # 12.111581435

# This library keeps the same syntax, but you can pass as input any iterable of values.
# This includes list, tuple, numpy.array, pd.Series, pd.DataFrame (with only a single column).


# Patch the original vollib library by importing py_vollib_vectorized
import py_vollib_vectorized  # The same functions now accept vectors as input!

# Note that the input arguments are broadcasted.
# You can specify ints, floats, tuples, lists, numpy arrays or Series.

flag = ['c', 'p']  # 'c' or 'call' for call, 'p' or 'put' for put
S = (100, 100)  # Underlying asset prices
K = [90]  # Strikes
t = pd.Series([0.5, 0.6])  # (Annualized) times-to-expiration
r = np.array([0.01])  # Interest free rates
iv = 0.2  # Implied Volatilities

option_price = vollib.black_scholes.black_scholes(flag, S, K, t, r, iv, return_as='array')  
# array([12.11158143,  2.02418536])
```

#### Using `vollib` without the patch

> **The patch applies to the whole process.**
> After `import py_vollib_vectorized`, a scalar call such as `vollib.black_scholes.black_scholes('c', 100, 90, 0.5, 0.01, 0.2)` returns a `pandas.DataFrame` instead of a float, also in other code of the same process that calls `vollib`.

Nothing in this library needs the patch: the `vectorized_` functions, the utility functions and the Polars expressions below work with and without it.
To keep the scalar functions of `vollib`, either set the environment variable `PY_VOLLIB_VECTORIZED_PATCH_VOLLIB=0` before the first import, or take the patch back after it:

```python
import vollib.black_scholes
import py_vollib_vectorized

py_vollib_vectorized.unpatch_vollib()  # vollib is as it was before the import
vollib.black_scholes.black_scholes('c', 100, 90, 0.5, 0.01, 0.2)  # 12.11158143496968, a float
py_vollib_vectorized.vectorized_black_scholes('c', 100, 90, 0.5, 0.01, 0.2, return_as='array')  # array([12.11158143])

py_vollib_vectorized.patch_vollib()  # applies the patch again
```

> **One function takes the interest rate before the time to expiration.**
> `vectorized_implied_volatility_black(price, F, K, r, t, flag)` keeps the argument order of `vollib.black.implied_volatility.implied_volatility`, and so does the Polars expression `implied_volatility_black`.
> Every other function takes `t` before `r`, as in `vectorized_implied_volatility(price, S, K, t, r, flag)`.
> In the wrong order the two give a wrong implied volatility, and no error: pass `r=` and `t=` by keyword.

#### Utility functions
We also define other utility functions to get all contract prices, implied volatilities, and greeks in a single call.

```python
import pandas as pd
from py_vollib_vectorized import price_dataframe, get_all_greeks

# Using the data above, we can calculate all contracts greeks in a single call
greeks = get_all_greeks(flag, S, K, t, r, iv, model='black_scholes', return_as='dict')

#   {'delta': array([ 0.80263679, -0.21293214]),
#    'gamma': array([0.0196385, 0.01875498]),
#    'theta': array([-0.01263557, -0.00964498]),
#    'rho': array([0.34073321, -0.13994668]),
#    'vega': array([0.19626478, 0.22493816])}

# We can also price a dataframe easily by specifying a dataframe and the corresponding columns

df = pd.DataFrame()
df['Flag'] = ['c', 'p']
df['S'] = 95
df['K'] = [100, 90]
df['T'] = 0.2
df['R'] = 0.2
df['IV'] = 0.2
result = price_dataframe(df, flag_col='Flag', underlying_price_col='S', strike_col='K', annualized_tte_col='T',
                     riskfree_rate_col='R', sigma_col='IV', model='black_scholes', inplace=False)
#   Price       delta       gamma       theta       rho        vega
#   2.895588    0.467506    0.046795    -0.045900   0.083035   0.168926
#   0.611094    -0.136447   0.025739    -0.005335   -0.027151  0.092838

```

#### Polars expressions

`py_vollib_vectorized.polars` has the same functions as expressions: strings are column names, and numbers and other expressions work too.

```python
import polars as pl
import py_vollib_vectorized.polars as pvp

df = pl.DataFrame({
    "flag": ["c", "p"],  # 'c' or 'call' for call, 'p' or 'put' for put
    "S": [95.0, 95.0],  # Underlying asset prices
    "K": [100.0, 90.0],  # Strikes
    "t": [0.2, 0.2],  # (Annualized) times-to-expiration
    "r": [0.2, 0.2],  # Interest free rates
    "sigma": [0.2, 0.2],  # Implied Volatilities
})

df.select(
    pvp.black_scholes("flag", "S", "K", "t", "r", "sigma"),
    pvp.all_greeks("flag", "S", "K", "t", "r", "sigma"),
).unnest("greeks")
# ┌──────────┬───────────┬──────────┬───────────┬───────────┬──────────┐
# │ Price    ┆ delta     ┆ gamma    ┆ theta     ┆ rho       ┆ vega     │
# ╞══════════╪═══════════╪══════════╪═══════════╪═══════════╪══════════╡
# │ 2.895588 ┆ 0.467506  ┆ 0.046795 ┆ -0.0459   ┆ 0.083035  ┆ 0.168926 │
# │ 0.611094 ┆ -0.136447 ┆ 0.025739 ┆ -0.005335 ┆ -0.027151 ┆ 0.092838 │
# └──────────┴───────────┴──────────┴───────────┴───────────┴──────────┘

# The expressions work in lazy queries, on the streaming engine, and in filter, group_by and over.
lazy = df.lazy().with_columns(pvp.black_scholes("flag", "S", "K", "t", "r", "sigma").alias("mid"))
lazy.select(pvp.implied_volatility("mid", "S", "K", "t", "r", "flag")).collect(engine="streaming")
# IV: [0.2, 0.2]

# parallel=True splits the contracts of one expression over every core: set it for frames in one or a few chunks.
df.select(pvp.implied_volatility(2.0, "S", "K", "t", "r", "flag", parallel=True))

# price_dataframe adds the prices or the implied volatilities, and the greeks, to a DataFrame or a LazyFrame.
pvp.price_dataframe(df, flag_col="flag", underlying_price_col="S", strike_col="K", annualized_tte_col="t",
                    riskfree_rate_col="r", sigma_col="sigma", model="black_scholes")
# ┌──────┬──────┬───────┬─────┬─────┬───────┬──────────┬───────────┬──────────┬───────────┬───────────┬──────────┐
# │ flag ┆ S    ┆ K     ┆ t   ┆ r   ┆ sigma ┆ Price    ┆ delta     ┆ gamma    ┆ theta     ┆ rho       ┆ vega     │
# ╞══════╪══════╪═══════╪═════╪═════╪═══════╪══════════╪═══════════╪══════════╪═══════════╪═══════════╪══════════╡
# │ c    ┆ 95.0 ┆ 100.0 ┆ 0.2 ┆ 0.2 ┆ 0.2   ┆ 2.895588 ┆ 0.467506  ┆ 0.046795 ┆ -0.0459   ┆ 0.083035  ┆ 0.168926 │
# │ p    ┆ 95.0 ┆ 90.0  ┆ 0.2 ┆ 0.2 ┆ 0.2   ┆ 0.611094 ┆ -0.136447 ┆ 0.025739 ┆ -0.005335 ┆ -0.027151 ┆ 0.092838 │
# └──────┴──────┴───────┴─────┴─────┴───────┴──────────┴───────────┴──────────┴───────────┴───────────┴──────────┘
```

The expressions return the same numbers as the functions above.
They return null where an input is null.
A price that has no implied volatility gives null as well, without a warning, where the functions above give NaN.

See the [documentation](https://py-vollib-vectorized.readthedocs.io/en/latest) for more details.

## Benchmarking

Compared to looping through contracts or to using built-in pandas functionality, this library scales to a large number of contracts.
The figure shows the time to price contracts with the Black-Scholes model and to compute the implied volatilities of those prices.
For one million contracts, the fastest loop over the scalar functions of `vollib` takes 44 seconds, the pandas API 0.90 seconds, and the Polars expressions 0.49 seconds on one thread and 0.037 seconds with `parallel=True` on 64 cores.

![Time to price option contracts and to compute their implied volatilities, for 10 to 10 million contracts](https://raw.githubusercontent.com/marcdemers/py_vollib_vectorized/main/docs/_static/benchmark.png "Benchmark")

See the [performance page](https://py-vollib-vectorized.readthedocs.io/en/latest/benchmarking.html) of the documentation for the numbers and for how they were measured.


## Acknowledgements

This library optimizes the `vollib` codebase, itself built upon Peter Jäckel's *Let's be rational* methodology.
The `numba` kernels of the implied volatility solver come from `py_lets_be_rational` 1.0.1 and are distributed with this library under its license (see `py_vollib_vectorized/_lets_be_rational/LICENSE`).
The plugin behind the Polars expressions is a Rust port of those kernels, under the same license, and follows the design of [polars_ds](https://github.com/abstractqqq/polars_ds_extension).

