LoginSignup
7
18

More than 3 years have passed since last update.

pythonで日本株価データをダウンロードしてくる

Posted at

Summary

スクレイピングなしで株式投資メモから株価情報をダウンロードするスクリプトを書いた。

使用法

python ./stockDownload.py -c 7203

7203 トヨタ自動車(株)の2019年の日足データがcsvでダウンロードできる。
ダウンロード成功ならばCode: 7203 download finished.、失敗ならばCode: not valid.と返す。

動機

Yahoo! financeからスクレイピングは禁止されている。株価情報を株式投資メモからスクレイピングする方法は公開されていた 1 が、フォーマットが変更されれパースが上手く行かなくなる可能性がある。一方で、サイト内にダウンロードボタンがあるため、そちらを上手く活用できないか調査していた。

ダウンロードがどのように行われているか

ダウンロードボタンを押した後、google developer toolのnetworkタブから解析した。
https://kabuoji3.com/stock/file.phpにdataをPOSTしているらしい。

kabuoji3_POST_edit.png

調整が必要な部分

  • スクリプトのfullNameが保存先となるので適宜変更。
  • headerがないと403エラーとなるため、user-agent をgoogle developer toolで確認しておく。2
  • sleep(3)を入れているのは、過度なサーバー負荷回避のため。

スクリプト

stockDownload.py
#!/usr/bin/env python

import requests
import re
import click
from time import sleep

@click.command()
@click.option("--code", "-c", "code", required=True,
        help="Stock code to download.")
def main(code):
    year = "2019"
    session = requests.Session()
    headers = {
                "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36"
                }
    data = {
            "code":code,
            "year":year,
            "csv":""
            }
    url = "https://kabuoji3.com/stock/file.php"
    res = session.post(url, data=data, headers=headers)
    try:
        contentDisposition = res.headers['Content-Disposition']
        fileName = re.findall(r'\"(.+?)\"', contentDisposition)[0]
        fullName = ~/Documents/projects/ipo/data/stock/{}".format(fileName)
        with open(fullName, "wb") as saveFile:
                saveFile.write(res.content)
        print("Code: {} download finished.".format(code))
    except KeyError:
        print("Code: {} not valid.".format(code))
    sleep(3)

if __name__ == '__main__':
    main()

諸感

初めてclickを使ってcliを作成した。sys.argvよりは読みやすい気がする。
あとは、shell のcat code | while read line: do python ./stockDownload.py -c $line; doneで回すだけ。
cp932エンコードなのでnkfなりで変換する必要がある。

参考資料

【Python】requestsでボタンを擬似クリック
How to Write Python Command-Line Interfaces like a Pro

7
18
0

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
7
18