2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】pandas_datareaderで株価取得

Last updated at Posted at 2021-10-31

概要

Pythonを使って株価データを取得します。
取得元はStooqからとし、pandas_datareader.stooqを使うと日足データが得られます。
株価データの保存形式はCSVです。

ソースコード

重要なのは、GetStockPriceの最後3行。
コマンドライン引数でデータ開始時刻と終了時刻は入力必須(YYYYMMDD形式)です。
オプションで銘柄と保存ファイルパスを指定してください。

downloadStooq.py
import argparse
import pandas_datareader.stooq as web

from datetime import datetime


def main():
    args = Parse()

    GetStockPrice(args)

    return
    
    

def Parse():
    """
    Get CommandLine Arguments
    
    Note:
        Input Date: YYYYMMDD
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("start", type=str)
    parser.add_argument("end", type=str)
    parser.add_argument("-b", "--brand", type=str, default="TSLA")
    parser.add_argument("-s", "--savePath", type=str, default="./stock.csv")
    args = parser.parse_args()

    return args



def GetStockPrice(args):
    """
    Get Daily Stock Price Between $start and $end

    Args:
        args (argparse): CommandLine Arguments
    """

    # str -> datetime
    start = datetime.strptime(args.start, "%Y%m%d")
    end = datetime.strptime(args.end,  "%Y%m%d")

    # データ読み込み&保存
    data = web.StooqDailyReader(args.brand, start=start, end=end)
    reader = data.read()
    reader.to_csv(args.savePath)
    
    return


    
if __name__ == "__main__":
    main()

使い方(例)

bash
python downloadStooq.py 20210101 20210930 -b AAPL -s test.csv

詳細

GitHubに置いています。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?