Reputation: 101
I have a list containing 29 time series -- list is called "lRet"
I need to lag all series by one time period and compute the first auto correlation. I then need to store these 29 numbers in the 6th colomn of a matrix.
> head(lRet$TRV)
TRV.Adjusted
2018-01-03 0.3177055
2018-01-04 0.0000000
2018-01-05 -0.1814193
2018-01-08 -0.5386908
2018-01-09 0.7729854
2018-01-10 -0.2721412
> head(lag(lRet$TRV))
TRV.Adjusted
2018-01-03 NA
2018-01-04 0.3177055
2018-01-05 0.0000000
2018-01-08 -0.1814193
2018-01-09 -0.5386908
2018-01-10 0.7729854
The autocorrelation is simply the correlation between the two series above. I need to do this for all 29 series ( the above is just 1).
DescStat[,6] <- diag(cor(lRet[-1], lag(lRet, 1)[-1]))
where I removed the first observation since the lag operator generates a "NA" as the first entry. This doesn't work because "x has to be numeric"
(error in R). I use diag
because cor
produces a matrix and I only want the correlation with the stock itself - not the correlation between stocks.
I then tried to change all values in the list to numeric values with "as.numeric":
DescStat[,6] <- diag(cor(sapply(lRet, as.numeric)[-1], sapply(lag(as.numeric(lRet),1))[-1]))
but I get the error "(list) cannot be coerced to type 'double'" which I interpret as my list still being a list.....
I feel like I am so close.. what am I doing wrong? Is there an incredibly simple way to do this?
Upvotes: 1
Views: 47
Reputation: 2613
You were close. The answer is much simpler. Just use sapply()
to apply the function on each element in the list. Since your list has returns on stocks as individual elements, you don't need to use diag()
. Just use the sapply()
to apply the correlation code you have on each element in the list. sapply()
returns a dataframe, so it will fill the rows in the six column with the values.
DescStat[,6] <- sapply(lRet, function(x) x <- cor(x[-1], lag(x, 1)[-1]))
Upvotes: 1