Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(quantlib): add analytical single-barrier options pricing engine

santhrealebd0cc151374
diff --git a/agent/src/quantlib/options.py b/agent/src/quantlib/options.py
index 8e4488d18..5ee39ad2d 100644
--- a/agent/src/quantlib/options.py
+++ b/agent/src/quantlib/options.py
@@ -30,7 +30,15 @@ import numpy as np
from scipy.optimize import brentq
from scipy.stats import norm
-__all__ = ["bs_price", "bs_greeks", "implied_volatility", "normalise_option_type"]
+__all__ = [
+ "BARRIER_TYPES",
+ "barrier_option_price",
+ "bs_greeks",
+ "bs_price",
+ "implied_volatility",
+ "normalise_barrier_type",
+ "normalise_option_type",
+]
#: Widest volatility the implied-vol search will consider (1000% annualised).
#: Anything solving above this is an outlier or a bad print, not a vol.
@@ -64,6 +72,51 @@ _CALL_ALIASES: frozenset[str] = frozenset({"call", "calls", "c", "看涨", "认
_PUT_ALIASES: frozenset[str] = frozenset({"put", "puts", "p", "看跌", "认沽"})
+#: Standard barrier types
+BARRIER_TYPES: tuple[str, ...] = (
+ "down-and-out",
+ "down-and-in",
+ "up-and-out",
+ "up-and-in",
+)
+
+_BARRIER_ALIASES: dict[str, str] = {
+ "down-and-out": "down-and-out",
+ "down_and_out": "down-and-out",
+ "down and out": "down-and-out",
+ "do": "down-and-out",
+ "doc": "down-and-out",
+ "dop": "down-and-out",
+ "down-and-in": "down-and-in",
+ "down_and_in": "down-and-in",
+ "down and in": "down-and-in",
+ "di": "down-and-in",
+ "dic": "down-and-in",
+ "dip": "down-and-in",
+ "up-and-out": "up-and-out",
+ "up_and_out": "up-and-out",
+ "up and out": "up-and-out",
+ "uo": "up-and-out",
+ "uoc": "up-and-out",
+ "uop": "up-and-out",
+ "up-and-in": "up-and-in",
+ "up_and_in": "up-and-in",
+ "up and in": "up-and-in",
+ "ui": "up-and-in",
+ "uic": "up-and-in",
+ "uip": "up-and-in",
+}
+
+
+def normalise_barrier_type(barrier_type: str) -> str:
+ """Fold a barrier-type string to one of :data:`BARRIER_TYPES`."""
+ cleaned = barrier_type.strip().lower()
+ if cleaned in _BARRIER_ALIASES:
+ return _BARRIER_ALIASES[cleaned]
+ raise ValueError(
+ f"unknown barrier type {barrier_type!r}; valid types: {BARRIER_TYPES}"
+ )
+
def normalise_option_type(option_type: str) -> str:
"""Fold an option-type string to ``"call"`` or ``"put"``.
@@ -446,3 +499,132 @@ def implied_volatility(market_price: float, S: float, K: float, T: float,
# the documented contract for that is nan, not an exception escaping
# from a private implementation detail.
return float("nan")
+
+
+def barrier_option_price(
+ S: float,
+ K: float,
+ H: float,
+ T: float,
+ r: float,
+ sigma: float,
+ barrier_type: str,
+ option_type: str = "call",
+ q: float = 0.0,
+ rebate: float = 0.0,
+) -> float:
+ """Analytical Black-Scholes pricing for single-barrier options (Reiner-Rubinstein 1991).
+
+ Supports all 8 standard barrier option combinations:
+ * Down-and-out / Down-and-in (Call / Put)
+ * Up-and-out / Up-and-in (Call / Put)
+
+ with continuous monitoring, continuous dividend yield ``q``, and optional
+ expiry cash rebate ``rebate``.
+
+ Satisfies the exact In-Out parity identity:
+ Price(Knock-In) + Price(Knock-Out) = Price(Vanilla) + rebate * exp(-r * T)
+
+ Args:
+ S: Current spot price, strictly positive.
+ K: Strike price, strictly positive.
+ H: Barrier price level, strictly positive.
+ T: Time to expiration in years.
+ r: Continuously compounded risk-free rate.
+ sigma: Annualised volatility.
+ barrier_type: One of :data:`BARRIER_TYPES` (or aliases e.g. ``'down-and-out'``, ``'ui'``).
+ option_type: ``'call'`` or ``'put'``.
+ q: Continuously compounded dividend yield.
+ rebate: Fixed cash rebate paid at expiration if knocked out (or never knocked in).
+
+ Returns:
+ Option price as a non-negative float.
+
+ Raises:
+ ValueError: If S, K, or H <= 0, or barrier_type is unknown.
+ """
+ if S <= 0.0 or K <= 0.0 or H <= 0.0:
+ raise ValueError(f"Spot, strike, and barrier must be strictly positive, got S={S}, K={K}, H={H}")
+
+ b_type = normalise_barrier_type(barrier_type)
+ opt_type = normalise_option_type(option_type)
+
+ # Degenerate expiry or zero/negative volatility
+ if T <= 0.0 or sigma <= 0.0:
+ vanilla = bs_price(S, K, T, r, sigma, opt_type, q)
+ # Check if breached at T=0
+ is_down = "down" in b_type
+ breached = (S <= H) if is_down else (S >= H)
+ if "out" in b_type:
+ return rebate if breached else vanilla
+ else: # "in"
+ return vanilla if breached else rebate
+
+ # Check initial boundary conditions
+ is_down = "down" in b_type
+ if is_down and S <= H:
+ if "out" in b_type:
+ return rebate * np.exp(-r * T)
+ else:
+ return bs_price(S, K, T, r, sigma, opt_type, q)
+ elif (not is_down) and S >= H:
+ if "out" in b_type:
+ return rebate * np.exp(-r * T)
+ else:
+ return bs_price(S, K, T, r, sigma, opt_type, q)
+
+ phi = 1.0 if opt_type == _CALL else -1.0
+ eta = 1.0 if is_down else -1.0
+
+ b = r - q
+ sigma_sqrt_T = sigma * np.sqrt(T)
+ mu = (b - 0.5 * sigma**2) / (sigma**2)
+
+ x1 = np.log(S / K) / sigma_sqrt_T + (1.0 + mu) * sigma_sqrt_T
+ x2 = np.log(S / H) / sigma_sqrt_T + (1.0 + mu) * sigma_sqrt_T
+ y1 = np.log(H**2 / (S * K)) / sigma_sqrt_T + (1.0 + mu) * sigma_sqrt_T
+ y2 = np.log(H / S) / sigma_sqrt_T + (1.0 + mu) * sigma_sqrt_T
+
+ df_q = np.exp(-q * T)
+ df_r = np.exp(-r * T)
+ hs_ratio = H / S
+
+ A = phi * S * df_q * norm.cdf(phi * x1) - phi * K * df_r * norm.cdf(phi * (x1 - sigma_sqrt_T))
+ B = phi * S * df_q * norm.cdf(phi * x2) - phi * K * df_r * norm.cdf(phi * (x2 - sigma_sqrt_T))
+ C = phi * S * df_q * (hs_ratio ** (2.0 * (mu + 1.0))) * norm.cdf(eta * y1) - phi * K * df_r * (
+ hs_ratio ** (2.0 * mu)
+ ) * norm.cdf(eta * (y1 - sigma_sqrt_T))
+ D = phi * S * df_q * (hs_ratio ** (2.0 * (mu + 1.0))) * norm.cdf(eta * y2) - phi * K * df_r * (
+ hs_ratio ** (2.0 * mu)
+ ) * norm.cdf(eta * (y2 - sigma_sqrt_T))
+
+ # Cash rebate component
+ if rebate > 0.0:
+ E = rebate * df_r * (norm.cdf(eta * (x2 - sigma_sqrt_T)) - (hs_ratio ** (2.0 * mu)) * norm.cdf(eta * (y2 - sigma_sqrt_T)))
+ else:
+ E = 0.0
+
+ if opt_type == _CALL:
+ if b_type == "down-and-out":
+ price = (A - C + E) if K >= H else (B - D + E)
+ elif b_type == "down-and-in":
+ price = (C + (rebate * df_r - E)) if K >= H else (A - B + D + (rebate * df_r - E))
+ elif b_type == "up-and-out":
+ price = E if K >= H else (A - B + C - D + E)
+ elif b_type == "up-and-in":
+ price = (A + (rebate * df_r - E)) if K >= H else (B - C + D + (rebate * df_r - E))
+ else:
+ raise ValueError(f"Unhandled barrier type {b_type}")
+ else: # PUT
+ if b_type == "down-and-out":
+ price = (A - B + C - D + E) if K >= H else E
+ elif b_type == "down-and-in":
+ price = (B - C + D + (rebate * df_r - E)) if K >= H else (A + (rebate * df_r - E))
+ elif b_type == "up-and-out":
+ price = (B - D + E) if K >= H else (A - C + E)
+ elif b_type == "up-and-in":
+ price = (A - B + D + (rebate * df_r - E)) if K >= H else (C + (rebate * df_r - E))
+ else:
+ raise ValueError(f"Unhandled barrier type {b_type}")
+
+ return float(max(0.0, price))
diff --git a/agent/tests/quantlib/test_options.py b/agent/tests/quantlib/test_options.py
index 6e429d9e0..d67d3ac9f 100644
--- a/agent/tests/quantlib/test_options.py
+++ b/agent/tests/quantlib/test_options.py
@@ -16,12 +16,16 @@ from __future__ import annotations
import math
+import numpy as np
import pytest
from src.quantlib.options import (
+ BARRIER_TYPES,
+ barrier_option_price,
bs_greeks,
bs_price,
implied_volatility,
+ normalise_barrier_type,
normalise_option_type,
)
@@ -499,3 +503,70 @@ def test_an_aliased_leg_prices_and_settles_as_the_same_side():
deep_itm = bs_price(200, 100, 0.01, 0.0, 0.2, alias) if folded == "call" else \
bs_price(50, 100, 0.01, 0.0, 0.2, alias)
assert deep_itm > 45.0
+
+
+# --------------------------------------------------------------------------
+# Barrier Options Tests
+# --------------------------------------------------------------------------
+
+
+class TestBarrierOptions:
+ """Analytical barrier option pricing tests and In-Out parity checks."""
+
+ @pytest.mark.parametrize(
+ ("S", "K", "H_down", "H_up", "T", "r", "sigma", "q"),
+ [
+ (100.0, 100.0, 90.0, 110.0, 0.5, 0.05, 0.25, 0.02),
+ (100.0, 95.0, 85.0, 115.0, 1.0, 0.03, 0.20, 0.0),
+ (100.0, 105.0, 90.0, 120.0, 0.75, 0.04, 0.30, 0.03),
+ ],
+ )
+ def test_in_out_parity_zero_rebate(self, S, K, H_down, H_up, T, r, sigma, q):
+ # Call options
+ vanilla_call = bs_price(S, K, T, r, sigma, "call", q=q)
+ doc = barrier_option_price(S, K, H_down, T, r, sigma, "down-and-out", "call", q=q)
+ dic = barrier_option_price(S, K, H_down, T, r, sigma, "down-and-in", "call", q=q)
+ assert doc + dic == pytest.approx(vanilla_call, rel=1e-5)
+
+ uoc = barrier_option_price(S, K, H_up, T, r, sigma, "up-and-out", "call", q=q)
+ uic = barrier_option_price(S, K, H_up, T, r, sigma, "up-and-in", "call", q=q)
+ assert uoc + uic == pytest.approx(vanilla_call, rel=1e-5)
+
+ # Put options
+ vanilla_put = bs_price(S, K, T, r, sigma, "put", q=q)
+ dop = barrier_option_price(S, K, H_down, T, r, sigma, "down-and-out", "put", q=q)
+ dip = barrier_option_price(S, K, H_down, T, r, sigma, "down-and-in", "put", q=q)
+ assert dop + dip == pytest.approx(vanilla_put, rel=1e-5)
+
+ uop = barrier_option_price(S, K, H_up, T, r, sigma, "up-and-out", "put", q=q)
+ uip = barrier_option_price(S, K, H_up, T, r, sigma, "up-and-in", "put", q=q)
+ assert uop + uip == pytest.approx(vanilla_put, rel=1e-5)
+
+ def test_in_out_parity_with_rebate(self):
+ S, K, H, T, r, sigma, q, rebate = 100.0, 100.0, 90.0, 0.5, 0.05, 0.25, 0.0, 5.0
+ vanilla_call = bs_price(S, K, T, r, sigma, "call", q=q)
+ doc = barrier_option_price(S, K, H, T, r, sigma, "down-and-out", "call", q=q, rebate=rebate)
+ dic = barrier_option_price(S, K, H, T, r, sigma, "down-and-in", "call", q=q, rebate=rebate)
+ expected_sum = vanilla_call + rebate * np.exp(-r * T)
+ assert doc + dic == pytest.approx(expected_sum, rel=1e-5)
+
+ def test_already_breached_barrier_behavior(self):
+ # Down-and-out when S <= H is knocked out immediately
+ assert barrier_option_price(85.0, 100.0, 90.0, 0.5, 0.05, 0.20, "down-and-out", "call", rebate=3.0) == pytest.approx(
+ 3.0 * np.exp(-0.05 * 0.5)
+ )
+ # Down-and-in when S <= H is already knocked in -> vanilla price
+ vanilla = bs_price(85.0, 100.0, 0.5, 0.05, 0.20, "call")
+ assert barrier_option_price(85.0, 100.0, 90.0, 0.5, 0.05, 0.20, "down-and-in", "call") == pytest.approx(
+ vanilla
+ )
+
+ def test_barrier_option_input_validation(self):
+ with pytest.raises(ValueError, match="strictly positive"):
+ barrier_option_price(-100.0, 100.0, 90.0, 1.0, 0.05, 0.2, "down-and-out")
+ with pytest.raises(ValueError, match="strictly positive"):
+ barrier_option_price(100.0, -100.0, 90.0, 1.0, 0.05, 0.2, "down-and-out")
+ with pytest.raises(ValueError, match="strictly positive"):
+ barrier_option_price(100.0, 100.0, -90.0, 1.0, 0.05, 0.2, "down-and-out")
+ with pytest.raises(ValueError, match="unknown barrier type"):
+ barrier_option_price(100.0, 100.0, 90.0, 1.0, 0.05, 0.2, "invalid-barrier")