options_pricer

Option pricing with Black-Scholes, Monte Carlo, SVI and SSVI calibration.

 1"""Option pricing with Black-Scholes, Monte Carlo, SVI and SSVI calibration."""
 2
 3__version__ = "1.1.0"
 4
 5from .american import BinomialResult, binomial
 6from .black_scholes import Greeks, OptionType, deltas, greeks, price, prices, vegas
 7from .implied_vol import implied_volatility
 8from .monte_carlo import MonteCarloResult, price_european
 9from .path_dependent import (
10    PathGreeks,
11    PathResult,
12    asian_price,
13    barrier_greeks,
14    barrier_price,
15)
16from .path_greeks import (
17    PathGreeksResult,
18    asian_greeks_fd,
19    asian_greeks_lr,
20    barrier_greeks_fd,
21    barrier_greeks_lr,
22)
23from .ssvi import SsviParams, calibrate_ssvi
24
25__all__ = [
26    "BinomialResult",
27    "Greeks",
28    "MonteCarloResult",
29    "OptionType",
30    "PathGreeks",
31    "PathGreeksResult",
32    "PathResult",
33    "SsviParams",
34    "asian_greeks_fd",
35    "asian_greeks_lr",
36    "asian_price",
37    "barrier_greeks",
38    "barrier_greeks_fd",
39    "barrier_greeks_lr",
40    "barrier_price",
41    "binomial",
42    "calibrate_ssvi",
43    "deltas",
44    "greeks",
45    "implied_volatility",
46    "price",
47    "price_european",
48    "prices",
49    "vegas",
50]
@dataclass(frozen=True)
class BinomialResult:
20@dataclass(frozen=True)
21class BinomialResult:
22    american: float
23    european: float
24    premium: float
25    steps: int
BinomialResult(american: float, european: float, premium: float, steps: int)
american: float
european: float
premium: float
steps: int
@dataclass(frozen=True)
class Greeks:
40@dataclass(frozen=True)
41class Greeks:
42    delta: float
43    gamma: float
44    vega: float
45    theta: float
46    rho: float
47    vanna: float
48    volga: float
49    charm: float
Greeks( delta: float, gamma: float, vega: float, theta: float, rho: float, vanna: float, volga: float, charm: float)
delta: float
gamma: float
vega: float
theta: float
rho: float
vanna: float
volga: float
charm: float
@dataclass(frozen=True)
class MonteCarloResult:
19@dataclass(frozen=True)
20class MonteCarloResult:
21    price: float
22    standard_error: float
23    ci_low: float
24    ci_high: float
25    paths: int
26    antithetic: bool
27    mean_terminal: float
MonteCarloResult( price: float, standard_error: float, ci_low: float, ci_high: float, paths: int, antithetic: bool, mean_terminal: float)
price: float
standard_error: float
ci_low: float
ci_high: float
paths: int
antithetic: bool
mean_terminal: float
OptionType = typing.Literal['call', 'put']
@dataclass(frozen=True)
class PathGreeks:
34@dataclass(frozen=True)
35class PathGreeks:
36    price: float
37    delta: float
38    vega: float
39    theta: float
PathGreeks(price: float, delta: float, vega: float, theta: float)
price: float
delta: float
vega: float
theta: float
@dataclass(frozen=True)
class PathGreeksResult:
28@dataclass(frozen=True)
29class PathGreeksResult:
30    price: float
31    delta: float
32    gamma: float
33    vega: float
PathGreeksResult(price: float, delta: float, gamma: float, vega: float)
price: float
delta: float
gamma: float
vega: float
@dataclass(frozen=True)
class PathResult:
24@dataclass(frozen=True)
25class PathResult:
26    price: float
27    standard_error: float
28    ci_low: float
29    ci_high: float
30    paths: int
31    steps: int
PathResult( price: float, standard_error: float, ci_low: float, ci_high: float, paths: int, steps: int)
price: float
standard_error: float
ci_low: float
ci_high: float
paths: int
steps: int
@dataclass(frozen=True)
class SsviParams:
25@dataclass(frozen=True)
26class SsviParams:
27    rho: float
28    eta: float
29    gamma: float
30
31    def to_dict(self) -> dict[str, float]:
32        return {"rho": self.rho, "eta": self.eta, "gamma": self.gamma}
33
34    @classmethod
35    def from_dict(cls, data: dict[str, float]) -> SsviParams:
36        return cls(rho=float(data["rho"]), eta=float(data["eta"]), gamma=float(data["gamma"]))
SsviParams(rho: float, eta: float, gamma: float)
rho: float
eta: float
gamma: float
def to_dict(self) -> dict[str, float]:
31    def to_dict(self) -> dict[str, float]:
32        return {"rho": self.rho, "eta": self.eta, "gamma": self.gamma}
@classmethod
def from_dict(cls, data: dict[str, float]) -> SsviParams:
34    @classmethod
35    def from_dict(cls, data: dict[str, float]) -> SsviParams:
36        return cls(rho=float(data["rho"]), eta=float(data["eta"]), gamma=float(data["gamma"]))
def asian_greeks_fd( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, steps: int = 100, paths: int = 100000, seed: int = 42, bump: float = 0.01, independent: bool = False) -> PathGreeksResult:
152def asian_greeks_fd(
153    option_type: OptionType,
154    spot: float,
155    strike: float,
156    rate: float,
157    vol: float,
158    expiry: float,
159    steps: int = 100,
160    paths: int = 100_000,
161    seed: int = 42,
162    bump: float = 0.01,
163    independent: bool = False,
164) -> PathGreeksResult:
165    """Finite differences with common random numbers unless independent is True."""
166    from .path_dependent import asian_price
167
168    spot_up, spot_down, vol_up, vol_down = _bump(spot, vol, bump)
169
170    def price_at(new_spot: float, new_vol: float, new_seed: int) -> float:
171        return asian_price(
172            option_type,
173            new_spot,
174            strike,
175            rate,
176            new_vol,
177            expiry,
178            steps=steps,
179            paths=paths,
180            seed=new_seed,
181        ).price
182
183    seed_up_spot = seed + 1 if independent else seed
184    seed_down_spot = seed + 2 if independent else seed
185    seed_up_vol = seed + 3 if independent else seed
186    seed_down_vol = seed + 4 if independent else seed
187
188    base = price_at(spot, vol, seed)
189    up_spot = price_at(spot_up, vol, seed_up_spot)
190    down_spot = price_at(spot_down, vol, seed_down_spot)
191    up_vol = price_at(spot, vol_up, seed_up_vol)
192    down_vol = price_at(spot, vol_down, seed_down_vol)
193
194    return PathGreeksResult(
195        price=base,
196        delta=(up_spot - down_spot) / (2.0 * spot * bump),
197        gamma=(up_spot - 2.0 * base + down_spot) / ((spot * bump) ** 2),
198        vega=(up_vol - down_vol) / (2.0 * bump),
199    )

Finite differences with common random numbers unless independent is True.

def asian_greeks_lr( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, steps: int = 100, paths: int = 100000, seed: int = 42) -> PathGreeksResult:
 89def asian_greeks_lr(
 90    option_type: OptionType,
 91    spot: float,
 92    strike: float,
 93    rate: float,
 94    vol: float,
 95    expiry: float,
 96    steps: int = 100,
 97    paths: int = 100_000,
 98    seed: int = 42,
 99) -> PathGreeksResult:
100    matrix = simulate_paths(spot, rate, vol, expiry, steps, paths, seed)
101    payoff = _asian_payoff(matrix, option_type, strike)
102    score_spot, score_gamma, score_vol = _scores(matrix, spot, rate, vol, expiry, steps)
103    discount = _discount(rate, expiry)
104
105    return PathGreeksResult(
106        price=discount * float(payoff.mean()),
107        delta=discount * float((payoff * score_spot).mean()),
108        gamma=discount * float((payoff * (score_spot * score_spot + score_gamma)).mean()),
109        vega=discount * float((payoff * score_vol).mean()),
110    )
def asian_price( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, steps: int = 100, paths: int = 50000, seed: int = 42, antithetic: bool = False) -> PathResult:
102def asian_price(
103    option_type: OptionType,
104    spot: float,
105    strike: float,
106    rate: float,
107    vol: float,
108    expiry: float,
109    steps: int = 100,
110    paths: int = 50_000,
111    seed: int = 42,
112    antithetic: bool = False,
113) -> PathResult:
114    """Arithmetic-average Asian option, averaging the prices after inception."""
115    matrix = simulate_paths(spot, rate, vol, expiry, steps, paths, seed, antithetic)
116    average = matrix[:, 1:].mean(axis=1)
117    payoff = _intrinsic(option_type, average, strike)
118    return _summarise(payoff, rate, expiry, paths, steps)

Arithmetic-average Asian option, averaging the prices after inception.

def barrier_greeks( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, barrier: float, kind: str = 'up-and-out', steps: int = 100, paths: int = 200000, seed: int = 42, bump: float = 0.01, continuous: bool = False) -> PathGreeks:
184def barrier_greeks(
185    option_type: OptionType,
186    spot: float,
187    strike: float,
188    rate: float,
189    vol: float,
190    expiry: float,
191    barrier: float,
192    kind: BarrierKind = "up-and-out",
193    steps: int = 100,
194    paths: int = 200_000,
195    seed: int = 42,
196    bump: float = 0.01,
197    continuous: bool = False,
198) -> PathGreeks:
199    """Delta, vega and theta by bump and reprice with common random numbers.
200
201    Every repricing uses the same seed, so the Monte Carlo noise cancels in the
202    finite difference. Gamma is not returned: the second difference is the same
203    order as the remaining noise unless the path count is much larger.
204    """
205    if bump <= 0.0:
206        raise ValueError("bump must be positive")
207    if expiry <= bump:
208        raise ValueError("expiry must be larger than the bump for theta")
209
210    def price_at(new_spot: float, new_vol: float, new_expiry: float) -> float:
211        return barrier_price(
212            option_type,
213            new_spot,
214            strike,
215            rate,
216            new_vol,
217            new_expiry,
218            barrier,
219            kind,
220            steps,
221            paths,
222            seed,
223            continuous=continuous,
224        ).price
225
226    base = price_at(spot, vol, expiry)
227    up_spot = price_at(spot * (1.0 + bump), vol, expiry)
228    down_spot = price_at(spot * (1.0 - bump), vol, expiry)
229    up_vol = price_at(spot, vol + bump, expiry)
230    down_vol = price_at(spot, vol - bump, expiry)
231    up_time = price_at(spot, vol, expiry + bump)
232    down_time = price_at(spot, vol, expiry - bump)
233
234    return PathGreeks(
235        price=base,
236        delta=(up_spot - down_spot) / (2.0 * spot * bump),
237        vega=(up_vol - down_vol) / (2.0 * bump),
238        theta=-(up_time - down_time) / (2.0 * bump),
239    )

Delta, vega and theta by bump and reprice with common random numbers.

Every repricing uses the same seed, so the Monte Carlo noise cancels in the finite difference. Gamma is not returned: the second difference is the same order as the remaining noise unless the path count is much larger.

def barrier_greeks_fd( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, barrier: float, kind: str = 'up-and-out', steps: int = 100, paths: int = 100000, seed: int = 42, bump: float = 0.01, independent: bool = False) -> PathGreeksResult:
202def barrier_greeks_fd(
203    option_type: OptionType,
204    spot: float,
205    strike: float,
206    rate: float,
207    vol: float,
208    expiry: float,
209    barrier: float,
210    kind: BarrierKind = "up-and-out",
211    steps: int = 100,
212    paths: int = 100_000,
213    seed: int = 42,
214    bump: float = 0.01,
215    independent: bool = False,
216) -> PathGreeksResult:
217    """Finite differences with common random numbers unless independent is True."""
218    from .path_dependent import barrier_price
219
220    if kind not in BARRIER_KINDS:
221        raise ValueError(f"kind must be one of {BARRIER_KINDS}")
222    if barrier <= 0.0:
223        raise ValueError("barrier must be positive")
224
225    spot_up, spot_down, vol_up, vol_down = _bump(spot, vol, bump)
226
227    def price_at(new_spot: float, new_vol: float, new_seed: int) -> float:
228        return barrier_price(
229            option_type,
230            new_spot,
231            strike,
232            rate,
233            new_vol,
234            expiry,
235            barrier=barrier,
236            kind=kind,
237            steps=steps,
238            paths=paths,
239            seed=new_seed,
240        ).price
241
242    seed_up_spot = seed + 1 if independent else seed
243    seed_down_spot = seed + 2 if independent else seed
244    seed_up_vol = seed + 3 if independent else seed
245    seed_down_vol = seed + 4 if independent else seed
246
247    base = price_at(spot, vol, seed)
248    up_spot = price_at(spot_up, vol, seed_up_spot)
249    down_spot = price_at(spot_down, vol, seed_down_spot)
250    up_vol = price_at(spot, vol_up, seed_up_vol)
251    down_vol = price_at(spot, vol_down, seed_down_vol)
252
253    return PathGreeksResult(
254        price=base,
255        delta=(up_spot - down_spot) / (2.0 * spot * bump),
256        gamma=(up_spot - 2.0 * base + down_spot) / ((spot * bump) ** 2),
257        vega=(up_vol - down_vol) / (2.0 * bump),
258    )

Finite differences with common random numbers unless independent is True.

def barrier_greeks_lr( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, barrier: float, kind: str = 'up-and-out', steps: int = 100, paths: int = 100000, seed: int = 42) -> PathGreeksResult:
113def barrier_greeks_lr(
114    option_type: OptionType,
115    spot: float,
116    strike: float,
117    rate: float,
118    vol: float,
119    expiry: float,
120    barrier: float,
121    kind: BarrierKind = "up-and-out",
122    steps: int = 100,
123    paths: int = 100_000,
124    seed: int = 42,
125) -> PathGreeksResult:
126    if kind not in BARRIER_KINDS:
127        raise ValueError(f"kind must be one of {BARRIER_KINDS}")
128    if barrier <= 0.0:
129        raise ValueError("barrier must be positive")
130
131    matrix = simulate_paths(spot, rate, vol, expiry, steps, paths, seed)
132    payoff = _barrier_payoff(matrix, option_type, strike, barrier, kind)
133    score_spot, score_gamma, score_vol = _scores(matrix, spot, rate, vol, expiry, steps)
134    discount = _discount(rate, expiry)
135
136    return PathGreeksResult(
137        price=discount * float(payoff.mean()),
138        delta=discount * float((payoff * score_spot).mean()),
139        gamma=discount * float((payoff * (score_spot * score_spot + score_gamma)).mean()),
140        vega=discount * float((payoff * score_vol).mean()),
141    )
def barrier_price( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, barrier: float, kind: str = 'up-and-out', steps: int = 100, paths: int = 50000, seed: int = 42, antithetic: bool = False, continuous: bool = False) -> PathResult:
121def barrier_price(
122    option_type: OptionType,
123    spot: float,
124    strike: float,
125    rate: float,
126    vol: float,
127    expiry: float,
128    barrier: float,
129    kind: BarrierKind = "up-and-out",
130    steps: int = 100,
131    paths: int = 50_000,
132    seed: int = 42,
133    antithetic: bool = False,
134    continuous: bool = False,
135) -> PathResult:
136    """Barrier option with discrete monitoring at the simulation steps.
137
138    With continuous=True the gap between steps is handled with a Brownian bridge
139    crossing probability, which approximates continuous monitoring without
140    refining the time grid.
141    """
142    if kind not in BARRIER_KINDS:
143        raise ValueError(f"kind must be one of {BARRIER_KINDS}")
144    if barrier <= 0.0:
145        raise ValueError("barrier must be positive")
146
147    matrix = simulate_paths(spot, rate, vol, expiry, steps, paths, seed, antithetic)
148    path_max = matrix.max(axis=1)
149    path_min = matrix.min(axis=1)
150
151    if kind.startswith("up"):
152        crossed = path_max >= barrier
153    else:
154        crossed = path_min <= barrier
155
156    terminal_payoff = _intrinsic(option_type, matrix[:, -1], strike)
157    knocked_out = kind.endswith("out")
158
159    if not continuous:
160        if knocked_out:
161            weight = np.where(crossed, 0.0, 1.0)
162        else:
163            weight = np.where(crossed, 1.0, 0.0)
164    else:
165        dt = expiry / steps
166        if kind.startswith("up"):
167            log_ratio = np.log(barrier / matrix)
168        else:
169            log_ratio = np.log(matrix / barrier)
170
171        exponent = -2.0 * log_ratio[:, :-1] * log_ratio[:, 1:] / (vol * vol * dt)
172        crossing_probability = np.exp(np.clip(exponent, -700.0, 0.0))
173        survival = np.prod(1.0 - crossing_probability, axis=1)
174
175        if knocked_out:
176            weight = np.where(crossed, 0.0, survival)
177        else:
178            weight = np.where(crossed, 1.0, 1.0 - survival)
179
180    payoff = weight * terminal_payoff
181    return _summarise(payoff, rate, expiry, paths, steps)

Barrier option with discrete monitoring at the simulation steps.

With continuous=True the gap between steps is handled with a Brownian bridge crossing probability, which approximates continuous monitoring without refining the time grid.

def binomial( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, steps: int = 1000, dividend_yield: float = 0.0) -> BinomialResult:
 72def binomial(
 73    option_type: OptionType,
 74    spot: float,
 75    strike: float,
 76    rate: float,
 77    vol: float,
 78    expiry: float,
 79    steps: int = 1_000,
 80    dividend_yield: float = 0.0,
 81) -> BinomialResult:
 82    """Price an American option and its European twin on the same CRR tree."""
 83    if spot <= 0.0 or strike <= 0.0:
 84        raise ValueError("spot and strike must be positive")
 85    if vol <= 0.0:
 86        raise ValueError("volatility must be positive")
 87    if expiry <= 0.0:
 88        raise ValueError("expiry must be positive, in years")
 89    if steps < 1:
 90        raise ValueError("steps must be positive")
 91    if option_type not in ("call", "put"):
 92        raise ValueError("option_type must be 'call' or 'put'")
 93
 94    american_value = _tree(
 95        option_type, spot, strike, rate, vol, expiry, steps, dividend_yield, True
 96    )
 97    european_value = _tree(
 98        option_type, spot, strike, rate, vol, expiry, steps, dividend_yield, False
 99    )
100
101    return BinomialResult(
102        american=american_value,
103        european=european_value,
104        premium=american_value - european_value,
105        steps=steps,
106    )

Price an American option and its European twin on the same CRR tree.

def calibrate_ssvi( expiries: list[float], log_moneyness: list[list[float]], vols: list[list[float]], weights: list[list[float]] | None = None) -> tuple[SsviParams, float, list[float]]:
 69def calibrate_ssvi(
 70    expiries: list[float],
 71    log_moneyness: list[list[float]],
 72    vols: list[list[float]],
 73    weights: list[list[float]] | None = None,
 74) -> tuple[SsviParams, float, list[float]]:
 75    """Fit rho, eta and gamma on all slices at once.
 76
 77    Returns the parameters, the RMSE in implied volatility and the theta of each
 78    expiry. Weights, when given, multiply each squared residual.
 79    """
 80    if len(expiries) != len(log_moneyness) or len(expiries) != len(vols):
 81        raise ValueError("expiries, log_moneyness and vols must have the same length")
 82    if not expiries:
 83        raise ValueError("at least one expiry is needed")
 84
 85    thetas = [
 86        atm_total_variance(ks, slice_vols, expiry)
 87        for expiry, ks, slice_vols in zip(expiries, log_moneyness, vols, strict=True)
 88    ]
 89
 90    flat: list[tuple[float, float, float, float]] = []
 91    for expiry, theta, ks, slice_vols in zip(expiries, thetas, log_moneyness, vols, strict=True):
 92        for k, vol in zip(ks, slice_vols, strict=True):
 93            flat.append((expiry, theta, k, vol * vol * expiry))
 94
 95    if len(flat) < 3:
 96        raise ValueError("at least three quotes are needed for three parameters")
 97
 98    if weights is None:
 99        flat_weights = np.ones(len(flat))
100    else:
101        if len(weights) != len(expiries):
102            raise ValueError("weights must have one entry per expiry")
103        flat_weights = np.array([weight for slice_weights in weights for weight in slice_weights])
104
105    def residuals(x: np.ndarray) -> np.ndarray:
106        candidate = SsviParams(rho=float(x[0]), eta=float(x[1]), gamma=float(x[2]))
107        errors = np.array(
108            [total_variance(k, theta, candidate) - width for _, theta, k, width in flat],
109            dtype=float,
110        )
111        errors = errors * np.sqrt(flat_weights)
112        violation = max(0.0, candidate.eta * (1.0 + abs(candidate.rho)) - 3.9)
113        return np.concatenate([errors, np.array([100.0 * violation])])
114
115    guess = np.array([-0.4, 1.0, 0.4])
116    lower = np.array([-0.999, 0.01, 0.01])
117    upper = np.array([0.999, 4.0, 0.5])
118    guess = np.clip(guess, lower + 1e-6, upper - 1e-6)
119
120    result = least_squares(residuals, guess, bounds=(lower, upper))
121
122    params = SsviParams(rho=float(result.x[0]), eta=float(result.x[1]), gamma=float(result.x[2]))
123
124    squared = [
125        (implied_vol(k, expiry, theta, params) - math.sqrt(width / expiry)) ** 2
126        for expiry, theta, k, width in flat
127    ]
128    rmse = math.sqrt(sum(squared) / len(squared))
129    return params, rmse, thetas

Fit rho, eta and gamma on all slices at once.

Returns the parameters, the RMSE in implied volatility and the theta of each expiry. Weights, when given, multiply each squared residual.

def deltas( option_type: Literal['call', 'put'], spot: object, strike: object, rate: float, vol: float, expiry: float, dividend_yield: float = 0.0) -> numpy.ndarray:
170def deltas(
171    option_type: OptionType,
172    spot: object,
173    strike: object,
174    rate: float,
175    vol: float,
176    expiry: float,
177    dividend_yield: float = 0.0,
178) -> np.ndarray:
179    """Vectorised delta, consistent with the scalar Greeks."""
180    d1, _, _, _ = _array_setup(spot, strike, rate, vol, expiry, dividend_yield)
181    discount_q = math.exp(-dividend_yield * expiry)
182
183    if option_type == "call":
184        return discount_q * ndtr(d1)
185    if option_type == "put":
186        return -discount_q * ndtr(-d1)
187    raise ValueError("option_type must be 'call' or 'put'")

Vectorised delta, consistent with the scalar Greeks.

def greeks( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, dividend_yield: float = 0.0) -> Greeks:
209def greeks(
210    option_type: OptionType,
211    spot: float,
212    strike: float,
213    rate: float,
214    vol: float,
215    expiry: float,
216    dividend_yield: float = 0.0,
217) -> Greeks:
218    """First and second order Greeks, with the conventions listed in the module docstring."""
219    _validate(spot, strike, vol, expiry)
220    d1, d2 = _d1_d2(spot, strike, rate, vol, expiry, dividend_yield)
221
222    sqrt_t = math.sqrt(expiry)
223    discount_r = math.exp(-rate * expiry)
224    discount_q = math.exp(-dividend_yield * expiry)
225    pdf_d1 = _norm_pdf(d1)
226    carry = rate - dividend_yield
227
228    gamma = discount_q * pdf_d1 / (spot * vol * sqrt_t)
229    vega = spot * discount_q * pdf_d1 * sqrt_t
230    vanna = -discount_q * pdf_d1 * d2 / vol
231    volga = vega * d1 * d2 / vol
232    charm_common = (
233        discount_q
234        * pdf_d1
235        * (math.log(spot / strike) - (carry + 0.5 * vol * vol) * expiry)
236        / (2.0 * vol * expiry * sqrt_t)
237    )
238    theta_common = -spot * discount_q * pdf_d1 * vol / (2.0 * sqrt_t)
239
240    if option_type == "call":
241        delta = discount_q * _norm_cdf(d1)
242        theta = (
243            theta_common
244            + dividend_yield * spot * discount_q * _norm_cdf(d1)
245            - rate * strike * discount_r * _norm_cdf(d2)
246        )
247        rho = strike * expiry * discount_r * _norm_cdf(d2)
248        charm = charm_common + dividend_yield * discount_q * _norm_cdf(d1)
249    elif option_type == "put":
250        delta = -discount_q * _norm_cdf(-d1)
251        theta = (
252            theta_common
253            - dividend_yield * spot * discount_q * _norm_cdf(-d1)
254            + rate * strike * discount_r * _norm_cdf(-d2)
255        )
256        rho = -strike * expiry * discount_r * _norm_cdf(-d2)
257        charm = charm_common - dividend_yield * discount_q * _norm_cdf(-d1)
258    else:
259        raise ValueError("option_type must be 'call' or 'put'")
260
261    return Greeks(
262        delta=delta,
263        gamma=gamma,
264        vega=vega,
265        theta=theta,
266        rho=rho,
267        vanna=vanna,
268        volga=volga,
269        charm=charm,
270    )

First and second order Greeks, with the conventions listed in the module docstring.

def implied_volatility( target_price: float, spot: float, strike: float, rate: float, expiry: float, option_type: Literal['call', 'put'] = 'call', upper: float = 5.0) -> float:
29def implied_volatility(
30    target_price: float,
31    spot: float,
32    strike: float,
33    rate: float,
34    expiry: float,
35    option_type: OptionType = "call",
36    upper: float = 5.0,
37) -> float:
38    """Volatility that reproduces target_price under Black-Scholes.
39
40    Raises ValueError when the price is outside the no-arbitrage range, which
41    means no positive volatility can produce it.
42    """
43    if target_price <= 0.0:
44        raise ValueError("target price must be positive")
45    if expiry <= 0.0:
46        raise ValueError("expiry must be positive, in years")
47
48    floor = intrinsic_value(option_type, spot, strike, rate, expiry)
49    if target_price < floor - 1e-12:
50        raise ValueError(f"price {target_price:.6f} is below the intrinsic value {floor:.6f}")
51
52    def gap(vol: float) -> float:
53        return black_scholes.price(option_type, spot, strike, rate, vol, expiry) - target_price
54
55    low = 1e-6
56    high = upper
57
58    if gap(low) > 0.0:
59        raise ValueError("price is above the attainable range")
60    if gap(high) < 0.0:
61        raise ValueError(f"price needs a volatility above {upper}")
62
63    return float(brentq(gap, low, high, xtol=1e-12, rtol=1e-12))

Volatility that reproduces target_price under Black-Scholes.

Raises ValueError when the price is outside the no-arbitrage range, which means no positive volatility can produce it.

def price( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, dividend_yield: float = 0.0) -> float:
77def price(
78    option_type: OptionType,
79    spot: float,
80    strike: float,
81    rate: float,
82    vol: float,
83    expiry: float,
84    dividend_yield: float = 0.0,
85) -> float:
86    """Black-Scholes price of a European call or put, with a continuous dividend yield."""
87    _validate(spot, strike, vol, expiry)
88    d1, d2 = _d1_d2(spot, strike, rate, vol, expiry, dividend_yield)
89    discount_r = math.exp(-rate * expiry)
90    discount_q = math.exp(-dividend_yield * expiry)
91
92    if option_type == "call":
93        return spot * discount_q * _norm_cdf(d1) - strike * discount_r * _norm_cdf(d2)
94    if option_type == "put":
95        return strike * discount_r * _norm_cdf(-d2) - spot * discount_q * _norm_cdf(-d1)
96    raise ValueError("option_type must be 'call' or 'put'")

Black-Scholes price of a European call or put, with a continuous dividend yield.

def price_european( option_type: Literal['call', 'put'], spot: float, strike: float, rate: float, vol: float, expiry: float, paths: int = 1000000, seed: int = 42, antithetic: bool = True) -> MonteCarloResult:
30def price_european(
31    option_type: OptionType,
32    spot: float,
33    strike: float,
34    rate: float,
35    vol: float,
36    expiry: float,
37    paths: int = 1_000_000,
38    seed: int = 42,
39    antithetic: bool = True,
40) -> MonteCarloResult:
41    """Price a European option by simulation, with a 95% confidence interval.
42
43    With antithetic sampling the number of paths is rounded down to an even
44    number, because each draw is paired with its mirror image.
45    """
46    if paths < 2:
47        raise ValueError("paths must be at least 2")
48    if spot <= 0.0 or strike <= 0.0:
49        raise ValueError("spot and strike must be positive")
50    if vol <= 0.0:
51        raise ValueError("volatility must be positive")
52    if expiry <= 0.0:
53        raise ValueError("expiry must be positive, in years")
54
55    rng = np.random.default_rng(seed)
56
57    if antithetic:
58        half = paths // 2
59        draws = rng.standard_normal(half)
60        draws = np.concatenate([draws, -draws])
61    else:
62        draws = rng.standard_normal(paths)
63
64    drift = (rate - 0.5 * vol * vol) * expiry
65    diffusion = vol * math.sqrt(expiry) * draws
66    terminal = spot * np.exp(drift + diffusion)
67
68    if option_type == "call":
69        payoff = np.maximum(terminal - strike, 0.0)
70    elif option_type == "put":
71        payoff = np.maximum(strike - terminal, 0.0)
72    else:
73        raise ValueError("option_type must be 'call' or 'put'")
74
75    discounted = math.exp(-rate * expiry) * payoff
76    estimate = float(discounted.mean())
77    error = float(discounted.std(ddof=1) / math.sqrt(discounted.size))
78
79    return MonteCarloResult(
80        price=estimate,
81        standard_error=error,
82        ci_low=estimate - 1.96 * error,
83        ci_high=estimate + 1.96 * error,
84        paths=int(discounted.size),
85        antithetic=antithetic,
86        mean_terminal=float(terminal.mean()),
87    )

Price a European option by simulation, with a 95% confidence interval.

With antithetic sampling the number of paths is rounded down to an even number, because each draw is paired with its mirror image.

def prices( option_type: Literal['call', 'put'], spot: object, strike: object, rate: float, vol: float, expiry: float, dividend_yield: float = 0.0) -> numpy.ndarray:
145def prices(
146    option_type: OptionType,
147    spot: object,
148    strike: object,
149    rate: float,
150    vol: float,
151    expiry: float,
152    dividend_yield: float = 0.0,
153) -> np.ndarray:
154    """Vectorised price for arrays of spot and strike. Broadcasting applies."""
155    d1, spot_array, strike_array, sqrt_t = _array_setup(
156        spot, strike, rate, vol, expiry, dividend_yield
157    )
158    d2 = d1 - vol * sqrt_t
159
160    discount_r = math.exp(-rate * expiry)
161    discount_q = math.exp(-dividend_yield * expiry)
162
163    if option_type == "call":
164        return spot_array * discount_q * ndtr(d1) - strike_array * discount_r * ndtr(d2)
165    if option_type == "put":
166        return strike_array * discount_r * ndtr(-d2) - spot_array * discount_q * ndtr(-d1)
167    raise ValueError("option_type must be 'call' or 'put'")

Vectorised price for arrays of spot and strike. Broadcasting applies.

def vegas( option_type: Literal['call', 'put'], spot: object, strike: object, rate: float, vol: float, expiry: float, dividend_yield: float = 0.0) -> numpy.ndarray:
190def vegas(
191    option_type: OptionType,
192    spot: object,
193    strike: object,
194    rate: float,
195    vol: float,
196    expiry: float,
197    dividend_yield: float = 0.0,
198) -> np.ndarray:
199    """Vectorised vega per unit of volatility, consistent with the scalar Greeks."""
200    d1, spot_array, _, sqrt_t = _array_setup(spot, strike, rate, vol, expiry, dividend_yield)
201    discount_q = math.exp(-dividend_yield * expiry)
202    density = np.exp(-0.5 * d1 * d1) / math.sqrt(2.0 * math.pi)
203
204    if option_type not in ("call", "put"):
205        raise ValueError("option_type must be 'call' or 'put'")
206    return spot_array * discount_q * density * sqrt_t

Vectorised vega per unit of volatility, consistent with the scalar Greeks.