为 getSymbols() 设置默认参数

在 R 中导入与管理金融数据

Joshua Ulrich

Quantitative Analyst & quantmod Co-Author and Maintainer

getSymbols() "方法"

  • getSymbols() 本身不包含导入数据的代码
  • 各数据源的代码在 getSymbols.[source] "方法"中
  • 例如:
# 您调用 getSymbols()
getSymbols("GDP", src = "FRED")

# getSymbols() 调用对应源的"方法"
getSymbols.FRED("GDP")
  • 不应直接调用 getSymbols() 的"方法"
在 R 中导入与管理金融数据

用 setDefaults() 更改默认数据源

setDefaults(getSymbols, src = "FRED")
gdp <- getSymbols("GDP", auto.assign = FALSE) 
# 注意 'src' 属性
str(gdp)
 An 'xts' object on 1947-01-01/2016-10-01 containing:
   Data: num [1:280, 1] 243 246 250 260 266 ...
  - attr(*, "dimnames")=List of 2
   ..$ : NULL
   ..$ : chr "GDP"
   Indexed by objects of class: [Date] TZ: UTC
   xts Attributes:  
 List of 2
  $ src    : chr "FRED"
  $ updated: POSIXct[1:1], format: "2017-02-13 08:46:50"
在 R 中导入与管理金融数据

setDefaults()

  • name = value 对设置新的默认参数
  • 仅影响 getSymbols() 的行为
  • 值存储在全局 options()
在 R 中导入与管理金融数据

其他参数

  • 查找某个 getSymbols() 源方法的形式参数
    • args()args(getSymbols.yahoo)
    • help()help("getSymbols.yahoo")
在 R 中导入与管理金融数据

默认 from 和 to 值

args(getSymbols.yahoo)
 function (Symbols, env, return.class = "xts", index.class = "Date", 
     from = "2007-01-01", to = Sys.Date(), ...)
setDefaults(getSymbols.yahoo, from = "2016-01-01", to = "2016-12-31")

aapl <- getSymbols("AAPL", auto.assign = FALSE) 
str(aapl)
 An 'xts' object on 2016-01-04/2016-12-30 containing:
   Data: num [1:252, 1:6] 102.6 105.8 100.6 98.7 98.6 ...
  - attr(*, "dimnames")=List of 2
   ..$ : NULL
   ..$ : chr [1:6] "AAPL.Open" "AAPL.High" "AAPL.Low" "AAPL.Close" ...
   Indexed by objects of class: [Date] TZ: UTC
   xts Attributes:  
 List of 2
  $ src    : chr "yahoo"
  $ updated: POSIXct[1:1], format: "2017-02-13 08:46:50"
在 R 中导入与管理金融数据

getDefaults()

getDefaults()
"getSymbols.yahoo"
getDefaults(getSymbols.yahoo)
$from
"'2016-01-01'"

$to
"'2016-12-31'"
  • 返回的值不代表这些函数可接受用户自定义默认值
setDefaults(load, 
            file = "my_file.RData")

# 不会改变行为
getDefaults(load)
$file
"'my_file.RData'"
在 R 中导入与管理金融数据

开始练习吧!

在 R 中导入与管理金融数据

Preparing Video For Download...