在 Rmarkdown 中使用 getSymbols 时出错

Error using getSymbols in Rmarkdown

我尝试使用 rmarkdown 编写一份简短的报告,我想使用 quantmod 程序包的 getSymbolds 功能从雅虎下载市场数据。

---
title: "TEST"
author: "TEST"
date: "Monday, January 25, 2016"
output: html_document
---
```{r, echo=FALSE}
require(quantmod)
prices = invisible(getSymbols("^GDAXI", return.class = "xts", auto.assign=FALSE ))
cat(getwd())
rets = na.omit(diff(log(prices[,4]))) - mean(na.omit(diff(log(prices[,4]))))
plot(rets['2015/2016'])
```

但是,调用 prices = invisible(getSymbols("^GDAXI", return.class = "xts", auto.assign=FALSE )) 不起作用,我收到错误消息:

Quitting from lines 8-13 (Preview-1a04527111.Rmd) 
Error in download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  : 
  cannot open URL 'http://ichart.finance.yahoo.com/table.csv?s=^GDAXI&a=0&b=01&c=2007&d=0&e=25&f=2016&g=d&q=q&y=0&z=^GDAXI&x=.csv'
Calls: <Anonymous> ... getSymbols -> do.call -> getSymbols.yahoo -> download.file

Execution halted

当我在通常的 R 模式下逐行 运行 R 代码时,我得到了预期的结果。 getSymbolsrmarkdown 是否存在已知问题?

我的sessionInfo()

R version 3.1.3 (2015-03-09)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] quantmod_0.4-5      TTR_0.23-0          xts_0.9-7           zoo_1.7-12          stochvol_1.2.2      coda_0.18-1        
 [7] XLConnect_0.2-11    XLConnectJars_0.2-9 plyr_1.8.3          reshape_0.8.5       svDialogs_0.9-57    svGUI_0.9-55       
[13] RODBC_1.3-12       

loaded via a namespace (and not attached):
[1] digest_0.6.8    grid_3.1.3      htmltools_0.2.6 lattice_0.20-30 Rcpp_0.12.1     rJava_0.9-7     rmarkdown_0.9.2 tools_3.1.3    
[9] yaml_2.1.13    

评论后编辑:使用 setInternet2(use=TRUE) 使它起作用。以下工作 - 即使在我公司的安全设置中。

---
title: "TEST"
author: "TEST"
date: "Monday, January 25, 2016"
output: html_document
---
```{r, echo=FALSE}
require(quantmod)
setInternet2(use = TRUE)
prices = invisible(getSymbols("^GDAXI", return.class = "xts", auto.assign=FALSE ))
cat(getwd())
rets = na.omit(diff(log(prices[,4]))) - mean(na.omit(diff(log(prices[,4]))))
plot(rets['2015/2016'])
```

对于您的代理问题,请使用 setInternet2()

从更一般的角度来看,我更喜欢手动下载文件,将其保存在 .rdata 文件中(使用 save())并在你的 rmarkdown 文件中使用 load() .

它会让你的编织速度更快(除非你使用了缓存或者没有犯错)并且不要多次 dl 同一个文件。 (仅在一次性分析而非报告的情况下)