SVI Volatility Surface in Python: Fit, Then Audit

A production volatility surface is not one regression — it is a pipeline. You pull a live option chain, cut an out-of-the-money slice, build the forward and K0 the way the Cboe VIX methodology does, convert mid-quotes to total variance, fit raw SVI per expiry with bounded least squares, and then run two explicit pass/fail arbitrage gates before the surface is allowed near a downstream model.

The pipeline: fit, then audit

The Gatheral–Jacquier SVI paper (arXiv:1204.0646) supplies both the parameterization and the acceptance criteria: a slice is butterfly-arbitrage-free iff g(k) ≥ 0, and the surface is calendar-arbitrage-free iff total variance is non-decreasing in maturity. Treat those as gates on a fitted object, not as theory decoration — a fit that violates them is discarded, re-seeded, or rejected, in that order.

Pulling the chain and cutting the OTM slice

The raw material is a live chain: yfinance exposes expirations through Ticker.options and per-expiry calls and puts through Ticker.option_chain(date), whose DataFrames carry bid, ask, strike and open interest (docs). The conventions below — OTM-only strikes, dropping zero bids, mid = (bid + ask)/2 — mirror how the VIX index aggregates only out-of-the-money options with a non-zero bid at mid-quote. The symbol here is illustrative, not a recommendation.

import numpy as np
import pandas as pd
import yfinance as yf

# Illustrative index symbol only -- not a trading recommendation.
TICKER = "^SPX"
RISK_FREE = 0.04  # flat illustrative rate; production code interpolates a Treasury curve

def pull_chain(ticker: str) -> dict:
    """Return {expiry_date: option_chain_object} for every listed expiry."""
    tk = yf.Ticker(ticker)
    return {exp: tk.option_chain(exp) for exp in tk.options}

def otm_slice(chain, spot: float, call: bool) -> pd.DataFrame:
    """One side of the chain, OTM only, zero bids dropped, mid computed."""
    side = chain.calls if call else chain.puts
    df = side[(side["bid"] > 0) & (side["ask"] > 0)].copy()
    if call:
        df = df[df["strike"] >= spot]
    else:
        df = df[df["strike"] <= spot]
    df["mid"] = (df["bid"] + df["ask"]) / 2.0
    return df[["strike", "bid", "ask", "mid"]].reset_index(drop=True)

def forward_and_k0(calls: pd.DataFrame, puts: pd.DataFrame,
                   T: float, r: float):
    """Cboe-style forward: pick the strike where |C - P| is smallest,
    then F = K + e^(rT) * (C - P); K0 is the first strike <= F."""
    merged = calls[["strike", "mid"]].merge(
        puts[["strike", "mid"]], on="strike", suffixes=("_c", "_p"))
    merged["abs_diff"] = (merged["mid_c"] - merged["mid_p"]).abs()
    row = merged.loc[merged["abs_diff"].idxmin()]
    K, c, p = float(row["strike"]), float(row["mid_c"]), float(row["mid_p"])
    F = K + np.exp(r * T) * (c - p)
    strikes = np.sort(calls["strike"].unique())
    k0 = float(strikes[strikes <= F][-1])
    return F, k0

Forward and K0 follow the VIX playbook

You do not need to invent a forward convention when the Cboe Volatility Index methodology, version 6.0 (last revised 26 February 2026) publishes one: the forward is F = strike + e^(RT) · (call − put) evaluated at the strike where the call–put difference is smallest, and K0 is the first strike at or immediately below F. The same document specifies Treasury constant-maturity yields with a cubic spline across expirations for the rate curve, and a 30-day bracket (its worked example uses a 24-day near term and a 31-day next term) for term selection on SPX options.

From mid-quotes to total variance

Each OTM mid-quote converts to implied volatility, then to total variance w = σ²T, and each strike maps to log-moneyness k = ln(K/F). Recomputing IV from mid-quotes with py_vollib — whose core is Peter Jaeckel’s LetsBeRational algorithm (vollib.org) — is preferable to trusting a vendor’s precomputed impliedVolatility column, because you control the rate, the time basis and the sanity band. The IV band used below is set by hand rather than derived: its job is to drop conversion artifacts before they reach the fit.

Raw SVI and what its five parameters do

Raw SVI, from Gatheral & Jacquier, eq. 3.1, parameterizes total implied variance as

w(k) = a + b · { ρ(k − m) + √((k − m)² + σ²) }

with a ∈ ℝ, b ≥ 0, |ρ| < 1, m ∈ ℝ, σ > 0, plus the constraint a + b·σ·√(1 − ρ²) ≥ 0 guaranteeing w ≥ 0 for all k. The paper’s own reading of the parameters: increasing a lifts the general variance level (a vertical translation); increasing b steepens both wings and tightens the smile; increasing ρ flattens the left wing and steepens the right — a counter-clockwise rotation; increasing m shifts the smile right; increasing σ reduces ATM curvature. The paper explicitly excludes ρ = ±1 (monotone smiles) and σ = 0 (a linear smile). For intuition on how these shapes map to traded skew, see our walkthrough of implied volatility skew in AI semiconductor names.

Bounded least squares per expiry

Fit each expiry independently with scipy.optimize.least_squares, which supports bounds and x_scale parameter scaling. The bounds encode the paper’s admissible region directly — b ≥ 0, |ρ| ≤ 1 − ε, σ ≥ ε — and the positivity condition a + b·σ·√(1 − ρ²) ≥ 0 is enforced as an explicit acceptance filter over multiple starting points. Starting-value heuristics and multi-start breadth matter and are deliberately left as tuning conventions here; what is not optional is rejecting any solution that violates the positivity condition, because such a slice has no valid interpretation as total variance.

from py_vollib.black_scholes.implied_volatility import implied_volatility
from scipy.optimize import least_squares

EPS = 1e-8

def to_total_variance(df: pd.DataFrame, S: float, F: float,
                      T: float, r: float) -> pd.DataFrame:
    """Mid-quotes -> implied vol (py_vollib) -> total variance w = iv^2 * T."""
    rows = []
    for _, row in df.iterrows():
        flag = "c" if row["strike"] >= F else "p"
        try:
            iv = implied_volatility(float(row["mid"]), S, float(row["strike"]),
                                    T, r, flag)
        except Exception:
            continue
        if 0.01 < iv < 3.0:  # sanity band: a convention, not a law
            rows.append({"strike": float(row["strike"]), "iv": iv})
    ivs = pd.DataFrame(rows)
    ivs["k"] = np.log(ivs["strike"] / F)
    ivs["w"] = ivs["iv"] ** 2 * T
    return ivs

def svi_w(k, a, b, rho, m, sigma):
    """Raw SVI total variance, Gatheral-Jacquier eq. 3.1."""
    return a + b * (rho * (k - m) + np.sqrt((k - m) ** 2 + sigma ** 2))

def raw_svi_fit(k: np.ndarray, w: np.ndarray) -> dict:
    """Bounded raw-SVI least squares with a positivity-condition filter."""
    def residuals(p):
        return svi_w(k, *p) - w

    def positivity_ok(p):
        a, b, rho, m, sigma = p
        # a + b*sigma*sqrt(1 - rho^2) >= 0 keeps w >= 0 for every k
        return a + b * sigma * np.sqrt(1.0 - rho ** 2) >= 0.0

    lo = [-np.inf, 0.0, -(1.0 - EPS), -np.inf, EPS]
    hi = [ np.inf, np.inf,  (1.0 - EPS),  np.inf, np.inf]

    best = None
    for a0 in (0.0, float(np.median(w))):
        for m0 in (0.0, float(np.mean(k))):
            res = least_squares(
                residuals, x0=[a0, 0.1, 0.0, m0, 0.1],
                bounds=(lo, hi),
                x_scale=[max(float(np.median(w)), EPS), 0.1, 0.1, 1.0, 0.1],
            )
            if positivity_ok(res.x) and (best is None or res.cost < best.cost):
                best = res
    if best is None:
        raise RuntimeError("no admissible SVI solution found for this slice")
    a, b, rho, m, sigma = best.x
    return {"a": a, "b": b, "rho": rho, "m": m, "sigma": sigma,
            "cost": float(best.cost)}

Butterfly audit: g(k) ≥ 0 as a pass/fail gate

Gatheral & Jacquier’s Lemma 2.2 states the acceptance criterion exactly: a slice is free of butterfly arbitrage if and only if g(k) ≥ 0 for all real k, together with lim(k → +∞) d₊(k) = −∞. For finite SVI parameters the limit holds by the asymptotic shape of w, so g(k) ≥ 0 is the operative check in code — and satisfying both implies a non-negative risk-neutral density.

g(k) = (1 − k·w′(k)/(2w(k)))² − (w′(k)²/4)·(1/w(k) + 1/4) + w″(k)/2,

and satisfying it implies a non-negative risk-neutral density. Differentiating the SVI formula gives w′(k) = b·ρ + b·(k − m)/√((k − m)² + σ²) and w″(k) = b·σ²/((k − m)² + σ²)^(3/2). The caveat here is practical rather than theoretical: nothing in a per-slice least-squares objective prevents g(k) from going negative in the wings, where quotes are thin and b and ρ are weakly identified. Evaluate g on a dense log-moneyness grid, report min(g), and fail the slice if it is negative anywhere.

Calendar audit on a shared log-moneyness grid

The second gate comes straight from the paper’s calendar-arbitrage characterization (§2.1 of arXiv:1204.0646): total implied variance must be non-decreasing in maturity. Because each expiry was fitted independently, nothing guarantees this — so evaluate every fitted slice on one shared k grid (resampling with scipy.interpolate.interp1d if your grids differ) and assert the ordering. A failure here is a typical symptom of a short-dated slice whose fitted variance level overshoots its neighbor, and the fix is a refit with tighter wing discipline, not a silent patch.

def svi_derivs(k, a, b, rho, m, sigma):
    """w, w', w'' obtained by differentiating the SVI formula."""
    dk = k - m
    root = np.sqrt(dk ** 2 + sigma ** 2)
    w   = a + b * (rho * dk + root)
    wp  = b * rho + b * dk / root
    wpp = b * sigma ** 2 / root ** 3
    return w, wp, wpp

def g_function(k, a, b, rho, m, sigma):
    """Gatheral-Jacquier butterfly density test function g(k)."""
    w, wp, wpp = svi_derivs(k, a, b, rho, m, sigma)
    return (1.0 - k * wp / (2.0 * w)) ** 2 \
        - (wp ** 2 / 4.0) * (1.0 / w + 0.25) \
        + wpp / 2.0

def butterfly_audit(params, k_lo=-2.0, k_hi=2.0, n=4001) -> dict:
    """Dense-grid g(k) evaluation; PASS requires min(g) >= 0.
    `params` may be the dict returned by raw_svi_fit (extra keys ignored)."""
    p = {key: params[key] for key in ("a", "b", "rho", "m", "sigma")}
    k = np.linspace(k_lo, k_hi, n)
    g = g_function(k, **p)
    return {"min_g": float(g.min()),
            "argmin_k": float(k[np.argmin(g)]),
            "pass": bool(g.min() >= 0.0)}

def calendar_audit(fits: dict, k_grid: np.ndarray) -> dict:
    """fits = {T: params}. Total variance must be non-decreasing in T
    on one shared log-moneyness grid."""
    maturities = sorted(fits)
    ws = np.vstack([svi_derivs(k_grid, **{key: fits[T][key] for key in
                                          ("a", "b", "rho", "m", "sigma")})[0]
                    for T in maturities])
    diffs = np.diff(ws, axis=0)
    return {"maturities": maturities,
            "min_increase": float(diffs.min()),
            "pass": bool(diffs.min() >= 0.0)}

SVI variants and honest baselines

Raw SVI is not the only surface model, and part of the audit discipline is knowing what each alternative is actually for. Natural SVI reparameterizes the same five parameters for better-conditioned optimization; SSVI imposes a single surface-wide structure with the paper’s surface-level no-arbitrage theorems; a polynomial baseline and an isotonic fit serve as diagnostics rather than production surfaces. The honest comparison is about structure and guarantees, not fit-quality numbers:

Model Parameters fitted Stated no-arbitrage condition What it is honestly good for Documented at
Raw SVI 5 per expiry (a, b, ρ, m, σ) g(k) ≥ 0 per slice (butterfly); w non-decreasing in T (calendar) Per-expiry smile fitting with explicit, checkable arbitrage gates Gatheral & Jacquier
Natural SVI 5 per expiry, reparameterized Same slice conditions, rewritten directly in the new parameters Same smiles with better-behaved optimization geometry SVI paper (HTML)
SSVI Few, shared across the surface Surface-wide conditions on total variance and correlation from the paper’s theorems Fitting all expiries jointly under one coherent structure SVI paper (PDF)
Polynomial smile (baseline) degree + 1 coefficients None — wings diverge and no density guarantee Quick visual baseline for skew direction and curvature numpy.polyfit
Isotonic regression (sanity check) None (monotone fit) Enforces monotonicity in whatever variable you fit Calendar-ordering diagnostic on total variance across maturities sklearn IsotonicRegression

For a deeper treatment of surface behavior beyond SVI, Gatheral’s The Volatility Surface: A Practitioner’s Guide remains the standard reference, and QuantLib implements several of these models if you want a battle-tested library behind your own pipeline.

FAQ

Why does my fit pass the butterfly audit but fail the calendar audit?

Because the two gates are independent: butterfly is a per-slice condition on the shape of w(k), while calendar is a cross-slice condition on how w grows with maturity (the paper’s §2.1 criterion). Independent per-expiry fits optimize each slice in isolation, so a short-dated slice can sit above a longer-dated one on the shared k grid. The remedy is a refit of the offending slice — usually with a lower-variance starting point — not a post-hoc adjustment of the fitted parameters.

How many strikes does a slice need before the fit means anything?

There is no universal minimum, and any threshold is a convention rather than a fact. What matters qualitatively: enough strikes on both sides of K0 to constrain the wings, enough liquid quotes near the money to pin a and m, and enough total points that five parameters are not fitting noise. Slices with sparse wings should be flagged as low-confidence regardless of whether the optimizer returns a solution, because b and ρ are precisely the parameters the wings determine.

Should I fit SVI to implied volatilities or directly to prices?

Fitting to total variance is the standard route because the SVI parameterization and both arbitrage conditions are stated in w(k), not in prices — and it is computationally simpler, since IV conversion via py_vollib happens once per quote. Fitting directly to mid-quotes weights illiquid far-wing quotes differently and couples the optimizer to a pricing model, which is why most practical pipelines convert first and fit second. Either way, the audit gates are evaluated on the fitted w(k), so the acceptance criteria do not change.

Can I use the fitted surface to forecast volatility?

No — SVI interpolates and lightly extrapolates the current surface; it is a snapshot, not a forecast. For forward-looking work, pair the surface with time-series models such as our GARCH volatility forecasting pipeline in Python and cross-check against realized volatility estimators. The surface tells you what the market prices today; the forecast layer tells you whether that price is rich or cheap relative to realized dynamics, which is the input a volatility targeting strategy actually consumes.

The Bottom Line

Treat SVI as a fit-then-audit pipeline, and make the audit the deliverable. Pull the chain, apply OTM and non-zero-bid conventions, build F and K0 exactly as the Cboe VIX methodology specifies, convert mids to total variance with py_vollib, fit raw SVI per expiry under the paper’s parameter bounds, and then enforce g(k) ≥ 0 per slice and non-decreasing total variance across maturities as hard acceptance gates. A surface that fails either gate is not a slightly worse surface — it is not a valid volatility surface at all.

How This Guide Was Built

This post is a source-transcription and reference-implementation effort, not a live trading study. The SVI parameterization, parameter-effect readings, positivity constraint, butterfly g(k) criterion and calendar condition were transcribed from Gatheral & Jacquier, “Arbitrage-free SVI volatility surfaces” (arXiv:1204.0646); the forward, K0, mid-quote, zero-bid-filter, rate-curve and 30-day-bracket conventions were transcribed from the Cboe Volatility Index methodology, version 6.0, last revised 26 February 2026. Library behavior was checked against the yfinance, py_vollib and SciPy documentation. No live chains were fitted, no fit-quality numbers are reported, and nothing here is investment advice — the code is a pipeline scaffold for readers who already trade and hedge on their own infrastructure.

← Back to all posts