Reputation: 81
I have a time series with tick frequency that look like the following:
V2 V3
2004-02-01 20:20:41 1.2474 1.2484
2004-02-01 21:13:52 1.2471 1.2481
2004-02-01 21:14:09 1.2469 1.2479
2004-02-01 21:38:57 1.2470 1.2480
2004-02-01 21:56:43 1.2468 1.2478
2004-02-01 21:56:47 1.2466 1.2476
In order to convert it to daily frequency, I use the following codes:
V.xts <- xts(V[, 2:3], order.by=as.POSIXct(V[, 1], format='%d/%m/%y %H:%M:%S'))
V.day<-to.daily(V.xts,OHLC=FALSE)
This results in the following time series with new frequency:
V2 V3
2004-02-01 1.2475 1.2485
2004-02-02 1.2430 1.2432
2004-02-03 1.2544 1.2546
2004-02-04 1.2537 1.2539
2004-02-05 1.2563 1.2565
2004-02-06 1.2696 1.2706
2004-02-08 1.2642 1.2652
2004-02-09 1.2690 1.2692
2004-02-10 1.2682 1.2684
2004-02-11 1.2827 1.2829
in which, I guess that my codes return the close price for the daily period and there is no price for the date "2004-02-07". However, if there is no price for date "2004-02-07", I would like to record the value of the previous period in replacement of the missing value. I then use:
V.a <- align.time(V.day)
tmp <- xts(, seq.POSIXt(start(V.a), end(V.a), by='days'))
output <- cbind(tmp, V.a)
However, I got this error after the second command:
Error in seq.POSIXt(start(V1.a), end(V1.a), by = "days") :
'from' must be a "POSIXt" object
I install 'xts' package with dependencies : 'zoo' and 'date'.
I then tried using seq
with the following commands:
tmp <- xts(, seq(start(V.a), end(V.a), by='days'))
output <- merge(tmp, V.a, fill=na.locf)
The new dataset that I got looks like :
2004-02-01 NA NA
2004-02-01 1.2475 1.2485
2004-02-02 1.2475 1.2485
2004-02-02 1.2430 1.2432
2004-02-03 1.2430 1.2432
2004-02-03 1.2544 1.2546
2004-02-04 1.2544 1.2546
2004-02-04 1.2537 1.2539
2004-02-05 1.2537 1.2539
2004-02-05 1.2563 1.2565
2004-02-06 1.2563 1.2565
2004-02-06 1.2696 1.2706
2004-02-07 1.2696 1.2706
2004-02-08 1.2696 1.2706
2004-02-08 1.2642 1.2652
It seems that those commands gave me opening and closing price for each day in which opening price is closing price of the previous day. However, on date 2004-02-07
, there is only price recorded which is the closing price of the previous day. This price will still be missed if I use
Y.data<-as.data.frame(output)
y<-Y.data$V2
y1<-y[seq(2,length(y),2)]
to extract all the closing price.
Upvotes: 0
Views: 1028
Reputation: 176648
You should not call methods directly for reasons like this. Your code will work fine if you just call the generic seq
and let it do method dispatch.
You can also use merge
and its fill
argument to replace the NA
with the previous value using na.locf
.
And you do not need to call align.time
. I'm not sure why you think you need to, but it's likely to only cause problems on daily data.
tmp <- xts(, seq(start(V.day), end(V.day), by='days'))
output <- merge(tmp, V.day, fill=na.locf)
Upvotes: 2