With lapply
you can operate the rollapply
function on each column resulting in
acf
series for the selected lag value. We then use Reduce
to combine results from the above step.
I have used dataset edhec
from PerformanceAnalytics
package for this demo. You
can change the width
parameter accordingly.
library("PerformanceAnalytics")
#load test dataset
data(edhec,package="PerformanceAnalytics")
#select subset with fewer columns
edhec_sub = edhec[,1:5]
fn_lag_ACF = function(lagValue = x) {
#for width as 1 year calculate acf for input lagValue for each column
acfList = lapply(edhec_sub,function(x) {
TS = rollapply(x, width = 12,
FUN = function(z) acf(z,na.action=na.pass,lag.max= lagValue,plot=FALSE)$acf[lagValue],
by.column = FALSE, align = "right")
colnames(TS) = colnames(x)
return(TS)
})
#combine acf output for all columns from above step
acfMerge = Reduce(function(x,y) merge.xts(x,y), acfList)
return(acfMerge)
}
#test with lagValue = 2
lag2DF = fn_lag_ACF(lagValue = 2)
Output:
head(lag2DF,15)
# Convertible.Arbitrage CTA.Global Distressed.Securities Emerging.Markets
#1997-01-31 NA NA NA NA
#1997-02-28 NA NA NA NA
#1997-03-31 NA NA NA NA
#1997-04-30 NA NA NA NA
#1997-05-31 NA NA NA NA
#1997-06-30 NA NA NA NA
#1997-07-31 NA NA NA NA
#1997-08-31 NA NA NA NA
#1997-09-30 NA NA NA NA
#1997-10-31 NA NA NA NA
#1997-11-30 NA NA NA NA
#1997-12-31 0.5560540 -0.3010264 0.02908761 0.3305791
#1998-01-31 0.5055951 -0.4245876 0.04278214 0.1761287
#1998-02-28 0.5195872 -0.4298767 0.01375580 0.1605579
#1998-03-31 0.5070003 -0.4656213 -0.04519778 0.2061610
# Equity.Market.Neutral
#1997-01-31 NA
#1997-02-28 NA
#1997-03-31 NA
#1997-04-30 NA
#1997-05-31 NA
#1997-06-30 NA
#1997-07-31 NA
#1997-08-31 NA
#1997-09-30 NA
#1997-10-31 NA
#1997-11-30 NA
#1997-12-31 -0.11842164
#1998-01-31 -0.05986578
#1998-02-28 -0.09663855
#1998-03-31 -0.09680819