This seems like it should be a common thing, but all my searching comes up with half or unfinished answers.
I have a set of data in a csv. But the data is set up so
from http://r.789695.n4.nabble.com/Convert-tick-data-to-OHLC-td926206.html
ohlc <- function(ttime,tprice,tvolume,fmt) {
ttime.int <- format(ttime,fmt)
data.frame(time = ttime[tapply(1:length(ttime),ttime.int,function(x) {head(x,1)})],
.Open = tapply(tprice,ttime.int,function(x) {head(x,1)}),
.High = tapply(tprice,ttime.int,max),
.Low = tapply(tprice,ttime.int,min),
.Close = tapply(tprice,ttime.int,function(x) {tail(x,1)}),
.Volume = tapply(tvolume,ttime.int,function(x) {sum(x)}),
.Adjusted = tapply(tprice,ttime.int,function(x) {tail(x,1)}))
}
Azoo
series can be reclassed as OHLC
with class(data) <- c('zoo', 'OHLC', 'some other class')
.
From ?quantmod::quantmod.OHLC
:
‘quantmod.OHLC’
is actually just a renaming of an object of class‘zoo’
, with the convention ofNAME.Open, NAME.High, ...
for the column names.
If you don't have the volume column, then there is no code you can write that will add that data. It seems like you just have a series of intraday prices. You can still class these as zoo
or xts
and do time series analysis. If you want to reduce the resolution of your data, you could always scan over each day and use the functions first
, max
, min
, last
to get your O
, H
, L
, C
.
To illustrate @JoshuaUlrich's comment:
x <- read.csv(header=TRUE, stringsAsFactor=FALSE,
text="time,price,volume,
7/18/10 0:09,0.04951,20,
7/18/10 4:43,0.05941,50.01,
7/18/10 18:48,0.0808,5,
7/18/10 22:44,0.08585,10,
7/18/10 23:00,0.08584,5,
7/18/10 23:00,0.08584,5,
7/19/10 4:53,0.0909,5,
7/19/10 17:24,0.09307,80,
7/19/10 18:03,0.08911,100,
7/19/10 18:07,0.08752,100,")
# create an xts object
myxts <- xts(x[, 2:3], order.by=as.POSIXct(x[, 1], format='%m/%d/%y %H:%M'))
myxts
myxts
# price volume
# 2010-07-18 00:09:00 0.04951 20.00
# 2010-07-18 04:43:00 0.05941 50.01
# 2010-07-18 18:48:00 0.08080 5.00
# 2010-07-18 22:44:00 0.08585 10.00
# 2010-07-18 23:00:00 0.08584 5.00
# 2010-07-18 23:00:00 0.08584 5.00
# 2010-07-19 04:53:00 0.09090 5.00
# 2010-07-19 17:24:00 0.09307 80.00
# 2010-07-19 18:03:00 0.08911 100.00
# 2010-07-19 18:07:00 0.08752 100.00
to.minutes(myxts)
# myxts.Open myxts.High myxts.Low myxts.Close myxts.Volume
# 2010-07-18 00:09:00 0.04951 0.04951 0.04951 0.04951 20.00
# 2010-07-18 04:43:00 0.05941 0.05941 0.05941 0.05941 50.01
# 2010-07-18 18:48:00 0.08080 0.08080 0.08080 0.08080 5.00
# 2010-07-18 22:44:00 0.08585 0.08585 0.08585 0.08585 10.00
# 2010-07-18 23:00:00 0.08584 0.08584 0.08584 0.08584 10.00
# 2010-07-19 04:53:00 0.09090 0.09090 0.09090 0.09090 5.00
# 2010-07-19 17:24:00 0.09307 0.09307 0.09307 0.09307 80.00
# 2010-07-19 18:03:00 0.08911 0.08911 0.08911 0.08911 100.00
# 2010-07-19 18:07:00 0.08752 0.08752 0.08752 0.08752 100.00
to.minutes
is one of many wrappers for to.period
. This is equivalent, but
more general:
to.period(myxts, 'minutes', 1)