简体   繁体   中英

plotting stock volatility in R using Shiny

hoping for some direction with this. I am new to 'R' and Shiny and have some programming background which I am trying to apply here but to no avail. Essentially I am using quantmod as an extension to Shiny so I can plot stock volatility. This was successful in the terminal by using the following commands:

getSymbols(‘SPY’,from=’2007/01/01′)
vol=volatility(SPY,n=25,N=252,calc=’close’)
chartSeries(vol)

However, when I try to convert this into a Shiny app in order to render it in a web browser I am met with several errors. Likely using the wrong functions? not sure... here is my code:

library(quantmod)
library(stringr)
library(tidyr)
library(dplyr)
library(ggplot2)
source("helpers.R")


# Define UI for application that draws a histogram
ui <- fluidPage(
    titlePanel("Theoretical Vol"),
    helpText("Select a stock to examine. Information will be collected from Yahoo finance."),
    textInput("symb", "Symbol", "SPY"),
    dateRangeInput("dates","Date range",start = "2019-01-01",end = as.character(Sys.Date())),
    plotOutput("plot")    
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    dataInput <- reactive({
        getSymbols(input$symb, src = "yahoo",
                   from = input$dates[1],
                   to = input$dates[2],
                   auto.assign = FALSE)
    })
    
    output$plot <- reactive(
        vol <- volatility(input$symb,n=25,N=252,calc="close"))
    
}

# Run the application 
shinyApp(ui = ui, server = server)

Error message:

Listening on http://127.0.0.1:5727
Warning: Error in log: non-numeric argument to mathematical function
  99: diff
  98: ROC
  97: volatility
  96: <reactive>
  80: output$plot
   1: runApp

Try this

ui <- fluidPage(
  titlePanel("Theoretical Vol"),
  helpText("Select a stock to examine. Information will be collected from Yahoo finance."),
  textInput("symb", "Symbol", value="SPY"),
  dateRangeInput("dates","Date range",start = "2019-01-01",end = as.character(Sys.Date())),
  plotOutput("plot")
)

# Define server logic required to draw a histogram
server <- function(input, output) {

  output$plot <- renderPlot({
    
    price <- getSymbols(req(input$symb), src = "yahoo",
               from = input$dates[1],
               to = input$dates[2],
               auto.assign = FALSE)
    vol <- volatility(price,n=25,N=252,calc="close")
    chartSeries(vol)
  })
  
}

# Run the application
shinyApp(ui = ui, server = server)

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM