Question

I've a data like this:

library("xts")
close <- c(0, -0.5, -0.75, -1, -0.75, -1.5, -2, -2.5, -3, -3.5, -3, -2.5, -2, -1, 0, 1, 1.5, 2, 2.5, 3, 2.5, 2, 0)
data <- xts(close, Sys.Date()-23:1)
colnames(data) <- "close"

I'd like to generate another column which will give me a trade signal based on the logic below:

  • Buy when the close is @ or below -1, -2 and -3.
  • Sell all the 3 when close is @ or above 0.
  • Short Sell when the close is @ or above 1, 2 and 3
  • Buy all the 3 when close is @ or below 0.

For this i've tried

data$trade <- 0
data$trade[data$close <= -1] <- 1
data$trade[data$close <= -2] <- 2
data$trade[data$close <= -3] <- 3
data$trade[data$close >= 1] <- -1
data$trade[data$close >= 2] <- -2
data$trade[data$close >= 3] <- -3

data trade column is giving me (0,0,0,1,0,1,2,2,,3,3,3,2,2,1,0,-1,-1,-2,-2,-3,-2,-2,0) but i want that it should give me ((0,0,0,1,1,1,2,2,3,3,3,3,3,3,0,-1,-1,-2,-2,-3,-3,-3,0) i want that when i buy @ say -1 or -2 the trade signal should be on till we reach 0 or above and similarly when we short sell it @ say -1, -2 etc the trade signal should be on till we reach 0 or below. Kindly help i've tried lots of combinations, but not getting the required result.

Was it helpful?

Solution

If I've understood correctly, this is hard to do efficiently because the choice depends upon the past. It's not elegant but this code gives the output you require,

library("xts")
close <- c(0, -0.5, -0.75, -1, -0.75, -1.5, -2, -2.5, -3, -3.5, -3, -2.5, -2, -1, 0, 1, 1.5, 2, 2.5, 3, 2.5, 2, 0)
data <- xts(close, Sys.Date()-23:1)
colnames(data) <- "close"

sig.buy <- c(F,F,F)
sig.short <- c(F,F,F)

for(i in 1:length(data))
{
    if(data$close[i] <= -1) sig.buy[1] <- T
    if(data$close[i] <= -2) sig.buy[2] <- T
    if(data$close[i] <= -3) sig.buy[3] <- T

    if(sig.buy[1] && data$close[i] >= 0) sig.buy[1] <- F
    if(sig.buy[2] && data$close[i] >= 0) sig.buy[2] <- F
    if(sig.buy[3] && data$close[i] >= 0) sig.buy[3] <- F

    if(data$close[i] >= 1) sig.short[1] <- T
    if(data$close[i] >= 2) sig.short[2] <- T
    if(data$close[i] >= 3) sig.short[3] <- T

    if(sig.short[1] && data$close[i] <= 0) sig.short[1] <- F
    if(sig.short[2] && data$close[i] <= 0) sig.short[2] <- F
    if(sig.short[3] && data$close[i] <= 0) sig.short[3] <- F

    data$trade[i] <- sum(sig.buy) - sum(sig.short)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top