If Python raises LinAlgError: Matrix is not positive definite on a correlation matrix, check the smallest eigenvalue before changing the matrix. A materially negative value means the correlations cannot all be true together. A value near zero can mean the matrix is valid but singular: the simulation needs fewer independent shocks, or the estimator needs more information.
Take three assets: A–B and A–C both have correlation 0.9, while B–C has correlation 0.5. Each pair looks plausible. Could you simulate all three returns together?
No. Given the first two correlations, B–C must lie between 0.62 and 1. The proposed matrix has a smallest eigenvalue of −0.0471. Set B–C to exactly 0.62 and the matrix is valid but singular: ordinary Cholesky still requires strict positive definiteness.
Correlation matrices form a constrained set, not a box
The mistake is treating a correlation matrix as a collection of independent numbers, each free to roam in
. The entries constrain each other. The positive semidefinite matrices form a cone; imposing a unit diagonal gives a convex slice of that cone, called the correlation elliptope. Correlation matrices themselves do not form a cone: multiplying one by two destroys the unit diagonal.
For three variables the constraint is explicit. Given
and
, the third correlation must satisfy
![]()
![]()
With
this collapses to
.
The admissible interval has width 0.38, just 19% of the full range from −1 to 1. A correlation below 0.62 is possible for B and C in isolation; it is incompatible with the two other estimates.
| Smallest eigenvalue | Status | |
|---|---|---|
| impossible | ||
| impossible | ||
| impossible | ||
| boundary | ||
| valid |
The row worth staring at is the third. A positive, moderate, entirely ordinary-looking 0.5 is already outside the feasible set. The usual teaching example uses a glaring
, which makes the phenomenon look like something you would notice. You would not notice this one.
A real correlation matrix must be symmetric, have ones on its diagonal and be positive semidefinite: all its eigenvalues are non-negative. For three variables that last condition gives the bound above. For a larger matrix, check the eigenvalues rather than inspecting each pair in isolation.
The portfolio with negative variance
Positive semidefiniteness is not a technical nicety imported from linear algebra. It is the statement that every portfolio has non-negative variance.
Take the impossible matrix with
and ask for the eigenvector of its smallest eigenvalue:
![]()
These positions have equal absolute exposure: short A, long B and C. They are normalised to Euclidean length one, not to sum to one. With 20% volatility on each name, the covariance matrix is
, giving:
![]()
The −0.032 result uses B–C = −0.9 and equal 20% volatilities. The opening example uses B–C = +0.5. Both matrices imply a negative variance in some direction, but the values differ. Taking the square root cannot produce a real portfolio volatility in either case.
There is a useful parallel with a discretisation of a CIR process producing a negative value, or an interpolated volatility surface implying a negative local variance. The causes differ, but each violates a mathematical constraint. The square-root or factorisation error can appear several steps after the problem was introduced.
In a Monte Carlo engine, a call to np.linalg.cholesky may be the first visible failure. This routine expects a positive definite matrix. Simulation itself does not: for a valid singular matrix, an eigenvalue factor using only the positive modes reproduces the dependence with fewer independent shocks.
Python: diagnose a Cholesky failure before repairing anything
import numpy as np
def diagnose_corr(R):
R = np.asarray(R, dtype=float)
if R.ndim != 2 or R.shape[0] != R.shape[1] or not R.size:
raise ValueError("Expected a nonempty square matrix")
if not np.isfinite(R).all():
raise ValueError("Found NaN or infinity; check input histories")
if not np.allclose(R, R.T, atol=1e-12, rtol=0):
raise ValueError("Asymmetric input; check asset order and overrides")
if not np.allclose(np.diag(R), 1.0, atol=1e-12, rtol=0):
raise ValueError("Diagonal must equal one")
eig = np.linalg.eigvalsh((R + R.T) / 2)
tol = 10 * R.shape[0] * np.finfo(float).eps * max(1.0, abs(eig).max())
state = ("indefinite" if eig[0] < -tol else
"singular or near-singular" if eig[0] <= tol else "positive definite")
return state, float(eig[0])
for bc in (0.50, 0.62, 0.70):
R = [[1, .9, .9], [.9, 1, bc], [.9, bc, 1]]
state, smallest = diagnose_corr(R)
print(f"{bc:.2f}: {state} ({smallest:.4f})")
The three runs return indefinite, singular or near-singular, and positive definite, respectively. The tolerance is a floating-point diagnostic for double precision, not a statistical tolerance. A matrix labelled positive definite can still be poorly conditioned. Inspect the eigenvalue spectrum and condition number when numerical stability matters.
NumPy’s Cholesky routine uses the selected triangle and does not verify symmetry, so passing Cholesky alone is not a complete validation. If correlations were rounded for export, inspect the original precision before dismissing a negative eigenvalue as roundoff.
Three ways a matrix can fail Cholesky
Expert overrides and stress scenarios. A matrix is estimated from data, then someone adjusts a few entries. Risk committee wants the equity-credit correlation stressed to 0.9. A trader insists two names are more linked than history suggests. A scenario specifies what happens “if correlations go to one”. An override may preserve validity, move the matrix towards the boundary, or make it indefinite. The direction is not predetermined. Even setting every correlation to one gives a valid, rank-one matrix, although ordinary Cholesky cannot factor it as positive definite. Check the whole matrix after each change.
Pairwise deletion. Listings, holidays and missing prices can leave each pair of assets with a different set of return dates. Individual sample correlations are still well defined if enough observations and variation remain. What you lose is the guarantee that the assembled matrix is positive semidefinite.
Here is a reproducible experiment. Every asset has loading 0.7 on an independent, standard-normal common factor and idiosyncratic volatility
. The population pairwise correlation is therefore 0.49. We randomly remove individual observations and estimate each correlation on the observations available for that pair.
import numpy as np
import pandas as pd
rng = np.random.default_rng(2026)
trials = 50
for n, t, missing in ((30, 500, .3), (30, 120, .3),
(60, 120, .4), (100, 60, .5)):
minima = []
undefined = 0
for _ in range(trials):
factor = rng.standard_normal((t, 1))
noise = rng.standard_normal((t, n))
returns = .7 * factor + np.sqrt(.51) * noise
returns[rng.random((t, n)) < missing] = np.nan
R = pd.DataFrame(returns).corr(min_periods=3).to_numpy()
if not np.isfinite(R).all():
undefined += 1
continue
minima.append(np.linalg.eigvalsh(R)[0])
failures = np.count_nonzero(np.array(minima) < -1e-10)
print(n, t, missing, 'indefinite', failures, 'undefined', undefined,
'of', trials, 'min_eig', f'{min(minima):.6f}')
The following results use 50 trials per configuration, seed 2026, NumPy 2.3.5 and pandas 2.2.3. “Indefinite” counts finite matrices with a smallest eigenvalue below
. “Undefined” counts matrices containing missing correlation estimates; those trials are excluded from the eigenvalue calculation.
| Assets / days / missing | Indefinite | Undefined | Worst finite eigenvalue |
|---|---|---|---|
| 30 / 500 / 30% | 0 of 50 | 0 of 50 | +0.1416 |
| 30 / 120 / 30% | 50 of 50 | 0 of 50 | −0.1948 |
| 60 / 120 / 40% | 50 of 50 | 0 of 50 | −0.6424 |
| 100 / 60 / 50% | 48 of 50 | 2 of 50 | −3.0515 |
These are outcomes of this experiment, not universal failure probabilities. In the second configuration, a pair has about
common observations on average. That exceeds the number of assets, but it does not create a shared observation matrix. Pairwise deletion removes the positive-semidefiniteness guarantee; shorter histories and missingness affect how often and how severely the estimate fails.
On a common set of dates, centred returns standardised to unit sample variance form a matrix
with
![]()
This Gram-matrix representation guarantees positive semidefiniteness in exact arithmetic. Correlations assembled from different date subsets need not have that representation.
More assets than history. For
common observations and nonconstant columns, the sample correlation matrix of
assets has rank at most
. If
, it must be singular, even with perfectly clean observations. The following are rank bounds, not guarantees that a particular dataset attains them:
| Assets | Days | Maximum rank | Minimum zero eigenvalues |
|---|---|---|---|
| 50 | 250 | 50 | 0 |
| 250 | 250 | 249 | 1 |
| 500 | 250 | 249 | 251 |
| 1000 | 250 | 249 | 751 |
With 500 assets and 250 common observations, there are at least 251 zero-eigenvalue directions in exact arithmetic. Floating-point calculations may report tiny positive or negative values instead of exact zeros. Extra linear dependencies can reduce the rank further.
Zero sample variance does not establish zero population risk. An unconstrained optimiser can exploit poorly estimated directions, making portfolio weights unstable even before expected-return estimation errors enter the problem. Singularity can also reflect genuine redundancy, such as duplicate assets; the source matters.
The two standard repairs, and what they cost
First identify the source. Correct a mismatched asset order, timestamp or data error upstream and estimate again. If the inputs are deliberate estimates or stresses, keep the original and state which entries must remain fixed before choosing a repair.
Eigenvalue clipping. For a symmetric input, replace negative eigenvalues with zero, reconstruct the matrix, then rescale to unit diagonal. This gives a semidefinite correlation matrix when the reconstructed diagonal is positive. Zero eigenvalues may remain, so the repair does not guarantee a successful Cholesky call.
Higham’s nearest correlation matrix. The alternating-projections algorithm with Dykstra’s correction finds the nearest positive semidefinite matrix with unit diagonal in the unweighted Frobenius norm, up to solver tolerance. Strict positive definiteness and preservation of specific stressed entries are separate requirements.
To compare the repairs transparently, reuse the opening matrix with
, whose smallest eigenvalue is
. The following compact implementation uses a symmetric input, an unweighted Frobenius norm and no fixed off-diagonal entries.
import numpy as np
def project_psd(A):
eig, Q = np.linalg.eigh((A + A.T) / 2)
return (Q * np.maximum(eig, 0.0)) @ Q.T
def clipped_corr(A):
B = project_psd(A)
d = np.sqrt(np.diag(B))
if np.any(d <= 0):
raise ValueError("Cannot normalise a zero diagonal")
return B / np.outer(d, d)
def nearest_corr(A, tol=1e-12, max_iter=1000):
# Symmetric input; unweighted Frobenius norm; no fixed off-diagonals.
Y = np.array(A, dtype=float, copy=True)
correction = np.zeros_like(Y)
for _ in range(max_iter):
previous = Y.copy()
residual = Y - correction
X = project_psd(residual)
correction = X - residual
Y = X.copy()
np.fill_diagonal(Y, 1.0)
scale = max(1.0, np.linalg.norm(Y, 'fro'))
change = np.linalg.norm(Y - previous, 'fro') / scale
gap = np.linalg.norm(Y - X, 'fro') / scale
if max(change, gap) < tol:
return (Y + Y.T) / 2
raise RuntimeError("Nearest-correlation iteration did not converge")
A = np.array([[1, .9, .9], [.9, 1, .5], [.9, .5, 1]])
for name, B in [('Clipping', clipped_corr(A)), ('Higham', nearest_corr(A))]:
print(name, '\n', B)
print('distance', np.linalg.norm(B-A, 'fro'), 'maxchange', np.max(abs(B-A)), 'eigmin', np.linalg.eigvalsh(B)[0])
| Method | Frobenius distance | Largest entry change |
|---|---|---|
| Clipping + normalisation | 0.065572 | 0.032616 |
| Higham iteration | 0.062934 | 0.029156 |
Higham’s result is about 4% closer in Frobenius norm in this example. It also has a smaller maximum entry change here, but that second property is not guaranteed: the objective minimises the sum of squared entry changes, not the largest individual change.
The iterative result has a minimum eigenvalue around
at the stated stopping tolerance. This is an approximately positive semidefinite solution, not a guarantee that a strict Cholesky call will succeed. A positive eigenvalue floor is an additional constraint or regularisation decision, not something this routine promises.
Two things matter more than the choice between them.
The repair changes your correlations. Here Higham moves A–B and A–C from 0.9 to about 0.87084, and B–C from 0.5 to about 0.51674. If the two 0.9 values must stay fixed, the unconstrained repair is the wrong problem: the bound requires B–C to be at least 0.62. State fixed entries explicitly, check whether the constraints are feasible, and report changes against the original matrix.
And a silent repair hides the evidence. A pipeline that overwrites the original without diagnostics converts a loud, informative failure into a quiet one. The Cholesky error was telling you something true about your data construction. Fixing the matrix without logging the magnitude of the violation means the next person inherits a system that appears to work.
What to do
Check the smallest eigenvalue every time a correlation matrix is built or modified, and log it. One line, and it turns an invisible corruption into a number on a dashboard.
Use a common observation set when enough representative data remain, or consider a model-based estimator that handles missing data coherently. Complete-case deletion restores the Gram-matrix structure, but can discard most of the history and can distort the sample when missingness is systematic. It is not automatically the best statistical estimator. Pairwise deletion is convenient, but its assembled matrix needs explicit validation.
If a common-history estimate is singular or poorly conditioned, consider shrinkage. For a positive semidefinite estimate
, any positive weight
on a positive definite target makes the mixture positive definite. Choose the weight as an estimation decision and check its effect on portfolio risk.
For identity shrinkage,
![]()
![]()
If the input is indefinite, an arbitrarily small positive weight is not enough. With
, strict positive definiteness requires
![]()
This threshold is about 4.5% for the opening matrix. A practical choice also needs a numerical margin and a statistical justification; merely crossing the threshold does not ensure good conditioning.
And when an override is applied, re-check afterwards and show the person who requested it what their override did to the rest of the matrix. They asked for one number to change. They are getting a different matrix.
The honest caveats
The three-correlation example is the smallest possible case and the constraint is tightest when the two known correlations are large. With
the admissible range for the third is
, which is most of the box. The phenomenon is real at any size; the severity depends on how strong the existing links are. Highly correlated books are the dangerous ones, which is unhelpful, because highly correlated books are also the ones where correlation assumptions matter most.
The simulations use a one-factor Gaussian structure with missingness completely at random. Real missingness often has structure, including market closures and corporate events. These examples do not quantify the resulting estimation bias. They show that pairwise deletion can produce an indefinite matrix even without systematic missingness.
The repair comparison is one matrix. The exact nearest-correlation solution cannot have a larger Frobenius distance than another feasible repair under the same constraints. The size of the gain, and the maximum individual entry change, are not guaranteed. Even a small adjustment can matter to a sensitive portfolio; review the risk impact as well as the matrix norm.
Technical references
Higham, N. J. (2002), Computing the Nearest Correlation Matrix—A Problem from Finance, IMA Journal of Numerical Analysis, 22(3), 329–343. Research paper. See also the official NumPy Cholesky documentation and pandas correlation documentation. Numerical tables above were reproduced with the code shown.
The same structural failure — an object that is non-negative by construction in the mathematics and negative in the implementation — shows up in a volatility surface interpolation, where a standard cubic spline produces a negative probability density.
Build and validate a Monte Carlo pricer. Once your simulated shocks have the intended dependence, how do you know the price is right? In Risk-Neutral Valuation with Python, you build a pricer, put confidence intervals around the estimate, and check it against pricing benchmarks.
Get the Quant Reference Card — four pages covering stochastic calculus, measure change, the models you’ll meet, discretisation, rates, credit and XVA. Free.