How to plot data from a variable in Shiny UI

Asked

Viewed 324 times

1

I’m starting my R/Shiny apprenticeship. I’m having trouble plotting a chart on the UI.

The content of the graph comes from the function "stock(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
  }) 
})

1 answer

0

The code you provided was all problematic.

Starting with the lack of (), {}, ... correctly closing enviroments, functions, etc. Be more careful to facilitate the life of those who will analyze your doubt.

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

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

Another point, if you call the function stock(ticker,rx) within renderTable({...}) it will not be available within the renderPlot({...}) because they 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 reacts to changes in inputs) and call within each of these renders.

There goes your code modified 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.