user3711502
user3711502

Reputation: 412

RCharts + Shiny dynamically change chart data

this my first time working with both rcharts and shiny. I am trying to create a basic shiny app where users can pick stocks from dropdown menus and compare their performance in a rcharts chart ( I want to use rcharts for the interactivity).

I've managed to create the dropdown menus and the rcharts chart, but cannot get the data that the chart is created from to change. code is below:

ui.R

    shinyUI(fluidPage(
  titlePanel("S&P 500 Retroactive Stock Comparision - 2009 and 2010"),
  sidebarLayout(
    sidebarPanel(uiOutput("stockA"), uiOutput("stockB"),submitButton("Submit")),
    mainPanel(showOutput("StockPlot","NVD3"))
  )
))

server.R:

stock.names<-reactive({
  ## data from :  http://pages.swcp.com/stocks/#historical%20data 
  stocks_data<-read.table("S.P.500_data.txt",sep=",")
  colnames(stocks_data)<-c("Date","Ticker","Open","High","Low","Close","Volume") 
  stocks_data$Date<- as.Date(as.character(stocks_data$Date), "%Y%m%d")

  stocks_data$Percent.Change<-((stocks_data$High-stocks_data$Low)/stocks_data$Open)*100

  #get company names + match with ticker symbols
  library(RCurl)
  company_names1 <- "http://data.okfn.org/data/core/s-and-p-500-companies/r/constituents.csv"
  company_names2<-getURL(company_names1)
  company_names3<-read.csv(textConnection(company_names2))

  stocks_data$Company.Names<-company_names3[match(stocks_data$Ticker,company_names3$Symbol),"Name"]

  x<-sort(unique(as.character(stocks_data$Company.Names)))
  return(x)
})

library(rCharts)


shinyServer(function(input,output){
  ########
  output$stockA <- renderUI({ 
    selectInput("stockA", "Select your first stock to compare:",choices=stock.names() )
  })
  ##########
  output$stockB <- renderUI({ 
    selectInput("stockB", "Select your second stock to compare:",choices=stock.names() )
  })

  ########
stockA.name<- reactive({
  input$StockA
}) 
  #########
stockB.name<- reactive({
  input$StockB
})

#######

chart.data<-reactive({
  data<-subset(stocks_data, Company.Names %in% input$stockA | Company.Names %in% input$stockB)
 return(data)
})
  ####### 
  output$StockPlot<-renderChart2({
    plot1<-nPlot(Close~Date,data=chart.data() ,group='Company.Names',type='lineChart')
    return(plot1)
  })
}
)

Upvotes: 1

Views: 552

Answers (1)

Carl Boneri
Carl Boneri

Reputation: 2722

Try adding session to your server args, and then you should be able to use

observeEvent(input $Submit, {

  stockA.name <- input$StockA
  stockB.name <- input$StockB

  chart.data <- subset(stocks_data, Company.Names %in% input$stockA | 
                                    Company.Names %in% input$stockB)

  output$StockPlot<-renderChart2({
    plot1 <- nPlot(Close~Date,data=chart.data(), 
                   group='Company.Names',type='lineChart')
    return(plot1)
  })

})

Freehanding this from my phone but I'll circle back later if it doesn't work

Upvotes: 0

Related Questions