仅使用getSymbols()返回指定列的函数

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

所以我试图建立这个简单的功能,只使用getSymbols()返回谷歌调整后的价格。

yahoo<-function(a){
a<-getSymbols("a", from= as.Date("1/1/13", format="%m/%d/%y"),to=Sys.time(), auto.assign = FALSE)
a[,6]

}

但是,这实际上得到了名为a或x的符号,无论它是什么。我期待像雅虎(GOOG)这样的东西将返回谷歌的调整价格。知道我怎么能这样做吗?

谢谢!

r quantmod
2个回答
0
投票

如果我们需要返回值,那么获取substitute参数并将其解析为字符串

library(quantmod)   
yahoo <- function(a){
   a <- deparse(substitute(a))
    res <- getSymbols(a, from= as.Date("1/1/13", 
           format="%m/%d/%y"),to=Sys.time(), auto.assign = FALSE)
    res[,6]

  }

out <- yahoo(GOOG)
head(out)
#           GOOG.Adjusted
#2013-01-02      359.2882
#2013-01-03      359.4968
#2013-01-04      366.6006
#2013-01-07      365.0010
#2013-01-08      364.2807
#2013-01-09      366.6751

tail(out)
#           GOOG.Adjusted
#2018-02-13       1052.10
#2018-02-14       1069.70
#2018-02-15       1089.52
#2018-02-16       1094.80
#2018-02-20       1102.46
#2018-02-21       1111.34

另一个选择是使用tidyquanttidyverse

library(dplyr)
library(tidyquant)
yahoo2 <- function(a) {
      a <- quo_name(enquo(a))
      tq_get(a, from = "2013-01-01", to = Sys.Date()) %>%
          select(date, adjusted)
 }  

yahoo2(GOOG)
# A tibble: 1,294 x 2
#   date       adjusted
#   <date>        <dbl>
# 1 2013-01-02      359
# 2 2013-01-03      359
# 3 2013-01-04      367
# 4 2013-01-07      365
# 5 2013-01-08      364
# 6 2013-01-09      367
# 7 2013-01-10      368
# 8 2013-01-11      368
# 9 2013-01-14      359
#10 2013-01-15      360
# ... with 1,284 more rows

0
投票

使用assign会做到这一点。

assign('AAPL',getSymbols(‘AAPL,from='2018-02-01',auto.assign = F)[,6] )

如果要在函数中执行此操作:

yahoo <- function(ticker, from){
  assign(ticker,
         getSymbols(ticker,from=from,auto.assign = F)[,6],
         pos = 1
         )
}
yahoo(‘AAPL’)

请注意,一些雅虎代码使用的特殊字符如^@将被删除/替换(即“^ GSPC”)。在命名对象时,您可以更灵活地使用非函数方法。

© www.soinside.com 2019 - 2024. All rights reserved.