2014-07-01 27 views
2

我已經從.csv導入刻度數據,並且似乎無法弄清楚如何轉換爲OHLC數據。我正在尋找轉換爲1或4HR OHLC酒吧。將刻度數據轉換爲OHLC 4HR條

請幫忙!

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" 

回答

2

您的問題是您的關閉數據存儲爲字符類型 - 您是否注意到從您的xts數據對象打印的數字周圍的引號?很可能是因爲你已經包含了名稱列,並且當xts發現包含字符向量的「coredata」時,它會將所有內容(包括數字向量)轉換爲字符類型。字符類型xts對象有其用途。例如,包quantstrat中的訂單對象是「Character」xts對象。但是,您想要將數字數據轉換爲較低的頻率。你需要一個'僅數字'xts對象來做到這一點。因此,將名稱列放入數據對象中(並將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')