np2000
np2000

Reputation: 37

Adjusting for dividend and splits using quantmod

I am using quantmod to adjust for dividends and splits. It seems to work but I have found the following problem: when adjusting my sma(200,0) historical values are wrong and they correct as the date approaches the current date. Please see the code below.

stockData <- new.env() #Make a new environment for quantmod to store data in
symbols = c("IWM","SPY","TLT","TSLA")
nr.of.positions<-3
getSymbols(symbols, src='yahoo',from = "2015-10-01",to = Sys.Date())
for (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() 
for (i in 1:length(symbols)) {
  x[[i]] <- get(symbols[i], pos=stockData)  # get data from 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]]))
}

Upvotes: 0

Views: 645

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

You're lucky that your code works. Or maybe you're unlucky, since an error would have let you know you did something wrong.

You create a stockData environment and the comment says you intended to store the data you pull in it. But you don't specify the stockData environment in your call to getSymbols, or your calls to assign and get in the first for loop. So they're all assigning and getting from the global environment.

Your code would be clearer if you avoid using get and assign within a for loop, and instead used convenience functions lapply and eapply.

stockData <- new.env()
symbols <- c("IWM","SPY","TLT","TSLA")
nr.of.positions <- 3
getSymbols(symbols, from = "2015-10-01", env = stockData)

# loop over objects in an environment with eapply
adj <- eapply(stockData, function(x) {
  symbol <- sub("\\.Close$", "", colnames(Cl(x)))
  adjustOHLC(x, symbol.name=symbol)
})

# loop over list returned by 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 the results of my code and your code are the same if you run them each in a clean R session. So the reason your code produced "wrong" results is probably because you had other objects in your workspace that were being assigned/accessed by your use of get and assign.

Upvotes: 1

Related Questions