rtime-serieszoo

Simple loop through large xts gives fatal error


I'm trying to add a variable that keeps track of the all-time high of a time series. The below code doesn't work - R encounters a fatal error during the for loop. I don't quite understand what's wrong here.

enter image description here

Edit: Even stranger now. Sometimes this works, and sometimes it doesn't.

library(quantmod)
GSPC_df <- getSymbols("^GSPC", src = "yahoo", auto.assign = FALSE,
                      from = "1927-12-30")
GSPC_df$GSPC.ATH <- GSPC_df$GSPC.Close
for (i in (2:nrow(GSPC_df))){
  GSPC_df$GSPC.ATH[i] <- max(GSPC_df$GSPC.Close[i], GSPC_df$GSPC.ATH[i - 1])
}

And - if it works - it is much, much slower than the (maybe not so) equivalent operation on a regular dataframe:

library(quantmod)
GSPC_df <- as.data.frame(getSymbols("^GSPC", src = "yahoo", auto.assign = FALSE,
                      from = "1927-12-30"))
GSPC_df$GSPC.ATH <- GSPC_df$GSPC.Close
for (i in (2:nrow(GSPC_df))){
  GSPC_df$GSPC.ATH[i] <- max(GSPC_df$GSPC.Close[i], GSPC_df$GSPC.ATH[i - 1])
}

Solution

  • Use cummax as shown. Returning zoo from getSymbols will improve the subsequent name processing but is otherwise similar to using xts. We convert to xts at the end. This last line is optional.

    library(magrittr)
    library(quantmod)
    
    stock <- "^GSPC" %>%
      getSymbols(auto.assign = FALSE, return.class = "zoo") %>%
      na.omit %>%
      transform(ATH = cummax(Cl(.))) %>%
      as.xts   # optional