You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny App使用quantmod绘制股票折线图报错求助

Fixing Your Quantmod Shiny Stock Chart Error

Let's break down the issues in your code and fix them step by step:

Key Problems in Your Original Code

  • Shiny Output Binding Missing: You didn't wrap your plotting logic in renderPlot() to connect it to the distPlot output defined in your UI. Shiny requires this reactive wrapper to render plots dynamically based on user input.
  • Invalid getSymbols() Parameter: The type="line" argument doesn't belong to getSymbols() — this function is only for fetching stock data, not specifying plot type.
  • Wrong Plotting Function: Using base R's plot() with the xts object returned by getSymbols() won't work as expected. Quantmod provides chartSeries(), which is purpose-built for its data structures and stock charting needs.
  • UI Syntax Error: The selected parameter in selectInput() was placed outside the function call, which breaks the UI setup.

Fixed Code

ui.R

library(shiny)
shinyUI(fluidPage(
  titlePanel("Stock Chart"),
  sidebarLayout(
    sidebarPanel(
      # Fixed: Moved `selected` inside the selectInput argument list
      selectInput("stockInput", "Pick your stock:", 
                  choices = c("AMZN","FB","GOOG","NVDA","AAPL"), 
                  selected = "GOOG")
    ),
    mainPanel(
      plotOutput("distPlot") 
    )
  )
))

server.R

library(quantmod)
shinyServer(function(input, output){
  # Fixed: Added renderPlot() to bind to the UI's distPlot output
  output$distPlot <- renderPlot({
    # Fixed: Removed invalid `type` argument from getSymbols
    price <- getSymbols(input$stockInput, 
                        from='2019-01-01',  # Added full date format to avoid parsing issues
                        auto.assign = FALSE)
    
    # Fixed: Used quantmod's chartSeries instead of base plot
    chartSeries(price, 
                main = paste("Stock Chart for", input$stockInput),
                theme = chartTheme('white'))
  })
})

Additional Notes

  • I added a full date (2019-01-01) to the from argument to avoid potential date parsing inconsistencies.
  • Updated the plot title to be more descriptive by combining the selected stock ticker with static text.
  • chartSeries() handles the xts object from getSymbols() natively, so you'll get a proper quantmod-style stock chart with volume bars by default. You can customize this further (e.g., hide volume with showVolume = FALSE) if needed.

内容的提问来源于stack exchange,提问作者Trungle83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:45:02