Mandy
Mandy

Reputation: 129

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)

I want create a candleStick graph. But my question is how to compute open,close,high ,low values. Is there any library in R ? Thank you.

And my loop:

    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]

  }


}

So open value mean that it is first value in each date and close value is last value in each date. Min and max is minimum and maximum value in each date

It is working but miss row with last date in example it is "2018-01-04 08:26:00"

Upvotes: 0

Views: 291

Answers (1)

MrSmithGoesToWashington
MrSmithGoesToWashington

Reputation: 1076

So maybe you can use dplyr : (here I assume that your data are sorted in chronologic order, you may need to sort or arrange somewhere) :

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))

Upvotes: 1

Related Questions