r - Adjusting for dividend and splits using quantmod -


i using quantmod adjust dividends , splits. seems work have found following problem: when adjusting sma(200,0) historical values wrong , correct date approaches current date. please see code below.

stockdata <- new.env() #make new environment quantmod store data in symbols = c("iwm","spy","tlt","tsla") nr.of.positions<-3 getsymbols(symbols, src='yahoo',from = "2015-10-01",to = sys.date()) (i in 1:length(symbols)) {   assign (symbols[i], adjustohlc(get(symbols[i]),                 adjust=c("split", "dividend"),                 use.adjusted=false,                symbol.name=symbols[i])) }  x <- list()  (i in 1:length(symbols)) {   x[[i]] <- get(symbols[i], pos=stockdata)  # data stockdata environment    x[[i]]$sma <-sma(cl(x[[i]]),10)   x[[i]]$smalong <-sma(cl(x[[i]]),200)   x[[i]]$adx<-adx(hlc(x[[i]]),10)   x[[i]]$rsi <-rsi(cl(x[[i]]),14)   x[[i]]$close <-(cl(x[[i]])) } 

you're lucky code works. or maybe you're unlucky, since error have let know did wrong.

you create stockdata environment , comment says intended store data pull in it. don't specify stockdata environment in call getsymbols, or calls assign , get in first loop. they're assigning , getting global environment.

your code clearer if avoid using get , assign within loop, , instead used convenience functions lapply , eapply.

stockdata <- new.env() symbols <- c("iwm","spy","tlt","tsla") nr.of.positions <- 3 getsymbols(symbols, = "2015-10-01", env = stockdata)  # loop on objects in environment eapply adj <- eapply(stockdata, function(x) {   symbol <- sub("\\.close$", "", colnames(cl(x)))   adjustohlc(x, symbol.name=symbol) })  # loop on list returned eapply x <- lapply(adj, function(x) {   x$sma <- sma(cl(x),10)   x$smalong <- sma(cl(x),200)   x$adx <- adx(hlc(x),10)   x$rsi <- rsi(cl(x),14)   x$close <- cl(x)   x }) 

you'll notice results of code , code same if run them each in clean r session. reason code produced "wrong" results because had other objects in workspace being assigned/accessed use of get , assign.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -