Johannes Heß
Johannes Heß

Reputation: 37

Adding xts objects in a loop

I have a function ugmfit that returns an xts object. Now I want to write a function out_of_sample_f that contains a loop. In that loop in each iteration fit$est_vol_oos gives an xts with unique dates. I want to add them all together, so that out_of_sample_f can return one xts of all the forecasts

How do I iteratively merge these xts in that loop so that out_of_sample_f returns just one xts object? I don't know if what I am doing is correct? I am thinking by initializing oosf in the beginning maybe something with the dates doesn't work out.

out_of_sample_f <- function(rtrn, r_w, re_est_w, exog) {


  oosf = xts(as.numeric(0), as.Date("2013-04-08"))
  
  for (i in 0:(length(rtrn) - r_w)) {
    if(i%%re_est_w == 0){
      mv_m<-mv_into_mat(rtrn[(i + 1):(i + r_w)],exog,K=12,"monthly")
      fit<-ugmfit(model="GM",skew="NO",distribution="norm",rtrn[(i + 1):(i+r_w)],mv_m,K=12, out_of_sample = re_est_w)
      oosf = c(oosf, fit$est_vol_oos)

    }
  }
  oosf <- oosf[-1,]


  return(oosf)
}

fit$est_vol_oos is the xts for a particular window. I want to iterate through my data and consecutively add my forecasts.

Later on I use this "merged" xts for something else where differences between this xts and another one are built but I get the error that the two arrays are non conformable. Edit: I later use this xts form out_of_sample_f and a original return series as input for yet another function. There it says: Error in *.default((tau - dummies), (realized - evaluated)) : non-conformable arrays

where realized is the original return series and evaluated is the xts from out_of_sample_f.

Upvotes: 1

Views: 292

Answers (1)

akrun
akrun

Reputation: 887241

If we want to rbind from a list, use

do.call(rbind, lst1)

where lst1 is the output from the out_of_sample_f stored in a list


In the OP's code, there is a line

oosf = c(oosf, fit$est_vol_oos)

which would be

oosf = rbind(oosf, fit$est_vol_oos)
out_of_sample_f <- function(rtrn, r_w, re_est_w, exog) {


  oosf = xts(as.numeric(0), as.Date("2013-04-08"))
  
  for (i in 0:(length(rtrn) - r_w)) {
    if(i%%re_est_w == 0){
      mv_m<-mv_into_mat(rtrn[(i + 1):(i + r_w)],exog,K=12,"monthly")
      fit<-ugmfit(model="GM",skew="NO",distribution="norm",rtrn[(i + 1):(i+r_w)],mv_m,K=12, out_of_sample = re_est_w)
      oosf = rbind(oosf, fit$est_vol_oos)

    }
  }
  oosf <- oosf[-1,]


  return(oosf)
}

Upvotes: 3

Related Questions