Search code examples
dygraphsr-dygraphs

how to plot candlestick + roller in dygraphs [r]


Hi I try to plot a candlestick plot + roller average line.

library(xts)
library(dygraphs)
data(sample_matrix)
m <- tail(sample_matrix, n = 32)

dygraph(m) %>% 
    dyCandlestick() %>% 
    dyRoller(showRoller = T, rollPeriod = 5)

yields this:

enter image description here

What I want is candlestick plot + roller average line, like this:enter image description here


Solution

  • dyRoller is a rolling average period text box added to the chart. What you want are moving averages of the closing price. Here is sample code. Function TTR::SMA (quantmod) could be replaced with forecast::ma.

    library(dygraphs); library(xts); library(quantmod)
    data(sample_matrix)
    m <- tail(sample_matrix, n=75)
    m <- cbind(m, SMA(m[,4], n=10))
    m <- cbind(m, SMA(m[,4], n=20))
    colnames(m)[5:6] <- c('SMA10','SMA20')
    dygraph(m) %>% 
      dyCandlestick()
    

    enter image description here