為 getSymbols() 設定預設引數

在 R 匯入與管理金融資料

Joshua Ulrich

Quantitative Analyst & quantmod Co-Author and Maintainer

getSymbols() 「methods」

  • getSymbols() 本身不含匯入資料的程式碼
  • 各資料來源的程式碼在 getSymbols.[source] 「method」 中
  • 例如:
# 你呼叫 getSymbols()
getSymbols("GDP", src = "FRED")

# getSymbols() 會呼叫來源的「method」
getSymbols.FRED("GDP")
  • 使用者不應直接呼叫 getSymbols() 的「methods」
在 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() 來源 method 的正式引數:
    • 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...