Question

Here is the code:

require("quantmod")

getSymbols("SPY")  

ticker <- SPY[,4]

win <- 0 

for(i in 11:NROW(ticker))

j <- i-10

if(ticker[i] > ticker[j])               

win <- win + 1

I'd like to check if today's close is greater than the close 10 days ago, and if it is to increment the win variable. I've also tried the following:

for(i in 11:NROW(ticker))

if(ticker[i] > ticker[i-10])               

win <- win + 1             

Both seem like they should work so I actually have two problems. First getting it to work, but also importantly understanding why they don't work. Both flag "argument is of length zero". My hunch is that it's the ticker[j] or ticker[i-10] that is the culprit. Mostly because when I replace them with a hard-coded value they work.

Was it helpful?

Solution

Problem is that ticker[i] does not return a numeric object so you can't compare or subtract from them. Try this for fun:

str(ticker[15])
ticker[15]-ticker[10]

So, just wrap them in as.numeric and you'll get what you need.

require("quantmod")
getSymbols("SPY")  
ticker <- SPY[,4]
win <- 0 
for(i in 11:NROW(ticker)){
    j <- i-10
    if(as.numeric(ticker[i]) > as.numeric(ticker[j])){             
        win <- win + 1
    }
}

OTHER TIPS

This has nothing to do with for loops. It's because xts/zoo are aligned by their index before any operations are performed. ticker[i] > ticker[j] is empty because the indexes are different.

You don't really need a for loop either. You can do this easily by lagging the series:

merged.ticker <- merge(ticker, lag(ticker,10))
win <- sum(merged.ticker[,1] > merged.ticker[,2], na.rm=TRUE)
lose <- sum(merged.ticker[,1] < merged.ticker[,2], na.rm=TRUE)

Curly braces are your friend, my friend.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top