Differential Calculus and Optimization Basics › Constrained Optimization and Lagrange Multipliers

Michael BrenndoerferOctober 24, 202515 min read
Quantitative FinanceAll chapters
Part 1 of 15Mathematical Foundations
Chapter 6Differential Calculus and Optimization Basics › Constrained Optimization and Lagrange Multipliers
Reading section 5 of 11 · Constrained Optimization and Lagrange Multipliers · 15 minSection 5 of 11 · 15 min

Book contents

Section 5 of 11 · 15 min read

Differential Calculus and Optimization Basics › Constrained Optimization and Lagrange MultipliersOne section · Sections in this chapter5 / 11 ↓
Reading tools Definitions & inline links

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

Many financial optimization problems involve constraints. An unlevered, fully invested mandate may require portfolio weights to sum to 100%, while a leveraged or margin-financed portfolio can have gross exposure above 100% of capital. A risk mandate may cap modeled volatility, and a trading mandate may impose position limits. These rules lead to constrained optimization problems.

Constraints reflect the rules of a financial decision. Regulations or mandates may prohibit specified positions, risk limits may restrict concentration, and a budget constraint limits admissible spending or leverage. Constrained optimization finds the best objective value within the resulting feasible set. Sensitivity analysis can separately ask how that optimum would change if a constraint were relaxed slightly.

The Lagrangian Method

Lagrange multipliers turn a smooth, regular equality-constrained problem into a stationarity system for decision variables and auxiliary multipliers. This is not unrestricted minimization over both sets of variables. Consider minimizing f(x)f(x) subject to g(x)=0g(x)=0.

Lagrange's approach augments the objective with a free multiplier rather than a fixed penalty. Differentiating the Lagrangian with respect to λ\lambda recovers g(x)=0g(x)=0, while differentiation with respect to xx encodes the required gradient alignment. Solving these stationarity equations produces constrained candidates, not guaranteed optima; each candidate still needs feasibility, constraint-qualification, and second-order or global optimality checks.

Lagrangian Function

The Lagrangian combines the objective function and constraints:

L(x,λ)=f(x)+λg(x)\mathcal{L}(x, \lambda) = f(x) + \lambda g(x)

where:

  • L\mathcal{L}: the Lagrangian function
  • xx: the decision variables we are optimizing
  • λ\lambda: an equality-constraint multiplier; under regularity, its correctly signed value gives local sensitivity of the optimized objective to a specified constraint right-hand side
  • f(x)f(x): the objective function we want to minimize or maximize
  • g(x)=0g(x) = 0: the equality constraint that must be satisfied

For continuously differentiable ff and gg near a feasible local optimum x∗x^*, with ∇g(x∗)≠0\nabla g(x^*)\ne0, there is a multiplier making ∇xL=0\nabla_x\mathcal{L}=0. Feasibility gives ∂L/∂λ=g(x∗)=0\partial\mathcal{L}/\partial\lambda=g(x^*)=0. For multiple equalities, a full-row-rank constraint Jacobian is a sufficient constraint qualification. Singular representations require separate analysis. The multiplier's value-versus-location distinction, sign, and units are developed below.

For this regular equality surface, the objective gradient at a local minimum is a scalar multiple of the constraint gradient: it has no component along a feasible tangent direction. Otherwise one tangent orientation would decrease the objective locally. A zero objective gradient has no unique uphill direction but still satisfies this normal-space condition.

Imagine standing on a hill while constrained to walk along a smooth path. At a constrained minimum, the objective gradient has no tangential component. If a nonzero component remained, walking in its opposite direction would take you downhill, contradicting the minimum. When nonzero, the gradient is normal to the feasible path. This is the geometry captured by the Lagrange conditions.

Mathematically, this means:

∇f(x∗)=−λ∇g(x∗)\nabla f(x^*) = -\lambda \nabla g(x^*)

Together with g(x∗)=0g(x^*)=0, these equations form a system for candidate points and multipliers. Each candidate still needs an optimality check.

The system consists of n+1n+1 equations in the nn components of xx and the multiplier λ\lambda. A nonsingular Jacobian at a solution can make that solution locally isolated, but matching the number of equations and unknowns does not guarantee existence or a unique global solution for a nonlinear system. Each candidate still requires constraint-qualification, feasibility, and second-order or global optimality checks.

Out[23]:
Visualization
Contour plot with constraint curve showing gradients parallel at the optimal point.
For the quadratic objective and regular linear equality shown, the objective and constraint gradients are parallel at the constrained minimum. Arrows are rescaled and slightly offset to show direction, not raw magnitude. Moving along this constraint cannot lower the objective from the minimum.

Worked Example: Portfolio Allocation

Consider allocating between two assets to minimize portfolio variance, subject to achieving a target expected return.

This example studies the mean-variance trade-off within a specified asset universe and constraint set. For each feasible target expected return, the model selects the portfolio with the lowest variance. Along the upper efficient branch beyond the global-minimum-variance point, increasing the target return raises that minimum attainable variance. Outside this model and opportunity set, a portfolio can be dominated by another portfolio with both higher expected return and lower risk.

Let w1w_1 and w2w_2 be the weights in assets 1 and 2, with expected returns μ1=0.10\mu_1 = 0.10 and μ2=0.05\mu_2 = 0.05, variances σ12=0.04\sigma_1^2 = 0.04 and σ22=0.01\sigma_2^2 = 0.01, and correlation ρ=0.3\rho = 0.3. The portfolio variance is:

σp2=w12σ12+w22σ22+2w1w2ρσ1σ2\sigma_p^2 = w_1^2 \sigma_1^2 + w_2^2 \sigma_2^2 + 2 w_1 w_2 \rho \sigma_1 \sigma_2

where:

  • σp2\sigma_p^2: portfolio variance
  • w1,w2w_1, w_2: portfolio weights for assets 1 and 2
  • σ12,σ22\sigma_1^2, \sigma_2^2: variances of assets 1 and 2
  • ρ\rho: correlation between the two assets
  • 2w1w2ρσ1σ22 w_1 w_2 \rho \sigma_1 \sigma_2: covariance contribution from the interaction between assets

The first two terms scale each asset's variance by its squared weight. The cross term is weighted covariance. With same-sign nonzero weights and positive volatilities, lowering correlation reduces this term; opposite-sign weights reverse the direction, and a zero exposure gives no change. For nonnegative weights summing to one, portfolio variance cannot exceed the weighted average of component variances. This benchmark is not necessarily the variance of the lower-risk individual asset. The displayed positive-weight example exhibits a diversification benefit, while the long-short case needs its position-sign conditions.

We want to minimize σp2\sigma_p^2 subject to:

  1. Target return: w1μ1+w2μ2=0.08w_1 \mu_1 + w_2 \mu_2 = 0.08
  2. Full investment: w1+w2=1w_1 + w_2 = 1

The Lagrangian is:

L=w12σ12+w22σ22+2w1w2ρσ1σ2+λ1(0.08−w1μ1−w2μ2)+λ2(1−w1−w2)\mathcal{L} = w_1^2 \sigma_1^2 + w_2^2 \sigma_2^2 + 2 w_1 w_2 \rho \sigma_1 \sigma_2 + \lambda_1(0.08 - w_1 \mu_1 - w_2 \mu_2) + \lambda_2(1 - w_1 - w_2)

where:

  • λ1\lambda_1: Lagrange multiplier for the return constraint, representing the marginal variance cost of achieving additional return
  • λ2\lambda_2: multiplier for the net-budget constraint; its sign depends on the Lagrangian convention, and its magnitude is a local objective sensitivity per unit change in the constraint's right-hand side

The return equality fixes expected return. The equation ∑iwi=1\sum_i w_i=1 fixes net exposure. In the accounting convention where these asset weights and residual net cash exhaust the normalized budget, it leaves no residual net cash. It does not rule out leveraged long-short portfolios: weights (2,−1)(2,-1) sum to one and have gross exposure three. Nonnegative fully invested weights or an explicit gross-exposure constraint are needed to exclude this leverage. With normalized weights, λ2\lambda_2 has variance units per unit change in the budget right-hand side; it is not directly a value per dollar unless the problem is formulated in dollar holdings and currency units.

In[24]:
Code
from scipy.optimize import minimize

# Asset parameters
mu = np.array([0.10, 0.05])  # Expected returns
sigma = np.array([0.20, 0.10])  # Standard deviations
rho = 0.3  # Correlation
target_return = 0.08

# Covariance matrix
cov_matrix = np.array(
    [
        [sigma[0] ** 2, rho * sigma[0] * sigma[1]],
        [rho * sigma[0] * sigma[1], sigma[1] ** 2],
    ]
)


def portfolio_variance(w):
    """Portfolio variance given weights w"""
    return w @ cov_matrix @ w


def portfolio_return(w):
    """Portfolio expected return given weights w"""
    return w @ mu


def checked_two_asset_weights(result, target):
    """Check this fixed two-asset budget/return problem before using a result."""
    weights = np.asarray(result.x, dtype=float)
    if (
        not result.success
        or weights.shape != (2,)
        or not np.all(np.isfinite(weights))
        or not np.isfinite(result.fun)
    ):
        raise RuntimeError(f"Portfolio solve failed: {result.message}")
    residual = max(abs(portfolio_return(weights) - target), abs(weights.sum() - 1))
    # The independent equalities fix one portfolio when the two means differ.
    exact_weight = (target - mu[1]) / (mu[0] - mu[1])
    exact_weights = np.array([exact_weight, 1 - exact_weight])
    if (
        residual > 1e-8
        or not np.allclose(weights, exact_weights, atol=1e-8, rtol=0)
        or not np.isclose(
            result.fun, portfolio_variance(exact_weights), atol=1e-10, rtol=0
        )
    ):
        raise RuntimeError("Portfolio result failed feasibility or closed-form checks")
    return weights.copy()


# Constraints
constraints = [
    {
        "type": "eq",
        "fun": lambda w: portfolio_return(w) - target_return,
    },  # Target return
    {"type": "eq", "fun": lambda w: np.sum(w) - 1},  # Full investment
]

# Initial guess
w0 = np.array([0.5, 0.5])

# Optimize
result = minimize(
    portfolio_variance,
    w0,
    method="SLSQP",
    constraints=constraints,
    options={"ftol": 1e-12, "maxiter": 100},
)
optimal_weights = checked_two_asset_weights(result, target_return)
Out[25]:
Console
Optimal Portfolio Allocation
------------------------------
Weight in Asset 1 (μ=10%, σ=20%): 0.6000
Weight in Asset 2 (μ=5%, σ=10%):  0.4000

Portfolio Statistics
------------------------------
Expected return: 0.0800 (8.00%)
Portfolio variance: 0.018880
Portfolio std dev: 0.1374 (13.74%)

The full-investment and 8% target-return equalities determine a 60% allocation to the higher-return, higher-risk asset and a 40% allocation to the lower-return, lower-risk asset before variance enters the calculation. With two assets, this is the only feasible portfolio at that target, so it is also the minimum-variance portfolio for that target.

Interpreting Lagrange Multipliers

Under regularity conditions, a Lagrange multiplier has a local envelope interpretation: after fixing the constraint's right-hand-side parameterization and the Lagrangian sign convention, the corresponding signed derivative gives the first-order change in the optimal objective value.

For a binding constraint, the correctly signed envelope derivative describes only a local, first-order response around the current optimum. A large magnitude means the optimized objective is locally sensitive to that specified right-hand-side change; whether this is a benefit or a cost depends on whether the problem minimizes or maximizes, how relaxation is parameterized, and the multiplier sign convention. A small magnitude likewise indicates local insensitivity, not that the constraint is globally unimportant.

For our minimization problem and the convention λ1(R−wTμ)\lambda_1(R-w^T\mu), the return multiplier equals the local derivative of minimum variance with respect to decimal target return. Its sign would reverse under the opposite Lagrangian convention.

Suppose the return-constraint multiplier is 0.02 variance units per unit of decimal expected return. Raising the target from 8% to 8.1% changes decimal return by 0.001, so the first-order variance change is approximately 0.02×0.001=0.000020.02 \times 0.001 = 0.00002. The corresponding standard-deviation change is nonlinear and must be computed from the square root rather than assigned the same units.

In[26]:
Code
# Examine how variance changes with target return
# Trace the upper frontier by solving minimum variance at each target.
gmv_return = (
    mu
    @ np.linalg.solve(cov_matrix, np.ones(len(mu)))
    / (np.ones(len(mu)) @ np.linalg.solve(cov_matrix, np.ones(len(mu))))
)
target_returns = np.linspace(gmv_return, 0.10, 50)
min_variances = []

for target in target_returns:
    constraints = [
        {"type": "eq", "fun": lambda w, t=target: portfolio_return(w) - t},
        {"type": "eq", "fun": lambda w: np.sum(w) - 1},
    ]
    result = minimize(
        portfolio_variance,
        w0,
        method="SLSQP",
        constraints=constraints,
        options={"ftol": 1e-12, "maxiter": 100},
    )
    checked_two_asset_weights(result, target)
    min_variances.append(result.fun)

min_variances = np.array(min_variances)
min_std = np.sqrt(min_variances)
Out[27]:
Visualization
Two-asset efficient branch from the global-minimum-variance portfolio to Asset 1, with both individual assets and the minimum-variance portfolio achieving the 8% target marked.
Upper efficient branch of the two-asset minimum-variance locus, beginning at the global-minimum-variance return of about 5.53%. With full investment and an exact target-return equality, each target fixes one portfolio; the dominated lower branch is omitted.

The plotted curve is the upper, mean-variance-efficient branch. It begins at the global-minimum-variance portfolio, whose expected return is about 5.53%; targets below that point lie on a dominated lower branch and are omitted. In this two-asset fully invested example, the budget and exact return equalities determine one portfolio for each target. The return-constraint multiplier measures the local change in minimum variance as the target increases.

Out[28]:
Visualization
Upper two-asset efficient branch beginning at the global-minimum-variance return, with selected higher target returns highlighted.
Upper efficient branch with highlighted target returns.
Line plot of the analytic local variance sensitivity per percentage point, starting at zero at the global-minimum-variance return and highlighting exact selected targets.
Analytic local variance slope scaled by 0.01 for a first-order one-percentage-point return change, not the exact finite change.