LoginSignup
0
4

More than 1 year has passed since last update.

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

Last updated at Posted at 2021-11-21

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

はじめに

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

  • 取得したい銘柄のコードをPythonコードの中に直に書いている

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

  • Excel ファイルにある銘柄一覧から株価データを取得するコード

Pandas の read_excel で Excel 読み込みが簡単にできる

まずは Excel ファイルを用意する

用意した Excel ファイルは,
A列に銘柄コード(列名: code),B列に銘柄名(列名: company)となっている
image.png
pandas を import し,

import pandas as pd;

あとは,read_excel で読み込んだ銘柄コード列,銘柄名列をそれぞれリストに変換

df = pd.read_excel('step04.xlsx', sheet_name = 'Sheet1', dtype = str);
codeList = df['code'].tolist();
companyList = df['company'].tolist();

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

step04.py
import pandas as pd;
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__':
    df = pd.read_excel('step04.xlsx', sheet_name = 'Sheet1', dtype = str);
    codeList = df['code'].tolist();
    companyList = df['company'].tolist();
    main(codeList, companyList);

実行した結果は次のようだ

❯ python step04.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]

おわりに

Excel ファイルに書かれた銘柄の
1年前から現在までの期間で株価データを取得することができた

便利すぎるぜ,Python

株価値動き分析のための,最初の一歩を踏み出せた気がする

今後は,

  • ローソク足
  • MACD
  • 一目均衡表
  • ボリンジャーバンド

などのチャートを描き,
売買のタイミングを教えてくれるようなコードを書いてみるつもりだ

0
4
2

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
4