You cannot add a date column to an object returned by getSymbols
or get.hist.quote
. These function return matrices. Matrices can only store data of the same type, in this case the matrices contain double
values (real numbers).
You can add a column of class Date
to the objects if you transform them into a data frame:
For getSymbols
:
library(quantmod)
getSymbols('IBM', from = "2014-02-10")
IBM
# IBM.Open IBM.High IBM.Low IBM.Close IBM.Volume IBM.Adjusted
# 2014-02-10 176.97 177.65 176.25 177.14 3540400 177.14
# 2014-02-11 176.81 180.39 176.80 179.70 4647300 179.70
# 2014-02-12 179.52 181.25 179.26 180.24 3983000 180.24
# 2014-02-13 178.22 182.36 177.86 181.84 4482000 181.84
# 2014-02-14 181.26 184.43 180.99 183.69 4659900 183.69
dat1 <- as.data.frame(IBM)
dat1$date <- time(IBM)
dat1
# IBM.Open IBM.High IBM.Low IBM.Close IBM.Volume date
# 2014-02-10 176.97 177.65 176.25 177.14 3540400 2014-02-10
# 2014-02-11 176.81 180.39 176.80 179.70 4647300 2014-02-11
# 2014-02-12 179.52 181.25 179.26 180.24 3983000 2014-02-12
# 2014-02-13 178.22 182.36 177.86 181.84 4482000 2014-02-13
# 2014-02-14 181.26 184.43 180.99 183.69 4659900 2014-02-14
The approach is similar for get.hist.quote
:
library(tseries)
res <- get.hist.quote(instrument = "ibm", start = "2014-02-10")
res
# Open High Low Close
# 2014-02-10 176.97 177.65 176.25 177.14
# 2014-02-11 176.81 180.39 176.80 179.70
# 2014-02-12 179.52 181.25 179.26 180.24
# 2014-02-13 178.22 182.36 177.86 181.84
# 2014-02-14 181.26 184.43 180.99 183.69
dat2 <- as.data.frame(res)
dat2$date <- time(res)
dat2
# Open High Low Close date
# 2014-02-10 176.97 177.65 176.25 177.14 2014-02-10
# 2014-02-11 176.81 180.39 176.80 179.70 2014-02-11
# 2014-02-12 179.52 181.25 179.26 180.24 2014-02-12
# 2014-02-13 178.22 182.36 177.86 181.84 2014-02-13
# 2014-02-14 181.26 184.43 180.99 183.69 2014-02-14