Skip to content

Instantly share code, notes, and snippets.

@helgasoft
Last active December 13, 2019 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helgasoft/7d702d52d827dd20c460ca4ba664011e to your computer and use it in GitHub Desktop.
Save helgasoft/7d702d52d827dd20c460ca4ba664011e to your computer and use it in GitHub Desktop.
remove time gaps from dygraph financial data display
# dygraph workaround: how to avoid time gaps in financial data display
# Please add your voice for a permanent fix in the following thread:
# https://github.com/rstudio/dygraphs/issues/70
# TODO: date+time "2017-01-25 09:00:00" - looks like the JS environment can't deal with this format !?
library(shiny)
library(dygraphs)
ui <- fluidPage(
titlePanel("Dygraph stock data"),
mainPanel(
checkboxInput('withGaps', 'show the data gaps', value=FALSE),
dygraphOutput("testPlot")
)
)
server <- function(input, output) {
# library(quantmod) # xts data
# dtraw <- getSymbols('QCOM', from=Sys.Date()-40, auto.assign=FALSE)
# dtraw <- OHLC(dtraw)
# colnames(dtraw) <- c('open','high','low','close')
# alld <- paste(as.Date(index(dtraw)), collapse="'),new Date('" )
require(xts)
data(sample_matrix) # matrix data
mid <- nrow(sample_matrix)/2
dtraw <- rbind(head(sample_matrix,20), sample_matrix[(mid-20):(mid+20),], tail(sample_matrix,20)) # make 2 gaps
alld <- paste(as.Date(rownames(dtraw)), collapse="'),new Date('" ) # collect the dates
output$testPlot <- renderDygraph({
if(input$withGaps) # original display with gaps
out <- dygraph(dtraw) %>% dyCandlestick()
else { # no gaps
jsdates <- paste0("var d=[new Date('",alld,"')];") # dates as JS array
vformatter <- paste("function(v) {",jsdates,"return d[v-1].toLocaleDateString() }")
aformatter <- paste("function(a) {",jsdates,"return (d[a-1] ? d[a-1].toDateString().slice(4,10) : null) }")
rownames(dtraw) <- NULL # for matrix data only
# now that the date-display is ready, build new dataframe with sequential numbers instead of dates
data <- data.frame(1:nrow(dtraw), coredata(dtraw))
out <- dygraph(data) %>% dyCandlestick() %>%
dyAxis("x",
valueFormatter = vformatter,
axisLabelFormatter = aformatter
)
}
out
})
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment