Hi, I'm working on a simple exercise to calibrate a CIR model to federal reserve data. I can get this to work with a Vasicek model but can't seem to get the calculation of lambda to work correctly using the CIR model. Any thoughts or suggestions? My code is below for the model and lambda calculation.

ZCB.Yield.CIR = function(r0, theta, kappa, sigma, lambda, T){

psi <- kappa + lambda*sigma
h <- sqrt(psi^2 + 2*sigma^2)

BT <- (2 * (exp(T * h) - 1)) / (2 * h + (psi + h)*(exp(T * h) - 1))

AT <- ((2 * h * exp((psi + h) * T / 2)) / (2 * h + (psi + h) * (exp(T * h) - 1)))^((2 * kappa * theta) / sigma^2)

zcb <- AT * exp(-BT * r0)

zcb.ey <- -log(zcb)/T

zcb.ey # return results

yieldDifference = function(lambda, r0, theta, kappa, sigma, maturities, termStructure){

yield.estimate = ZCB.Yield.CIR(r0, theta, kappa, sigma, lambda, maturities)

sum(abs(termStructure - yield.estimate))

lambda.est <- nlm(yieldDifference, c(lambda=0), r0=r0, theta=theta.est, kappa=kappa.est, sigma=sigma.est, maturities=maturities, termStructure=termStructure.real)$estimate