This is somewhat of a simple manner, yet I couldn't really find a quick (1,2,3)-liner to solve it. I have a vector of rolling mean of 10 day returns - the strategy is simple: go long when the rolling mean crosses the zero barrier from below and sell when it crosses the barrier from above. To be more precise, let us say the rolling mean returns are stored in vector Returns.
which(Returns > 0)
[1] 3 4 5 9 10 11 14 18 27 28 29 36 37 38 47 48
Based on this I would be long at times 4,5,6 (at 3 we only get the entrance signal and at 6 we exit), 10,11,12,15,19 and so on. How can I get this vector? I have experimented with diff, another which and several other combinations but nothing really solves the problem. Any help will be greatly appreciated.
Edit (based on the first answer):
Initiate_Long_Position <- which(ifelse(goLong == TRUE, 1,0) == 1)
Terminate_Long_Position <- which(ifelse(goShort == TRUE, 1,0) == 1)
if (length(Terminate_Long_Position) > length(Initiate_Long_Position) ){
Terminate_Long_Position <- Terminate_Long_Position[-1]
}
Days_Long_Returns <- rep(0, dim(ticker)[1])
Daily_returns <- returns(Cl(ticker))
for (i in 1:length(Initiate_Long_Position)){
Days_Long_Returns[(Initiate_Long_Position[i]+1):(Terminate_Long_Position[i])] <-
Daily_returns[(Initiate_Long_Position[i]+1):(Terminate_Long_Position[i])]
}
I have added +1 to Initiate_Long_Position[i] in the foor loop as we only get the next period return after the signal to go long is observed, whereas selling is done in "real time". Am I missing something, i.e are returns properly indexed so that we are not looking into the future of using the returns i-1 at time i?