Quantmod save tickers to files in a loop or lapply

我只是一个虾纸丫 提交于 2019-12-03 21:28:34

UPDATE: The solution below doesn't solve the OP's problem (see comments). See the edit after the jump.

The default of auto.assign=TRUE is supposed to make things easier when using getSymbols interactively. Set auto.assign=FALSE when using getSymbols in a function; it will make things much easier.

buildhist <- function(x,start,end) {
  y <- getSymbols(x, from=start, to=end, adjust=TRUE, auto.assign=FALSE)
  save(y, file= paste(x, "hist.rda", sep="_"), ascii = FALSE)  
}

You can remove punctuation characters (including the caret) via gsub. See ?gsub and ?regex for details.

X <- gsub("[[:punct:]]","",x)  # remove all punctuation
X <- gsub("\\^","",x)          # remove just the carat

I didn't test my initial answer. This solution should work.

buildhist <- function(x,start,end) {
  getSymbols(x, from=start, to=end, adjust=TRUE)
  X <- toupper(gsub("\\^","",x))  # what getSymbols.yahoo does
  save(list=X, file= paste(X, "hist.rda", sep="_"), ascii = FALSE)  
}

require(quantmod)
tckr <- c("^GSPC","YHOO","XLB")
lapply(tckr,buildhist,start="1995-01-01",end="2011-11-30")

If you're only using daily data on a small number of symbols, you may be able to load them all to one environment and just save the environment. That could save you a lot of trouble. Then you could load the environment to a new session, attach it, and have all the data at your fingers.

myEnv <- new.env()
getSymbols(paste(tckr,sep=";"), start="1995-01-01", end="2011-11-30",
  env=myEnv, adjust=TRUE)
save(myEnv, file="myTickerData.rda")

Can you verify your getSymbols call succeeded by doing something like summary(YHOO) ? You definitely do not want to write (save(get(x)) because there is no object named "get(x)".

I suspect your problem is related to proper use of lapply . This works:

foo <- 5
oof <- 4
bar<-c("foo","oof")
lapply(lapply(bar,get),sqrt)

(where of course you'd be using buildhist not sqrt)

In below, SymbolList is a vector that has the symbols. i.e.

SymbolList <- c("IBM","GOOG","YHOO")

Get the historical data for these using getSymbols

getSymbols(SymbolList)

define a function and use the do.call,

fun <- function(i) {return(adjustOHLC(get(SymbolList[i]),adjust = "split", use.Adjusted=TRUE))}
mydata <- do.call(merge, lapply(1:length(SymbolList), fun))

this will give you the data merged, couple other things you could use, i.e. if you want only the closing values and adjust for the splits.

 fun <- function(i) {return(Cl(adjustOHLC(get(SymbolList[i]),adjust = "split", use.Adjusted=TRUE)))}

you may want to cast into a data frame as well.

mydata<-as.data.frame(mydata)

from there you could write this to a csv file.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!