diff --git a/examples/scripts/equity/example_equity_volatility_swap.py b/examples/scripts/equity/example_equity_volatility_swap.py new file mode 100644 index 00000000..f553ff6f --- /dev/null +++ b/examples/scripts/equity/example_equity_volatility_swap.py @@ -0,0 +1,64 @@ +# ============================================================================ +# FINANCEPY EXAMPLES - EquityVolatilitySwap +# ============================================================================ +# +# Copyright (C) 2018-2026 Dominic O'Kane +# +# This example demonstrates the valuation of an equity volatility swap using +# static option replication of the underlying variance swap combined with a +# convexity adjustment for stochastic volatility (Demeterfi et al. 1999; +# Brockhaus and Long 2000). +# +# ============================================================================ + +import numpy as np + +from financepy.utils.date import Date +from financepy.market.volatility.equity_vol_curve import EquityVolCurve +from financepy.products.equity.equity_variance_swap import EquityVarianceSwap +from financepy.products.equity.equity_volatility_swap import EquityVolatilitySwap +from financepy.market.curves.flat_discount_curve import FlatDiscountCurve + + +def vol_skew(k, atm_vol, atm_k, skew): + """Simple linear implied-volatility skew.""" + return atm_vol + skew * (k - atm_k) + + +start_dt = Date(20, 3, 2018) +value_dt = Date(20, 3, 2018) +tenor = "3M" + +stock_price = 100.0 +r = 0.05 +q = 0.01 +t = 0.25 + +discount_curve = FlatDiscountCurve(value_dt, r) +dividend_curve = FlatDiscountCurve(value_dt, q) + +strikes = np.linspace(50.0, 160.0, 23) +vols = vol_skew(strikes, 0.20, 100.0, -0.0015) +vol_curve = EquityVolCurve(strikes, vols, stock_price, t, r, q) + +var_swap = EquityVarianceSwap(start_dt, tenor, 0.20**2) +vol_swap = EquityVolatilitySwap(start_dt, tenor, 0.20, notional=1_000_000.0) + +fair_var = var_swap.fair_strike( + value_dt, stock_price, dividend_curve, vol_curve, 12, 12, 5.0, discount_curve +) +print(f"Fair variance strike : {fair_var:.6f} (sqrt = {np.sqrt(fair_var):.6f})") + +for nu in [0.0, 0.25, 0.50, 0.75]: + fair_vol = vol_swap.fair_strike( + value_dt, + stock_price, + dividend_curve, + vol_curve, + 12, + 12, + 5.0, + discount_curve, + vol_of_vol=nu, + ) + print(f"Fair vol strike (nu={nu:4.2f}) : {fair_vol:.6f}") diff --git a/financepy/products/equity/__init__.py b/financepy/products/equity/__init__.py index 222f4f67..7f56bf87 100644 --- a/financepy/products/equity/__init__.py +++ b/financepy/products/equity/__init__.py @@ -17,6 +17,7 @@ from .equity_rainbow_option import * from .equity_vanilla_option import * from .equity_variance_swap import * + from .equity_volatility_swap import * from .equity_one_touch_option import * from .equity_forward import * from .equity_swap_leg import * diff --git a/financepy/products/equity/equity_volatility_swap.py b/financepy/products/equity/equity_volatility_swap.py new file mode 100644 index 00000000..cbac4406 --- /dev/null +++ b/financepy/products/equity/equity_volatility_swap.py @@ -0,0 +1,267 @@ +############################################################################## +# Copyright (C) 2018-2026 Dominic O'Kane +############################################################################## + +from typing import Union + +import numpy as np + +from ...utils.error import FinError +from ...utils.date import Date +from ...utils.global_vars import ONE_MILLION, G_DAYS_IN_YEAR +from ...utils.helpers import label_to_string, check_argument_types +from ...market.curves.discount_curve import DiscountCurve + +from .equity_variance_swap import EquityVarianceSwap + +######################################################################################## + + +class EquityVolatilitySwap: + """Class for managing an equity volatility swap contract. + + A volatility swap exchanges realised annualised volatility over + [start_dt, maturity_dt] against a fixed strike volatility. Because + volatility is a concave function of variance (sqrt(V_T)), the fair + volatility strike is strictly less than the square root of the fair + variance strike whenever volatility is stochastic (Jensen's inequality). + """ + + def __init__( + self, + start_dt: Date, + maturity_dt_or_tenor: Union[Date, str], + strike_volatility: float, + notional: float = ONE_MILLION, + pay_strike_flag: bool = True, + ) -> None: + """Create an equity volatility swap contract.""" + + check_argument_types(self.__init__, locals()) + + if strike_volatility < 0.0: + raise FinError("Strike volatility must be non-negative") + + if isinstance(maturity_dt_or_tenor, Date): + maturity_dt = maturity_dt_or_tenor + else: + maturity_dt = start_dt.add_tenor(maturity_dt_or_tenor) + + if start_dt >= maturity_dt: + raise FinError("Start date after or same as maturity date") + + self.start_dt = start_dt + self.maturity_dt = maturity_dt + self.strike_volatility = strike_volatility + self.notional = notional + self.pay_strike_flag = pay_strike_flag + + # Underlying variance swap used for static replication + self._var_swap = EquityVarianceSwap( + start_dt, + maturity_dt, + strike_volatility * strike_volatility, + notional, + pay_strike_flag, + ) + + # Replication portfolio is stored for inspection via print_weights() + self.num_put_options = 0 + self.num_call_options = 0 + self.put_wts = [] + self.put_strikes = [] + self.call_wts = [] + self.call_strikes = [] + + ########################################################################### + + def value( + self, + value_dt: Date, + realised_vol: float, + fair_strike_vol: float, + discount_curve: DiscountCurve, + ) -> float: + """Value the volatility swap from realised and remaining fair volatility. + + Expected total variance over [start_dt, maturity_dt] is aggregated in + variance space (time-weighted average of realised variance and + remaining fair variance) and converted back to volatility. Paying the + strike receives the floating volatility payoff; receiving the strike + reverses the net payoff. + """ + + if value_dt < self.start_dt or value_dt > self.maturity_dt: + raise FinError("Valuation date must be within the volatility swap life") + + if realised_vol < 0.0 or fair_strike_vol < 0.0: + raise FinError("Realised and fair strike volatilities must be non-negative") + + t1 = (value_dt - self.start_dt) / G_DAYS_IN_YEAR + t2 = (self.maturity_dt - self.start_dt) / G_DAYS_IN_YEAR + + expected_variance = (t1 * (realised_vol**2) + (t2 - t1) * (fair_strike_vol**2)) / t2 + expected_volatility = float(np.sqrt(expected_variance)) + + payoff = expected_volatility - self.strike_volatility + if not self.pay_strike_flag: + payoff = -payoff + + df = discount_curve.df(self.maturity_dt) + v = payoff * self.notional * df + return v + + ########################################################################### + + @staticmethod + def convexity_adjustment_from_var_of_var( + fair_variance: float, + var_of_variance: float, + ) -> float: + """Second-order Taylor / Brockhaus-Long convexity adjustment. + + Approximates sqrt(E[V_T]) - E[sqrt(V_T)] ~= Var(V_T) / (8 * E[V_T]^(3/2)). + """ + + if fair_variance <= 0.0: + raise FinError("Fair variance must be positive") + if var_of_variance < 0.0: + raise FinError("Variance of variance must be non-negative") + + return float(var_of_variance / (8.0 * (fair_variance**1.5))) + + ########################################################################### + + @staticmethod + def fair_strike_from_variance( + fair_variance: float, + t_mat: float, + vol_of_vol: float = 0.0, + ) -> float: + """Convert a fair variance strike into a fair volatility strike. + + Applies the second-order convexity adjustment assuming lognormal + volatility dynamics with annualised vol-of-vol `vol_of_vol` (nu), where + Var(V_bar) ~= (4/3) * nu^2 * T * K_var^2, yielding: + K_vol ~= sqrt(K_var) * (1 - (1/6) * nu^2 * T). + When vol_of_vol == 0.0, returns sqrt(K_var). + """ + + if fair_variance < 0.0: + raise FinError("Fair variance must be non-negative") + if t_mat < 0.0: + raise FinError("Time to maturity must be non-negative") + if vol_of_vol < 0.0: + raise FinError("Volatility of volatility must be non-negative") + + if fair_variance == 0.0: + return 0.0 + + var_of_variance = (4.0 / 3.0) * (vol_of_vol**2) * t_mat * (fair_variance**2) + adj = EquityVolatilitySwap.convexity_adjustment_from_var_of_var( + fair_variance, var_of_variance + ) + fair_vol = float(np.sqrt(fair_variance) - adj) + if fair_vol < 0.0: + raise FinError( + "Convexity adjustment exceeds sqrt(fair_variance); " + "second-order approximation breaks down for this vol_of_vol and maturity" + ) + return fair_vol + + ########################################################################### + + def fair_strike_approx( + self, + value_dt: Date, + fwd_stock_price: float, + strikes: np.ndarray, + volatilities: np.ndarray, + vol_of_vol: float = 0.0, + ) -> float: + """Approximate the fair volatility strike from a linear skew curve + (Demeterfi et al. 1999) with an optional vol-of-vol convexity adjustment.""" + + fair_var = self._var_swap.fair_strike_approx( + value_dt, fwd_stock_price, strikes, volatilities + ) + t_mat = (self.maturity_dt - value_dt) / G_DAYS_IN_YEAR + return self.fair_strike_from_variance(fair_var, t_mat, vol_of_vol) + + ########################################################################### + + def fair_strike( + self, + value_dt: Date, + stock_price: float, + dividend_curve: DiscountCurve, + volatility_curve, + num_call_options: int, + num_put_options: int, + strike_spacing: float, + discount_curve: DiscountCurve, + use_forward: bool = True, + vol_of_vol: float = 0.0, + ) -> float: + """Calculate the fair volatility strike via static option replication of + the underlying variance swap (Demeterfi et al. 1999) minus a convexity + adjustment for stochastic volatility.""" + + fair_var = self._var_swap.fair_strike( + value_dt, + stock_price, + dividend_curve, + volatility_curve, + num_call_options, + num_put_options, + strike_spacing, + discount_curve, + use_forward, + ) + + # Mirror replication portfolio state on self + self.num_put_options = self._var_swap.num_put_options + self.num_call_options = self._var_swap.num_call_options + self.put_wts = self._var_swap.put_wts + self.put_strikes = self._var_swap.put_strikes + self.call_wts = self._var_swap.call_wts + self.call_strikes = self._var_swap.call_strikes + + t_mat = (self.maturity_dt - value_dt) / G_DAYS_IN_YEAR + return self.fair_strike_from_variance(fair_var, t_mat, vol_of_vol) + + ########################################################################### + + def realised_volatility(self, close_prices, use_logs: bool = True) -> float: + """Calculate annualised realised volatility from closing prices.""" + + var = self._var_swap.realised_variance(close_prices, use_logs=use_logs) + return float(np.sqrt(var)) + + ########################################################################### + + def print_weights(self) -> None: + """Print the list of puts and calls used to replicate the underlying + variance swap hedge.""" + + self._var_swap.print_weights() + + ########################################################################### + + def __repr__(self) -> str: + s = label_to_string("OBJECT TYPE", type(self).__name__) + s += label_to_string("START DATE", self.start_dt) + s += label_to_string("MATURITY DATE", self.maturity_dt) + s += label_to_string("STRIKE VOLATILITY", self.strike_volatility) + s += label_to_string("NOTIONAL", self.notional) + s += label_to_string("PAY STRIKE FLAG", self.pay_strike_flag, "") + return s + + ########################################################################### + + def _print(self) -> None: + """Simple print function for backward compatibility.""" + print(self) + + +######################################################################################## diff --git a/tests/unit/test_equity_volatility_swap.py b/tests/unit/test_equity_volatility_swap.py new file mode 100644 index 00000000..202bc3e1 --- /dev/null +++ b/tests/unit/test_equity_volatility_swap.py @@ -0,0 +1,199 @@ +# Copyright (C) 2018-2026 Dominic O'Kane + +from decimal import Decimal, localcontext +import numpy as np +import pytest + +from financepy.market.curves.flat_discount_curve import FlatDiscountCurve +from financepy.market.volatility.equity_vol_curve import EquityVolCurve +from financepy.products.equity.equity_variance_swap import EquityVarianceSwap +from financepy.products.equity.equity_volatility_swap import EquityVolatilitySwap +from financepy.utils.date import Date +from financepy.utils.error import FinError +from financepy.utils.global_vars import G_DAYS_IN_YEAR + + +def _vol_skew(k, atm_vol, atm_k, skew): + return atm_vol + skew * (k - atm_k) + + +def test_fair_strike_zero_vol_of_vol_matches_sqrt_variance(): + """With vol_of_vol=0, fair volatility strike equals sqrt(fair variance strike).""" + start_dt = Date(20, 3, 2018) + value_dt = Date(20, 3, 2018) + tenor = "3M" + s = 100.0 + r = 0.05 + q = 0.01 + t = 0.25 + + discount_curve = FlatDiscountCurve(value_dt, r) + dividend_curve = FlatDiscountCurve(value_dt, q) + + strikes = np.linspace(50.0, 160.0, 23) + vols = _vol_skew(strikes, 0.20, 100.0, -0.0015) + vol_curve = EquityVolCurve(strikes, vols, s, t, r, q) + + var_swap = EquityVarianceSwap(start_dt, tenor, 0.04) + vol_swap = EquityVolatilitySwap(start_dt, tenor, 0.20) + + k_var = var_swap.fair_strike( + value_dt, s, dividend_curve, vol_curve, 12, 12, 5.0, discount_curve, True + ) + k_vol = vol_swap.fair_strike( + value_dt, s, dividend_curve, vol_curve, 12, 12, 5.0, discount_curve, True, vol_of_vol=0.0 + ) + + assert k_vol == pytest.approx(np.sqrt(k_var), rel=1e-12) + assert vol_swap.num_put_options == var_swap.num_put_options + assert vol_swap.num_call_options == var_swap.num_call_options + + k_var_approx = var_swap.fair_strike_approx(value_dt, s, strikes, vols) + k_vol_approx = vol_swap.fair_strike_approx(value_dt, s, strikes, vols, vol_of_vol=0.0) + assert k_vol_approx == pytest.approx(np.sqrt(k_var_approx), rel=1e-12) + + +def test_fair_strike_flat_vol_limit(): + """Under flat volatility and zero vol-of-vol, fair strike approaches sigma.""" + value_dt = Date(1, 1, 2026) + maturity_dt = Date(1, 1, 2027) + t_exp = (maturity_dt - value_dt) / G_DAYS_IN_YEAR + r, q, sigma, stock_price = 0.05, 0.02, 0.25, 100.0 + + discount_curve = FlatDiscountCurve(value_dt, r) + dividend_curve = FlatDiscountCurve(value_dt, q) + strikes = np.linspace(20.0, 300.0, 281) + vol_curve = EquityVolCurve( + strikes, np.full(len(strikes), sigma), stock_price, t_exp, r, q + ) + + vol_swap = EquityVolatilitySwap(value_dt, maturity_dt, sigma) + fair_vol = vol_swap.fair_strike( + value_dt, stock_price, dividend_curve, vol_curve, 120, 120, 1.0, discount_curve + ) + assert abs(fair_vol - sigma) / sigma < 0.01 + + +def test_convexity_adjustment_reduces_fair_strike(): + """By Jensen's inequality, positive vol-of-vol strictly lowers fair vol strike.""" + start_dt = Date(1, 1, 2026) + maturity_dt = Date(1, 1, 2027) + t_mat = (maturity_dt - start_dt) / G_DAYS_IN_YEAR + fair_var = 0.04 + + k_vol_0 = EquityVolatilitySwap.fair_strike_from_variance(fair_var, t_mat, vol_of_vol=0.0) + k_vol_1 = EquityVolatilitySwap.fair_strike_from_variance(fair_var, t_mat, vol_of_vol=0.3) + k_vol_2 = EquityVolatilitySwap.fair_strike_from_variance(fair_var, t_mat, vol_of_vol=0.6) + + assert k_vol_0 == pytest.approx(0.20, rel=1e-12) + assert k_vol_2 < k_vol_1 < k_vol_0 + expected_k1 = 0.20 * (1.0 - (1.0 / 6.0) * (0.3**2) * t_mat) + assert k_vol_1 == pytest.approx(expected_k1, rel=1e-12) + + +def test_convexity_adjustment_against_monte_carlo_lognormal_vol(): + """Verify the analytical convexity adjustment against Monte Carlo simulation + of lognormal instantaneous volatility d(sigma)/sigma = nu dW.""" + rng = np.random.default_rng(42) + sigma0 = 0.25 + nu = 0.40 + t_mat = 1.0 + num_steps = 252 + num_paths = 40_000 + dt = t_mat / num_steps + + z = rng.standard_normal((num_paths, num_steps)) + log_sigma = np.zeros((num_paths, num_steps + 1)) + log_sigma[:, 0] = np.log(sigma0) + drift = -0.5 * (nu**2) * dt + vol_step = nu * np.sqrt(dt) + log_sigma[:, 1:] = log_sigma[:, [0]] + np.cumsum(drift + vol_step * z, axis=1) + + sigma_paths = np.exp(log_sigma) + # Integrated variance over [0, T] using trapezoidal rule on sigma_t^2 + v_bar = np.trapezoid(sigma_paths**2, dx=dt, axis=1) / t_mat + mc_fair_var = float(np.mean(v_bar)) + mc_fair_vol = float(np.mean(np.sqrt(v_bar))) + + analytic_fair_vol = EquityVolatilitySwap.fair_strike_from_variance( + mc_fair_var, t_mat, vol_of_vol=nu + ) + # Second-order Taylor matches MC E[sqrt(V_bar)] within ~5 bps + assert mc_fair_vol < np.sqrt(mc_fair_var) + assert abs(analytic_fair_vol - mc_fair_vol) < 5e-4 + + +@pytest.mark.parametrize("pay_strike", [None, True, False], ids=["default", "pay", "receive"]) +@pytest.mark.parametrize( + "elapsed, realised, remaining", + [ + (0, "0.25", "0.18"), + (91, "0.30", "0.15"), + (200, "0.12", "0.22"), + (365, "0.24", "0.18"), + (365, "0.20", "0.18"), + ], + ids=["inception", "mid_above", "mid_below", "maturity", "par"], +) +def test_volatility_swap_direction_and_valuation(pay_strike, elapsed, realised, remaining): + """Receiving the strike reverses the discounted net payoff, and mid-life + expected volatility aggregates in variance space.""" + start = Date(1, 1, 2025) + maturity = Date(1, 1, 2026) + value_dt = start.add_days(elapsed) + curve = FlatDiscountCurve(value_dt, 0.031) + kwargs = {} if pay_strike is None else {"pay_strike_flag": pay_strike} + swap = EquityVolatilitySwap(start, maturity, 0.20, notional=1_000_000.0, **kwargs) + + with localcontext() as ctx: + ctx.prec = 60 + total = Decimal(365) + elapsed_d = Decimal(elapsed) + left = total - elapsed_d + df = (-Decimal("0.031") * left / total).exp() + expected_var = ( + elapsed_d * (Decimal(realised) ** 2) + left * (Decimal(remaining) ** 2) + ) / total + expected_vol = expected_var.sqrt() + signed = -1 if pay_strike is False else 1 + expected = signed * df * Decimal(1_000_000) * (expected_vol - Decimal("0.20")) + + actual = swap.value(value_dt, float(realised), float(remaining), curve) + assert actual == pytest.approx(float(expected), rel=1e-12, abs=1e-10) + + +def test_realised_volatility_constant_returns(): + """Constant daily log returns r give annualised realised vol sqrt(252) * |r|.""" + start = Date(1, 1, 2025) + swap = EquityVolatilitySwap(start, "3M", 0.20) + daily_r = 0.01 + prices = 100.0 * np.exp(daily_r * np.arange(21)) + assert swap.realised_volatility(prices, use_logs=True) == pytest.approx( + np.sqrt(252.0) * daily_r, rel=1e-12 + ) + + +def test_validation_errors(): + """Invalid inputs raise FinError.""" + start = Date(1, 1, 2025) + maturity = Date(1, 1, 2026) + curve = FlatDiscountCurve(start, 0.03) + + with pytest.raises(FinError): + EquityVolatilitySwap(start, maturity, -0.1) + + with pytest.raises(FinError): + EquityVolatilitySwap(maturity, start, 0.2) + + swap = EquityVolatilitySwap(start, maturity, 0.20) + with pytest.raises(FinError): + swap.value(start.add_days(-1), 0.2, 0.2, curve) + + with pytest.raises(FinError): + swap.value(start, -0.1, 0.2, curve) + + with pytest.raises(FinError): + EquityVolatilitySwap.fair_strike_from_variance(0.04, 1.0, vol_of_vol=-0.1) + + with pytest.raises(FinError): + EquityVolatilitySwap.fair_strike_from_variance(0.04, 1.0, vol_of_vol=3.0)