I need to collapse a zoo object in R from daily values to weekly, monthly or yearly. I've tried the to.monthly() etc. approach, but it doesn't seem to do the trick.
The data is organized as follows:
CARL.B.CO.Adjusted COLOB.CO.Adjusted
2001-03-01 339.70 2.98
2001-03-02 358.57 3.03
2001-03-05 360.46 3.02
2001-03-06 360.46 3.00
2001-03-07 360.46 3.02
2001-03-08 360.46 3.02
It's a matrix containing daily stockprices from Yahoo.finance downloaded through the QuantMod package, and rearranged to use only adjusted close prices. This should be an easy manouvre, but I've spent quite a lot of time googling without any luck.
Thanks in advance.
EDIT:
dput output:
> dput(head(data))
structure(c(339.7, 358.57, 360.46, 360.46, 360.46, 360.46, 2.98,
3.03, 3.02, 3, 3.02, 3.02), .Dim = c(6L, 2L), .Dimnames = list(
c("2001-03-01", "2001-03-02", "2001-03-05", "2001-03-06",
"2001-03-07", "2001-03-08"), c("CARL.B.CO.Adjusted", "COLOB.CO.Adjusted"
)), index = structure(c(11382, 11383, 11386, 11387, 11388,
11389), class = "Date"), class = "zoo")
Code for retrieving data:
GetData <- function(tickers, startdate, enddate, fillforward = TRUE)
{
getSymbols(tickers, from=startdate, to = enddate,src="yahoo")
if (fillforward == TRUE)
{
na.locf(zoo(do.call(merge, lapply(tickers, function(x) Ad(get(x))))))
}
else
{
do.call(merge, lapply(tickers, function(x) Ad(get(x))))
}
}
I've tried the to.monthly() as proposed here: https://stat.ethz.ch/pipermail/r-sig-finance/2009q1/003704.html
But it won't do the trick when retrieving more than one symbol.
1) aggregate.zoo Assuming that z has a Date class index try this:
library(zoo)
aggregate(z, f, tail, 1)
where function f
is one of these:
as.year <- function(x) as.numeric(format(x, "%Y"))
last.date.of.year <- function(x) as.Date(format(x, "%Y-12-31"))
as.yearmon
last.date.of.month <- function(x) as.Date(as.yearmon(x), frac = 1)
nextfri # Date of next Fri or same date if Fri
The nextfri
function is a one line function defined in the zoo-quickref vignette.
For example, aggregate(z, nextfri, tail, 1)
.
2) period.apply Another approach is to use period.apply
in the xts package. See ?period.apply