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/

备注:之後文章修改更新,以个人部落格为主


<<:  [Day - 19] - Spring 例外处理之优雅化客制化错误讯息原理与设计

>>:  Day22: WAF、Firewall Manager、Shield简介

Day 17 - SwiftUI开发学习1(按钮)

我们统整一下前16天的内容,我们花了很多的时间学习swift语言的基本,学完语言之後我们要开始进入到...

GPU程序设计(5) -- Python

前言 前面我们介绍C++的使用,有些读者可能会希望使用Python撰写(包括我),因此,我们就来看看...

Day 4 基本 flask 函式 (1)

前言 昨天提到了一些 flask 的例子,而今天会继续深入讨论他提供的一些函式,可以让写出来的网页有...

第四天:在 Linux 上安装 Gradle

接下来要跟大家谈谈如何在三大主流作业系统上安装 Gradle,读者可以依据自己习惯使用的作业系统跟着...

[Python 爬虫这样学,一定是大拇指拉!] DAY17 - 爬虫事前准备

爬虫事前准备 本篇章之後将进入爬虫环节,但开始撰写程序前,我们先来安装会使用的套件吧! 本系列文将使...