Search code examples
rshinyquantmod

R zoomChart Shiny


i've been trying to interactively zoom in certain parts of a chartSeries with zoomChart and shiny, but can't find the right solution. I would use dateRangeInput or a slider, but i'm not sure how to connect the zoomChart-option from quantmod with shiny. As you might have already assumed, I'm relatively new to shiny and very thankful for your advices!

edit: Data is in the xts-format.

MyCode:

library(quantmod)
library(shiny)

date_range <- as.POSIXct(index(data))
if (interactive()) {
  options(device.ask.default = FALSE)
  ui <- fluidPage(  
    titlePanel("Select Range to zoom-in:"),
    sidebarLayout(
      sidebarPanel(
        dateRangeInput("Range", "Choose Date Range:", min=first(date_range),
                   max=last(date_range), format = "dd-mm-yyyy")
      ),
      mainPanel(
        plotOutput("Plot")
      )
    )
  )

  server <- function(input, output) {
    output$Plot <- renderPlot({
      chartSeries(data, type = c("auto", "candlesticks", "matchsticks",   "bars","line"), 
              theme=chartTheme("white"), name=paste(start(data), end(data),sep = " ")) 
      zoomChart(dateRangeInput) 
    })
  }
   shinyApp(ui, server)
}

Solution

  • Actually, you were very close. Note the changes in dateRangeInput(): The start and end argument are used instead of min, max. And then you can use the input on the server-side to use zoom-chart.

    library(quantmod)
    library(shiny)
    getSymbols("YHOO")
    data <- YHOO
    date_range <- index(data)
    if (interactive()) {
      options(device.ask.default = FALSE)
      ui <- fluidPage(  
        titlePanel("Select Range to zoom-in:"),
        sidebarLayout(
          sidebarPanel(
            dateRangeInput("Range", "Choose Date Range:", start=first(date_range),
                           end=last(date_range), format = "yyyy-mm-dd")
          ),
          mainPanel(
            plotOutput("Plot")
          )
        )
      )
      server <- function(input, output) {
        output$Plot <- renderPlot({
          chartSeries(data, type = c("auto", "candlesticks", "matchsticks",   "bars","line"), 
                      theme=chartTheme("white"), name=paste(start(data), end(data),sep = " ")) 
          zoomChart(paste(input$Range, collapse = "::")) 
        })
    
        observe({
          print(input$Range)
        })
      }
      shinyApp(ui, server)
    }
    

    As @drmariod indicated It would be beneficial to have a fully reproducible exmaple, which was easy to get in this case via getSymbols().