[R-SIG-Finance] Convertion of a zoo object to a ts object

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Thu May 24 11:28:26 CEST 2007


Sylvain:

> I use get.hist.quote to read historical prices on various quotes from
> Finance Yahoo. It works fine on daily prices and most of the time on monthly
> prices but it is sometimes difficult to synchronize monthly data without
> duplicating months when extracting more than one quote.

OK, there are some useful tools in this situation. Which you want to use 
depends what exactly what to end up with.

## obtain series
x <- get.hist.quote("^FCHI", compression = "m", start = as.Date(0),
   quote = "Close")
y <- get.hist.quote("CS.PA", compression = "m", start = as.Date(0),
   quote = "Close")

## merge based on "Date" time stamps (which might not match)
xy <- merge(x, y)

## remove NAs by averaging in each month
xy1 <- aggregate(xy, as.yearmon, mean, na.rm = TRUE)
## (which gives NaN rather NA for the first "y" observations)

## alternatively: first go to "yearmon" scale and then merge
x2 <- aggregate(x, as.yearmon, mean)
y2 <- aggregate(y, as.yearmon, mean)
xy2 <- merge(x2, y2)

## to convert to "ts", you can simply do
xy1ts <- as.ts(xy1)
xy2ts <- as.ts(xy2)

## Of course, you could also keep the merged series with "Date" time 
## stamp, e.g., using the first of the month
xy2d <- xy2
time(xy2d) <- as.Date(time(xy2))

hth,
Z



More information about the R-SIG-Finance mailing list