1

我正在从雅虎提取 15 个符号的 ETF 数据,并且即将编写相同的代码行 15 次。我已经阅读了,lapply但在这种情况下未能掌握它。

加载我的getSymbols文件后,我已经启动了下面前两个符号的代码,但是会有复制和粘贴,然后更改符号,15 次。我知道必须有一种方法来执行这些步骤lapply或类似的东西......

library(quantmod)
library(tseries)
library(PerformanceAnalytics)
library(xts)
library(timeSeries)
library(TTR)

#load asset class symbols and data
loadSymbolLookup(file="assetclassymbols.rda")
getSymbols(c("ACWI","ITOT","IJR","EFA","EEM","AGG","MUB","TIP","TLH","TLT","HYG","EMB","IYR","GSG","GLD"))

#pull adjusted close value for a specific time period
ACWI.adj=Ad(ACWI)['2015-12-31::2016']
AGG.adj=Ad(AGG)['2015-12-31::2016']
#REPEAT FOR EACH SYMBOL

#calculate returns for the specific time period and remove prior-period "NA" row
ACWI.return=Return.calculate(ACWI.adj)
AGG.return=Return.calculate(AGG.adj)
ACWI.return=ACWI.return[-c(1)]
AGG.return=AGG.return[-c(1)]
#REPEAT FOR EACH SYMBOL

#merge asset class return streams to a single dataset
asset.returns=(merge(ACWI.return,AGG.return)) #...CONT. MERGING ALL SYMBOLS.return
colnames(asset.returns)=c("ACWI","AGG") #...CONT. LIST OF ALL SYMBOLS

我的目标是完成一个包含所有符号作为列标题的数据集,并计算每行的回报。

4

1 回答 1

0

FUN您可以在 的参数中定义匿名函数lapplya la

syms <- c("ACWI","ITOT","IJR","EFA","EEM","AGG","MUB",
          "TIP","TLH","TLT","HYG","EMB","IYR","GSG","GLD")


lapply(syms, function(s) 
  Return.calculate(Ad(getSymbols(s, auto.assign = FALSE)
                      )['2015-12-31::2016'])[-1L])
于 2016-02-09T02:10:00.210 回答