LoginSignup
0
2

More than 1 year has passed since last update.

【Python】Pandas で株価データを取得する(その3)

Posted at

はじめに

前回書いた株価データを取得するコードは問題があった

  • 株価データ取得期間が固定
  • 取得したい銘柄のコードをPythonコードの中に直に書いている

今回は,前回のコードを次のように書きかえてみる

  • 1年前から現在までの期間で株価データを取得するコード

dateutil.relativedelta で,N日前の日付を求める

N日前の日付を求めるには,dateutil.relativedelta を使うのが便利そうだ
dateutil.relativedelta の動作を確認してみる

本日2021/11/21の1年前(12か月前)を求めるのは次のようだ

>>> st = datetime.datetime.now() - relativedelta(months = 12);
>>> st.year, st.month, st.day
(2020, 11, 21)

現在日時を返す getToday 関数と,
指定の日時からのNか月前を返す getMonthAgo 関数を用意する

def getToday():
    return datetime.datetime.now();

def getMonthAgo(day, month):
    return (day - relativedelta(months = month));

main 関数内で,getToday 関数,getMonthAgo 関数を使い,
データ取得の期間を設定している
print 関数で,銘柄のコードとデータ取得期間の開始と終了を出力している

def main(codeList, companyList):
    ed = getToday();
    st = getMonthAgo(ed, 12);
    for code, company in zip(codeList, companyList):
        df = pdr.DataReader(code + '.T', 'yahoo', st, ed);
        print('%s [%s]-[%s]' % (company, df.head(1).index[-1], df.tail(1).index[-1]));

まとめると,次のようなコードになる

step03.py
import pandas_datareader.data as pdr
import datetime;
from dateutil.relativedelta import relativedelta;

def getToday():
    return datetime.datetime.now();

def getMonthAgo(day, month):
    return (day - relativedelta(months = month));

def main(codeList, companyList):
    ed = getToday();
    st = getMonthAgo(ed, 12);
    for code, company in zip(codeList, companyList):
        df = pdr.DataReader(code + '.T', 'yahoo', st, ed);
        print('%s [%s]-[%s]' % (company, df.head(1).index[-1], df.tail(1).index[-1]));

if __name__ == '__main__':
    codeList = ['7203', '7201', '7267'];
    companyList = ['トヨタ', '日産', 'ホンダ'];
    main(codeList, companyList);

実行した結果は次のようだ
2020年11月20日から2020年11月23日はマーケットはお休みなので,
2020年11月24日からのデータが取得できたことがわかる

❯ python step03.py
トヨタ [2020-11-24 00:00:00]-[2021-11-19 00:00:00]
日産 [2020-11-24 00:00:00]-[2021-11-19 00:00:00]
ホンダ [2020-11-24 00:00:00]-[2021-11-19 00:00:00]

おわりに

1年前から現在までの期間で株価データを取得することができた

次回は,次のようなコードを書いてみよう

  • 取得する銘柄コードをExcelファイルで用意し,Excelファイルを読み込み株価データが取得できるコード
0
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
0
2