Search code examples
rlapplyperformanceanalytics

Using lapply in R when there isn't a function?


I'm pulling ETF data from Yahoo for 15 symbols and am about to write the same lines of code 15 times. I've read up on lapply but am failing to grasp it in this context.

After loading my getSymbols file, I have started the code for the first two symbols below, but will have copy and paste, then change the symbol, 15 times. I know there has to be a way to do these steps with lapply or something similar...

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

My goal is to finish with a data set containing all the symbols as column headers, and calculated returns in each row.


Solution

  • You are allowed to define an anonymous function in the FUN argument of lapply, a 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])