你必須很努力

Day21 - 用 Ruby on Rails 抓臺灣證券交易所資料-除權除息計算結果表

2021/10/04
字數統計: 513閱讀時間: 2 min

前言

這篇主要以抓「臺灣證券交易所」的「除權除息計算結果表」為主

取得「除權除息計算結果表」CSV 檔

目標是從臺灣證券交易所的「除權除息計算結果表」取得每日的 CSV 檔

note: 本資訊自民國92年5月5日起提供

下載的檔案內容如下

從上面已經知道,只提供 2003-05-05 之後的檔案

實作

下載「除權除息計算結果表」時,資料日期可以直接從 2003-05-05 直接抓到最新一天,需留意時間範圍太大時,可能會遇到 read_timeout ,可選擇時間範圍別抓這麼廣,或把 read_timeout 時間拉長

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# app/features/twse/twt_49u/download.rb

module Twse::Twt49u
class Download

include Twse::Helpers

def execute
current_time = Time.current
puts "#{self.class}, start_time: #{current_time.to_s}"
start_date = find_latest_data_date(current_time)
return puts "#{self.class}, 已經是最新的資料" if start_date == false

data_path = Rails.root.join("data/twse/TWT49U")
file_path = data_path.join("TWT49U_#{start_date.strftime("%Y%m%d")}_#{current_time.strftime("%Y%m%d")}.csv")
return if File.exists?(file_path)

FileUtils.mkdir_p(data_path) unless File.directory?(data_path)

download_file(start_date, current_time, data_path, file_path)
upload_to_github
puts "#{self.class}, done_time:#{Time.current}, #{(Time.current - current_time).to_s} sec"
rescue StandardError => e
puts "errors: #{e.inspect}, backtrace: #{e.backtrace}"
end

private

def find_latest_data_date(current_time)
latest_data_date = ExStock.latest_data_date

if latest_data_date
return false if latest_data_date == current_time

latest_data_date + 1.day
else
Date.parse("2003-05-05") # 僅支援抓 2003-05-05 之後的資料
end
end

def download_file(start_date, current_time, data_path, file_path)
remote_file = Down::NetHttp.download(
"#{BASE_URL}exchangeReport/TWT49U?response=csv&strDate=#{start_date.strftime("%Y%m%d")}&endDate=#{current_time.strftime("%Y%m%d")}",
read_timeout: 120,
)

if remote_file.size < 3
FileUtils.rm_rf(remote_file.path)
else
FileUtils.mv(remote_file.path, data_path.join(file_path.basename.to_s))
end
end

end
end

小結

find_latest_data_date 中的 ExStock 為建立的 Model,這篇可以先略過,下一篇會說明 DB 的設計

有了處理「每日收盤行情」的經驗後,在處理類似的資料時,會比較快些


鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10272820
medium 文章連結:https://link.medium.com/FasXk7JuTjb
本文同步發布於 小菜的 Blog https://riverye.com/

備註:之後文章修改更新,以個人部落格為主

CATALOG
  1. 1. 前言
  2. 2. 取得「除權除息計算結果表」CSV 檔
    1. 2.1. 下載的檔案內容如下
  3. 3. 實作
  4. 4. 小結