LoginSignup
9
16

More than 3 years have passed since last update.

PythonでYahoo!ファイナンスから時系列データをダウンロードする方法

Last updated at Posted at 2019-09-28

目次

株のデータ収集についての記事一覧をこちらに記載しております。

目的

  • Yahoo!ファイナンスから東京証券取引所に上場している銘柄の時系列データをダウンロードする
  • Pythonのライブラリのインストール手順などは省略しております
  • 時系列データでは始値、高値、安値、終値、出来高、調整後終値が取得できます。 image.png

事前準備

  • Yahoo!ファイナンスVIP倶楽部に加入する。(VIP倶楽部に加入すると時系列データをcsvファイル形式でダウンロードすることが可能になります。)
  • 証券コードを取得する為に、事前に日本取引所グループから東証上場銘柄一覧をダウンロードする
  • ダウンロードした東証上場銘柄一覧のコードの列のみをコピーしてファイル名をcodeList.txtとして保存する(ヘッダー行は不要)
codeList.txt
1301
1305
1306
〜
9995
9996
9997

実装

Yahooにログインする

  • Seleniumを使ってYahooにログインします。
  • Seleniumのインストール、webdriverのダウンロードのなどの手順は省略しております。
  • Seleniumのインストール手順などはこちらのサイトが参考になります。
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox(executable_path="./geckodriver")
LOGIN_URL = "https://login.yahoo.co.jp/config/login?.src=www&.done=https://www.yahoo.co.jp"
USER_ID = "yahoo_user_id"
PASSWORD = "yahoo_password"
self.driver.get("https://www.yahoo.co.jp/")
self.driver.get(LOGIN_URL) #Yahooのログインページに遷移
self.driver.find_element_by_id("username").send_keys(USER_ID) #テキストボックスにユーザiDを入力
self.driver.find_element_by_id("btnNext").click() #次へボタンをクリック
self.driver.implicitly_wait(5) #5秒待機
self.driver.find_element_by_id("passwd").send_keys(PASSWORD) #テキストボックスにパスワードを入力
self.driver.find_element_by_id("btnSubmit").click() #ログインボタンをクリック

Yahoo!ファイナンスから時系列データをダウンロード

  • Yahoo!ファイナンスから東証に上場している銘柄の時系列データをダウンロードします。
  • Yahoo!ファイナンス!では時系列データのダウンロードページのURLは証券コードの後に市場略称を付与するルールとなっているようです。
  • Yahoo!ファイナンス!の東証の市場略称はTとなっているので、URLの最後にTを付与します。 https://www.yahoo-help.jp/app/answers/detail/p/546/a_id/45387
SECURITIES_CODE_LIST_PATH = "./codeList.txt" #事前準備で作成したcodeList.txt
with open(SECURITIES_CODE_LIST_PATH, "r") as code_list:
    for code in code_list:
        # 東証のデータのみをダウンロードするので証券コードの後にTを付与
        csv_url = "https://stocks.finance.yahoo.co.jp/stocks/history/?code={0}.T".format(code)
        self.driver.get(csv_url)
        self.driver.implicitly_wait(3)
        try:
            # 指定したURLが存在しない場合はfor文の先頭に戻る
            self.driver.find_element_by_class_name("selectFinTitle")
            time.sleep(1)
            continue
        except NoSuchElementException:
            pass
        try:
            self.driver.find_element_by_css_selector('a.stocksCsvBtn').click() #時系列データをダウンロード(CSV)のボタンをクリック
        except NoSuchElementException:
            pass
        time.sleep(5)

9
16
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
16