[R-sig-Finance] Moving zoo objects to a db and back again

Michael Cohen michaelbcohen at gmail.com
Sat Jun 17 03:49:49 CEST 2006

I need to store some larger zoo objects on a local database.
I realize that this is a vast subject, but I suspect that I am not
alone in needing to use a database for storing equity prices, volumes,
etc. I have not been able to find much help on designing the db
tables, and pointers to the literature are more than welcome.

The following code works, but I would like to make it more robust or elegant.

"prices" is a df with the prices of shares.
# str(prices)
#   num [1:1872, 1:25] 9184 9311 9545 9538 9643 ...
#   - attr(*, "dimnames")=List of 2
#    ..$ : NULL
#    ..$ : chr [1:25] "AdjClose" "A" "AA" "AAC" ...
#   - attr(*, "index")=Class 'Date'  num [1:1872] 10595 10596 10597
10598 10599 ..

# extract the date from the zoo object:
Date <- index(prices)
# extract the data from the zoo object:
y <- coredata(prices)
# combine into a df . Note: I can not write a zoo object directly to
the db - correct?
z <- as.data.frame(cbind(Date,y))

# Write to db:
dbWriteTable(con, "Prices", z)

# Read from db:
a <- dbReadTable(con, "Prices")
# extract the date
index.date <- as.Date(a[[1]])
# form the zoo object
b <- zoo(a[-1], index.date)

Many thanks,

Michael Cohen
Southern Cross University

More information about the R-SIG-Finance mailing list