Friday, 15 February 2013

r - Using lapply on quantmod, get straight to xts object? -



r - Using lapply on quantmod, get straight to xts object? -

i importing stock info yahoo , calculate daily range high - low. want set each stock's range in single xts object. below code accomplishes seems convoluted me.

the problem starts lapply. list of xts objects, need refer individual objects "a layer down" using [[ ]]. if refer each xts object quotes[i], go on utilize apply functions rather loops. tried utilize sapply instead of lapply got error, "error in array(r, dim = d, dimnames = if (!(is.null(n1 <- names(x[[1l]])) & : length of 'dimnames' [1] not equal array extent"

furthermore, hate practice used in sec loop. range doesn't yet exist, need create doing in way seems defeat purpose of loop. there improve way? i'd avoid creating empty xts object know not practice either.

require(quantmod) tickers <- c("erx", "ewj", "eww", "ewz", "fas", "faz") quotes <- lapply(tickers,function(x) getsymbols(x, src="yahoo", from="2014-10-10", auto.assign=false)) names(quotes) <- tickers (i in 1:length(quotes)){ quotes[[i]] <- quotes[[i]][,2] - quotes[[i]][,3] colnames(quotes[[i]]) <- paste(names(quotes)[i], "range") } (i in 1:length(quotes)){ if (i == 1) {range <- quotes[[i]]} else {range <- merge(range, quotes[[i]])} }

thank you.

the easiest way store info in environment, , loop on objects in environment eapply:

require(quantmod) tickers <- c("erx", "ewj", "eww", "ewz", "fas", "faz") dataenv <- new.env() getsymbols(tickers, env=dataenv) # calculate range objects, # merge range columns 1 object hl <- do.call(merge, eapply(dataenv, function(x) hi(x)-lo(x))) # update column names colnames(hl) <- gsub("(.*)high$", "\\1range", colnames(hl))

r xts quantmod

No comments:

Post a Comment