I am trying to convert the following old Mᴀᴛʟᴀʙ™ to R. Here the old Mᴀᴛʟᴀʙ code:
sw=[2.40096 2.72778 3.09914 3.25061 3.29394 3.63792 3.90653 3.92677 3.85058 4.14440 4.43973 4.27808 4.82375 4.56853 4.86894]./100;
tau = [1;2;3;4;5;6;7;8;9;10;12;15;20;25;30];
T=(1:tau(end))';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Calibration CIR%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [d,fi,ni,r,SSE,scarti]=calibCir(x0,lb,ub,T,tau,swap)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Data%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% x0 = [0.2 0.12 0.8 0.02];
% Lower bounds
% lb = [0 0 0 10^-8];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
options=optimset('tolfun',10e-20,'maxfunevals',20000,'tolx',10e-20,'tolfun',10e-20,'maxiter',20000);
[P,SSE,scarti] = lsqnonlin(@fun,x0,lb,ub,options,T,tau,swap);
d = P(1);
fi = P(2);
ni = P(3);
r = P(4);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [F] = fun(x,T,tau,swap)
A_tau = ((x(1)*exp(x(2).*T))./(x(2)*(exp(x(1).*T)-1)+x(1))).^x(3);
B_tau = (exp(x(1).*T)-1)./(x(2)*(exp(x(1).*T)-1)+x(1));
v_model = A_tau.*exp(-x(4).*B_tau);
% model prices
% where: x(1)=d, x(2)=fi, x(3)=ni, x(4)=r
sum_v_model = cumsum(v_model);
Q = 100;
Z = 100*swap.*sum_v_model(tau)+v_model(tau).*100;
F = Z-Q;
end
end
here the new R code I am building:
sw <- c(2.40096, 2.72778, 3.09914, 3.25061, 3.29394, 3.63792, 3.90653, 3.92677, 3.85058, 4.14440, 4.43973, 4.27808, 4.82375, 4.56853, 4.86894)
sw <- sw/100
tau <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 25, 30)
# Valori di inizializzazione CIR: di0, fi0, ni0, r0
x0 <- c(0.2, 0.12, 0.8, 0.02)
# Lower bounds
lb <- c(0, 0, 0, 10^-8)
#d = 0.2
#fi = 0.12
#ni = 0.8
#r = 0.02
getCIR <- function(x0,lb,ub,t,tau,swap)
{
# https://www.rdocumentation.org/packages/stats/versions/3.6.1/topics/nls
df <- data.table(tau,sw)
# CIR
CIR <- function(tau, d, fi, ni, r)
{
#t = 1 : tau[length(tau)]
t = 1 : length(tau)
A_tau <- ((d*exp(fi*t))/(fi*(exp(d*t)-1)+d)^ni)
B_tau <- (exp(d*t)-1)/fi*(exp(d*t)-1)+d
# Model Prices
v_model <- A_tau*exp(-r*B_tau)
sum_v_model <- cumsum(v_model)
Q <- 100
# Model ZCB Prices
Z <- 100*sw*100*sum_v_model(tau)+v_model(tau)*100
# delta market vs model
CIRres = Z-Q
return(CIRres)
}
CIRParameters <- nls(sw ~ CIR(tau, d, fi, ni, r),
data = df,
start = list(d=0.1, fi=0.1, ni=0.1, r=0.1),
algorithm="port",
lower = list(d=0, fi=0, ni=0, r=10^-8),
trace = TRUE)
summary(CIRParameters)
Question 1: how is it possible to translate it
Z <- 100*sw*100*sum_v_model(tau)+v_model(tau)*100
in R?
Question 2: is it correct to translate
T=(1:tau(end))';
to
t = 1 : length(tau)
Question 3: any other big mistakes?