使用R中的quantmod包检索每月调整后的股票报价

问题描述 投票:2回答:3

我这学期学习R,这是我的第一个任务。我想使用for循环在设定的日期范围内检索每月调整后的股票报价。一旦我能够做到这一点,我想将所有数据合并到一个数据框中。

到目前为止,我的代码检索了设定日期范围内5个股票代码的每日股票报价,它将对象分配给指定的环境,并仅在列表中放置.Adjusted列。

有人能指出我在获得月度报价方面的更好方向,并且我的代码是正确的。

谢谢。

#Packages
library(quantmod)

#Data structure that contains stock quote objects
ETF_Data <- new.env()

#Assign dates to set range for stock quotes
sDate <- as.Date("2007-08-31")
eDate <- as.Date("2014-09-04")

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

#Assign number of ticker symbols.
total_ticker_symbols <- length(ticker_symbol)

#Assign empty list to for each object contained in my environment. 
Temp_ETF_Data <- list()

#Assign integer value to counter.
counter <- 1L

#Loop and retrieve each ticker symbols quotes from Yahoo's API 
for(i in ticker_symbol)  
{  

  getSymbols(
    i, 
    env = ETF_Data, 
    reload.Symbols = FALSE, 
    from = sDate, 
    to = eDate,
    verbose = FALSE,
    warnings = TRUE,
    src = "yahoo",
    symbol.lookup = TRUE) 

  #Add only Adjusted Closing Prices for each stock or object into list. 
  Temp_ETF_Data[[i]] <- Ad(ETF_Data[[i]])  

  if (counter == length(ticker_symbol))
  { 
     #Merge all the objects of the list into one object. 
     ETF_Adj_Daily_Quotes   <- do.call(merge, Temp_ETF_Data)
     ETF_Adj_Monthly_Quotes <- ETF_Adj_Daily_Quotes[endpoints(ETF_Adj_Daily_Quotes,'months')]
  }
  else
  {
    counter <- counter + 1
  }

}
r xts quantmod
3个回答
2
投票

没有必要使用for循环。您可以使用eapply遍历环境中的所有对象:

getSymbols(ticker_symbol, env=ETF_Data, from=sDate, to=eDate)
# Extract the Adjusted column from all objects,
# then merge all columns into one object
ETF_Adj_Data <- do.call(merge, eapply(ETF_Data, Ad))
# then extract the monthly endpoints
Monthly_ETF_Adj_Data <- ETF_Adj_Data[endpoints(ETF_Adj_Data,'months')]

0
投票

我知道这是一个老问题,但这个答案可能有助于潜在的未来用户寻求更好的答案。

quantmod现在introducedgetSymbols函数的另一个参数,称为periodicity,它可以取dailyweeklymonthly的值。

我测试了以下内容,它似乎按预期工作:

getSymbols("EURGBP=X", from = starting, src = 'yahoo', periodicity = 'monthly')

-1
投票

只是用

to.monthly(your_ticker)
© www.soinside.com 2019 - 2024. All rights reserved.