Milktrader
Milktrader

Reputation: 9828

for loop not working in R

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.

Upvotes: 2

Views: 1974

Answers (3)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

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)

Upvotes: 1

Vincent
Vincent

Reputation: 17725

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
    }
}

Upvotes: 2

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

Curly braces are your friend, my friend.

Upvotes: -1

Related Questions