European option pricing built on the Black-Scholes-Merton formula, with the full Greek set, implied-volatility inversion, and a vectorised Monte Carlo reference implementation for cross-checking.
- Correct by construction. Put-call parity is exact to 1e-10, Greeks are validated against finite differences, and every public library function carries runnable doctests.
- Three front ends. Python API, a
bsCLI, and a Tkinter GUI. - Honest numbers. Every numeric result is a native
float, not a NumPy scalar, so results serialise cleanly.
The package is not on PyPI yet (see Known gaps), so install from a checkout, with the development extras:
git clone https://github.com/buzludeniz/black_scholes_model.git
cd black_scholes_model
pip install -e ".[dev]"Once it is published, pip install black_scholes_model will work too.
Requires Python 3.10 or newer.
The distribution is black_scholes_model but the import name is shorter,
black_scholes:
import black_scholesfrom black_scholes import OptionParams, OptionType, price_option, implied_volatility
params = OptionParams(
spot=100.0,
strike=100.0,
time_to_maturity=1.0,
risk_free_rate=0.05,
volatility=0.20,
option_type=OptionType.CALL,
)
result = price_option(params)
print(f"Price: {result.price:.4f}") # 10.4506
print(f"Delta: {result.greeks.delta:.4f}") # 0.6368
# Recover the volatility the market is pricing in.
iv = implied_volatility(result.price, params)
print(f"Implied vol: {iv:.2%}") # 20.00%# Price with Greeks
bs price 100 100 1 0.05 0.2 call
# Machine-readable output
bs price 100 100 1 0.05 0.2 call --format json
# Cross-check against a simulation
bs price 100 100 1 0.05 0.2 call --mc
# Implied volatility from a market price
bs iv 10.450584 100 100 1 0.05 call
# Strike-by-strike surface
bs surface --spot 100 --time 1 --rate 0.05 --vol 0.2 --strikes "80,90,100,110,120"
# Greeks with explanations
bs greeks 100 100 1 0.05 0.2 callcall also accepts c and put accepts p. Use -q/--div-yield for a
continuous dividend yield.
# American option: CRR binomial tree and Barone-Adesi-Whaley, next to the European
bs american 100 100 1 0.05 0.2 put
bs american 100 100 1 0.05 0.2 put --method crr --steps 2000 --format jsonbs-guiEnter the spot, strike, maturity, rate, volatility, and dividend yield; pick call or put; press Calculate Price & Greeks. Tick the Monte Carlo box to see the simulation cross-check the closed form, or Implied Volatility to solve for the volatility behind a market price.
| Function | Purpose |
|---|---|
black_scholes_price(params) |
Closed-form price |
black_scholes_greeks(params) |
Delta, Gamma, Vega, Theta, Rho |
price_option(params) |
Price and Greeks together |
implied_volatility(price, params) |
Invert price to volatility |
arbitrage_bounds(params) |
No-arbitrage price interval |
monte_carlo_price(params, ...) |
Simulated price with standard error |
American exercise lives in black_scholes.american:
| Function | Purpose |
|---|---|
binomial_price(params, steps=1000, american=True) |
Cox-Ross-Rubinstein tree, with continuous dividend yield |
barone_adesi_whaley_price(params) |
Barone-Adesi-Whaley (1987) quadratic approximation |
american_price(params, method="crr" | "baw") |
Either of the above |
from black_scholes import OptionParams, OptionType
from black_scholes.american import barone_adesi_whaley_price, binomial_price
put = OptionParams(100.0, 100.0, 1.0, 0.05, 0.20, OptionType.PUT)
binomial_price(put, steps=2000) # 6.090
barone_adesi_whaley_price(put) # 6.098The tree converges to the true value as steps grows (it reproduces Hull's
published American-put tree values). BAW is much faster and is within about a
cent of the tree for short maturities, but it is an approximation: for one-year,
40%-volatility options near the exercise boundary it can be off by ten cents or
so on a 100 strike. With no dividend an American call equals the European call,
and both methods return exactly that.
Greek units: Vega is per 1% volatility move, Theta is per calendar day, Rho is per 1% rate move. Gamma and Vega are identical for calls and puts.
Call: S·e^(-qT)·N(d1) - K·e^(-rT)·N(d2)
Put: K·e^(-rT)·N(-d2) - S·e^(-qT)·N(-d1)
d1 = (ln(S/K) + (r - q + σ²/2)·T) / (σ·√T)
d2 = d1 - σ·√T
This is the European option model under geometric Brownian motion with a constant volatility and a continuous dividend yield.
Real markets do not quote a flat volatility, they quote a smile. The
black_scholes.surface module fits that smile from market prices using the SVI
parameterisation, and refuses to return a fit that would let someone price
arbitrage out of it.
from black_scholes.surface import VolSurface
surface = VolSurface.from_market_prices(
spot=100.0,
strikes=[70.0, 90.0, 100.0, 110.0, 150.0],
prices=[34.3824, 18.0797, 11.7507, 7.4028, 1.3415],
time_to_maturity=1.0,
risk_free_rate=0.05,
)
fit = surface.fit()
print(fit.curve.a, fit.curve.b, fit.curve.rho) # SVI parameters
print(fit.rms_error, fit.max_error) # fit qualityFrom the shell:
bs fit-surface --spot 100 --time 1 --rate 0.05 \
--strikes "70,90,100,110,150" \
--prices "34.3824,18.0797,11.7507,7.4028,1.3415"Total implied variance is written as a function of log-moneyness k = ln(K/F):
w(k) = a + b·(ρ·(k − m) + √((k − m)² + σ²))
Five parameters, and the shape stays economically sensible where a polynomial
would eventually turn over: b sets the smile, ρ the skew, σ the wings.
- Parameter arbitrage, closed form:
b ≥ 0,|ρ| < 1,σ > 0, and a non-negative minimum total variance. - Butterfly arbitrage, Gatheral's density condition, checked numerically:
(1 − k·w′/2w)² − (w′)²/4·(1/w + 1/4) + w″/2 ≥ 0. - Error tolerance: SVI cannot fit every quoted shape. Without this bound the optimiser can return a curve that passes both arbitrage checks yet misses the data by tens of volatility points, and report success.
fit_relaxed() lifts guards 2 and 3 so a rejected fit can be inspected instead
of vanishing.
black_scholes.term_structure.TermStructure stacks one SVI slice per expiry,
rejects calendar-spread arbitrage between every pair of adjacent expiries, and
interpolates total implied variance linearly in time (flat forward variance
between expiries) so an implied volatility can be read at any (k, T) inside
the quoted range:
from black_scholes.surface import SVICurve
from black_scholes.term_structure import TermStructure
ts = TermStructure.from_slices(
{
0.5: SVICurve(0.02, 0.10, -0.30, 0.0, 0.15),
1.0: SVICurve(0.04, 0.10, -0.30, 0.0, 0.15),
}
)
ts.implied_volatility(k=0.0, maturity=0.75) # 0.2449...TermStructure.from_surfaces([...]) fits each single-expiry VolSurface and
stacks the results. The calendar check needs two things per adjacent pair: the
slices must not cross, and the later slice must lie above the earlier one (a
uniformly lower later slice never crosses but is still arbitrage). Maturities
outside [first expiry, last expiry] raise ValueError rather than
extrapolate. Linear interpolation in total variance preserves calendar
no-arbitrage but not necessarily butterfly no-arbitrage of the intermediate
smiles; ts.butterfly_arbitrage_free(T) checks one.
pip install -e ".[dev]"
pytest # tests plus doctests, prints coverage
pytest --cov-fail-under=85 # the same, enforcing the CI coverage gate
ruff check . && ruff format --check .
mypy src/black_scholes
python -m build # wheel and sdist
python check_layout.py # GUI layout audit, exits non-zero if clipped
python demo_gui.py # drive the real GUI widgets and print the display
python launch_gui.py # run the GUI
python examples/basic_usage.pyCurrent state: 576 tests pass, 97% line coverage, with ruff and mypy clean.
Coverage per module: gui.py 100%, black_scholes core 99%, cli.py 97%,
surface.py 93%.
The coverage gate is enforced by CI, not by pytest addopts. A gate in
addopts also applies to partial runs, so pytest tests/test_gui.py and even
pytest --collect-only would report failure for a suite that is entirely green.
Coverage is still measured on every local run; only the pass/fail decision moved.
Honest inventory of what is still not done:
- Not on PyPI.
python -m buildproduces valid artifacts and a Trusted-Publishing workflow is committed, but the package is not published, sopip install black_scholes_modelwill not resolve until the PyPI project is created and linked to the workflow. - Calendar arbitrage is a numerical check over a stated range.
SVICurve.calendar_arbitrage_freelocates the extrema of the difference between two slices rather than sampling it, so it does not depend on grid spacing, and it reports a crossing that the grid would otherwise step over. It is still not a proof: it says nothing outside[k_low, k_high], and the range is part of the contract. There is no closed form for it in the raw parameterisation. - Butterfly arbitrage is a grid check, not a proof. No closed form exists for raw SVI, and SSVI's closed-form conditions come from a stricter parameterisation that cannot fit every quoted smile. A finer grid can find more violations, never fewer.
- No extrapolation in time.
TermStructureinterpolates between the quoted expiries only; maturities before the first or after the last are rejected. - No SABR or eSSVI. SVI only.
- Slices are fitted independently.
TermStructure.from_surfacesfits each expiry on its own and then checks calendar arbitrage; it does not fit the expiries jointly under a calendar constraint. - No American Greeks.
black_scholes.americanprices American options but does not compute their Greeks; Bermudan exercise is not supported.
- American options are priced by a binomial tree or the Barone-Adesi-Whaley approximation; Bermudan options are not implemented.
black_scholes_priceassumes a single flat volatility. For a real smile, price each strike with its own implied volatility or use the fitted surface.implied_volatilityneeds a no-arbitrage price and a volatility bracket that contains the answer. Prices at the theoretical bound require a wider bracket, and anything outside the bounds is rejected rather than extrapolated.- The SVI fit is a least-squares approximation. SVI cannot represent every quoted shape, and the error bound exists so that failure is visible rather than silent.
MIT. See LICENSE.