Optimisation#

Calibration chooses the parameters that fit a model to prices, a portfolio is built to minimise a risk, and a curve is fitted by minimising an error. All are optimisation: find the point \(x\) that makes an objective \(f(x)\) as small as possible, possibly subject to constraints. The methods differ in what they need, a gradient, a Hessian or nothing, and in what they promise, the nearest minimum or the best one. This page sets out the main families, shows how they compare on a curved valley, how often a gradient method finds the global minimum when there are many local ones, and what a constraint does to a solution.

The problem#

An unconstrained problem is \(\min_x f(x)\). At a minimum the gradient is zero, \(\nabla f(x^*) = 0\), and the Hessian \(H = \nabla^2 f(x^*)\) is positive semi-definite. These are conditions for a local minimum only. A function with several valleys has several, and a method that follows the slope downhill finds the one it starts near. A constrained problem adds equalities \(g(x) = 0\), inequalities \(h(x) \le 0\) and bounds, and the minimum satisfies the Karush-Kuhn-Tucker conditions: the gradient of \(f\) is a combination of the gradients of the constraints that are active, with multipliers that say what each constraint costs.

Methods that use the gradient#

Steepest descent moves against the gradient, \(x_{k+1} = x_k - \alpha_k \nabla f(x_k)\). It is simple and slow: in a narrow curved valley it zigzags across it.

Newton’s method uses the curvature,

\[x_{k+1} = x_k - H(x_k)^{-1} \nabla f(x_k)\]

which converges quadratically near a minimum, and needs the Hessian, the Jacobian of the gradient (The Jacobian), which costs \(n^2\) second derivatives and a linear solve (Numerical Linear Algebra). Far from the minimum the Hessian may not be positive definite and the step may go uphill, and so a line search or a trust region limits the step.

Quasi-Newton methods, of which BFGS is the standard, build an approximation to the inverse Hessian from the successive gradients. They need only the gradient, converge faster than linearly, and are the usual choice for smooth problems of moderate size. Limited-memory variants (L-BFGS) store a few vectors and suit large problems, with simple bounds. Conjugate gradient methods need only the gradient and a few vectors, and suit very large problems.

Trust-region methods minimise a quadratic model within a region where it is trusted, and enlarge or shrink the region by comparing the predicted and the actual fall. They are robust when the Hessian is indefinite.

Least-squares problems, \(f = \tfrac12 \sum r_i(x)^2\), have a special structure: the Hessian is approximately \(J^\top J\), where \(J\) is the Jacobian of the residuals. Gauss-Newton and Levenberg-Marquardt use it, and are the methods of Regression and Fitting, Part 3: Non-linear Regression.

Methods without a gradient#

Nelder-Mead keeps a simplex of \(n + 1\) points and replaces the worst by reflecting, expanding or contracting it. It needs only values of \(f\), tolerates some noise, and is slow, and unreliable beyond a handful of parameters. It is the fallback when the gradient cannot be computed. A numerical gradient, with the errors of Numerical Differentiation, is the other option, and it costs \(n\) or \(2n\) evaluations of \(f\) at each step.

Global methods#

A gradient method finds a local minimum. For a function with many, there are two common approaches. Multi-start runs a local method from many points, and keeps the best. Population methods, such as differential evolution, keep a set of candidate points and combine them, so that the set spreads over the whole region and then converges. They need bounds, many evaluations and no gradient, and they give a good starting point for a local method, not a precise answer. Simulated annealing accepts uphill steps with a probability that falls, and is similar in use. None guarantees the global minimum.

Constraints#

Simple bounds are handled by projected and active-set methods (L-BFGS-B). General constraints use sequential quadratic programming (SLSQP), which solves a quadratic problem with linearised constraints at each step, or interior-point methods, which stay inside the feasible region by adding a barrier. A constraint that is active at the solution is a statement that the unconstrained optimum is not allowed, and the multiplier is its price. Parameters that finish on a bound often show a model that is trying to do something that it is not allowed to do.

Stopping#

An optimiser stops when the gradient is small, the step is small or the fall is small. These are not the same as being close to the minimum. In a flat valley the objective can be within \(10^{-6}\) of its minimum while the parameters are far from theirs, and a tolerance that is too loose stops early and returns a point that depends on the starting value.

Worked example#

The example minimises the Rosenbrock function, a curved valley with a minimum at (1, 1), with six methods, and with BFGS at three stopping tolerances. It then runs BFGS from 500 starting points on a function with many local minima, the two-dimensional Rastrigin function, and compares multi-start with differential evolution. Finally it finds the minimum-variance portfolio of four assets with a sum constraint, by a linear solve and by SLSQP, and again with a long-only bound.

Python code
"""Optimisation: gradient and derivative-free methods on a curved valley, local minima, and a constrained portfolio problem."""
import numpy as np
from scipy.optimize import differential_evolution, minimize, rosen, rosen_der, rosen_hess


def rastrigin(x):
    x = np.asarray(x)
    return 20 + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))


if __name__ == "__main__":
    print("1. Rosenbrock function in two dimensions, start (-1.2, 1), minimum at (1, 1)")
    print(f"   {'Method':<34} {'iterations':>10} {'f evals':>8} {'gradient evals':>15} {'distance to minimum':>20}")
    runs = (
        ("Nelder-Mead (no gradient)", dict(method="Nelder-Mead", options={"xatol": 1e-10, "fatol": 1e-14})),
        ("BFGS, numerical gradient", dict(method="BFGS", options={"gtol": 1e-8})),
        ("BFGS, analytic gradient", dict(method="BFGS", jac=rosen_der, options={"gtol": 1e-8})),
        ("Conjugate gradient, analytic", dict(method="CG", jac=rosen_der, options={"gtol": 1e-8})),
        ("Newton-CG, analytic Hessian", dict(method="Newton-CG", jac=rosen_der, hess=rosen_hess, options={"xtol": 1e-10})),
        ("Trust region, analytic Hessian", dict(method="trust-exact", jac=rosen_der, hess=rosen_hess, options={"gtol": 1e-10})),
    )
    for name, kw in runs:
        r = minimize(rosen, [-1.2, 1.0], **kw)
        print(f"   {name:<34} {r.nit:10d} {r.nfev:8d} {getattr(r, 'njev', 0):15d} {np.linalg.norm(r.x - 1):20.1e}")

    print("\n   The same problem with BFGS and a looser stopping tolerance on the gradient")
    for gtol in (1e-2, 1e-4, 1e-8):
        r = minimize(rosen, [-1.2, 1.0], method="BFGS", jac=rosen_der, options={"gtol": gtol})
        print(f"   gtol {gtol:7.0e}: iterations {r.nit:3d}, distance to minimum {np.linalg.norm(r.x - 1):.1e}, objective {r.fun:.1e}")

    print("\n2. Local minima: the two-dimensional Rastrigin function, minimum 0 at the origin, many local minima")
    rng = np.random.default_rng(3)
    starts = rng.uniform(-5.12, 5.12, size=(500, 2))
    finals = np.array([minimize(rastrigin, s, method="BFGS").fun for s in starts])
    print(f"   BFGS from 500 random starts: reaches the global minimum in {np.mean(finals < 1e-6):.1%}, median final value {np.median(finals):.3f}, worst {finals.max():.3f}")
    best_of = [min(minimize(rastrigin, s, method="BFGS").fun for s in rng.uniform(-5.12, 5.12, size=(20, 2))) for _ in range(100)]
    print(f"   Best of 20 starts, repeated 100 times: reaches the global minimum in {np.mean(np.array(best_of) < 1e-6):.0%}")
    wins, evals = 0, []
    for seed in range(20):
        r = differential_evolution(rastrigin, [(-5.12, 5.12)] * 2, seed=seed, tol=1e-10)
        wins += r.fun < 1e-6
        evals.append(r.nfev)
    print(f"   Differential evolution, 20 seeds: reaches the global minimum in {wins / 20:.0%}, mean evaluations {np.mean(evals):.0f}")

    print("\n3. Minimum-variance portfolio of four assets, weights sum to 1")
    vol = np.array([0.15, 0.20, 0.25, 0.30])
    corr = np.array([[1.0, 0.9, 0.8, 0.2], [0.9, 1.0, 0.85, 0.3], [0.8, 0.85, 1.0, 0.4], [0.2, 0.3, 0.4, 1.0]])
    cov = corr * np.outer(vol, vol)
    ones = np.ones(4)
    exact = np.linalg.solve(cov, ones)
    exact /= ones @ exact
    variance = lambda w: w @ cov @ w
    sum_one = {"type": "eq", "fun": lambda w: w.sum() - 1}
    free = minimize(variance, ones / 4, constraints=[sum_one], method="SLSQP", options={"ftol": 1e-14})
    long_only = minimize(variance, ones / 4, constraints=[sum_one], bounds=[(0, 1)] * 4, method="SLSQP", options={"ftol": 1e-14})
    print(f"   {'':<28} " + " ".join(f"{'w' + str(i + 1):>8}" for i in range(4)) + f" {'volatility':>11}")
    for name, w in (("Closed form (linear solve)", exact), ("SLSQP, sum constraint", free.x), ("SLSQP, long-only", long_only.x)):
        print(f"   {name:<28} " + " ".join(f"{x:8.4f}" for x in w) + f" {np.sqrt(variance(w)):11.4%}")
    print(f"   largest difference between the closed form and SLSQP: {np.max(np.abs(exact - free.x)):.1e}")

The output is:

1. Rosenbrock function in two dimensions, start (-1.2, 1), minimum at (1, 1)
   Method                             iterations  f evals  gradient evals  distance to minimum
   Nelder-Mead (no gradient)                 132      249               0              5.4e-11
   BFGS, numerical gradient                   34      123              41              1.0e-05
   BFGS, analytic gradient                    34       41              41              1.2e-12
   Conjugate gradient, analytic               37       80              79              1.2e-10
   Newton-CG, analytic Hessian                85      107             107              8.1e-10
   Trust region, analytic Hessian             26       27              24              0.0e+00

   The same problem with BFGS and a looser stopping tolerance on the gradient
   gtol   1e-02: iterations  29, distance to minimum 5.3e-03, objective 5.7e-06
   gtol   1e-04: iterations  32, distance to minimum 6.1e-08, objective 2.5e-15
   gtol   1e-08: iterations  34, distance to minimum 1.2e-12, objective 4.4e-25

2. Local minima: the two-dimensional Rastrigin function, minimum 0 at the origin, many local minima
   BFGS from 500 random starts: reaches the global minimum in 1.0%, median final value 15.919, worst 64.671
   Best of 20 starts, repeated 100 times: reaches the global minimum in 18%
   Differential evolution, 20 seeds: reaches the global minimum in 90%, mean evaluations 1963

3. Minimum-variance portfolio of four assets, weights sum to 1
                                   w1       w2       w3       w4  volatility
   Closed form (linear solve)     1.4517  -0.3597  -0.2940   0.2020    12.6293%
   SLSQP, sum constraint          1.4517  -0.3597  -0.2940   0.2020    12.6293%
   SLSQP, long-only               0.8571   0.0000   0.0000   0.1429    14.3427%
   largest difference between the closed form and SLSQP: 6.9e-08

Reading the output:

  • The gradient and the curvature save evaluations. The trust-region method with exact derivatives takes 26 iterations and 27 function evaluations. BFGS with an analytic gradient takes 34 iterations and 41. Nelder-Mead, which uses the function alone, takes 249 evaluations, six times as many, and reaches the minimum to 5e-11 only with a tight tolerance.

  • A numerical gradient limits the accuracy. The same BFGS with a finite-difference gradient takes the same 34 iterations, but stops 1e-5 from the minimum and not 1e-12, and takes 123 function evaluations, which include the two per gradient that the differences need. The error of the gradient sets the accuracy of the answer.

  • More information is not always faster. Newton-CG with the exact Hessian takes 85 iterations, more than BFGS, which builds its own estimate of the curvature from the gradients.

  • The tolerance decides how close the answer is. With a gradient tolerance of 1e-2 the optimiser stops after 29 iterations at a distance of 5.3e-3 from the minimum, though the objective is 5.7e-6. The objective is a poor guide to the parameters: it is small in the whole valley. With 1e-8 the distance is 1.2e-12.

  • A gradient method finds the global minimum by luck. On a function with many local minima BFGS reaches the global one from 1.0% of 500 random starts, with a median final value of 15.9. The best of 20 starts finds it 18% of the time. Differential evolution finds it in 90% of 20 runs, using about 1,960 evaluations.

  • A constraint has a price. The unconstrained minimum-variance portfolio holds 145% of the first asset and is short two others, with a volatility of 12.63%, and SLSQP agrees with the linear solve to 7e-8. With the long-only bound, two weights are on the bound at zero and the volatility is 14.34%, 1.7 points higher.

A valuation control view#

  • Ask what the optimiser was and how it was set: the method, the starting point, the tolerances, the bounds, the maximum number of iterations. They are part of the model, and a change in any of them can change a calibrated parameter.

  • Test from several starting points: if the result depends on the start, the problem has more than one minimum, or a flat valley. Report the spread, and the objective at each. See Calibration.

  • Do not judge convergence by the objective alone: a small objective with parameters that move when the tolerance tightens is not a solution. Check that the gradient is small and that the parameters are stable.

  • Look at parameters that finish on a bound: the bound is an assumption of the model. A parameter that sits on its limit in every run is evidence that the model is wrong, or that the bound is hiding an instability.

  • Use a smooth, deterministic objective: an objective computed by simulation with fresh random numbers is noisy, the gradient is wrong, and the optimiser stops early. Fix the random numbers, or use a deterministic pricer.

  • Provide a gradient where it exists: an analytic or adjoint gradient is faster and more accurate than a finite difference, and the accuracy of the result depends on it.

Next, Calibration uses optimisation to fit a model to a set of prices, and shows what it can and cannot determine.