简体   繁体   English

使用 Shiny 绘制 R 中的股票波动率

[英]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.我是“R”和 Shiny 的新手,并且有一些编程背景,我想在这里申请,但无济于事。 Essentially I am using quantmod as an extension to Shiny so I can plot stock volatility.本质上,我使用quantmod作为 Shiny 的扩展,因此我可以使用 plot 股票波动率。 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.但是,当我尝试将其转换为 Shiny 应用程序以便在 web 浏览器中呈现它时,我遇到了几个错误。 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)

输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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