Window accumulated in R

Asked

Viewed 31 times

1

I need to rank days based on a cumulative window of all the days before it. In this case, I need to start with a 252-day window, sort the observations, make a ranking of 20 equally distributed percentiles. Hence take the observation of day 253, compare with that rank, if it is within the rank values, classify according to it, if it is less than the minimum, classify as 0 and if it is greater than the maximum, classify as 21. That done, I need to run this function all over the base, increasing the rank window, starting for 252 days, going to 253, and so on.

I have the following code, which does exactly what I said at the beginning, but with the 252 day fixed window.

    qtl.rank2<-function(x,obs.1=1,obs.t=252,qtl.intl=20)
{
  #x: list;
  #obs.1: calibragem, 1a obs;
  #obs.t: calibragem, última obs;
  #qtl.intl: quantidade de intervalos.

  x.length<-length(x) #tamanho da lista
  i<-t #contador dos quantis
  j<-1 #contador
  qtl.width<-100/qtl.intl #tamanho do intervalo
  pi<-0 #inicializa variável que armazena o quantil
  pi.vec<-matrix(0,nrow=qtl.intl,ncol=1) #matriz para armazenar os percentis

  calibration.list<-list(0,obs.t)

  matriz.resultados<-matrix(0,nrow=(x.length-obs.t),2)

  for(i in obs.1:(x.length-obs.t))
  {
    calibration.list <- x[i:(i+obs.t-1)]  
    pctl<-quantile(calibration.list,1:qtl.intl*qtl.width/100)
    pi.vec<-as.matrix(pctl)
    rownames(pi.vec)<-rownames(as.matrix(pctl))
    colnames(pi.vec)<-"Percentis"

    new.pi.vec<-matrix(c(pi.vec,0),nrow=qtl.intl+1,ncol=1)

    new.pi.vec[qtl.intl+1,]<-x[i+obs.t]

    o<-order(new.pi.vec, decreasing=FALSE)
    new.pi.vec<-as.matrix(new.pi.vec[o,])

    res<-c(x[i+obs.t],which(new.pi.vec[,1]==x[i+obs.t],arr.ind=TRUE))
    num_aval<-res[1]
    qtl.order<-res[2]

    if(qtl.order==1)
    {
      print(calibration.list)
      if(num_aval<min(calibration.list))
      {
        qtl.order<-0
      }

    res<-c(num_aval,qtl.order)

    }

    matriz.resultados[i,1]<-res[1]
    matriz.resultados[i,2]<-res[2]

    if(i<x.length-(obs.t+1)){print(matriz.resultados[i+1,])}

    print(c(i,res))

  }
 return(matriz.resultados)
}

How do I adjust this code so that it can accumulate the days of the window to make the ranking?

Thank you!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.