R Code - Retrieve previous data from previous date(row) and update current one

Hello everyone,


I’m trying to do the following in R code but I’m blocked on one point :


  • Create a new XTS data values from prices and indicator
  • Update this XTS with the following steps (blocked):
  • at T0 -> Check previous value T-1 to update the current one T0
  • at T+1 -> Check the previous updated value T0 and update the current one T+1
  • and so on until the and on the XTS


Perhaps using the lag function to create a new XTS and using in in parallel of the orignal.


Hope you see my need :slight_smile:


Can you please help me to implement this in R code ?


Thanks

Regards

Greg

Hi Greg,

You are trying to build a path dependent indicator, where current values depend on past computed values.

Basically, you will need to construct you indicator day by day, meaning you will need to loop through you time series.

I have written a toy example below. This will add a long position if the mean spread between two times series over a given period (nDay) is above a threshold (threshold) and the indicator yesterday was 0. Please look at the code below and let me know if it helps:


pathDependentIndicator = function(oneTimeSeries, anotherTimeSeries, threshold, nDay){

   

  #write some code to check formats are correct

  stopifnot(any(class(oneTimeSeries)==‘xts’), any(class(anotherTimeSeries)==‘xts’), is.numeric(threshold))

   

  #check the two time series are on the same time axis

  if (!identical(index(oneTimeSeries), index(anotherTimeSeries))){

    stop(‘Time axis are of different length, please resize first’)

  }

   

  #Basically you need to loop through dates one by one and build your indicator day after day

#initialise indicator

  indic = rep(0, length=dim(oneTimeSeries)[1]) # construct indicator series of correct length, all flat positions

   

#loop through days

  for (i in 1:dim(oneTimeSeries)[1]){

    if (i==1){

      #do some initial / setup transformations if need be on day 1

      #for example, start with a long bias

      indic[i] = 1

    } else {

      # You can check the value of indicator yesterday

      yest = indic[i-1]

       

      #You can access data from the past in the time series

      ## !! Make sure to only use indices from 1:i !!

      pastSpreadNDay = oneTimeSeries[max(i-nDay,1):i-1]-oneTimeSeries[max(i-nDay,1):i-1] #spreads over the N past days

      indic[i] = ifelse(mean(pastSpreadNDay)>threshold&yest==0,1,0)

    }

    indic = xts(indic, order.by = index(oneTimeSeries)) #build time series object

    return(na.omit(indic))

  }

}


Thanks

Thanks Herve,


It was exactly what I was looking for.


Regards

Greg