ThallyHo
ThallyHo

Reputation: 2833

For loop with an xts

I am trying to write a function that loops over the open and close values in an xts object. The function should return 1 when the close of i+1 is greater than the open of i.

Here is the function

longsig <- function(x){
    ls <- numeric(length=nrow(x))

    for(i in 1:length(ls)){

        if(Cl(x[i+1]) > Op(x[i])) {
            ls[i] <- 1
        } else {
            ls[i] <- 0
      } 
    }
    return(ls)
}

and here is the section of data I am trying to apply this function to. It is an xts object.

     Open     High      Low    Close
2014-01-03 116.9000 119.6400 114.5300 116.9925
2014-01-10 116.9463 116.9463 111.9700 113.8825
2014-01-17 115.4144 115.5700 112.1500 114.0975
2014-01-24 114.7559 118.3400 114.1500 116.0950
2014-01-31 115.4255 119.0900 115.4255 117.5475
2014-02-07 116.4865 120.7400 116.4865 118.9450

The function returns the following error

Error in if (Cl(x[i + 1]) > Op(x[i])) { : argument is of length zero

Clearly I am doing something wrong in applying this loop to the xts object, but I have very limited experience with xts. Any help would be greatly appreciated.

Upvotes: 0

Views: 474

Answers (1)

hvollmeier
hvollmeier

Reputation: 2986

I strongly advise not to use a loop for this kind of situation. A simple ifelse will accomplish what you want to do and much, much faster than a loop.

Data: 6 days of AMZN

           AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume AMZN.Adjusted
2019-01-23   1656.00   1657.43  1612.00    1640.02     5225200       1640.02
2019-01-24   1641.07   1657.26  1631.78    1654.93     4089900       1654.93
2019-01-25   1670.50   1683.48  1661.61    1670.57     4945900       1670.57
2019-01-28   1643.59   1645.00  1614.09    1637.89     4837700       1637.89
2019-01-29   1631.27   1632.38  1590.72    1593.88     4632800       1593.88
2019-01-30   1623.00   1676.95  1619.68    1670.43     5751700       1670.43

ifelse(Cl(AMZN)-lag(Op(AMZN)) > 0,1,0)

           AMZN.Close
2019-01-23         NA
2019-01-24          0
2019-01-25          1
2019-01-28          0
2019-01-29          0
2019-01-30          1

If you want to put this into a function

compareOpCl <- function(x){
     ifelse(Cl(x)-lag(Op(x)) > 0,1,0)
 }

will do it.

Upvotes: 1

Related Questions