How to plot data from a variable in shiny UI

0

I'm starting learning in R / Shiny. I'm having trouble plotting a graph in the UI.

The content of the graph comes from the stock function (tiker, rx), variable "price", follows the function:

stock<- function(ticker,rx){

re<- ({as.numeric(rx)})
#re=0
#ticker="vale3"
p1=ticker
p=140
#re=0#retrocede candles de 15 minutos
options(max.print=15)##qtdadde reg para impressao na tela

p1<-toupper(p1)
ta=length(p1)

options(max.print=15)##qtdadde reg para impressao na tela
p2="https://finance.google.com/finance/getprices?q="
p4="&x=BVMF&i=900&p=100d&f=c"
####################looping

URL<-paste(p2,p1,p4,sep="")
xx<- read.csv(URL)
colnames(xx)[1] <- "co1"  #muda none EXCHANGE.#DBMF para close
c1=(xx$co1)
t1=length(c1)
c2=c1[(t1-500):t1]
c3 <- c2[ c2 != "TIMEZONE_OFFSET=-180" ]
preco<-as.numeric(as.character(c3))###that that a want to plot in UI

return(paste0("Ativo.: ", p1, br()

#####
UI
library(shiny)
#modelo bom pasta apteste9
ui = shinyUI(fluidPage(
  h3("Pesquisa Ativo da Bolsa -Defasados 15 Minutos,Fornece 5 periodos (top/down atual e 4 anteriores de 15 Minutos - Testes:"),

   h4("Sugestao Base, (W INDICATOR BUY & SELL),......... VENDA Qdo Wibs e WIbs1 >=9,..........  Compra Qdo WIBS E WIBS1  <=1:"),

  h5("Analise abrangendo 5 Dias de Pregao 15 em 15 Minutos,ou seja - Dados reais Defasados 15 Minutos -        Analise Base Modelagem Regressao x Ruido" ),

  br(),

  fluidRow(
    column(6,selectizeInput("ticker", "Selecione Ativo Desejado,ou Digite Nome da Empresa", width="100%",multiple=TRUE,
                            choices = list("AMBEV S/A"="ABEV3","BRASIL"="BBAS3","BRADESCO"="BBDC3","BRADESCO"="BBDC4",

                                           "BBSEGURIDADE"="BBSE3","BRADESPAR"="BRAP4","BRF SA"="BRFS3"))),

    column(3,selectizeInput("rx", "Retroceder x Candles de 15 Minutos", width="100%",
                            choices = list(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,22))),
    br(),
    br(),
    column(3,actionButton(inputId = "input_action", label = "Processa os Dados.???"))   
  ),  
  mainPanel(
    h5(textOutput("caption")),    
    tableOutput("saida")),
    plotOutput("plot")



###server

library(shiny)
source("stock.R",local = TRUE)

shinyServer(function(input, output) {   


  observeEvent(input$input_action, {
    ticker= input$ticker
    rx = input$rx
    output$saida <- renderTable({
    stock(ticker,rx)
    })    
  })
  output$plot <- renderPlot({
    source("stock.R",local = TRUE)   
    plot<-preco
  }) 
})
    
asked by anonymous 19.03.2018 / 02:24

1 answer

0

The code that you provided was all problematic.

Starting with the lack of (), {}, ... correctly closing the enviroments, functions, etc. Be more careful to make life easier for those who are going to analyze your doubt.

Another problem, if you want the stock function to return the price vector then it should be within return() . A function of R follows two lines of thought, either it returns the object on the last line or it returns the object that is within the first return() that is called (and ends there).

Now in the Shiny part itself. You should not put output$saida <- renderTable({...}) within observeEvent({}) , every render ... function must be primary within server .

Another point, if you call the function stock(ticker,rx) within renderTable({...}) it will not be available within renderPlot({...}) because there are two different environments.

As you will use the data for two different outputs (table and graph) I suggest you create them as a reactive environment (which is a function that responds to changes in inputs) and call within each of those renders.

There goes your modified code and working.

library(shiny)

stock<- function(ticker,rx){

  re<- ({as.numeric(rx)})
  #re=0
  #ticker="vale3"
  p1=ticker
  p=140
  #re=0#retrocede candles de 15 minutos
  options(max.print=15)##qtdadde reg para impressao na tela

  p1<-toupper(p1)
  ta=length(p1)

  options(max.print=15)##qtdadde reg para impressao na tela
  p2="https://finance.google.com/finance/getprices?q="
  p4="&x=BVMF&i=900&p=100d&f=c"
  ####################looping

  URL<-paste(p2,p1,p4,sep="")
  xx<- read.csv(URL)
  colnames(xx)[1] <- "co1"  #muda none EXCHANGE.#DBMF para close
  c1=(xx$co1)
  t1=length(c1)
  c2=c1[(t1-500):t1]
  c3 <- c2[ c2 != "TIMEZONE_OFFSET=-180" ]

  preco<-as.numeric(as.character(c3))###that that a want to plot in UI
  return(preco)
}

#####


ui <- shinyUI(
  fluidPage(
    h3("Pesquisa Ativo da Bolsa -Defasados 15 Minutos,Fornece 5 periodos (top/down atual e 4 anteriores de 15 Minutos - Testes:"),
    h4("Sugestao Base, (W INDICATOR BUY & SELL),......... VENDA Qdo Wibs e WIbs1 >=9,..........  Compra Qdo WIBS E WIBS1  <=1:"),
    h5("Analise abrangendo 5 Dias de Pregao 15 em 15 Minutos,ou seja - Dados reais Defasados 15 Minutos -        Analise Base Modelagem Regressao x Ruido" ),
    br(),

    fluidRow(
      column(6,selectizeInput("ticker", "Selecione Ativo Desejado,ou Digite Nome da Empresa", width="100%",multiple=TRUE,
                              choices = list("AMBEV S/A"="ABEV3","BRASIL"="BBAS3","BRADESCO"="BBDC3","BRADESCO"="BBDC4",
                                             "BBSEGURIDADE"="BBSE3","BRADESPAR"="BRAP4","BRF SA"="BRFS3"))),
      column(3,selectizeInput("rx", "Retroceder x Candles de 15 Minutos", width="100%",
                              choices = list(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,22),
                              selected= character(0))),
      br(),
      br(),
      column(3,actionButton(inputId = "input_action", label = "Processa os Dados.???"))   
    ),  
    mainPanel(
      h5(textOutput("caption")),    
      tableOutput("saida")),
    plotOutput("plot")
  )
)


server <- shinyServer(function(input, output) {   

  data <- reactive({
    # atualizado apenas quando clicar no botão
    req(input$input_action)
    # Conferindo se o ticker foi escolhido
    req(input$ticker)
    # retornando os inputs
    ticker <- input$ticker
    rx <- input$rx
    # retorna o vetor de preços
    stock(ticker,rx)
  })

  output$saida <- renderTable({
    data()
  }) 

  output$plot <- renderPlot({
    plot(data())
  }) 
})

shinyApp(ui = ui, server = server)
    
22.03.2018 / 17:17