Home > Software engineering >  Issues with reactivity in R - You tried to do something that can only be done from inside a reactive
Issues with reactivity in R - You tried to do something that can only be done from inside a reactive

Time:12-16

I am trying to put this code in Shiny with dynamic dates and ticker selection, but I get the following error Operation not allowed without an active reactive context. You tried to do something that can only be done from inside a reactive consumer.

library(quantmod)
library(PerformanceAnalytics)

dt <- "2017-2-1"

aapl <- getSymbols.yahoo("AAPL", from=dt, auto.assign = F)
aaplClose <- getSymbols.yahoo("AAPL", from=dt, auto.assign = F)[,6]

aaplRets <- na.omit(dailyReturn(aaplClose, type="log"))

Here is my shiny implementation

library(shiny)
library(quantmod)
library(PerformanceAnalytics)
#dt <- "2017-2-1"

ui <- fluidPage(
  dateInput("dt", "Select a date:"),
  textInput("tkr", "Enter a ticker symbol"),
  plotOutput("myplot")
)

server <- function(input, output, session) {
  aapl <- reactive ({
    getSymbols.yahoo(input$tkr, from=input$dt, auto.assign = F)
    })
  aaplClose <- reactive ({
    getSymbols.yahoo(input$tkr, from=input$dt, auto.assign = F)[,6]
  })
  aaplRets <- na.omit(dailyReturn(aaplClose(), type="log"))
  
  output$myplot <- renderPlot(
    { chartSeries(aapl())}
  ) 
}

shinyApp(ui, server)

CodePudding user response:

Since you have a text input to select the ticker, the data should not be called apple, because it can be everything. Keeping everything in reactive contextes:

library(shiny)
library(quantmod)
library(PerformanceAnalytics)


ui <- fluidPage(
  dateInput("dt", "Select a date:", value = "2017-2-1"),
  textInput("tkr", "Enter a ticker symbol", value = "AAPL"),
  plotOutput("myplot")
)

server <- function(input, output, session) {
  data <- reactive({
    getSymbols.yahoo(input$tkr, from = input$dt, auto.assign = F)
  })

  output$myplot <- renderPlot({
    chartSeries(data())
  })
}

shinyApp(ui, server)

enter image description here

Or with Alphabet:

enter image description here

  • Related