Try   HackMD

R語言-股票套件quantmod & tidyquant

LHB阿好伯, 2020/02/09

tags: R 股票 可視化

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

最近找了一些資料學習R語言中的quantmod套件
目前tidyquant套件整合收集和分析財務數據的相關套件如:zoo、xts、quantmod、TTR和PerformanceAnalytics

xts/zoo: 處理時間序列之套件。
TTR: 計算金融資產技術指標之套件。
quantmod: 金融資產技術分析回測套件,可至Yahoo Finance或Google Finance下載歷史股價數據或其他金融相關數據。並且整合TTR套件,繪製出漂亮的技術分析圖析。
PerformanceAnalytics: 計算金融資產報酬績效指標之套件。

用tidyverse允許每個套件之間的無縫使用
今天來介紹最基本的抓取台股資料與畫圖
quantmod套件官網
quantmod套件文檔

tidyquant套件官網

股票代號與名稱對應

目前quantmod套件中的名稱都是英文
所以我依照證交所提供的資料建立了對應表
用於後續畫圖可以顯示股票名稱

#R Code install.packages('quantmod') #安裝套件 library(quantmod) # 載入套件 #股票代號對照表-2021/02/12更新 library(readr) Snum_data <- read_csv("https://raw.githubusercontent.com/gtgrthrst/OpenData/main/%E8%82%A1%E7%A5%A8%E5%B0%8D%E7%85%A7.csv") head(Snum_data)

number name Codename date type1 type2 type3
<dbl> <chr> <chr> <chr> <chr> <chr> <chr>
1 50 元大台灣50 TW0000050004 2003/6/30 上市 NA CEOGEU
2 51 元大中型100 TW0000051002 2006/8/31 上市 NA CEOGEU
3 52 富邦科技 TW0000052000 2006/9/12 上市 NA CEOGEU
4 53 元大電子 TW0000053008 2007/7/16 上市 NA CEOGEU
5 54 元大台商50 TW0000054006 2007/7/16 上市 NA CEOGEU
6 55 元大MSCI金融 TW0000055003 2007/7/16 上市 NA CEOGEU

股票資料

抓取股票資料預設為yahoo的資料
台灣股票代碼格式為"XXXX.TW"
也可以添加src ="google"選擇Google財經的資料
也支援其他幾種資料
聖路易斯聯邦儲備銀行FRED®(11,000個經濟系列)
Oanda,貨幣網站(外彙和金屬)
MySQL數據庫(本地數據庫)
R二進制格式(.RData和.rda)
逗號分隔檔(.csv)

首先我們就先來看看台灣護國神山的股票

#R Code Snum <- 2330 #設定台灣股票代碼 #取得股票資料 Sdata <- get(getSymbols(paste0(Snum,".TW"),src="yahoo",from="2020-01-01",to=Sys.Date())) #from為起始時間 Sname <- as.character(subset(Snum_data, number == Snum)[2]) chartSeries(Sdata, name = paste0(Snum,".TW"))

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

均線(MovingAverage, MA)

全名為移動平均線
在看盤軟體中簡稱為MA
是股票技術分析中重要的參考指標之一

=N/N
使用runMean()計算均線
在使用addTA()畫上均線即可

ma20<-runMean(Sdata[,4],n=20) #20天均線 ma60<-runMean(Sdata[,4],n=60) #60天均線 addTA(ma20,on=1,col="blue") addTA(ma60,on=1,col="red")

大家若仔細看可以看到ma20與ma60的起點是不同的
主要原因就是平均資料是歷史資料
所以ma20在第20天過後才會有第一筆數值
ma60在60天過後才有

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

布林通道(Bollinger Band)

又稱為布林軌道、布林帶、布林線,是由均線和標準差組成的指標
總共有三條線:中線,上線,下線
中線就是股價的移動平均線,一般是設定為20日的移動平均線(MA20)
上線也可稱為壓力線,通常是用中線加2個標準差
下線也稱為支撐線,通常是用中線減2個標準差(sd)
上下線構成的區域就是布林通道
在R中只需要使用addBBands(n = 20, sd = 2)就可以快速添加布林通道

addBBands(n = 20, sd = 2) #布林通道

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Shiny 股票查詢網頁

最後在建立一個簡單的Shiny網站

#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 = "2010-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) 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) #布林通道 }) } # Run the application shinyApp(ui = ui, server = server)

目前上傳至shinyapps.io出現一些問題

等之後要是解決了在分享網址給大家
要是知道問題的歡迎指教

參考資料

證券編碼公告
證交所

r語言自學日記-6-移動平均-ma-與常見股票圖表繪製

Tidyquant套件介紹
指導教授: 中山大學財務管理學系 王昭文 教授
文章撰寫: 中山大學財務管理學系 蘇彥庭 研究助理

參考書籍-R語言:數學計算、統計模型與金融大數據分析(第二版)

自動查詢上市上櫃股票資訊_R語言_tryCatch()

🌟全文可以至下方連結觀看或是補充
https://hackmd.io/@LHB-0222/quantmod

全文分享至

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

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

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

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

有所錯誤歡迎指教

全部文章列表