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