I\'m coming to Python from R and trying to reproduce a number of things that I\'m used to doing in R using Python. The Matrix library for R has a very nifty function called
I would submit a non-iterative approach. This is slightly modified from Rebonato and Jackel (1999) (page 7-9). Iterative approaches can take a long time to process on matrices of more than a few hundred variables.
import numpy as np
def nearPSD(A,epsilon=0):
n = A.shape[0]
eigval, eigvec = np.linalg.eig(A)
val = np.matrix(np.maximum(eigval,epsilon))
vec = np.matrix(eigvec)
T = 1/(np.multiply(vec,vec) * val.T)
T = np.matrix(np.sqrt(np.diag(np.array(T).reshape((n)) )))
B = T * vec * np.diag(np.array(np.sqrt(val)).reshape((n)))
out = B*B.T
return(out)
Code is modified from a discussion of this topic here around nonPD/PSD matrices in R.