【问题标题】:R code to rename header of an xts object using name(object) <- vector使用名称(对象)<-向量重命名xts对象的标头的R代码
【发布时间】:2015-02-13 20:44:42
【问题描述】:

我是学习 R 的新手,我的一些 R 代码有问题。为了您的方便,我放置了所有代码,以便您可以看到我正在尝试做的事情的逻辑。我的问题是重命名我的 xts 对象 Monthly_Quotes 的标题。我知道当股票代码无效时,getsymbols 函数不会检索“zzzz”的引号,这就是我遇到重命名标题问题的原因。我想解决这个问题,如果我有一个更大的股票代码列表没有被下载,我不会有从我的股票代码列表中重命名标题的问题。

#Environment to store stock symbols data
ETF_Data <- new.env()

#Dates needed for getSymbols function
sDate <- as.Date("2007-09-04") #Start Date
eDate <- as.Date("2014-09-02") #End   Date

#Assign vector of ticker symbols
ticker_symbol <- c("zzzz","IVW","JKE","QQQ","SPYG","VUG" )

#Load functions  
source("Functions.R")

#Create empty list
Temp_ETF_Data <- list()

#Variable is a connection to a specific file that appends the output to the file
connection_string <- file("Log_File.txt", open = "wt")

#Sink allows the R output to a connection file which is connection_string
#Log_File.txt is created to the directory that has been set
sink(connection_string, type="message")

#Loop to retrieve prices from Yahoo's API and assign only the Adjusted column to the list.
for(i in ticker_symbol){  
  tryCatch(
  {
      getSymbols(i, env = ETF_Data, from = sDate, to = eDate, src = "yahoo", warning = FALSE) 
      Temp_ETF_Data[[i]] <- Ad(ETF_Data[[i]])
  },    

  error = function(e) {
      message("-ERROR-")
      message(paste("Error for ticker symbol  :", i, "\n"))
      message("Here's the original error message: ")
      message(e)
      message("")
      return(i)},
 finally = {
     message(paste("Data was processed for symbol:", "[", i, "]" ))
     message("\n","******************************************", "\n")  
}) 
}

#Turns off message once it is on the console and reads the line. 
#Then it closes the sink connection and closes the connection to the Log_File.txt
sink(type = "message")
readLines("Log_File.txt")
close(connection_string)

#Merge list into columns from list 
Daily_Quotes <- do.call(merge, Temp_ETF_Data)

#Create new xts object with the 1st trading day price of each month and assign column headers 
Monthly_Quotes  <- Daily_Quotes[startpoints(Daily_Quotes,'months')]
#This piece of code creates this error
#     "Error in `colnames<-`(`*tmp*`, value = c("zzzz", "IVW", "JKE", "QQQ",  : 
#         length of 'dimnames' [2] not equal to array extent"
names(Monthly_Quotes) <- c(ticker_symbol)

我试过这个:

ticker_symbol 名称(Monthly_Quotes)

【问题讨论】:

  • names(Daily_Quotes) 不包括 zzzz(例如,没有列 zzzz.Adjusted),但向量 ticker_symbols 包括。因此,您尝试将本例中长度为 5 的 names(...) 设置为长度为 6 的向量。因此出现错误。
  • @jlhoward - 我是故意这样做的,所以我可以学习如何处理错误。我意识到无论出于何种原因,所有符号都不会下载。我添加了一些我认为可以解决我的问题的新代码。除非有人有更好的解决方案。

标签: r xts quantmod performanceanalytics


【解决方案1】:

这并不能直接回答你的问题(见评论),但这不是更容易吗:

library(quantmod)
ticker_symbol <- c("zzzz","IVW","JKE","QQQ","SPYG","VUG" )
sDate <- as.Date("2007-09-04") #Start Date
eDate <- as.Date("2014-09-02") #End   Date

get.symbol <- function(ticker) {  
  tryCatch(temp <- Ad(getSymbols(ticker, auto.assign=FALSE, 
                                 from = sDate, to = eDate, warning = FALSE)),    
           error = function(e) {
             message("-ERROR-")
             message(paste("Error for ticker symbol  :", ticker, "\n"))
             message("Here's the original error message: ")
             message(e)
             message("")
             return(NULL)},
           finally = {
             message(paste("Data was processed for symbol:", "[", ticker, "]" ))
             message("\n","******************************************", "\n")  
           }) 
}
result <- do.call(cbind,lapply(ticker_symbol,get.symbol))
names(result) <- gsub("\\..+","",names(result))  # remove ".Adjusted" from names
head(result)
#              IVW   JKE   QQQ  SPYG   VUG
# 2007-09-04 61.71 65.37 46.56 52.42 57.36
# 2007-09-05 61.37 64.78 46.10 51.95 56.85
# 2007-09-06 61.47 65.13 46.06 52.18 57.13
# 2007-09-07 60.58 64.06 45.21 51.29 56.31
# 2007-09-10 60.36 64.13 45.18 51.24 56.12
# 2007-09-11 61.19 65.03 45.86 51.90 56.89

这利用了getSymbols(...)auto.assign=... 参数来避免所有这些环境设置并将临时结果累积到一个列表中。

【讨论】:

  • 这看起来更干净。谢谢 jlhoward。
猜你喜欢
  • 2021-06-02
  • 1970-01-01
  • 2016-02-19
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
相关资源
最近更新 更多