iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
自我挑戰組

Ruby on Rails 與它們相關的東西 II系列 第 21

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

前言

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

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

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

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

下載的檔案內容如下

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

實作

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

# 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/

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


上一篇
Day20 - 用 Ruby on Rails 抓臺灣證券交易所資料-每日收盤行情
下一篇
Day22 - 用 Ruby on Rails 處理臺灣證券交易所資料-DB 設計
系列文
Ruby on Rails 與它們相關的東西 II30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言