Calibration & Parameter Estimation

Michael BrenndoerferDecember 13, 202572 min read

Covers model calibration techniques for quantitative finance. Topics include SABR, Heston, GARCH.

Quantitative FinanceAll chapters
Part 8 of 15Econometrics and Statistical Modeling
Chapter 45Calibration and Parameter Estimation in Models
Reading the full chapter · 17 sections · 72 min17 sections · 72 min

All 17 sections · 72 min read

Calibration and Parameter Estimation in ModelsFull chapter · Sections in this chapter1 / 17 ↓
Reading tools Definitions, links & notes

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Notes & comments

Calibration and Parameter Estimation in Models

A $1 pricing error on a $100 option and a $0.10 error on a $10 option are equal in percentage terms, but raw-price squared error gives the first one a hundred times the influence. Calibration starts with choices like this: the objective determines which discrepancies the optimizer tries hardest to reduce. We will compare objectives, fit synthetic option and yield-curve data, and use held-out errors and parameter diagnostics to assess the results.

Throughout this book, we've developed sophisticated pricing models: the Black-Scholes framework for options, short-rate models like Vasicek and Hull-White for interest rate derivatives, and GARCH models for volatility dynamics. Each of these models contains parameters that must be determined from data. The volatility parameter σ\sigma in Black-Scholes, the mean reversion speed κ\kappa in the Vasicek model, and the persistence coefficient in GARCH: none of these are given to us by theory. They must be estimated or calibrated.

Statistical estimation typically uses historical observations to fit a model of past and future real-world dynamics, often through maximum likelihood or method of moments. Calibration to derivative prices instead fits current market quotes and generally identifies parameters under a pricing measure, often denoted QQ. These prices reflect uncertainty together with risk premia and market conditions; pricing parameters are not automatically forecasts under the physical measure PP. Combining the two requires a model of their relationship, rather than interchanging the fitted parameters.

This chapter develops the theory and practice of calibration. We'll formalize the calibration problem, explore different objective functions and optimization techniques, and work through practical examples. We'll also address the dangers of overfitting: the tendency to fit noise rather than signal when models have too many free parameters relative to the information content of the data.

The Calibration Problem

Calibration begins with a model that produces prices or other observable quantities as a function of parameters. To understand this formally, let M(θ)M(\theta) denote model prices for a vector of parameters θ=(θ1,θ2,…,θk)\theta = (\theta_1, \theta_2, \ldots, \theta_k). The market provides observed prices Pmkt=(P1mkt,P2mkt,…,Pnmkt)P^{mkt} = (P_1^{mkt}, P_2^{mkt}, \ldots, P_n^{mkt}) for nn instruments. The calibration problem seeks parameters θ^\hat{\theta} such that model prices M(θ^)M(\hat{\theta}) are as close as possible to market prices PmktP^{mkt}.

Calibration

The process of determining model parameters by minimizing the discrepancy between model-implied prices and observed market prices. A well-calibrated model reproduces current market quotes while remaining stable and economically sensible.

This simple description masks several important choices. What does "as close as possible" mean? How do we measure discrepancy? How do we search for optimal parameters? And what happens when perfect agreement is impossible because the model cannot reproduce all market prices simultaneously? These questions form the core of calibration theory and drive the methodological choices we explore throughout this chapter.

Why Models Can't Fit Perfectly

Consider calibrating the Black-Scholes model to a set of option prices. Black-Scholes assumes constant volatility σ\sigma for all options on the same underlying. But as we discussed in the chapter on implied volatility and the volatility smile, the market assigns different implied volatilities to options with different strikes and maturities. No single value of σ\sigma can reproduce all observed option prices.

This fundamental tension arises because models simplify reality. The Black-Scholes model ignores jumps, stochastic volatility, and many other market features. When we calibrate, we're finding the best compromise: the parameter values that make the model least wrong across the calibration instruments. This perspective is essential for understanding calibration not as a search for "truth" but as a practical optimization that acknowledges model limitations.

More flexible models can reduce these discrepancies, and a finite set of quotes can sometimes be fitted exactly. The five-parameter Heston model captures some smile dynamics but generally cannot reproduce an arbitrary set of market quotes. For nested model families fitted to the same data under the same objective, the exact optimal loss cannot worsen when parameters are added, although it need not improve strictly. A finite optimizer may not reach that optimum. Additional flexibility can also complicate optimization, weaken identification and increase the risk of fitting noise.

Mathematical Formulation

Let Mi(θ)M_i(\theta) denote the model price for instrument ii given parameters θ\theta. The calibration problem is typically formulated as an optimization problem. We seek parameters that minimize some measure of discrepancy between what the model predicts and what the market shows us. Mathematically, this takes the form:

θ^=arg⁡min⁡θ∈ΘL(θ)\hat{\theta} = \arg\min_{\theta \in \Theta} L(\theta)

where:

  • θ^\hat{\theta}: the optimal set of parameters that we seek
  • θ\theta: a vector of model parameters over which we optimize
  • L(θ)L(\theta): a loss function measuring the discrepancy between model and market prices
  • Θ\Theta: the set of feasible parameters, typically constrained by economic requirements such as positivity of volatility or valid correlation bounds

This formulation captures the essence of calibration: we have a loss function that quantifies how poorly the model matches the market, and we search over the space of allowable parameters to find those that minimize this loss. The choice of loss function determines the calibration outcome because different functions emphasize different aspects of fit quality.

The most common loss functions include several variations that each serve distinct purposes:

Sum of squared errors (SSE):

L(θ)=∑i=1n(Mi(θ)−Pimkt)2L(\theta) = \sum_{i=1}^{n} \left( M_i(\theta) - P_i^{mkt} \right)^2

where:

  • nn: number of calibration instruments
  • Mi(θ)M_i(\theta): model price for instrument ii given parameters θ\theta
  • PimktP_i^{mkt}: observed market price for instrument ii

This is the simplest and most intuitive loss function. It sums the squared differences between model and market prices across all instruments. Squaring ensures that positive and negative errors don't cancel, and larger errors receive disproportionately more penalty than smaller ones. This makes SSE particularly sensitive to outliers, which can be either an advantage (outliers might indicate important mispricings) or a disadvantage (outliers might represent data errors).

Weighted sum of squared errors:

L(θ)=∑i=1nwi(Mi(θ)−Pimkt)2L(\theta) = \sum_{i=1}^{n} w_i \left( M_i(\theta) - P_i^{mkt} \right)^2

where:

  • wiw_i: nonnegative weight assigned to instrument ii, with at least one positive weight
  • nn: number of calibration instruments
  • Mi(θ)M_i(\theta): model price for instrument ii given parameters θ\theta
  • PimktP_i^{mkt}: observed market price for instrument ii

Weighted SSE introduces flexibility by allowing different instruments to contribute differently to the objective. You might assign higher weights to more liquid instruments whose prices are more reliable, or to instruments that are most relevant to your trading book. The weights wiw_i encode your beliefs about which prices are most important to match accurately.

Relative errors:

L(θ)=∑i=1n(Mi(θ)−PimktPimkt)2L(\theta) = \sum_{i=1}^{n} \left( \frac{M_i(\theta) - P_i^{mkt}}{P_i^{mkt}} \right)^2

where:

  • nn: number of calibration instruments
  • Mi(θ)M_i(\theta): model price for instrument ii
  • PimktP_i^{mkt}: observed market price for instrument ii

Relative errors normalize by a nonzero target price, so a $1 error on a $100 instrument counts the same as a $0.10 error on a $10 instrument. This removes emphasis caused solely by absolute price scale; an instrument can still dominate if its proportional error is large. Zero prices make this loss undefined, and very small prices can receive excessive influence. A spread-based or noise-based scale may be more appropriate for such quotes.

The loss function determines which errors receive the most attention. Weights can emphasize liquid near-the-money options or maturities relevant to a trading book, but actual liquidity depends on the market, maturity and liquidity measure. Relative errors instead compare proportional discrepancies. These are choices about the purpose and reliability of the calibration targets.

VisualizationsOut [4]
CollapseExpand
Bar chart showing per-strike loss contributions under SSE, with the 80-strike contract dominating because it has the largest absolute error.
Illustrative per-strike shares of SSE. The objective squares dollar errors; the displayed contributions are then normalized to sum to 100%.
Bar chart showing per-strike loss contributions under relative-error weighting, redistributing emphasis toward low-priced OTM options.
Illustrative per-strike shares of relative squared error. Equal percentage errors contribute equally; this panel is separately normalized to sum to 100%.
Bar chart showing per-strike loss contributions under ATM-weighted SSE, with the heaviest weight concentrated near the 100 strike.
Illustrative per-strike shares of ATM-weighted SSE. Assumed weights emphasize strikes near 100; displayed contributions are normalized to sum to 100%. These weights are not measured liquidity.

Objective Functions for Calibration

The loss function defines what "good calibration" means. Different objectives can lead to different calibrated parameters, and the choice should reflect how the model will be used. A model calibrated for pricing exotic derivatives may need different parameter values than one calibrated for risk management, even if based on the same underlying framework.

Price-Based Calibration

The most direct approach minimizes differences between model and market prices. Matching vanilla quotes aligns the model prices of those hedging instruments with the market. Exotic valuations still depend on dynamics and assumptions that the vanilla calibration may not identify.

For options, a common choice is to calibrate in volatility space rather than price space. Instead of minimizing price errors, we minimize implied volatility errors:

L(θ)=∑i=1nwi(σimodel(θ)−σimkt)2L(\theta) = \sum_{i=1}^{n} w_i \left( \sigma_i^{model}(\theta) - \sigma_i^{mkt} \right)^2

where:

  • σimodel(θ)\sigma_i^{model}(\theta): implied volatility derived from the model price for instrument ii
  • σimkt\sigma_i^{mkt}: observed market implied volatility for instrument ii
  • wiw_i: nonnegative weight for instrument ii, with at least one positive weight
  • nn: number of calibration instruments

Volatility-space calibration offers several useful interpretations:

  • Quote units are comparable: a one-percentage-point volatility error has the same volatility units across options. Its dollar impact still depends on Vega, the sensitivity of price to volatility.
  • Numerical behavior depends on the instruments and model. Low Vega can amplify price errors during IV inversion, so volatility loss need not have smoother gradients or better conditioning.
  • Errors are convenient to interpret when the market quotes the instruments in implied volatility.

Model and market prices must admit an implied volatility under the same option conventions. For the no-dividend European calls used below, prices strictly between discounted intrinsic value and spot have a finite positive Black-Scholes IV. Boundary and invalid prices require explicit handling.

Bid-Ask Spread Considerations

Market prices are not single values; they come with bid-ask spreads that reflect the cost of transacting and the uncertainty about fair value. A sophisticated calibration might seek parameters such that model prices fall within observed bid-ask bounds rather than matching midpoint prices exactly:

minimize L(θ)subject toPibid≤Mi(θ)≤Piaskfor all i\text{minimize } L(\theta) \quad \text{subject to} \quad P_i^{bid} \leq M_i(\theta) \leq P_i^{ask} \quad \text{for all } i

where:

  • PibidP_i^{bid}: market bid price, the highest price at which someone is willing to buy
  • PiaskP_i^{ask}: market ask price, the lowest price at which someone is willing to sell
  • Mi(θ)M_i(\theta): model price
  • L(θ)L(\theta): loss function to minimize
  • θ\theta: model parameters

A model price inside an executable bid-ask interval is compatible with that individual quote, but it does not establish joint no-arbitrage or model adequacy. The constraints are usable only when they are jointly feasible: a restricted model may not intersect all quote bands. If no feasible fit exists, investigate the quotes and model restrictions or use explicit slack variables or outside-spread penalties.

Maximum Likelihood Estimation

For time-series models like GARCH or short-rate models estimated from historical data, maximum likelihood estimation (MLE) provides a principled framework rooted in statistical theory. Given observations y1,y2,…,yTy_1, y_2, \ldots, y_T and a model specifying the conditional density f(yt∣yt−1,…,y1;θ)f(y_t | y_{t-1}, \ldots, y_1; \theta), the log-likelihood is:

ℓ(θ)=∑t=1Tlog⁡f(yt∣yt−1,…,y1;θ)\ell(\theta) = \sum_{t=1}^{T} \log f(y_t | y_{t-1}, \ldots, y_1; \theta)

where:

  • ℓ(θ)\ell(\theta): log of the observed data's joint density under the model, viewed as a function of the parameters
  • θ\theta: vector of model parameters
  • TT: number of time series observations
  • f(⋅)f(\cdot): conditional probability density specified by the model
  • yty_t: observation at time tt

For continuous observations, likelihood compares joint densities as a function of θ\theta; the probability of one exact observed vector is zero. For discrete observations, use probability masses instead. Higher likelihood means a better fit by this criterion under the assumed model, rather than a higher posterior probability that the parameter is true.

Maximizing ℓ(θ)\ell(\theta) fits the specified joint or conditional likelihood to the observed sample. The displayed sum uses the conditional-density factorization; the first term requires an initial-density or conditioning convention. This likelihood approach is commonly used for fitting GARCH models to return data.

Under appropriate regularity, identification and correct-specification conditions, MLE is consistent and asymptotically normal. It can attain the asymptotic information bound within the regular estimator class; this is not a minimum-variance guarantee among every consistent estimator. A computable likelihood alone does not ensure a finite maximizer, correct specification or reliable finite-sample recovery.

Combined Objectives

Calibration may need to preserve an initial yield curve while fitting option prices. Exact curve matching must be built into the parameterization, imposed as equality constraints or preserved by a hierarchical procedure. A weighted composite objective generally trades discrepancies unless a separate mechanism enforces the exact curve fit.

Optimization Techniques

Once we've specified an objective function, we need algorithms to find the minimizing parameters. Calibration optimization presents particular challenges: objective functions may be non-convex with multiple local minima, parameter spaces may be constrained, and model evaluations (especially for derivatives requiring Monte Carlo or PDE methods) may be computationally expensive. Choosing an optimization technique requires matching these constraints to the algorithm's capabilities.

Gradient-Based Methods

When the objective function is smooth and its gradient is available (analytically or via automatic differentiation), gradient-based methods can be efficient. The simplest is gradient descent, which takes steps opposite the gradient:

θk+1=θk−αk∇L(θk)\theta_{k+1} = \theta_k - \alpha_k \nabla L(\theta_k)

where:

  • θk\theta_k: parameter vector at iteration kk
  • αk\alpha_k: step size (learning rate) controlling how far we move at each iteration
  • ∇L(θk)\nabla L(\theta_k): gradient of the objective function, pointing in the direction of steepest increase

For a differentiable objective and a nonzero gradient, moving opposite the gradient gives a local descent direction in the usual Euclidean coordinates. A sufficiently small positive step reduces the loss, provided the step remains in the objective's domain and respects any parameter constraints. An arbitrary finite step need not reduce the loss: a step that is too large can overshoot and increase it. At a zero gradient, this update leaves the parameters unchanged and does not by itself establish a minimum.

BFGS and L-BFGS build approximate curvature information from changes in gradients. Under suitable regularity and line-search conditions near an optimum, they can converge faster than basic gradient descent. This is a conditional benefit, not a guarantee for every calibration objective.

Gradient methods can find local minima efficiently under suitable conditions, but non-convex objectives can also contain stationary points that are not minima and suboptimal local minima. Initialization and local curvature affect the outcome. This limitation motivates the global optimization methods discussed next.

Global Optimization

For non-convex objectives, stochastic global-search methods seek broader exploration through populations or moves between regions. A finite run does not guarantee thorough coverage or a global optimum:

Differential evolution maintains a population of candidates and proposes new vectors through mutation and crossover, retaining candidates according to their objective values. It is derivative-free. Bounds and general constraints require explicit handling by the selected implementation; constraint satisfaction is not intrinsic to the mutation formula.

Simulated annealing can accept uphill moves with probability that decreases as the temperature falls, for a fixed loss increase. Cooling concentrates the search, but convergence claims require assumptions about the schedule and proposals. The analogy is annealing in solids, where controlled heating and cooling can allow lower-energy configurations; it is not a universal material-strengthening rule.

Basin hopping perturbs a candidate, locally minimizes from the perturbed point, and accepts or rejects the resulting basin, while retaining the lowest minimum found. It can revisit the same basin. Independent additional runs can help assess sensitivity to initialization without proving global optimality.

These methods often explore more broadly than one local run, usually at greater function-evaluation cost; sensitivity to initialization remains problem dependent. A hybrid can use a broad search to find a promising region and then refine it with a local method.

Constraints and Regularization

Model parameters often have economic constraints that must be respected. Volatility is nonnegative in general and must be strictly positive where the chosen formula or parameterization requires it. Mean-reversion speeds should be positive for stability. Correlation parameters must lie in [−1,1][-1, 1]. These constraints can be enforced through several mechanisms:

Constrained optimization: SLSQP and constrained trust-region methods accept supplied bounds and general constraints and seek feasible solutions to a specified tolerance. This does not guarantee that every intermediate objective evaluation is feasible. Model evaluations must handle possible trial points, and final constraint residuals must be checked.

Parameter transformation: For a strictly positive parameter σ\sigma, finite real coordinates η\eta map through σ=exp⁡(η)\sigma=\exp(\eta) in exact arithmetic. For a correlation, ρ=tanh⁡(ρ~)\rho=\tanh(\tilde{\rho}) covers (−1,1)(-1,1) at finite coordinates, excluding the endpoints. These maps remove the represented interior scalar constraints; coupled constraints still require separate handling. Floating-point overflow and underflow also need numerical checks.

Penalty methods: Add a large penalty to the objective when constraints are violated:

Lpenalized(θ)=L(θ)+λ∑jmax⁡(0,gj(θ))2L_{penalized}(\theta) = L(\theta) + \lambda \sum_j \max(0, g_j(\theta))^2

where:

  • Lpenalized(θ)L_{penalized}(\theta): penalized objective function that combines fit quality and constraint satisfaction
  • L(θ)L(\theta): original loss function measuring fit to data
  • λ\lambda: penalty parameter controlling the severity of constraint violation penalties
  • gj(θ)≤0g_j(\theta) \leq 0: inequality constraints (positive values indicate violation)
  • θ\theta: model parameters

For a fixed violation, increasing λ\lambda increases its cost. A finite quadratic penalty generally encourages approximate rather than exact feasibility, and arbitrarily small violations have arbitrarily small penalties. Report residual constraint violations explicitly and use a suitable hard-constraint method when required.

Regularization adds penalties for large parameter values or parameter instability, encouraging parsimonious solutions:

Lregularized(θ)=L(θ)+λ∥θ∥2L_{regularized}(\theta) = L(\theta) + \lambda \|\theta\|^2

where:

  • Lregularized(θ)L_{regularized}(\theta): regularized objective function balancing fit and parameter magnitude
  • L(θ)L(\theta): original loss function
  • λ\lambda: regularization strength controlling the trade-off
  • ∥θ∥2\|\theta\|^2: squared Euclidean norm of the parameters

This L2 penalty encourages a smaller parameter norm in the chosen coordinates. Its meaning depends on units, scaling and centering; it is not automatically a penalty on economic complexity or changes over time. A temporal stability penalty would instead compare successive parameter vectors. Regularization can reduce variance while adding bias, so choose its strength using an appropriate validation design rather than assuming it improves generalization.

Calibrating Implied Volatility Surfaces

We will fit a SABR implied-volatility smile at one maturity to synthetic option quotes. This illustrates a slice of the wider surface-calibration problem, not calibration across maturities.

SABR is widely used for interest-rate option smiles. Its algebraic implied-volatility approximation enables fast calibration, with accuracy that must be checked for the intended strikes, maturities and parameters. Under an appropriate forward or annuity pricing measure, the model specifies:

dFt=σtFtβdWt1dσt=νσtdWt2\begin{aligned} dF_t &= \sigma_t F_t^\beta dW_t^1 \\ d\sigma_t &= \nu \sigma_t dW_t^2 \end{aligned}

where:

  • FtF_t: forward price at time tt
  • σt\sigma_t: stochastic volatility at time tt
  • α\alpha: initial volatility (σ0\sigma_0 in some notations), setting the overall level of the volatility smile
  • ν\nu: volatility of volatility (vol-vol), determining how much the volatility itself fluctuates
  • β\beta: elasticity parameter, controlling the relationship between the forward price and local volatility
  • dWt1,dWt2dW_t^1, dW_t^2: standard Brownian motions with correlation ρ\rho
  • ρ\rho: correlation coefficient between the forward price and volatility processes

The first equation has a constant-elasticity-of-variance backbone determined by β\beta. With β=1\beta=1 this is stochastic-lognormal SABR, and with β=0\beta=0 it is stochastic-normal SABR. The volatility coefficient remains random, so these backbone labels do not by themselves specify a normal or lognormal terminal distribution. The second equation drives its changes with vol-of-vol ν\nu.

The correlation ρ\rho relates signed forward-price and volatility innovations. Negative correlation tends to associate downward forward moves with increases in volatility, contributing to downside implied-volatility skew. It does not specify a deterministic relationship between volatility level and the magnitude of every price move.

Hagan et al. derived an asymptotic approximation for Black implied volatility as a function of strike KK and forward FF. The unshifted form below assumes positive forwards and strikes, α>0\alpha>0, ν≥0\nu\geq0, ∣ρ∣<1|\rho|<1, and T≥0T\geq0, with the ATM and zero-zz limits evaluated continuously. The initial coefficient α\alpha is not generally the Black implied volatility. Check approximation accuracy and no-arbitrage behavior, especially in the wings, at long maturities or for extreme parameters:

σimpl(K)≈α(FK)(1−β)/2[1+(1−β)224log⁡2FK+(1−β)41920log⁡4FK]⋅(zχ(z))⋅[1+T((1−β)2α224(FK)1−β+ρβνα4(FK)(1−β)/2+2−3ρ224ν2)]\begin{aligned} \sigma_{impl}(K) \approx \frac{\alpha}{(FK)^{(1-\beta)/2}\left[1 + \frac{(1-\beta)^2}{24}\log^2\frac{F}{K} + \frac{(1-\beta)^4}{1920}\log^4\frac{F}{K}\right]} & \cdot \left(\frac{z}{\chi(z)}\right) \\ & \cdot \left[1 + T\left(\frac{(1-\beta)^2\alpha^2}{24(FK)^{1-\beta}} + \frac{\rho\beta\nu\alpha}{4(FK)^{(1-\beta)/2}} + \frac{2-3\rho^2}{24}\nu^2\right)\right] \end{aligned}

where:

  • FF: current forward price
  • KK: strike price
  • TT: time to expiration
  • α\alpha: initial volatility level
  • β\beta: elasticity parameter
  • ρ\rho: correlation between Brownian motions
  • ν\nu: volatility of volatility
  • z=να(FK)(1−β)/2log⁡FKz = \frac{\nu}{\alpha}(FK)^{(1-\beta)/2}\log\frac{F}{K}: a vol-of-vol-scaled log-moneyness variable used in the approximation
  • χ(z)=log⁡(1−2ρz+z2+z−ρ1−ρ)\chi(z) = \log\left(\frac{\sqrt{1-2\rho z + z^2} + z - \rho}{1-\rho}\right): skew adjustment function that modifies implied volatility based on the correlation structure

The formula decomposes into three interpretable parts. The first fraction establishes the primary volatility level, scaled appropriately for the moneyness. The skew adjustment term zχ(z)\frac{z}{\chi(z)} modifies this level based on how correlation between price and volatility affects options at different strikes. The final bracket in the formula provides a time-dependent correction factor that accounts for how the smile dynamics evolve as we look further into the future.

This formula looks intimidating, but it's straightforward to implement. Let's calibrate SABR to synthetic option data.

PythonIn [5]
CollapseExpand
import numpy as np


def sabr_implied_vol(F, K, T, alpha, beta, rho, nu):
    """
    Scalar unshifted SABR Black-IV approximation (Hagan et al. 2002).
    """
    values = (F, K, T, alpha, beta, rho, nu)
    if not all(np.isscalar(x) and np.isfinite(x) for x in values):
        raise ValueError("SABR inputs must be finite scalars")
    if F <= 0 or K <= 0 or T < 0 or alpha <= 0 or nu < 0:
        raise ValueError("Require positive F, K, alpha and nonnegative T, nu")
    if not 0 <= beta <= 1 or abs(rho) >= 1:
        raise ValueError("Require beta in [0, 1] and rho in (-1, 1)")
    if abs(F - K) < 1e-10:
        # ATM approximation
        vol = (
            alpha
            / (F ** (1 - beta))
            * (
                1
                + T
                * (
                    ((1 - beta) ** 2 / 24) * alpha**2 / (F ** (2 - 2 * beta))
                    + 0.25 * rho * beta * nu * alpha / (F ** (1 - beta))
                    + (2 - 3 * rho**2) / 24 * nu**2
                )
            )
        )
        return vol

    FK = F * K
    log_FK = np.log(F / K)
    FK_mid = FK ** ((1 - beta) / 2)

    # z and the ratio z / chi(z)
    z = (nu / alpha) * FK_mid * log_FK

    # Handle small z
    if abs(z) < 1e-10:
        chi_z = 1
    else:
        sqrt_term = np.sqrt(1 - 2 * rho * z + z**2)
        chi_z = z / np.log((sqrt_term + z - rho) / (1 - rho))

    # Coefficient terms
    term1 = (
        1 + ((1 - beta) ** 2 / 24) * log_FK**2 + ((1 - beta) ** 4 / 1920) * log_FK**4
    )

    term2 = 1 + T * (
        ((1 - beta) ** 2 / 24) * alpha**2 / (FK ** (1 - beta))
        + 0.25 * rho * beta * nu * alpha / FK_mid
        + (2 - 3 * rho**2) / 24 * nu**2
    )

    vol = (alpha / (FK_mid * term1)) * chi_z * term2
    return vol

Now let's generate synthetic market data from known SABR parameters and add noise:

PythonIn [6]
CollapseExpand
# "True" market parameters (what we're trying to recover)
F_true = 100  # Forward price
sabr_maturity = 1.0  # Keep this example's one-year maturity separate from other models
alpha_true = 0.20
beta_true = 0.5  # We'll fix beta in calibration
rho_true = -0.30
nu_true = 0.40

# Generate strikes around ATM
strikes = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120])

# Calculate "market" implied vols with some noise
np.random.seed(42)
market_vols = np.array(
    [
        sabr_implied_vol(
            F_true, K, sabr_maturity, alpha_true, beta_true, rho_true, nu_true
        )
        for K in strikes
    ]
)
noise = np.random.normal(0, 0.005, len(strikes))  # 50bp noise
market_vols_noisy = market_vols + noise
ConsoleOut [7]
CollapseExpand
Strike | True IV | Market IV (noisy)
----------------------------------------
   80  |  0.0463 |     0.0487
   85  |  0.0391 |     0.0384
   90  |  0.0322 |     0.0354
   95  |  0.0255 |     0.0331
  100  |  0.0202 |     0.0191
  105  |  0.0202 |     0.0190
  110  |  0.0237 |     0.0316
  115  |  0.0278 |     0.0316
  120  |  0.0317 |     0.0294

This deliberately simplified example adds independent Gaussian noise to model-generated implied volatilities. Actual quote errors can reflect spreads, staleness, dependence and other market effects; the synthetic noise is not an empirical model of those errors. We now fit the selected objective to these synthetic quotes.

PythonIn [8]
CollapseExpand
from scipy.optimize import minimize


def validate_sabr_quotes(strikes, market_vols, F, T, beta):
    strikes = np.asarray(strikes, dtype=float)
    market_vols = np.asarray(market_vols, dtype=float)
    if (
        strikes.ndim != 1
        or market_vols.ndim != 1
        or strikes.size == 0
        or strikes.shape != market_vols.shape
    ):
        raise ValueError("Require nonempty equal-length one-dimensional quote arrays")
    if (
        not np.all(np.isfinite(strikes))
        or not np.all(strikes > 0)
        or not np.all(np.isfinite(market_vols))
        or not np.all(market_vols > 0)
    ):
        raise ValueError("Require positive finite strikes and implied volatilities")
    if (
        not all(np.isfinite(x) for x in (F, T, beta))
        or F <= 0
        or T < 0
        or not 0 <= beta <= 1
    ):
        raise ValueError("Invalid SABR market setup")
    return strikes, market_vols


def calibration_objective(params, F, T, strikes, market_vols, beta):
    """Sum of squared IV errors; invalid candidates have infinite loss."""
    strikes, market_vols = validate_sabr_quotes(strikes, market_vols, F, T, beta)
    params = np.asarray(params, dtype=float)
    if params.shape != (3,) or not np.all(np.isfinite(params)):
        return np.inf
    alpha, rho, nu = params
    if alpha <= 0 or nu < 0 or abs(rho) >= 1:
        return np.inf
    try:
        model_vols = np.array(
            [sabr_implied_vol(F, K, T, alpha, beta, rho, nu) for K in strikes]
        )
    except (ValueError, FloatingPointError, OverflowError):
        return np.inf
    if not np.all(np.isfinite(model_vols)) or not np.all(model_vols > 0):
        return np.inf
    return float(np.sum((model_vols - market_vols) ** 2))


def require_successful_fit(result, label):
    if (
        not result.success
        or not np.isfinite(result.fun)
        or not np.all(np.isfinite(result.x))
    ):
        raise RuntimeError(f"{label} failed: {result.message}")
    return result


# Fix beta at 0.5 (common convention)
beta_fixed = 0.5

# Initial guess
x0 = [0.25, -0.20, 0.35]

# Bounds for parameters
bounds = [(0.01, 1.0), (-0.99, 0.99), (0.01, 2.0)]

# Calibrate using L-BFGS-B (handles bounds)
result = minimize(
    calibration_objective,
    x0,
    args=(F_true, sabr_maturity, strikes, market_vols_noisy, beta_fixed),
    method="L-BFGS-B",
    bounds=bounds,
)

require_successful_fit(result, "SABR calibration")
alpha_cal, rho_cal, nu_cal = result.x
ConsoleOut [9]
CollapseExpand
Calibration Results:
----------------------------------------
Parameter |   True   | Calibrated |  Error
----------------------------------------
  alpha   |  0.2000  |   0.2264   | 0.0264
  rho     | -0.3000  |  -0.2943   | 0.0057
  nu      |  0.4000  |   0.3911   | 0.0089

Final SSE: 0.000120
RMSE (implied volatility): 36.46 bps

The fitted parameters and their discrepancies from the generating values are reported above. This is one noisy synthetic fit, not evidence of reliable parameter recovery or unique identification. Compare the IV RMSE with the added 50-basis-point noise scale and the intended pricing tolerance. The plot shows the fitted smile and the generating curve separately:

VisualizationOut [11]
CollapseExpand
Line plot showing calibrated SABR volatility smile fitting noisy market data points across strikes from 80 to 120.
SABR fit to noisy synthetic one-year implied-volatility quotes. The solid curve is the fit found in this run; parameter discrepancies are reported separately and need not be small.

The fitted smile approximates these synthetic one-year quotes. A least-squares fit need not interpolate every noisy observation. Validate approximation accuracy, interpolation, extrapolation and no-arbitrage conditions before using strikes outside the observed range.

VisualizationOut [13]
CollapseExpand
Filled contour plot of the SABR calibration objective over rho and nu, with a star marking the calibrated optimum and a circle marking the true parameter values.
SABR objective on a finite 50-by-50 rho-nu grid with alpha fixed at its calibrated value and high losses clipped for display. The displayed slice shows a low-loss basin near the calibrated point; it does not establish a global minimum over the full parameter space.

Key Parameters

The key parameters for the SABR model are:

  • α\alpha: Initial volatility level. Controls the overall height of the implied volatility ATM.
  • β\beta: Elasticity parameter. Determines the relationship between asset price and volatility (backbone). Often fixed (e.g., to 0.5) during calibration.
  • ρ\rho: Correlation between the asset price and volatility. Controls the skew (slope) of the volatility smile.
  • ν\nu: Volatility of volatility (vol-vol). Controls the curvature (convexity) of the volatility smile.

Calibrating Short-Rate Models to the Yield Curve

Short-rate models specify the dynamics of the instantaneous interest rate. For market-consistent pricing, fit the current term structure as closely as the chosen family permits; constant-parameter Vasicek generally cannot match an arbitrary initial curve exactly. In this example the Vasicek coefficients are under the risk-neutral pricing measure QQ, rather than historical estimates under PP. The bond pays one default-free unit at maturity.

The Vasicek model is one of the foundational short-rate models, valued for its analytical tractability and intuitive interpretation. It specifies the evolution of the instantaneous short rate through the following stochastic differential equation:

drt=κ(θ−rt)dt+σdWtdr_t = \kappa(\theta - r_t)dt + \sigma dW_t

where:

  • rtr_t: instantaneous short rate at time tt
  • κ\kappa: mean reversion speed, determining how quickly the rate returns to equilibrium
  • θ\theta: long-term mean rate, the equilibrium level toward which rates are pulled
  • σ\sigma: volatility of the rate, controlling the magnitude of random fluctuations
  • dWtdW_t: standard Brownian motion driving the random component

For κ>0\kappa>0, the drift κ(θ−rt)\kappa(\theta-r_t) pulls the conditional mean toward θ\theta: it is negative above that level and positive below it. Larger κ\kappa gives faster conditional-mean reversion. This is the model's idealization, not a claim that market rates or Gaussian sample paths stay in a bounded range.

Under the Vasicek model, zero-coupon bond prices have a closed-form solution. This analytical tractability is one of the model's key advantages, enabling rapid calibration and pricing:

P(t,T)=A(t,T)e−B(t,T)rtP(t, T) = A(t, T) e^{-B(t, T) r_t}

where:

  • P(t,T)P(t, T): price at time tt of a bond maturing at TT
  • rtr_t: instantaneous short rate at time tt
  • tt: current time
  • TT: maturity time
  • κ,θ,σ\kappa, \theta, \sigma: Vasicek model parameters
  • B(t,T)=1−e−κ(T−t)κB(t, T) = \frac{1 - e^{-\kappa(T-t)}}{\kappa}: duration-like factor that captures how bond prices respond to rate changes
  • A(t,T)=exp⁡[(θ−σ22κ2)(B(t,T)−(T−t))−σ24κB(t,T)2]A(t, T) = \exp\left[\left(\theta - \frac{\sigma^2}{2\kappa^2}\right)(B(t, T) - (T-t)) - \frac{\sigma^2}{4\kappa}B(t, T)^2\right]: exponential-affine prefactor incorporating the expected mean-reverting rate path and variance-induced convexity

The function B(t,T)B(t, T) resembles modified duration in some ways, measuring the sensitivity of the bond price to changes in the short rate. The function A(t,T)A(t, T) incorporates convexity effects and the impact of the long-term mean on bond pricing.

The continuously compounded yield can be derived from the bond price formula:

R(t,T)=−ln⁡P(t,T)T−t=−ln⁡(A(t,T)e−B(t,T)rt)T−t(substitute bond price)=B(t,T)rt−ln⁡A(t,T)T−t(simplify)\begin{aligned} R(t, T) &= -\frac{\ln P(t, T)}{T - t} \\ &= -\frac{\ln\left(A(t, T) e^{-B(t, T) r_t}\right)}{T - t} && \text{(substitute bond price)} \\ &= \frac{B(t, T) r_t - \ln A(t, T)}{T - t} && \text{(simplify)} \end{aligned}

where:

  • R(t,T)R(t, T): continuously compounded yield for maturity TT
  • P(t,T)P(t, T): zero-coupon bond price
  • A(t,T),B(t,T)A(t, T), B(t, T): Vasicek bond price coefficients defined above
  • rtr_t: instantaneous short rate
  • tt: current time
  • TT: maturity time

This relationship translates the pricing-measure parameters into observable yields. For stable numerical evaluation, the code uses the Gaussian integral I=∫0Trs dsI=\int_0^T r_s\,ds. Its mean is m=r0B+θ(T−B)m=r_0B+\theta(T-B) and its variance is v=σ2∫0T[(1−e−κu)/κ]2 duv=\sigma^2\int_0^T[(1-e^{-\kappa u})/\kappa]^2\,du, so log⁡P=−m+v/2\log P=-m+v/2. At κ=0\kappa=0, this becomes −r0T+σ2T3/6-r_0T+\sigma^2T^3/6, with a positive variance correction. Near zero, a series for the integrated variance avoids subtracting large cancelling terms; yields use log prices directly.

PythonIn [14]
CollapseExpand
from math import expm1, factorial, fsum


def vasicek_log_bond_price(r0, T, kappa, theta, sigma):
    """Log price of a unit zero-coupon bond under risk-neutral Vasicek."""
    if not all(np.isfinite(x) for x in (r0, T, kappa, theta, sigma)):
        raise ValueError("Vasicek inputs must be finite")
    if T <= 0 or kappa < 0 or sigma < 0:
        raise ValueError("Require T > 0, kappa >= 0 and sigma >= 0")
    x = kappa * T
    if not np.isfinite(x):
        raise ValueError("kappa * T is outside the supported range")
    if x < 0.1:
        b = fsum((-x) ** n / factorial(n + 1) for n in range(13))
        one_minus_b = fsum(
            (-1) ** (n + 1) * x**n / factorial(n + 1) for n in range(1, 13)
        )
        j = fsum(
            (-1) ** n * (2 ** (n + 2) - 2) * x**n / (factorial(n + 2) * (n + 3))
            for n in range(13)
        )
    else:
        b = -expm1(-x) / x
        one_minus_b = 1 - b
        b2 = -expm1(-2 * x) / (2 * x)
        j = fsum((1.0, -2 * b, b2)) / x**2
    mean_integral = T * (r0 * b + theta * one_minus_b)
    variance_integral = sigma**2 * T**3 * j
    log_price = -mean_integral + variance_integral / 2
    if not np.isfinite(log_price):
        raise ValueError("Unrepresentable Vasicek log price")
    return log_price


def vasicek_bond_price(r0, T, kappa, theta, sigma):
    """Unit bond price, with an explicit finite-representation check."""
    with np.errstate(over="raise", under="raise"):
        return float(np.exp(vasicek_log_bond_price(r0, T, kappa, theta, sigma)))


def vasicek_yield(r0, T, kappa, theta, sigma):
    """Continuously compounded yield, evaluated directly from log price."""
    return -vasicek_log_bond_price(r0, T, kappa, theta, sigma) / T

Let's create a synthetic market yield curve and calibrate the Vasicek model to it:

PythonIn [15]
CollapseExpand
# Market yield curve (maturities in years)
maturities = np.array([0.25, 0.5, 1, 2, 3, 5, 7, 10])
market_yields = np.array([0.02, 0.022, 0.025, 0.028, 0.030, 0.033, 0.035, 0.037])


def vasicek_calibration_objective(params, maturities, market_yields):
    """Squared yield errors in basis points."""
    maturities = np.asarray(maturities, dtype=float)
    market_yields = np.asarray(market_yields, dtype=float)
    if (
        maturities.ndim != 1
        or market_yields.ndim != 1
        or maturities.size == 0
        or maturities.shape != market_yields.shape
        or not np.all(np.isfinite(maturities))
        or not np.all(maturities > 0)
        or not np.all(np.isfinite(market_yields))
    ):
        raise ValueError("Require paired finite yields and positive maturities")
    params = np.asarray(params, dtype=float)
    if params.shape != (4,) or not np.all(np.isfinite(params)):
        return np.inf
    r0, kappa, theta, sigma = params
    if kappa < 0 or sigma < 0:
        return np.inf
    try:
        model = np.array(
            [vasicek_yield(r0, T, kappa, theta, sigma) for T in maturities]
        )
    except (ValueError, FloatingPointError, OverflowError):
        return np.inf
    if not np.all(np.isfinite(model)):
        return np.inf
    return float(np.sum(((model - market_yields) * 10000) ** 2))


# Initial guess
x0_vasicek = [0.02, 0.5, 0.03, 0.01]

# Bounds
bounds_vasicek = [(0.001, 0.10), (0.01, 2.0), (0.01, 0.10), (0.001, 0.10)]

# Calibrate
result_vasicek = minimize(
    vasicek_calibration_objective,
    x0_vasicek,
    args=(maturities, market_yields),
    method="L-BFGS-B",
    bounds=bounds_vasicek,
    options={"ftol": 1e-12, "gtol": 1e-6, "maxiter": 2000},
)

require_successful_fit(result_vasicek, "Vasicek calibration")
r0_cal, kappa_cal, theta_cal, sigma_cal = result_vasicek.x
ConsoleOut [16]
CollapseExpand
Vasicek Calibration Results:
----------------------------------------
r0 (short rate):     0.0189 (1.89%)
kappa (mean rev.):   0.4418
theta (long-term):   0.0494 (4.94%)
sigma (volatility):  0.0591

Calibration SSE (bps squared): 112.64440100
RMSE (yield): 3.75 bps
VisualizationOut [18]
CollapseExpand
Scatter plot of market yield observations overlaid with the calibrated Vasicek yield curve across maturities from 0.25 to 10 years.
Vasicek fit to a synthetic yield curve. Compare the fitted curve with its target yields and inspect the residuals and optimizer diagnostics before assessing adequacy.
VisualizationOut [20]
CollapseExpand
Bar chart of Vasicek model calibration residuals in basis points across maturities from 0.25 to 10 years, showing small positive and negative deviations around zero.
Residuals of this Vasicek fit in basis points. Their size reflects numerical fitting as well as model restrictions; assess scaling, tolerances and starting points before attributing remaining structure to the model family.

The printed values are fitted parameters for this synthetic curve, not a validation of economic realism. Inspect the numerical objective, stopping diagnostics and sensitivity to scaling and starting points before interpreting residual patterns. Constant-parameter Vasicek restricts the shapes it can represent, but the residuals of one finite run also contain optimization error. Time-dependent extensions such as Hull-White can preserve an exact fit to a suitable initial curve.

Key Parameters

The key parameters for the Vasicek model are:

  • κ\kappa: Mean reversion speed. Determines how quickly the short rate returns to the long-term mean θ\theta.
  • θ\theta: Long-term mean rate. The conditional mean approaches this level while the rate continues to fluctuate around it.
  • σ\sigma: Volatility of the short rate. Controls the magnitude of random rate fluctuations.
  • r0r_0: Current instantaneous short rate. The starting point for the rate process.

Calibrating the Heston Stochastic Volatility Model

Heston is a standard stochastic-volatility model for equity derivatives, with joint dynamics for price and variance. In the no-dividend pricing example below, use the risk-neutral measure QQ, set μ=r\mu=r, and interpret the variance coefficients as pricing-measure parameters. Historical coefficients require a separate measure-change model.

dSt=μStdt+vtStdWtSdvt=κ(θ−vt)dt+ξvtdWtv\begin{aligned} dS_t &= \mu S_t dt + \sqrt{v_t} S_t dW_t^S \\ dv_t &= \kappa(\theta - v_t)dt + \xi \sqrt{v_t} dW_t^v \end{aligned}

where:

  • StS_t: asset price at time tt
  • vtv_t: instantaneous variance at time tt (note: variance, not volatility)
  • μ\mu: drift rate of the asset price
  • dWtS,dWtvdW_t^S, dW_t^v: Brownian motions with correlation ρ\rho
  • v0v_0: initial variance, the starting level for the variance process
  • κ\kappa: speed of mean reversion for variance, determining how fast variance returns to its long-run level
  • θ\theta: long-term variance level, the equilibrium to which variance is pulled
  • ξ\xi: volatility of variance (vol of vol), controlling how much the variance itself fluctuates
  • ρ\rho: correlation between spot price and variance, typically negative for equities

The variance process vtv_t follows a Cox-Ingersoll-Ross (CIR) process and exhibits mean reversion to the long-run level θ\theta. With positive parameters and positive initial variance, the strict Feller inequality 2κθ>ξ22\kappa\theta>\xi^2 is sufficient for the exact continuous-time variance to stay strictly positive. This is a sufficient restriction chosen for the calibration below, not a requirement for every valid Heston specification. The square root in the variance diffusion term ensures that variance fluctuations scale appropriately with the variance level: when variance is high, it can fluctuate more; when variance is low, fluctuations are dampened.

Negative spot-variance correlation tends to associate downward price innovations with increases in variance. It contributes to the downside implied-volatility skew often observed in equity options: lower-strike options have higher implied volatility than higher-strike options at the same maturity. This does not universally rank raw premiums of puts and calls at different strikes.

The Heston model has a semi-closed-form solution for European option prices via characteristic functions. The call price is:

C=StP1−Ke−rTP2C = S_t P_1 - K e^{-rT} P_2

where:

  • CC: call option price
  • StS_t: asset price at time tt
  • KK: strike price
  • rr: risk-free interest rate
  • TT: time to expiration
  • P1,P2P_1, P_2: probabilities derived from the characteristic function, representing the delta and the risk-neutral exercise probability respectively

The terms P1P_1 and P2P_2 are obtained by characteristic-function quadrature. For European options, this can cost substantially less than Monte Carlo at a comparable accuracy target, but performance depends on parameters and implementation. Numerical integration still requires convergence and price-accuracy checks.

Let's implement calibration to option prices. The numerical helper below compares successive integration cutoffs and lower endpoints and retains quadrature error checks. These are convergence diagnostics, not a rigorous universal bound on truncation error. Its supported parameter range and small-price accuracy must be checked independently before interpreting implied-volatility features:

PythonIn [21]
CollapseExpand
from scipy.integrate import quad


def heston_char_func(u, S0, K, T, r, v0, kappa, theta, xi, rho):
    """
    Heston characteristic function for pricing.
    """
    i = complex(0, 1)
    a = kappa * theta
    b = kappa

    d = np.sqrt((rho * xi * i * u - b) ** 2 + xi**2 * (i * u + u**2))
    g = (b - rho * xi * i * u - d) / (b - rho * xi * i * u + d)

    C = r * i * u * T + (a / xi**2) * (
        (b - rho * xi * i * u - d) * T - 2 * np.log((1 - g * np.exp(-d * T)) / (1 - g))
    )
    D = (
        (b - rho * xi * i * u - d)
        / xi**2
        * (1 - np.exp(-d * T))
        / (1 - g * np.exp(-d * T))
    )

    return np.exp(C + D * v0 + i * u * np.log(S0))


def heston_call_price(
    S0, K, T, r, v0, kappa, theta, xi, rho, price_tol=1e-7, max_cutoff=1600
):
    """Approximate no-dividend European-call price with convergence checks."""
    inputs = (S0, K, T, r, v0, kappa, theta, xi, rho, price_tol)
    if not all(np.isfinite(x) for x in inputs):
        raise ValueError("Heston inputs must be finite")
    if min(S0, K, T, v0, kappa, theta, xi, price_tol) <= 0 or abs(rho) >= 1:
        raise ValueError("Invalid Heston parameter domain")
    discounted_strike = K * np.exp(-r * T)
    intrinsic = max(S0 - discounted_strike, 0.0)

    def integrand1(u):
        cf = heston_char_func(u - 1j, S0, K, T, r, v0, kappa, theta, xi, rho)
        return np.real(np.exp(-1j * u * np.log(K)) * cf / (1j * u * S0 * np.exp(r * T)))

    def integrand2(u):
        cf = heston_char_func(u, S0, K, T, r, v0, kappa, theta, xi, rho)
        return np.real(np.exp(-1j * u * np.log(K)) * cf / (1j * u))

    def integrate(lower, cutoff):
        scale = max(S0 + abs(discounted_strike), 1.0)
        epsabs = price_tol * np.pi / (32 * scale)
        values = [
            quad(f, lower, cutoff, epsabs=epsabs, epsrel=1e-10, limit=500)
            for f in (integrand1, integrand2)
        ]
        p1, p2 = (0.5 + item[0] / np.pi for item in values)
        price = S0 * p1 - discounted_strike * p2
        error = (S0 * values[0][1] + abs(discounted_strike) * values[1][1]) / np.pi
        if not np.isfinite(price) or not np.isfinite(error):
            raise ValueError("Nonfinite Heston quadrature")
        return price, error

    # Check both the omitted near-zero interval and increasing tail cutoffs.
    lower = 1e-7
    previous, _ = integrate(lower, 100)
    cutoff = 200
    while cutoff <= max_cutoff:
        coarse, _ = integrate(lower, cutoff)
        current, error = integrate(lower / 100, cutoff)
        if (
            abs(current - previous) <= price_tol
            and abs(current - coarse) <= price_tol / 4
            and error <= price_tol / 4
        ):
            if current < intrinsic or current >= S0:
                raise ValueError("Numerical Heston price violates call bounds")
            return float(current)
        previous = current
        lower /= 100
        cutoff *= 2
    raise RuntimeError("Heston quadrature did not converge to the requested tolerance")

We generate synthetic option quotes with 1% multiplicative noise and then calibrate. The generating parameters have 2κθ=0.202\kappa\theta=0.20 and ξ2=0.25\xi^2=0.25, so the strict Feller restriction imposed below excludes the generating parameter vector. This example is a constrained fit to noisy synthetic inputs, not a test of recovering the generating parameters inside the feasible set:

PythonIn [22]
CollapseExpand
# Market setup
S0 = 100
r = 0.03

# True Heston parameters
v0_true = 0.04  # 20% initial vol
kappa_true = 2.0
theta_true = 0.05  # 22.4% long-term vol
xi_true = 0.5  # vol of vol
rho_true_h = -0.7  # Heston correlation, separate from the SABR example

# Generate market option prices for different strikes and maturities
option_data = []
maturities_opt = [0.25, 0.5, 1.0]
strikes_by_moneyness = [0.85, 0.90, 0.95, 1.00, 1.05, 1.10, 1.15]

np.random.seed(123)
for T in maturities_opt:
    for m in strikes_by_moneyness:
        K = S0 * m
        true_price = heston_call_price(
            S0, K, T, r, v0_true, kappa_true, theta_true, xi_true, rho_true_h
        )
        # Add small noise
        noisy_price = true_price * (1 + np.random.normal(0, 0.01))
        option_data.append({"T": T, "K": K, "price": noisy_price})
PythonIn [23]
CollapseExpand
from scipy.optimize import differential_evolution


def heston_calibration_objective(params, S0, r, option_data):
    """Relative squared price errors under the chosen strict Feller restriction."""
    if not option_data or not np.isfinite(S0) or S0 <= 0 or not np.isfinite(r):
        raise ValueError("Require finite setup and nonempty quotes")
    for opt in option_data:
        if (
            not all(np.isfinite(opt[k]) for k in ("K", "T", "price"))
            or min(opt["K"], opt["T"], opt["price"]) <= 0
        ):
            raise ValueError("Require finite positive strikes, maturities and prices")
    params = np.asarray(params, dtype=float)
    if params.shape != (5,) or not np.all(np.isfinite(params)):
        return np.inf
    v0, kappa, theta, xi, rho = params
    if min(v0, kappa, theta, xi) <= 0 or abs(rho) >= 1:
        return np.inf
    if 2 * kappa * theta <= xi**2:
        return np.inf
    try:
        model_prices = np.array(
            [
                heston_call_price(S0, opt["K"], opt["T"], r, v0, kappa, theta, xi, rho)
                for opt in option_data
            ]
        )
    except (ValueError, RuntimeError, FloatingPointError, OverflowError):
        return np.inf
    targets = np.array([opt["price"] for opt in option_data])
    if not np.all(np.isfinite(model_prices)):
        return np.inf
    return float(np.sum(((model_prices - targets) / targets) ** 2))


# Use differential evolution for global optimization
bounds_heston = [
    (0.001, 0.5),  # v0
    (0.1, 5.0),  # kappa
    (0.001, 0.5),  # theta
    (0.1, 2.0),  # xi
    (-0.99, 0.99),  # rho
]

result_heston = differential_evolution(
    heston_calibration_objective,
    bounds_heston,
    args=(S0, r, option_data),
    maxiter=200,
    seed=42,
    polish=True,  # Finish with L-BFGS-B
)

require_successful_fit(result_heston, "Heston calibration")
v0_cal, kappa_cal_h, theta_cal_h, xi_cal, rho_cal_h = result_heston.x
if 2 * kappa_cal_h * theta_cal_h <= xi_cal**2:
    raise RuntimeError("Heston fit failed the full-precision strict Feller check")
ConsoleOut [24]
CollapseExpand
Heston Model Calibration Results:
--------------------------------------------------
Parameter   |   True    | Calibrated |  Error
--------------------------------------------------
v0          |  0.0400   |   0.0378   | 0.0022
kappa       |  2.0000   |   1.4323   | 0.5677
theta       |  0.0500   |   0.0527   | 0.0027
xi          |  0.5000   |   0.3884   | 0.1116
rho         | -0.7000   |  -0.7300   | 0.0300

Full-precision Feller check: 2κθ = 0.1508535690, ξ² = 0.1508321712, margin = 2.140e-05: ✓

The Heston calibration gives a constrained fit to the noisy synthetic quotes. The fitted parameters differ from the generating values in a calibration that includes both added quote noise and the strict Feller restriction. The generating vector is excluded; this example does not isolate how those factors affect the individual parameter estimates. The printed check uses full-precision calibrated parameters to test 2κθ>ξ22\kappa\theta>\xi^2. The rounded displayed values alone do not establish the margin of that inequality. With the positive parameters and initial variance used here, this restriction is sufficient for strictly positive exact continuous-time variance.

To visualize the model's behavior, we compute the implied volatility surface corresponding to the calibrated parameters. This involves generating Heston prices across a grid of strikes and maturities, then inverting the Black-Scholes formula to find the implied volatility for each.

PythonIn [25]
CollapseExpand
from scipy.optimize import brentq
from scipy.stats import norm


def black_scholes_call(S, K, T, r, sigma):
    if sigma == 0:
        return max(S - K * np.exp(-r * T), 0.0)
    d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    return S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)


def implied_vol_from_price(price, S, K, T, r, tol=1e-8):
    """Invert an unmodified valid call price with an expanding bracket."""
    if not all(np.isfinite(x) for x in (price, S, K, T, r, tol)):
        raise ValueError("Option inputs must be finite")
    if min(S, K, T, tol) <= 0:
        raise ValueError("Require S, K, T and volatility tolerance > 0")
    intrinsic = max(S - K * np.exp(-r * T), 0.0)
    if price < intrinsic or price >= S:
        raise ValueError("Target is outside the finite-IV call price domain")
    if price == intrinsic:
        return 0.0

    def price_error(sigma):
        return black_scholes_call(S, K, T, r, sigma) - price

    upper_vol = 1.0
    for _ in range(20):
        upper_error = price_error(upper_vol)
        if not np.isfinite(upper_error):
            raise ValueError("Nonfinite Black-Scholes bracket evaluation")
        if upper_error >= 0:
            return brentq(price_error, 0.0, upper_vol, xtol=tol)
        upper_vol *= 2
    raise RuntimeError(
        "Valid target was not bracketed within the numerical search limit"
    )


# Create volatility surface
# Selected display domain; each price must pass the quadrature checks.
# A positive price or a successful IV inversion alone does not establish accuracy.
strikes_surface = np.linspace(80, 118, 20)
maturities_surface = np.linspace(0.1, 1.5, 15)

vol_surface = np.zeros((len(maturities_surface), len(strikes_surface)))

for i, T in enumerate(maturities_surface):
    for j, K in enumerate(strikes_surface):
        price = heston_call_price(
            S0, K, T, r, v0_cal, kappa_cal_h, theta_cal_h, xi_cal, rho_cal_h
        )
        vol_surface[i, j] = implied_vol_from_price(price, S0, K, T, r)
VisualizationOut [27]
CollapseExpand
3D surface plot of implied volatility varying across strikes and maturities from the calibrated Heston model.
Heston implied volatilities for the fitted parameters on the selected grid, using numerically checked prices. The shape describes this example; numerical accuracy must be sufficient to interpret small tail features.

The surface and cross-sections describe the joint effect of this fitted parameter vector over the selected grid. Negative correlation contributes to downside skew, while mean reversion and vol of vol affect the maturity profile. One fitted surface does not isolate those effects, and small numerical tail features require separate accuracy checks.

VisualizationOut [29]
CollapseExpand
Line chart showing Heston implied volatility smiles at four maturities from 0.1 to 1.5 years, with the smile becoming progressively flatter at longer maturities.
Selected maturity cross-sections of the fitted Heston example. Compare their strike ranges and numerical accuracy before interpreting skew and term-structure differences.

Key Parameters

The key parameters for the Heston model are:

  • v0v_0: Initial variance. The starting level of the variance process.
  • κ\kappa: Mean reversion speed of variance. Determines how fast variance returns to θ\theta.
  • θ\theta: Long-run average variance. The conditional mean approaches this level while variance continues to fluctuate.
  • ξ\xi: Volatility of variance (vol-of-vol). Controls the variance of the variance process itself, affecting the smile curvature and kurtosis.
  • ρ\rho: Correlation between the asset price and variance processes. Controls the skew of the implied volatility surface.

Maximum Likelihood Estimation for Time-Series Models

While calibration to market prices is essential for pricing derivatives, statistical estimation from historical data remains important for risk modeling and forecasting. Let's demonstrate MLE for the GARCH(1,1) model, building on our discussion in the chapter on modeling volatility.

GARCH(1,1) models time-varying conditional variance. It captures volatility clustering: large-magnitude returns of either sign tend to follow large-magnitude returns, while small-magnitude returns tend to follow small-magnitude returns. The model specifies:

rt=μ+ϵt,ϵt=σtzt,zt∼iidN(0,1)σt2=ω+αϵt−12+βσt−12\begin{aligned} r_t &= \mu + \epsilon_t, \quad \epsilon_t = \sigma_t z_t, \quad z_t \stackrel{iid}{\sim} N(0,1) \\ \sigma_t^2 &= \omega + \alpha \epsilon_{t-1}^2 + \beta \sigma_{t-1}^2 \end{aligned}

where:

  • rtr_t: return at time tt
  • μ\mu: mean return
  • ϵt\epsilon_t: return innovation (residual), the unexpected component of the return
  • σt2\sigma_t^2: conditional variance, the variance of returns conditional on past information
  • ztz_t: independent standard-normal innovation, independent of the past information set
  • ω,α,β\omega, \alpha, \beta: GARCH parameters controlling the variance dynamics

The conditional variance σt2\sigma_t^2 depends on three components. The baseline variance ω\omega provides a floor that prevents variance from collapsing to zero. The recent market shock ϵt−12\epsilon_{t-1}^2 (the ARCH term) allows large return surprises to increase future variance immediately. The previous period's variance σt−12\sigma_{t-1}^2 (the GARCH term) captures the persistence of volatility over time. Together, these components enable the model to capture volatility clustering, where high-volatility periods tend to persist.

Under the usual finite-second-moment assumptions, α+β<1\alpha+\beta<1 and the unconditional variance is ω/(1−α−β)\omega/(1-\alpha-\beta). When α+β\alpha+\beta is close to one from below, variance shocks decay slowly but geometrically. This is persistent behavior, not mathematical long memory. Strict stationarity has a different condition and should not be identified solely with the finite-variance inequality.

The log-likelihood for TT observations is derived from the assumption that innovations are conditionally normal:

ℓ(θ)=−T2log⁡(2π)−12∑t=1T[log⁡(σt2)+ϵt2σt2]\ell(\theta) = -\frac{T}{2}\log(2\pi) - \frac{1}{2}\sum_{t=1}^{T}\left[\log(\sigma_t^2) + \frac{\epsilon_t^2}{\sigma_t^2}\right]

where:

  • ℓ(θ)\ell(\theta): conditional log density of the observed returns, viewed as a function of the parameters
  • TT: number of observations
  • σt2\sigma_t^2: conditional variance at time tt, computed recursively from the GARCH equation
  • ϵt\epsilon_t: residual at time tt, equal to rt−μr_t - \mu
  • π\pi: mathematical constant pi

The log-variance term discourages unnecessarily large variances, while the squared standardized residual penalizes variances too small for the observed innovation. Their balance fits a statistically plausible variance path under the assumed model. Tracking the unobserved variance accurately is a separate question to assess on simulations or validation data.

PythonIn [30]
CollapseExpand
def garch_log_likelihood(params, returns):
    """Conditional Gaussian NLL up to the parameter-independent constant.

    Initialize with the unconditional variance; no stationary marginal density
    for the first observation is included.
    """
    returns = np.asarray(returns, dtype=float)
    if returns.ndim != 1 or returns.size == 0 or not np.all(np.isfinite(returns)):
        raise ValueError("Require a nonempty finite one-dimensional return array")
    params = np.asarray(params, dtype=float)
    if params.shape != (4,) or not np.all(np.isfinite(params)):
        return np.inf
    mu, omega, alpha, beta = params
    if omega <= 0 or min(alpha, beta) < 0 or alpha + beta >= 1:
        return np.inf
    eps = returns - mu
    sigma2 = np.empty(len(returns))
    sigma2[0] = omega / (1 - alpha - beta)
    for t in range(1, len(returns)):
        sigma2[t] = omega + alpha * eps[t - 1] ** 2 + beta * sigma2[t - 1]
    if not np.all(np.isfinite(sigma2)) or not np.all(sigma2 > 0):
        return np.inf
    # Conditional negative log-likelihood without T*log(2*pi)/2.
    value = 0.5 * np.sum(np.log(sigma2) + eps**2 / sigma2)
    return float(value) if np.isfinite(value) else np.inf


# Generate synthetic daily GARCH returns (252 trading days per year convention).
np.random.seed(42)
T_sim = 2000

# True parameters
mu_true = 0.0005
omega_true = 0.00001
alpha_true_g = 0.08
beta_true_g = 0.88

# Simulate
returns_sim = np.zeros(T_sim)
sigma2_sim = np.zeros(T_sim)
sigma2_sim[0] = omega_true / (1 - alpha_true_g - beta_true_g)
# One period is a trading day; draw the initial observation as well.
returns_sim[0] = mu_true + np.sqrt(sigma2_sim[0]) * np.random.normal()

for t in range(1, T_sim):
    sigma2_sim[t] = (
        omega_true
        + alpha_true_g * (returns_sim[t - 1] - mu_true) ** 2
        + beta_true_g * sigma2_sim[t - 1]
    )
    returns_sim[t] = mu_true + np.sqrt(sigma2_sim[t]) * np.random.normal()
PythonIn [31]
CollapseExpand
# MLE estimation
x0_garch = [0.0, 0.00002, 0.05, 0.90]
bounds_garch = [
    (-0.01, 0.01),  # mu
    (1e-8, 0.001),  # omega
    (0.001, 0.5),  # alpha
    (0.5, 0.999),  # beta
]

# Scale differently sized coordinates before finite-difference optimization.
garch_scale = np.array([0.001, 0.00001, 0.1, 1.0])
scaled_bounds = [
    (lower / scale, upper / scale)
    for (lower, upper), scale in zip(bounds_garch, garch_scale)
]
garch_candidates = []
for start in (x0_garch, [0.001, 0.00002, 0.10, 0.80]):
    fit = minimize(
        lambda scaled: garch_log_likelihood(scaled * garch_scale, returns_sim),
        np.asarray(start) / garch_scale,
        method="L-BFGS-B",
        bounds=scaled_bounds,
        options={"ftol": 1e-12, "gtol": 1e-6, "maxiter": 2000},
    )
    if fit.success and np.isfinite(fit.fun) and np.all(np.isfinite(fit.x)):
        fit.x = fit.x * garch_scale
        if fit.x[2] + fit.x[3] < 1:
            garch_candidates.append(fit)
if not garch_candidates:
    raise RuntimeError("No successful finite feasible GARCH likelihood fit")
result_garch = min(garch_candidates, key=lambda fit: fit.fun)
print(f"Accepted scaled local starts: {len(garch_candidates)}/2")
print(f"Best conditional NLL (constant omitted): {result_garch.fun:.8f}")

mu_cal_g, omega_cal, alpha_cal_g, beta_cal_g = result_garch.x
ConsoleOut [32]
CollapseExpand
GARCH(1,1) Local Likelihood-Fit Results:
--------------------------------------------------
Parameter |   True     | Estimated  |  Error
--------------------------------------------------
mu        |  0.000500 |  0.001231 | 0.000731
omega     | 0.0000100| 0.0000186 | 0.0000086
alpha     |  0.080000 |  0.078642 | 0.001358
beta      |  0.880000 |  0.837991 | 0.042009

Persistence (α + β): 0.9166
Unconditional vol: 23.74% annualized

These are local likelihood-fit estimates, with numerical diagnostics reported alongside the parameter discrepancies. A successful stopping flag does not prove a likelihood maximum or accurate recovery of every generating parameter. Compare objective values across scaled starts, then assess conditional-volatility tracking separately. Each simulated period is a trading day; annualization uses an explicit 252-trading-day convention.

VisualizationOut [34]
CollapseExpand
Time series plot of 2000 simulated GARCH returns in percent, showing alternating calm and turbulent periods consistent with volatility clustering.
Simulated GARCH returns showing volatility clustering. The series displays characteristic periods of high and low variance.
VisualizationOut [36]
CollapseExpand
Time series plot comparing true GARCH conditional volatility as a dashed line against the MLE-estimated conditional volatility as a solid line over 2000 simulated periods.
Estimated and generating GARCH conditional volatility on this synthetic sample. The comparison describes variance-path tracking, separately from parameter recovery and optimizer optimality.

Key Parameters

The key parameters for the GARCH(1,1) model are:

  • ω\omega: Constant baseline variance term.
  • α\alpha: ARCH parameter. Measures the reaction of volatility to recent return shocks (innovations).
  • β\beta: GARCH parameter. Measures the persistence of past variance.
  • μ\mu: Mean return parameter.

Overfitting and Model Selection

Overfitting means fitting sample-specific noise or patterns that do not transfer to the intended prediction task. An overfit model can have nonzero training residuals, and exact interpolation alone does not imply poor generalization. Compare calibration fit with suitable held-out data rather than identifying overfitting from training error alone.

Overfitting

The tendency of flexible models to fit noise in calibration data, leading to unstable parameters and poor out-of-sample performance. Overfit models appear excellent on calibration instruments but fail on new data.

Symptoms of Overfitting

Overfitting manifests in several characteristic ways that you learn to recognize:

  • Parameter instability is a warning to investigate: small data changes can expose weak identification, poor conditioning, optimizer problems or changing market conditions, as well as overfitting. Erratic fitted parameters alone do not establish that the model is fitting noise.

  • Extreme or boundary parameter values warrant checking constraints, data, model assumptions and the optimizer. They may reflect underlying dynamics and do not alone prove that the model is fitting noise. Economic intuition can help assess whether the fitted values are plausible.

  • Poor out-of-sample performance tests generalization. A precise calibration fit followed by large errors on held-out instruments is a warning, but does not isolate overfitting from misspecification or distribution shift. Reserve separate data for testing and investigate the source of the failure.

Sources of Overfitting

The primary sources of overfitting include:

  • Too many parameters relative to information. Extra free parameters can fit noise when the data weakly constrain them. Information depends on parameter sensitivities and quote-error covariance; redundant sensitivities or correlated errors can reduce it. Adjacent strikes alone do not establish a universal information ranking, and effective independent observations differ from fitted model degrees of freedom.

  • Noisy data. Measurement error, staleness and temporary dislocations can influence fitted parameters. Such artifacts may persist or be correlated, but they need not transfer to the intended pricing or forecasting task. Assess their data-quality origin and dependence rather than assuming they vanish immediately.

  • Model misspecification. A restricted model can use compensating parameters to approximate dynamics it cannot represent. This is distinct from fitting sample noise, though the two can interact. Extra flexibility can also reduce genuine systematic bias; assess held-out behavior and the economic meaning of the fitted parameters.

Preventing Overfitting

Several strategies mitigate overfitting:

Regularization adds penalties for complex solutions:

Lreg(θ)=L(θ)+λR(θ)L_{reg}(\theta) = L(\theta) + \lambda R(\theta)

where:

  • R(θ)R(\theta): penalty function (e.g., parameter magnitude or parameter variability)
  • λ\lambda: regularization parameter controlling the trade-off between fit and complexity

Regularization encourages the chosen measure of simplicity or stability. It can improve generalization when the penalty and its strength suit the problem, but it also adds bias. Specify the parameter scaling and choose the penalty using an appropriate validation procedure.

Cross-validation fits on training subsets and evaluates held-out data. It estimates predictive error for the chosen data and split design; randomly held-out strikes do not establish performance in future market regimes. Use date-based or other deployment-relevant holdouts when that is the intended task.

Information criteria like AIC and BIC provide principled model selection that balances fit quality against model complexity:

AIC=2k−2ln⁡(L^)BIC=kln⁡(n)−2ln⁡(L^)\begin{aligned} AIC &= 2k - 2\ln(\hat{L}) \\ BIC &= k\ln(n) - 2\ln(\hat{L}) \end{aligned}

where:

  • AICAIC: Akaike Information Criterion
  • BICBIC: Bayesian Information Criterion
  • kk: number of parameters
  • nn: sample size
  • L^\hat{L}: maximized likelihood value

Compare these criteria using compatible maximized likelihoods on the same observations and a count of all fitted free parameters, including nuisance parameters such as an estimated error variance. An arbitrary SSE is not itself L^\hat L. Lower values favor a model by the selected criterion under its assumptions, not universally better predictions. BIC's klog⁡nk\log n penalty exceeds AIC's 2k2k when n>e2n>e^2; their usual asymptotic interpretations require suitable regularity and identification.

Justified parameter bounds can exclude implausible values and reduce some extreme noise-fitting, but they do not prevent overfitting within the interval. Historical parameter ranges should not be transferred to a different pricing measure without a model of that relationship.

Let's evaluate held-out fit for the fixed-beta SABR specification:

PythonIn [37]
CollapseExpand
from sklearn.model_selection import KFold


def cross_validate_sabr(strikes, market_vols, F, T, beta, n_folds=5):
    """
    Cross-validation for SABR calibration.
    Returns the unweighted mean of held-out-fold RMSEs.
    """
    strikes, market_vols = validate_sabr_quotes(strikes, market_vols, F, T, beta)
    if not isinstance(n_folds, (int, np.integer)) or not 2 <= n_folds <= len(strikes):
        raise ValueError("Require 2 <= n_folds <= number of quotes")
    kf = KFold(n_splits=n_folds, shuffle=True, random_state=42)
    cv_errors = []

    for train_idx, test_idx in kf.split(strikes):
        # Training data
        strikes_train = strikes[train_idx]
        vols_train = market_vols[train_idx]

        # Test data
        strikes_test = strikes[test_idx]
        vols_test = market_vols[test_idx]

        # Calibrate on training set
        x0 = [0.25, -0.20, 0.35]
        bounds = [(0.01, 1.0), (-0.99, 0.99), (0.01, 2.0)]

        result = minimize(
            calibration_objective,
            x0,
            args=(F, T, strikes_train, vols_train, beta),
            method="L-BFGS-B",
            bounds=bounds,
        )

        require_successful_fit(result, "SABR cross-validation fold")
        alpha_cv, rho_cv, nu_cv = result.x

        # Evaluate on test set
        test_errors = []
        for K, vol_true in zip(strikes_test, vols_test):
            vol_model = sabr_implied_vol(F, K, T, alpha_cv, beta, rho_cv, nu_cv)
            if not np.isfinite(vol_model) or vol_model <= 0:
                raise RuntimeError("Invalid held-out SABR volatility")
            test_errors.append((vol_model - vol_true) ** 2)

        cv_errors.append(np.sqrt(np.mean(test_errors)))

    return np.mean(cv_errors)


# Generate more strikes for better CV demonstration
strikes_full = np.linspace(75, 125, 21)
market_vols_full = np.array(
    [
        sabr_implied_vol(
            F_true, K, sabr_maturity, alpha_true, beta_true, rho_true, nu_true
        )
        for K in strikes_full
    ]
)
market_vols_full += np.random.normal(0, 0.008, len(strikes_full))

cv_rmse = cross_validate_sabr(
    strikes_full, market_vols_full, F_true, sabr_maturity, beta_fixed, n_folds=5
)
ConsoleOut [38]
CollapseExpand
Cross-Validation RMSE: 0.73 vol points (73.4 bps)

This unweighted mean of fold RMSEs summarizes error on randomly held-out strikes for these training subsets and this synthetic dataset. A small value is evidence about that evaluation design, not proof of future-market performance or the absence of overfitting. Compare suitable baselines and reserve independent data for any subsequent model-selection claims.

Parameter Stability Analysis

Examining how calibrated parameters change with different data provides insight into identification and overfitting:

PythonIn [39]
CollapseExpand
def bootstrap_parameter_stability(
    strikes, market_vols, F, T, beta, n_bootstrap=50, rng=None
):
    """Paired resampling with explicit solver screening and failure counts."""
    strikes, market_vols = validate_sabr_quotes(strikes, market_vols, F, T, beta)
    if not isinstance(n_bootstrap, (int, np.integer)) or n_bootstrap <= 0:
        raise ValueError("n_bootstrap must be a positive integer")
    rng = np.random.default_rng(42) if rng is None else rng
    params_samples = []
    failed = 0
    n = len(strikes)
    for _ in range(n_bootstrap):
        idx = rng.choice(n, size=n, replace=True)
        result = minimize(
            calibration_objective,
            [0.25, -0.20, 0.35],
            args=(F, T, strikes[idx], market_vols[idx], beta),
            method="L-BFGS-B",
            bounds=[(0.01, 1.0), (-0.99, 0.99), (0.01, 2.0)],
        )
        if result.success and np.isfinite(result.fun) and np.all(np.isfinite(result.x)):
            params_samples.append(result.x.copy())
        else:
            failed += 1
    print(
        f"Bootstrap fits accepted: {len(params_samples)}/{n_bootstrap}; failed: {failed}"
    )
    if failed:
        raise RuntimeError(
            "Bootstrap contains failed fits; inspect them before inference"
        )
    return np.array(params_samples)


param_samples = bootstrap_parameter_stability(
    strikes_full, market_vols_full, F_true, sabr_maturity, beta_fixed, n_bootstrap=100
)
VisualizationsOut [41]
CollapseExpand
Histogram of bootstrap alpha estimates with a dashed line at the true value and a solid line at the bootstrap mean.
Bootstrap distribution of calibrated SABR alpha across 100 successfully fitted resampled datasets. The reference lines mark the generating value and the resampling mean; their separation and the spread summarize sensitivity in this example, not proof of unique identification.
Histogram of bootstrap rho estimates with a dashed line at the true value and a solid line at the bootstrap mean.
Bootstrap distribution of calibrated SABR rho across 100 successfully fitted resampled datasets. Compare the resampling mean with the generating correlation and inspect the spread; this resampling exercise does not establish structural identification.
Histogram of bootstrap nu estimates with a dashed line at the true value and a solid line at the bootstrap mean.
Bootstrap distribution of calibrated SABR nu across 100 successfully fitted resampled datasets. The spread and tail behavior describe uncertainty across these fits, rather than demonstrating robust or uniquely identified calibration.
ConsoleOut [42]
CollapseExpand
Parameter Stability Summary:
--------------------------------------------------
Parameter |  Mean  |  Std Dev  | Relative dispersion (%) |  True
--------------------------------------------------
  alpha  |  0.174 |   0.0318  |  18.3%  | 0.200
  rho    | -0.398 |   0.1307  |  32.9%  | -0.300
  nu     |  0.378 |   0.0702  |  18.6%  | 0.400

These bootstrap samples describe how the fitted parameters respond to resampling this particular synthetic dataset. Their spread and any shift from the generating values are useful uncertainty diagnostics, not proof of structural or unique identification or of the absence of overfitting. The displayed relative dispersion is 100 times the standard deviation divided by the absolute sample mean. It becomes unstable near a zero mean; for signed parameters such as correlation, inspect absolute spread, scale and the sampled distribution rather than treating this ratio as a scale-free identification measure.

VisualizationOut [44]
CollapseExpand
Line chart comparing a degree-5 overfit polynomial against a degree-2 smoother and the true SABR model, showing the overfit curve oscillating wildly outside training points.
Polynomial illustration on a synthetic SABR slice: a degree-5 interpolant fits the six noisy training points, while a degree-2 smoother has lower error against the known generating function on the displayed grid. Smoothness alone does not establish general calibration adequacy.

Practical Calibration Workflows

Real-world calibration requires clean data and stable optimization, backed by ongoing monitoring.

Data Preparation

Before calibration, market data must be cleaned and prepared:

  • Quote filtering removes stale, erroneous, or illiquid quotes. Options with very low open interest or wide bid-ask spreads may contain noise that degrades calibration.

  • Consistency checks detect possible static-arbitrage violations. Check strike convexity using correctly weighted long butterfly spreads. Calendar consistency requires the carry-adjusted or forward-moneyness conditions appropriate to the instruments; raw same-strike price monotonicity is not universal with dividends or other carry. Selected checks alone do not certify an entire interpolated surface.

  • Standardization converts raw prices to a common format. Options at different maturities should use appropriate day-count conventions and settlement rules.

Multi-Start Optimization

Multiple starting points are often useful for checking a non-convex fit's sensitivity to initialization:

PythonIn [45]
CollapseExpand
def multi_start_sabr_calibration(
    strikes, market_vols, F, T, beta, n_starts=10, rng=None
):
    """Return the best successful finite candidate among explicit starts."""
    strikes, market_vols = validate_sabr_quotes(strikes, market_vols, F, T, beta)
    if not isinstance(n_starts, (int, np.integer)) or n_starts <= 0:
        raise ValueError("n_starts must be a positive integer")
    rng = np.random.default_rng(42) if rng is None else rng
    best_result = None
    rejected = 0
    for _ in range(n_starts):
        start = [rng.uniform(0.1, 0.5), rng.uniform(-0.8, 0.2), rng.uniform(0.2, 0.8)]
        try:
            result = minimize(
                calibration_objective,
                start,
                args=(F, T, strikes, market_vols, beta),
                method="L-BFGS-B",
                bounds=[(0.01, 1.0), (-0.99, 0.99), (0.01, 2.0)],
            )
        except (ValueError, FloatingPointError, OverflowError):
            rejected += 1
            continue
        if (
            not result.success
            or not np.isfinite(result.fun)
            or not np.all(np.isfinite(result.x))
        ):
            rejected += 1
            continue
        if best_result is None or result.fun < best_result.fun:
            best_result = result
    print(
        f"Multi-start fits accepted: {n_starts - rejected}/{n_starts}; rejected: {rejected}"
    )
    if best_result is None:
        raise RuntimeError("No successful finite SABR calibration candidate")
    return best_result


# Run multi-start
multistart_result = multi_start_sabr_calibration(
    strikes, market_vols_noisy, F_true, sabr_maturity, beta_fixed, n_starts=20
)
alpha_ms, rho_ms, nu_ms = multistart_result.x
ConsoleOut [46]
CollapseExpand
Multi-Start Calibration Results:
Best SSE found: 0.00011966
Parameters: α=0.2264, ρ=-0.2940, ν=0.3909

The multi-start comparison uses the same one-year SABR quotes and maturity as the initial calibration, with sabr_maturity kept separate from the Heston examples' maturity loops. The best multi-start run reaches a similar parameter region to the initial run. Agreement across these starting points is evidence of stability in these runs, not a proof of global optimality or unique parameter identification.

VisualizationsOut [48]
CollapseExpand
Trajectory lines in alpha-rho parameter space leading from circular starting markers toward a star marking the best calibration found among the attempted starts.
Multi-start L-BFGS-B trajectories in the alpha-rho plane, showing the recorded paths from the selected starting points and the best calibrated point. These paths do not establish unique parameter identification.
Trajectory lines in alpha-nu parameter space leading from circular starting markers toward a star marking the best calibration found among the attempted starts.
Multi-start L-BFGS-B trajectories in the alpha-nu plane, showing the recorded paths from the selected starting points and the best calibrated point. Agreement in these runs is not a guarantee for other initializations.

Calibration Monitoring

In production, monitor calibration for problems:

  • Fit quality metrics track calibration RMSE over time. Sudden increases may indicate market regime changes or data problems.

  • Parameter drift monitors how fitted parameters evolve. Large daily changes can reflect market moves, data changes, weak identification, optimization instability or overfitting; they are a warning to investigate, not a diagnosis.

  • Constraint binding tracks how often fitted parameters reach their bounds. Repeated bound hits warrant checking the bounds, data, objective and numerical diagnostics; they do not by themselves establish model inadequacy.

Limitations and Impact

Calibration is both essential and inherently limited. Understanding these limitations helps us use calibrated models appropriately.

A calibration fits a snapshot of observations, while markets and data change. A fit can become unsuitable after a volatility or correlation change. More frequent recalibration can transmit noisy quote changes into parameters and hedges, but instability is not inevitable; data quality, smoothing and regularization affect the trade-off.

Calibration seeks parameters that fit a chosen model and objective. Numerical verification is needed because a finite optimizer need not find the best feasible parameters. Fit diagnostics can inform model assessment, but fit alone cannot establish adequate dynamics for a new instrument or task. Residual structure can reflect model restrictions, data errors or incomplete numerical optimization.

The impact of calibration extends throughout derivatives pricing and risk management. Well-calibrated models enable consistent pricing between standard instruments (used for hedging) and exotics (being priced). They support model-based hedging strategies, where Greeks computed from calibrated models guide position adjustments. And they set up risk measurement, where consistent valuation across a portfolio requires coherent model parameters.

The estimation and validation methods used here also support portfolio optimization in Part IX, where expected returns and covariances require an appropriate physical-measure model. In Part X, volatility and dependence models support Value-at-Risk and stress testing when combined with suitable real-world dynamics and scenario assumptions. Option-implied pricing parameters alone do not supply those distributions.

Summary

This chapter developed the theory and practice of model calibration, one of the most practically important skills in quantitative finance.

We established the calibration problem: finding model parameters that minimize the discrepancy between model outputs and market observations. Different objective functions (such as price errors, implied volatility errors, or likelihood functions) encode different notions of fit quality. The choice should reflect the model's intended use.

Optimization techniques range from gradient-based methods for smooth, well-behaved objectives to global optimization for complex, non-convex objectives. Practical calibration uses multi-start optimization, appropriate constraints, and regularization to find solutions that are stable across starting points.

Through worked examples, we calibrated the SABR model to option implied volatilities, the Vasicek model to yield curves, and the Heston model to option prices across strikes and maturities. The examples illustrate objective definition, numerical fitting and fit reporting. Solver-status and finite-output checks help screen results; independent numerical-accuracy and validation checks remain necessary before relying on them.

The dangers of overfitting received substantial attention. Overfit models match calibration data well but generalize poorly. Warning signs include parameter instability, extreme values, and poor out-of-sample performance. Mitigation strategies include regularization, cross-validation, information criteria for model selection, and bootstrap analysis of parameter uncertainty.

Calibration is an ongoing process. In production, monitor fit and choose recalibration schedules or market-event triggers suited to the model's use and the available data. The goal is practical adequacy for the intended pricing, hedging or risk task, rather than a perfect description of every market outcome. Assess that adequacy with numerical checks, validation and continuing monitoring.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about calibration and parameter estimation in financial models.

Calibration and Parameter Estimation

Question 1 of 80 of 8 completed
As used in this chapter, what distinguishes historical dynamics estimation from current market-price calibration?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Quantitative Finance · Vol. 3

Principal Component Analysis: Factor Extraction for Finance

Covers PCA for extracting factors from yield curves and equity returns. Topics include dimension reduction, eigendecomposition.

47 min read
Quantitative Finance · Vol. 3

Regression Analysis: Beta Estimation & Factor Models

Covers regression analysis for finance: estimate market beta, test alpha significance, diagnose heteroskedasticity.

49 min read
Quantitative Finance · Vol. 3

GARCH Volatility Models: Capturing Time-Varying Market Risk

Covers GARCH and ARCH models for time-varying volatility forecasting. Topics include estimation, persistence analysis, and dynamic VaR with Python examples.

51 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2025calibrationparameter, author = {Michael Brenndoerfer}, title = {Calibration & Parameter Estimation}, year = {2025}, url = {https://mbrenndoerfer.com/writing/calibration-parameter-estimation-financial-models}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-11-13} }
APAAcademic
Michael Brenndoerfer (2025). Calibration & Parameter Estimation. Retrieved from https://mbrenndoerfer.com/writing/calibration-parameter-estimation-financial-models
MLAAcademic
Michael Brenndoerfer. "Calibration & Parameter Estimation." 2026. Web. November 13, 2026. <https://mbrenndoerfer.com/writing/calibration-parameter-estimation-financial-models>.
CHICAGOAcademic
Michael Brenndoerfer. "Calibration & Parameter Estimation." Accessed November 13, 2026. https://mbrenndoerfer.com/writing/calibration-parameter-estimation-financial-models.
HARVARDAcademic
Michael Brenndoerfer (2025) 'Calibration & Parameter Estimation'. Available at: https://mbrenndoerfer.com/writing/calibration-parameter-estimation-financial-models (Accessed: November 13, 2026).
SimpleBasic
Michael Brenndoerfer (2025). Calibration & Parameter Estimation. https://mbrenndoerfer.com/writing/calibration-parameter-estimation-financial-models
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy