Spaces:
Sleeping
Sleeping
File size: 9,192 Bytes
72fc0ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | """
Volatility surface construction from market option prices.
Builds implied volatility surfaces from:
- Market option prices (calls and puts)
- Strike-maturity grid
- Arbitrage-free constraints
The surface maps (strike, maturity) β implied volatility Ο(K, T).
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Optional
import numpy as np
import pandas as pd
from scipy.interpolate import RBFInterpolator, griddata
from quantlib_pro.options import implied_volatility
from quantlib_pro.utils.validation import ValidationError, require_positive
log = logging.getLogger(__name__)
@dataclass
class SurfacePoint:
"""Single point on volatility surface."""
strike: float
maturity: float # Years
implied_vol: float
market_price: float
option_type: str # 'call' or 'put'
moneyness: float # K/S
@dataclass
class VolatilitySurface:
"""Implied volatility surface."""
points: list[SurfacePoint]
spot_price: float
risk_free_rate: float
timestamp: float
def to_dataframe(self) -> pd.DataFrame:
"""Convert surface points to DataFrame."""
return pd.DataFrame([
{
'strike': p.strike,
'maturity': p.maturity,
'implied_vol': p.implied_vol,
'moneyness': p.moneyness,
'option_type': p.option_type,
}
for p in self.points
])
def get_strikes(self) -> np.ndarray:
"""Get unique strike prices."""
return np.unique([p.strike for p in self.points])
def get_maturities(self) -> np.ndarray:
"""Get unique maturities."""
return np.unique([p.maturity for p in self.points])
def get_atm_vol(self, maturity: float) -> Optional[float]:
"""
Get at-the-money volatility for a given maturity.
Parameters
----------
maturity : float
Time to maturity (years)
Returns
-------
float or None
ATM implied vol, or None if not found
"""
# Find points close to ATM (moneyness β 1.0)
atm_points = [
p for p in self.points
if abs(p.maturity - maturity) < 0.01 and abs(p.moneyness - 1.0) < 0.05
]
if not atm_points:
return None
return np.mean([p.implied_vol for p in atm_points])
def build_surface_from_prices(
option_prices: pd.DataFrame,
spot_price: float,
risk_free_rate: float = 0.02,
) -> VolatilitySurface:
"""
Build volatility surface from market option prices.
Parameters
----------
option_prices : pd.DataFrame
Columns: ['strike', 'maturity', 'price', 'option_type']
spot_price : float
Current spot price
risk_free_rate : float
Risk-free rate
Returns
-------
VolatilitySurface
Constructed volatility surface
"""
require_positive(spot_price, "spot_price")
required_cols = ['strike', 'maturity', 'price', 'option_type']
missing = set(required_cols) - set(option_prices.columns)
if missing:
raise ValidationError(f"option_prices missing columns: {missing}")
points = []
for _, row in option_prices.iterrows():
strike = row['strike']
maturity = row['maturity']
market_price = row['price']
option_type = row['option_type']
if maturity <= 0:
log.warning(f"Skipping expired option: K={strike}, T={maturity}")
continue
# Calculate implied volatility
try:
iv = implied_volatility(
market_price=market_price,
S=spot_price,
K=strike,
T=maturity,
r=risk_free_rate,
option_type=option_type,
)
if iv is None or iv <= 0:
log.warning(f"Invalid IV for K={strike}, T={maturity}: {iv}")
continue
moneyness = strike / spot_price
points.append(SurfacePoint(
strike=strike,
maturity=maturity,
implied_vol=iv,
market_price=market_price,
option_type=option_type,
moneyness=moneyness,
))
except Exception as e:
log.warning(f"Failed to calculate IV for K={strike}, T={maturity}: {e}")
continue
if not points:
raise ValidationError("No valid surface points computed")
return VolatilitySurface(
points=points,
spot_price=spot_price,
risk_free_rate=risk_free_rate,
timestamp=0.0,
)
def interpolate_surface(
surface: VolatilitySurface,
method: str = 'rbf',
) -> callable:
"""
Create interpolation function for volatility surface.
Parameters
----------
surface : VolatilitySurface
Volatility surface
method : str
Interpolation method: 'rbf', 'linear', 'cubic'
Returns
-------
callable
Function that takes (strike, maturity) and returns implied vol
"""
df = surface.to_dataframe()
strikes = df['strike'].values
maturities = df['maturity'].values
vols = df['implied_vol'].values
points = np.column_stack([strikes, maturities])
if method == 'rbf':
# Radial basis function interpolation (smooth)
interpolator = RBFInterpolator(points, vols, kernel='thin_plate_spline')
def interp_func(K: float, T: float) -> float:
result = interpolator([[K, T]])
return float(result[0])
return interp_func
elif method in ['linear', 'cubic']:
# Grid-based interpolation
def interp_func(K: float, T: float) -> float:
result = griddata(points, vols, (K, T), method=method)
return float(result) if not np.isnan(result) else surface.get_atm_vol(T) or 0.2
return interp_func
else:
raise ValidationError(f"Unknown interpolation method: {method}")
def extract_volatility_slice(
surface: VolatilitySurface,
maturity: float,
tolerance: float = 0.01,
) -> pd.DataFrame:
"""
Extract volatility smile for a specific maturity.
Parameters
----------
surface : VolatilitySurface
Volatility surface
maturity : float
Target maturity (years)
tolerance : float
Tolerance for maturity matching
Returns
-------
pd.DataFrame
Smile: columns ['strike', 'implied_vol', 'moneyness']
"""
matching_points = [
p for p in surface.points
if abs(p.maturity - maturity) < tolerance
]
if not matching_points:
raise ValidationError(f"No points found near maturity {maturity}")
df = pd.DataFrame([
{
'strike': p.strike,
'implied_vol': p.implied_vol,
'moneyness': p.moneyness,
}
for p in matching_points
])
return df.sort_values('strike')
def compute_volatility_skew(smile: pd.DataFrame) -> float:
"""
Compute volatility skew from a smile.
Skew = (IV_put - IV_call) for OTM options at symmetric strikes.
Approximated as slope of IV vs moneyness.
Parameters
----------
smile : pd.DataFrame
Volatility smile with ['moneyness', 'implied_vol']
Returns
-------
float
Skew coefficient (negative = put skew)
"""
if len(smile) < 2:
return 0.0
# Fit linear regression: IV = a + b * log(K/S)
log_moneyness = np.log(smile['moneyness'].values)
iv = smile['implied_vol'].values
# Slope coefficient
coeffs = np.polyfit(log_moneyness, iv, deg=1)
skew = coeffs[0] # Slope
return skew
def compute_volatility_smile_curvature(smile: pd.DataFrame) -> float:
"""
Compute smile curvature (convexity).
Measures how much the smile deviates from flat.
Positive curvature = U-shaped (typical).
Parameters
----------
smile : pd.DataFrame
Volatility smile
Returns
-------
float
Curvature coefficient
"""
if len(smile) < 3:
return 0.0
# Fit quadratic: IV = a + b*x + c*x^2
log_moneyness = np.log(smile['moneyness'].values)
iv = smile['implied_vol'].values
coeffs = np.polyfit(log_moneyness, iv, deg=2)
curvature = coeffs[0] # Quadratic term
return curvature
# βββ Convenience Aliases ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def construct_volatility_surface(*args, **kwargs):
"""
Alias for build_surface_from_prices.
This function provides backward compatibility for UI components
that use the construct_volatility_surface naming convention.
"""
return build_surface_from_prices(*args, **kwargs)
|