def cov_nearest(cov, method='clipped', threshold=1e-15, n_fact=100, return_all=False):
 from statsmodels.stats.moment_helpers import cov2corr, corr2cov
 (cov_, std_) = cov2corr(cov, return_std=True)
 if (method == 'clipped'):
  corr_ = corr_clipped(cov_, threshold=threshold)
 elif (method == 'nearest'):
  corr_ = corr_nearest(cov_, threshold=threshold, n_fact=n_fact)
 cov_ = corr2cov(corr_, std_)
 if return_all:
  return (cov_, corr_, std_)
 else:
  return cov_

def cov_nearest ( cov , method = 'clipped' , threshold = 1e-15 , n_fact = 100 , return_all = False ) : from statsmodels . stats . moment_helpers import cov2corr , corr2cov ( cov_ , std_ ) = cov2corr ( cov , return_std = True ) if ( method == 'clipped' ) : corr_ = corr_clipped ( cov_ , threshold = threshold ) elif ( method == 'nearest' ) : corr_ = corr_nearest ( cov_ , threshold = threshold , n_fact = n_fact ) cov_ = corr2cov ( corr_ , std_ ) if return_all : return ( cov_ , corr_ , std_ ) else : return cov_
find the nearest covariance matrix that is postive definite this leaves the diagonal .