R 上的实时图表 - Shiny

2024-03-05

我正在尝试制作一个交互式图表,在一个闪亮的应用程序上绘制金融股票数据。我的尝试是不断更新数据,从而更新图表。我使用一个名为 Highcharter 的包来管理这个。下面显示了服务器部分的部分代码(getDataIntraday() 接收两个输入并返回更新的 xts)。

getID <- reactive({
  invalidateLater(60000)
  y <- getDataIntraDay(input$text, input$radio)
  return(y)
})

output$plot1 <- renderHighchart({

y <- getID()

highchart() %>% 
  hc_credits(enabled = TRUE,
  hc_exporting(enabled = TRUE)%>%
  hc_add_series_ohlc(y) %>% 
  hc_add_theme(hc_theme_538(colors = c("red", "blue", "green"),
                            chart = list(backgroundColor = "white")))
})

这是可行的:图表和数据每 60 秒自动更新一次。问题如下:

  1. 当数据和图表更新时,不保持用户设定的缩放比例。

  2. 图表需要太多秒才能更新自身,因为它计算了所有结构,而不是仅添加最后一个蜡烛。

是否有一些方法(某些包)允许更新图表而无需再次计算整个函数?或者,至少有没有办法修复图表中除蜡烛之外的所有元素?


您可以尝试通过以下方式参考我的数据采集 https://beta.rstudioconnect.com/content/3153/.

require('shiny')
require('shinyTime')
#'@ require('rdrop2')
require('magrittr')
require('plyr')
require('dplyr')
require('stringr')
require('data.table')
#'@ require('rvest')
require('quantmod')
require('TFX')
require('lubridate')
require('ggplot2')
require('DT')

#'@ drop_auth()
## email : [email protected] /cdn-cgi/l/email-protection
## pass : trader888
#
# https://github.com/karthik/rdrop2
#
#'@ token <- drop_auth()
#'@ saveRDS(token, "droptoken.rds")
# Upload droptoken to your server
# ******** WARNING ********
# Losing this file will give anyone 
# complete control of your Dropbox account
# You can then revoke the rdrop2 app from your
# dropbox account and start over.
# ******** WARNING ********
# read it back with readRDS
#'@ token <- readRDS("droptoken.rds")
# Then pass the token to each drop_ function
#'@ drop_acc(dtoken = token)
#'@ token <<- readRDS("droptoken.rds")
# Then pass the token to each drop_ function
#'@ drop_acc(dtoken = token)

# === Data =====================================================
Sys.setenv(TZ = 'Asia/Tokyo')
zones <- attr(as.POSIXlt(now('Asia/Tokyo')), 'tzone')
zone <- ifelse(zones[[1]] == '', paste(zones[-1], collapse = '/'), zones[[1]])

# === UI =====================================================
ui <- shinyUI(fluidPage(

  titlePanel(
    tags$a(href='https://github.com/scibrokes', target='_blank', 
           tags$img(height = '120px', alt='HFT', #align='right', 
                    src='https://raw.githubusercontent.com/scibrokes/real-time-fxcm/master/www/HFT.jpg'))), 
  pageWithSidebar(
    mainPanel(
      tabsetPanel(
        tabPanel('Data Price', 
                 tabsetPanel(
                   tabPanel('Board', 
                            h3('Real Time Board'), 
                            p(strong(paste0('Current time (', zone, '):')),
                              textOutput('currentTime')),
                            br(), 
                            p(strong('Latest FX Quotes:'),
                              tableOutput('fxdata'), 
                              checkboxInput('pause', 'Pause updates', FALSE))), 
                   tabPanel('Chart', 
                            h3('Real Time Chart'), 
                            p(strong(paste0('Current time (', zone, '):')),
                              textOutput('currentTime2')),
                            br(), 
                            plotOutput("plotPrice")#, 
                            #'@ tags$hr(),
                            #'@ plotOutput("plotAskPrice")
                            ), 
                   tabPanel('Data', 
                            h3('Data Download'), 
                            p(strong(paste0('Current time (', zone, '):')),
                              textOutput('currentTime3')), 
                            p('The time zone of data in GMT, Current time (GMT) :', 
                              textOutput('currentTime4')), 
                            dataTableOutput('fxDataTable'), 
                            p(strong('Refresh'), 'button will collect the latest dataset ', 
                              '(time unit in seconds).'), 
                            p('Please becareful, once you click on', 
                              strong('Reset'), 'button, ', 
                              'all data will be lost. Kindly download the dataset ', 
                              'as csv format prior to reset it.'), 
                            actionButton('refresh', 'Refresh', class = 'btn-primary'), 
                            downloadButton('downloadData', 'Download'), 
                            actionButton('reset', 'Reset', class = 'btn-danger')))), 

        tabPanel('Appendix', 
                 tabsetPanel(
                   tabPanel('Reference', 
                            h3('Speech'), 
                            p('I try to refer to the idea from below reference to create this web ', 
                              'application for data collection.'), 
                            p(HTML("<a href='https://beta.rstudioconnect.com/content/3138/'>Q1App2</a>"), 
                              '(', strong('Q1App2'), 'inside 2nd reference link at below', 
                              strong('Reference'), 'tab) for algorithmic trading. Kindly browse over', 
                              HTML("<a href='https://github.com/scibrokes/real-time-fxcm'>Real Time FXCM</a>"), 
                              'for more information about high frequency algorithmic trading.'), 
                            br(), 
                            h3('Reference'), 
                            p('01. ', HTML("<a href='https://github.com/cran/TFX'>TFX r package</a>")), 
                            p('02. ', HTML("<a href='https://www.fxcmapps.com/apps/basic-historical-data-downloader/'>Basic Historical Data Downloader</a>")), 
                            p('03. ', HTML("<a href='https://github.com/englianhu/binary.com-interview-question'>binary.com : Job Application - Quantitative Analyst</a>"))), 

                   tabPanel('Author', 
                            h3('Author'), 
                            tags$iframe(src = 'https://beta.rstudioconnect.com/content/3091/ryo-eng.html', 
                                        height = 800, width = '100%', frameborder = 0)))))), 
    br(), 
    p('Powered by - Copyright® Intellectual Property Rights of ', 
      tags$a(href='http://www.scibrokes.com', target='_blank', 
             tags$img(height = '20px', alt='scibrokes', #align='right', 
                      src='https://raw.githubusercontent.com/scibrokes/betting-strategy-and-model-validation/master/regressionApps/oda-army.jpg')), 
      HTML("<a href='http://www.scibrokes.com'>Scibrokes®</a>")))))

# === Server =====================================================
server <- shinyServer(function(input, output, session){

  output$currentTime <- renderText({
    # Forces invalidation in 1000 milliseconds
    invalidateLater(1000, session)
    as.character(now('Asia/Tokyo'))
  })

  output$currentTime2 <- renderText({
    # Forces invalidation in 1000 milliseconds
    invalidateLater(1000, session)
    as.character(now('Asia/Tokyo'))
  })

  output$currentTime3 <- renderText({
    # Forces invalidation in 1000 milliseconds
    invalidateLater(1000, session)
    as.character(now('Asia/Tokyo'))
  })

  output$currentTime4 <- renderText({
    # Forces invalidation in 1000 milliseconds
    invalidateLater(1000, session)
    as.character(now('GMT'))
  })

  fetchData <- reactive({
    if (!input$pause)
      invalidateLater(750)
    qtf <- QueryTrueFX()
    qtf %<>% mutate(TimeStamp = as.character(TimeStamp))
    names(qtf)[6] <- 'TimeStamp (GMT)'
    return(qtf)
  })

  output$fxdata <- renderTable({
    update_data()

    fetchData()
  }, digits = 5, row.names = FALSE)

  # Function to get new observations
  get_new_data <- function(){
    readLines('http://webrates.truefx.com/rates/connect.html')
    }

  ## ----------------- Start fxData ---------------------------
  # Initialize fxData
  fxData <<- get_new_data()

  # Function to update fxData, latest data will be showing upside.
  update_data <- function(){
    fxData <<- rbind(fxData, get_new_data())#  %>% unique
    saveRDS(fxData, paste0(str_replace_all(now('GMT'), ':', 'T'), 'GMT.rds'))
    }

  output$plotPrice <- renderPlot({
    invalidateLater(1000, session)
    #update_data()

    if(any(file.exists(paste0(dir(pattern = '.rds'))))) {
      realPlot <<- llply(dir(pattern = '.rds'), readRDS)
      realPlot <<- do.call(rbind, realPlot) %>% unique
      realPlot <<- ldply(realPlot, ParseTrueFX) %>% unique %>% 
        filter(Symbol == 'USD/JPY')
    }

    if(nrow(realPlot) > 10) {

      ggplot(tail(realPlot, 10), aes(TimeStamp)) + 
        geom_line(aes(y = Bid.Price, colour = 'Bid.Price')) + 
        geom_line(aes(y = Ask.Price, colour = 'Ask.Price')) + 
        ggtitle('Real Time USD/JPY')

    } else {

      ggplot(realPlot, aes(TimeStamp)) + 
        geom_line(aes(y = Bid.Price, colour = 'Bid.Price')) + 
        geom_line(aes(y = Ask.Price, colour = 'Ask.Price')) + 
        ggtitle('Real Time USD/JPY')
    }
    })

  #'@ output$plotAskPrice <- renderPlot({
  #'@   invalidateLater(1000, session)
    #'@ update_data()
  #'@   
  #'@   dt <- terms()
  #'@   if(nrow(dt) > 40) {
  #'@     ggplot(data = tail(dt, 40), aes(x = TimeStamp, y = Ask.Price, 
  #'@                           group = Symbol, colour = Symbol)) +
  #'@       geom_line() + geom_point( size = 4, shape = 21, fill = 'white') + 
  #'@       ggtitle('Real Time Graph 2 : Forex Ask Price')
  #'@     
  #'@   } else {
  #'@     ggplot(data = dt, aes(x = TimeStamp, y = Ask.Price, 
  #'@                           group = Symbol, colour = Symbol)) +
  #'@       geom_line() + geom_point( size = 4, shape = 21, fill = 'white') + 
  #'@       ggtitle('Real Time Graph 2 : Forex Ask Price')
  #'@   }
  #'@ })
  ## ------------------ End fxData ----------------------------

  terms <- reactive({
    input$refresh

    if(any(file.exists(paste0(dir(pattern = '.rds'))))) {
      realData <<- llply(dir(pattern = '.rds'), readRDS)
      realData <<- do.call(rbind, realData) %>% unique
      realData <<- ldply(realData, ParseTrueFX) %>% unique
    }
  })

  # Downloadable csv
  output$downloadData <- downloadHandler(
    filename = function() {
      paste('fxData.csv', sep = '')
    },
    content = function(file) {
      fwrite(terms(), file, row.names = FALSE)
    }
  )

  observe({
    if(input$reset){
      do.call(file.remove, list(dir(pattern = '.rds')))
      rm(list = ls())
      stopApp('Delete all downloaded dataset!')
    }
  })

  output$fxDataTable <- renderDataTable({

    terms() %>% datatable(
      caption = "Table : Forex", 
      escape = FALSE, filter = "top", rownames = FALSE, 
      extensions = list("ColReorder" = NULL, "RowReorder" = NULL, 
                        "Buttons" = NULL, "Responsive" = NULL), 
      options = list(dom = 'BRrltpi', scrollX = TRUE, #autoWidth = TRUE, 
                     lengthMenu = list(c(10, 50, 100, -1), c('10', '50', '100', 'All')), 
                     ColReorder = TRUE, rowReorder = TRUE, 
                     buttons = list('copy', 'print', 
                                    list(extend = 'collection', 
                                         buttons = c('csv', 'excel', 'pdf'), 
                                         text = 'Download'), I('colvis'))))
  })

  ## Set this to "force" instead of TRUE for testing locally (without Shiny Server)
  ## If session$allowReconnect(TRUE), stopApp() will auto reconnect and  there will be endless 
  ##   reconnect and disconnect step only and not able to reset the app.
  #'@ session$allowReconnect(TRUE) 

  llply(c('plotPrice', 'fxdata', 'fxDataTable'), function(x) {
    outputOptions(output, x, suspendWhenHidden = FALSE)
  })
})

shinyApp(ui, server)

来源 :数据采集 https://beta.rstudioconnect.com/content/3153/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R 上的实时图表 - Shiny 的相关文章

  • 我可以调整scale_color_brewer的下限吗?

    我已经订购了我想使用 color Brewer 的分类数据 但我很难看到非常低的值 有没有办法去掉这些较低的值或设置范围的下限 ggplot data frame x 1 6 y 10 15 w letters 1 6 aes x y co
  • 分割单个 SpatialPolygons 对象的多边形部分

    在 R 中 我有一个SpatialPolygons包含数百个多边形的对象 即多个多边形 我想分割这个SpatialPolygons对象放入列表中Polygons 即孔应保持连接到父多边形 知道如何做到这一点吗 EDITED 使用以下提供的示
  • 如何将 mcmc.list 转换为 bugs 对象?

    我正在使用rjagsR 库 功能coda samples产生一个mcmc list 例如 来自example coda samples library rjags data LINE LINE recompile LINE out lt c
  • 通过 RCpp 返回 NA

    新手 RCpp 问题在这里 How can I make a NumericVector returnNA到R 例如 假设我有一个 RCpp 代码 它分配NA到向量的第一个元素 RCpp export NumericVector myFun
  • R:如何更改ggvis闪亮应用程序中特定范围的绘图背景颜色

    I have a simple shiny app like below and you can run it The plots are created by ggvis and user can choose student name
  • 在 ggplot 中过滤管道 df

    我正在使用 dplyr 管道来清理我的 df 然后直接输入到 ggplot 中 但是 我只想一次只绘制一组 因此我需要过滤到该组 问题是 我希望比例保持不变 就好像所有群体都存在一样 是否可以在 ggplot 命令中进一步过滤管道 df 例
  • 替换rmarkdown/knitr/pdf中字幕的自动编号

    我正在使用 Rmarkdown 生成 PDF 文档 我想在其中手动定义图号 下面是一个块的示例 r chunk26 fig cap Fig 5 3 My figure caption plot 1 1 我使用特殊的编号来遵循文档的章节 问题
  • 使用插入符和方法 = gamLoess 进行训练时 R 崩溃

    当我运行下面的代码时 R 崩溃了 如果我在训练调用中注释掉tuneGrid行 就不会发生崩溃 我已经用另一个数据集尝试过此操作 但仍然使 R 崩溃 崩溃消息是 R 会话中止 R遇到致命错误 会话被终止 开始新会话 代码是 library s
  • R 在安装包依赖项时不考虑最大版本

    假设我正在开发一个名为magicr做一些统计魔术 我希望它使用另一个名为的包中的函数fairydust 假设 存在于 CRAN 上 很遗憾fairydust刚刚向 CRAN 发布了 2 0 0 版本 完全破坏了我计划使用的功能 所以我更新了
  • R Shiny - 使用 DataTable 移动列名称

    我有一个非常复杂的闪亮代码 其中有几个面板和这些面板内的几个表格 启动应用程序时 列名称与列值正确对齐 但是 一旦我更改应用程序表格下的页码 列名称就会移动到左侧 而值仍保留在中间 如何强制应用程序使列名称与列值对齐 一个可重现的例子 li
  • R 中 if-else 中的逻辑运算符

    我有一个名为 mat 的下表 5 列和 3 行 AC CA RES 1 0 2 2 1 3 0 0 0 1 正在执行的操作是mat 1 mat 1 mat 2 我正在测试以下内容 1 如果一行的两列都为零 则结果应为 NA 2 如果一行中只
  • 在 R 中,如何将 SpatialPolygons* 转换为地图对象

    我正在尝试利用ProportionalSymbolMap在此定义的地图JSS论文 http www jstatsoft org v15 i05 为了绘制比例符号 我首先需要一个地图类的对象 The methods http www ncea
  • R 中的线性模型 - 乘法表达式

    我有 3 个数值变量A B and C 我正在尝试创建一个能够预测的线性模型A 我使用的表达式是B C为了预测A 然而 当查看输出时 我无法得到我的方程 因为我得到了额外的变量 但我不知道它是什么 这是我的代码 MyData lt read
  • 如何强制在较新版本的 R 上安装较旧的软件包?

    我无法安装proj4string进入我当前版本的 R 2 15 1 Warning message package proj4string is not available for R version 2 15 1 我认为这是因为 2 15
  • 在r中拆分数据并将所有拆分文件保存在csv中

    我有一个名为 data 的数据集 Model Garage City Honda C Chicago Maruti B Boston Porsche A New York Honda B Chicago Honda C New York 它
  • 如何在 R 中为所有plot.default、plot 或lines 调用设置默认颜色

    为了简化我的日常 R 交互 我想为所有绘图设置默认颜色 例如 假设我想要用红线绘制所有绘图 例如在 gnuplot 中 到目前为止 这是我的 Rprofile 的片段 setHook packageEvent grDevices onLoa
  • 计算不包括当前值的平均值

    我有下表 a b avg 1 1 7 3 2 1 0 3 3 1 2 3 4 2 1 2 5 2 3 2 其中 a 和 b 是数据 avg 计算按 a 分组的 b 的平均值 现在我想计算按 a 分组的 b 的平均值 avg2 不包括当前值
  • 安装 gplots 时出错

    我正在 OSX v 10 9 2 上运行 R v 3 0 3 当尝试使用以下命令在 R studio 中安装 gplots 包时 出现错误 gt library gplots Error in library gplots there is
  • R:中断 for 循环

    你能确认下一个break是否取消了内部for循环吗 for out in 1 n old id velho lt old table df id out for in in 1 n id novo lt new table df ID in
  • R 中的 ddply:对于每个组,查找特定变量的出现百分比

    我有一个数据集 其中包含两列 user type 和滞后响应时间 以天为单位 user type imp date lag Consumer 20130613 1 Consumer 20130612 2 Consumer 20130611

随机推荐

  • 安全删除 StackView 转换中使用的 QML 组件

    Overview 我的问题涉及一个人的一生QObject由 制作QQmlComponent create http doc qt io qt 5 qqmlcomponent html create 1 返回的对象create 是一个实例化Q
  • 使用 mongo-go-driver,如何有效地从 WriteError 中检索重复的字段名称?

    我的收藏中有三个独特的索引 当用户不小心插入字段中重复的数据时B 我怎么知道重复项来自字段B 在违反唯一索引约束时 mongo go driver 行为返回错误WriteException 它基本上由 WriteError 数组和一些其他对
  • SftpClient.UploadFile 和 SftpClient.WriteAllBytes 有什么区别?

    当我使用 SSH NET 通过 SFTP 传输文件时 我观察到一些奇怪的行为 我正在使用 SFTP 将 XML 文件传输到另一个服务 我不控制 进行处理 如果我使用SftpClient WriteAllBytes该服务抱怨该文件不是有效的
  • 如何在reportlab、python中创建具有不同页面大小的PDF文档

    是否可以在reportlab中创建具有不同页面大小的PDF文档 我想创建一个文档 其中第一页的尺寸与其他页面的尺寸不同 有人可以帮忙吗 是的 这应该是可能的 因为 PDF 支持这一点 这只是如何在 ReportLab 中实现它的问题 我从来
  • Ajp 收到带有签名的无效消息

    我使用的是 Tomcat 7 0 29 前端是 Apache 2 2 22 modproxy 在 httpd conf 中将 Ajp 配置为协议 在 server xml 中将 AjpNioProtocol 配置为 AjpNioProtoc
  • 连接到 pyqtSignal 的 lambda 中对象的生命周期

    假设我有一个对象 并希望在发出 PyQt 信号时执行其方法之一 假设我希望它使用信号未传递的参数来执行此操作 所以我创建了一个 lambda 作为信号槽 class MyClass object def init self model mo
  • 仅使用页面数据通过 Javascript 触发浏览器的“另存为”对话框

    作为页面输出的一部分 我在文本区域中包含了数据表的 CSV 格式版本 以便用户可以轻松地将 CSV 导出复制 粘贴到他们选择的电子表格中 我想要一种方法 有一个按钮 当单击该按钮时 将触发 另存为 对话框 该对话框将下载页面文本区域中已存在
  • 动态数组:使用 realloc() 无内存泄漏

    我使用 realloc 来调整分配的内存大小 char get channel name void char result int n result char 0 for elem snd mixer first elem handle n
  • 在快速中间件中记录请求和响应

    我正在尝试实现一个记录器Express http expressjs com应用 我需要它能够记录请求以及为每个请求发回的响应 状态代码和正文 我开始编写一个如下所示的中间件 function req res next res on fin
  • 从数据库检索数据时如何转义特殊字符?

    我将根据从 SQL Server 返回的数据生成 XML 文件 但有一些特殊字符 例如 x1F and x1C 可能还有其他类似的字符 这将使 XML 失败 有什么办法可以逃离他们吗 Thanks 控制字符 U 001C 文件分隔符 和 U
  • 在Java中一次向ArrayList添加多个项目[重复]

    这个问题在这里已经有答案了 如何一次向 ArrayList 添加多个项目 ArrayList
  • 如何从虚拟环境 (virtualenv) 启动 python Idle

    我有一个从虚拟环境安装的软件包 如果我只是启动 python 解释器 则可以很好地导入该包 但是 如果我启动 Idle 则无法导入该包 因为它仅在一个特定的 virtualenv 中可用 而不是在全局中可用 如何从 virtualenv 启
  • 使用 GDI+ 和 C# 更改图像对比度

    我的问题如下 我正在制作一个程序 可以通过 C 代码操纵亮度 伽玛和对比度 对于亮度和伽玛来说还可以 我已经通过在网上找到的代码实现了它 但我不能进行对比 到目前为止我唯一发现的是CalculateRamp方法 其输入参数 double l
  • 如何使用 JavaScript 更改 div 内容?

    我有简单的 HTML 代码和一些 JavaScript 看起来像
  • Chrome 和可能 Opera 自动对对象属性进行排序

    问题是 Chrome 会自动对对象的属性进行排序 如果我有一个像这样的对象 var obj 4 first 2 second 1 third 然后当我下一步时 for var i in obj console debug obj i 我看到
  • 在网页中嵌入 IRC 客户端的最佳方式

    我正在寻找一个好的 免费的 最好是开源的 IRC 客户端来嵌入网页中 支持大多数浏览器的明显要求是 如果需要插件 则该插件应该是已经广泛部署的插件 并且不应该给提供页面服务的网络服务器带来太大压力 不是一个真正的编程问题 但是Mibbit
  • JQuery - 从数据动态生成图形树视图

    我想动态生成一个树视图来表示应用程序中的用户连接 但我不希望它看起来像普通的树视图 看起来像文件系统结构 如下所示 但更像是这样的流程图 所以基本上我想以比树视图更图形化的方式显示它 如果可能的话 能够放大和缩小 如何才能实现这一目标 你知
  • Blackberry - 具有不同 ID 的可点击 BitmapField

    我正在创建一个应用程序 在其中我通过 JSON 从 Web 服务器获取带有 id 的礼品图像 当我点击任何礼物图像时 它会进入下一页 其中显示该图像的所有信息 通过 JSON 从 Web 服务器获取图像信息及其 ID 问题是 当我点击页面上
  • 轴。即使api返回404错误,如何在try catch finally中获得错误响应

    for e g async gt let apiRes null try apiRes await axios get https silex edgeprop my api v1 a catch err console error err
  • R 上的实时图表 - Shiny

    我正在尝试制作一个交互式图表 在一个闪亮的应用程序上绘制金融股票数据 我的尝试是不断更新数据 从而更新图表 我使用一个名为 Highcharter 的包来管理这个 下面显示了服务器部分的部分代码 getDataIntraday 接收两个输入