I downloaded MSFT historic daily stock data using quantmod package. What I got is xts/zoo object. I want to convert it to ts object, so that I can do daily price forecasting with forecast package.
library(quantmod)
library(forecast)
library(xts)
library(zoo)
start <- as.Date('2018-01-01')
end <- as.Date('2018-08-14')
getSymbols('MSFT', src='yahoo', from=start, to=end)
#msft is xts/zoo object
msft <- MSFT[, 'MSFT.Close']
#convert msft to ts object
msft.ts <-ts(as.numeric(msft),
start=c(2018, yday(start(msft))),
frequency = 365)
index of msft (xts object) look like below. They are weekly data with weekend missing. Obviously stock only trade on weekdays.
[1] "2018-01-02" "2018-01-03" "2018-01-04" "2018-01-05" "2018-01-08"
[6] "2018-01-09" "2018-01-10" "2018-01-11" "2018-01-12" "2018-01-16"
[11] "2018-01-17" "2018-01-18" "2018-01-19" "2018-01-22" "2018-01-23"
index of msft.ts (ts object) look like this:
[1] 2018.003 2018.005 2018.008 2018.011 2018.014 2018.016 2018.019 2018.022
[9] 2018.025 2018.027 2018.030 2018.033 2018.036 2018.038 2018.041 2018.044
[17] 2018.047 2018.049 2018.052 2018.055 2018.058 2018.060 2018.063 2018.066
I'm confused about what those index mean. Are the digits after 2018. the day number? Those does not seem to be right. My guess is it might not be because I set the frequency to be 365
, but actually there is not data on weekends. In this case, what should I do?
I googled and find that ts
only work for evenly spaced data. But in order to use forecasting package, I need to supply ts
object, although it looks like I lose all the date info after conversion from xts
to ts
object.
I really appreciate it if anyone could kindly clarify me on this. What is the right way to do? I'm really confused. I want to make a forecast model using forecast package. Thanks a lot in advance.
ts
object does not know about weekends, and will put the monday exactly one day after friday. Depending on your model this might be fine, or you might want to addNA
values on those days.ts
objects only allow for a regular index by design (that's whygetSymbols
returnsxts
instead). – Chris Haugdiff(index(msft.ts))
can't not be the same value because, as I said,ts
only allows for a regular index: it doesn't store an explicit index at all, just a start, stop and frequency intsp
. Have a look at the functionzoo::index.ts
to see how the index is inferred. – Chris Haug