CandleStick 图表准备数据(开盘价、收盘价、最高价、最低价)

CandleStick chart prepare data (open,close,high ,low)

InvoiceDate<-c("2018-01-01 08:26:00","2018-01-01 08:26:00","2018-01-01 08:26:00","2018-01-01 08:26:00","2018-01-02 08:26:00","2018-01-02 08:26:00","2018-01-02 08:26:00","2018-01-02 08:26:00","2018-01-03 08:26:00","2018-01-04 08:26:00","2018-01-04 08:26:00","2018-01-04 08:26:00")
UnitPrice<-c(2.27,2.28,2.29,2.30,2.31,2.32,3.22,5.26,2,26,3.23,2.50)
myData<-data.frame(InvoiceDate,UnitPrice)

我想创建一个 candleStick 图表。但我的问题是如何计算开盘价、收盘价、高价和低价。 R 中有图书馆吗?谢谢。

我的循环:

    df<-data.frame(

  open=double(),
  close=double(),
  min=double(),
  max=double(),
  date=as.Date(character())

)



firstDate<-as.Date(myData$InvoiceDate[1])
firstOpen<-myData$UnitPrice[1]
min<-myData$UnitPrice[1]
max<-myData$UnitPrice[1]


for(row in 1:nrow(myData))
{

  actualDate<-as.Date(myData$InvoiceDate[row])
  actualPrice<-myData$UnitPrice[row]

  if(actualDate==firstDate)
  {

    if(min>actualPrice)
    {
      min<-actualPrice
    }


    if(max<actualPrice)
    {
      max<-actualPrice
    }

  }


  if(actualDate!=firstDate)
  {
    open=firstOpen
    close=myData$UnitPrice[row-1]
    date=as.Date(myData$InvoiceDate[row-1])

    values<-data.frame(open,close,minPrice,maxPrice,date)
    df<-rbind(df,values)

    firstDate<-actualDate
    firstOpen<-myData$UnitPrice[row]
    min<-myData$UnitPrice[row]
    max<-myData$UnitPrice[row]

  }


}

所以开放值意味着它是每个日期的第一个值 收盘价是每个日期的最后一个值。 Min和max是每个日期的最小值和最大值

它正在运行,但缺少最后一个日期的行,例如“2018-01-04 08:26:00”

也许你可以使用 dplyr : (这里我假设你的数据是按时间顺序排序的,你可能需要在某处排序或排列):

library(dplyr)
myData %>% group_by(trunc(as.Date(InvoiceDate), "day")) %>% summarize(open_val = first(UnitPrice), close_val = last(UnitPrice), max_val = max(UnitPrice), min_val = min(UnitPrice))