---
# System prepended metadata

title: 自動查詢上市上櫃股票資訊_R語言_tryCatch()_quantmod
tags: [可視化, 股票, R]

---

---
disqus: ahb0222
GA : G-VF9ZT413CG
---
# 自動查詢上市上櫃股票資訊_R語言_tryCatch()_quantmod
> [color=#40f1ef][name=LHB阿好伯, 2022/05/09][:earth_africa:](https://www.facebook.com/LHB0222/)
###### tags: `R` `股票` `可視化`

[TOC]

相關文章[R語言-股票套件quantmod & tidyquant](/S5L5O_vrREu2iLqpQblW3w)

前幾天有人詢問如何在之前分享的Shiny上自動帶入TW跟TWO的方式查詢股票資料
這兩天研究的結果最後使用tryCatch()函數先搜尋XXXX.TW
根據獲取函數的執行結果若發生錯誤、警告等就搜尋XXXX.TWO


![](https://hackmd.io/_uploads/HkEvH3UI5.png)


```r=
#install.packages(c("quantmod","readr","shiny"))
library(shiny)
library(readr)
library(quantmod)
Snum_data <- read_csv("https://raw.githubusercontent.com/gtgrthrst/OpenData/main/%E8%82%A1%E7%A5%A8%E5%B0%8D%E7%85%A7.csv")

# Define UI for application that draws a histogram
ui <- fluidPage(
  # Application title
  titlePanel("股票查詢"),
  
  # Sidebar with a slider input for number of bins 
  
  sidebarLayout(
    sidebarPanel( textInput("Snum", "台股編號", value = 2330),
                  helpText("輸入台股代碼4-6碼即可查詢走勢"),
                  dateRangeInput("daterange1", "Date range:",
                                 start  = "2021-01-01",
                                 min    = "2010-01-01",
                                 max    = Sys.Date(),
                                 end   = Sys.Date()),
                  sliderInput("bins1",
                              "布林通道樣本數:",
                              min = 2,
                              max = 90,
                              value = 20),
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      verbatimTextOutput("Sname"),
      plotOutput("distPlot")
    )
  )
)

# Define server logic required to draw a histogram

server <- function(input, output) {
  
  output$Sname <- renderText(as.character(subset(Snum_data, number == input$Snum)[2]))
  
  output$distPlot <- renderPlot({
    ma1<-runMean(Sdata[,4],n=input$bins1)
    
   
    
    f1 <- function(a){getSymbols(paste0(a,".TW"),src="yahoo",
                                     from="2020-1-1",
                                     to="2020-2-1")}
    

      tryCatch({
        Sdata <- na.omit(get(getSymbols(paste0(input$Snum,".TW"),src="yahoo",
                                        from=as.character(format(input$daterange1[1],"%Y-%m-%d")),
                                        to=as.character(format(input$daterange1[2],"%Y-%m-%d"))))) #from改成自己要的起日
        chartSeries(Sdata, name =  paste0(input$Snum,".TW")) 
        #        addTA(ma20,on=1,col="blue")
        #        addTA(ma60,on=1,col="red")
        addBBands(n = input$bins1, sd = 2)  #布林通道
      }
      ,
               error = function(e){
                 
                 Sdata <- na.omit(get(getSymbols(paste0(input$Snum,".TWO"),src="yahoo",
                                                 from=as.character(format(input$daterange1[1],"%Y-%m-%d")),
                                                 to=as.character(format(input$daterange1[2],"%Y-%m-%d"))))) #from改成自己要的起日
                 chartSeries(Sdata, name =  paste0(input$Snum,".TWO")) 
                 #        addTA(ma20,on=1,col="blue")
                 #        addTA(ma60,on=1,col="red")
                 addBBands(n = input$bins1, sd = 2)  #布林通道
               },
               warning = function(e){
                 
                 Sdata <- na.omit(get(getSymbols(paste0(input$Snum,".TWO"),src="yahoo",
                                                 from=as.character(format(input$daterange1[1],"%Y-%m-%d")),
                                                 to=as.character(format(input$daterange1[2],"%Y-%m-%d"))))) #from改成自己要的起日
                 chartSeries(Sdata, name =  paste0(input$Snum,".TWO")) 
                 #        addTA(ma20,on=1,col="blue")
                 #        addTA(ma60,on=1,col="red")
                 addBBands(n = input$bins1, sd = 2)  #布林通道
               })


  })
}

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

```

🌟

🌟全文可以至下方連結觀看或是補充


全文分享至

https://www.facebook.com/LHB0222/

https://www.instagram.com/ahb0222/

有疑問想討論的都歡迎於下方留言

喜歡的幫我分享給所有的朋友 \o/

有所錯誤歡迎指教

# [:page_with_curl: 全部文章列表](https://hackmd.io/@LHB-0222/AllWritings)



![](https://i.imgur.com/nHEcVmm.jpg)


