将刻度数据转换为OHLC 4HR条

时间:2014-07-01 17:42:35

标签: r xts quantmod

我从.csv导入了tick数据,似乎无法弄清楚如何转换为OHLC数据。我希望转换为1或4HR OHLC条。

请帮忙!

library(TFX)

library(quantmod)

library(zoo)

library(xts)

head(data)

                    Name      Close  

2014-05-01 00:00:00 "AUD/JPY" "94.874"

2014-05-01 00:00:00 "AUD/JPY" "94.876"

2014-05-01 00:00:00 "AUD/JPY" "94.876"

2014-05-01 00:00:00 "AUD/JPY" "94.877"

2014-05-01 00:00:00 "AUD/JPY" "94.877"

2014-05-01 00:00:00 "AUD/JPY" "94.877"

is.OHLC(data)

## [1] FALSE

periodicity(data)

## 0.161999940872192 seconds periodicity from 2014-05-01 00:00:00 to 2014-05-30 20:59:58

to.weekly(data)

## Error in to.period(x, "weeks", name = name, ...) : unsupported type

to.period(data,"seconds",5)

## Error in to.period(data, "seconds", 5) : unsupported type

bars <- period.apply(data,

+                     endpoints(data,"secs",60),

+                     function(xx){

+                       ticks=coredata(data$close)

+                       c( first(ticks),max(ticks), min(ticks),

+                          last(ticks) )

+                     })

## There were 50 or more warnings (use warnings() to see the first 50)

head(bars)

                    Name Close

2014-05-01 00:00:57 -Inf   Inf

2014-05-01 00:01:58 -Inf   Inf

2014-05-01 00:02:59 -Inf   Inf

2014-05-01 00:03:56 -Inf   Inf

2014-05-01 00:04:54 -Inf   Inf

2014-05-01 00:05:50 -Inf   Inf

to.period(data,"seconds")

## Error in to.period(data, "seconds") : unsupported type

xx<-to.minutes(data[,1],5,'minutes')

## Error in to.period(x, "minutes", k = k, name = name, ...) : unsupported type

head(data)

                    Name      Close  

2014-05-01 00:00:00 "AUD/JPY" "94.874"

2014-05-01 00:00:00 "AUD/JPY" "94.876"

2014-05-01 00:00:00 "AUD/JPY" "94.876"

2014-05-01 00:00:00 "AUD/JPY" "94.877"

2014-05-01 00:00:00 "AUD/JPY" "94.877"

2014-05-01 00:00:00 "AUD/JPY" "94.877"

1 个答案:

答案 0 :(得分:3)

您的问题是您的关闭数据存储为字符类型 - 您是否注意到从xts数据对象打印的数字周围的引号?很可能是因为你已经包含了name列,当xts找到包含字符向量的“coredata”时,它会转换所有内容,包括数字向量到字符类型。字符类型xts对象有其用途。例如,包quantstrat中的订单对象是“Character”xts对象。但是,您要做的是将数字数据转换为较低的频率。你需要一个'仅数字'的xts对象来做到这一点。因此,删除数据对象中的name列(并将Close转换为数字类型)。

加载xts后,请仔细阅读文档?to.period

to.weekly, to.daily等基本上都是to.period

的包装器

这是一个让你开始的人为例子:

library(xts)
#create contrived 5 min xts object
getSymbols("AAPL")
n <- NROW(AAPL)
time <- seq(as.POSIXct("2014-06-28"), as.POSIXct("2014-07-10"), by = "5 mins")

#' Here is the 5 min xts data object created.  
xtsdata <- xts(x = coredata(AAPL), order.by = time[1:n])

#' Want to convert it to hourly? 

xtsdata_hourly <- to.period(x = xtsdata, period = "hours", indexAt = 'startof')

#' Want to convert it to 4 hour bars? k is the number of bars to aggregate over 
xtsdata_4hours <- to.period(x = xtsdata, period = "hours", k = 4, indexAt = 'startof')