I have no idea of the R financial packages (I wish I knew). I am guessing that your main problem is to know when to trade and when not to trade, and, that after figuring out that, your problem is solved.
First you may try with a pure R solution. I am a fan of Reduce
so you may try with this.
deltaTrade <- function(currentTrend,nextSignal) ifelse(lastOp != nextSignal,1,-1)
trade <- Reduce('deltaTrade',signal,init=signal[1],accumulate=TRUE)
tradePeriods = which(trade==1)
If it is too slow I have recently seen in other SO questions that switching to C++ for an efficient solution is a good way to tackle the problem. You can do that with the cpp
package, which apparently has become a real hip.
library(Rcpp)
cppFunction("NumericVector selectTrades(NumericVector x, NumericVector out) {
int n = x.length();
int current = x[0];
for(int i = 0; i < n; ++i) {
if (x[i] == current) {
out[i] = 0; // hold position
} else {
current = x[i];
out[i] = 1; // play position
}
}
return out;
}")
trades = which(selectTrades(signal,out)==1)
Anyway, I hope that any of these helps.