4
2

More than 1 year has passed since last update.

investypyで日ごとの株価をグラフ化する。

Posted at

環境

Python version:3.9.7
OS: windows 10.0
Anaconda:conda 4.11.0

実装したかったこと

・日ごとのデータをグラフ化したかった。

code

investpyについての説明は、一番下のリンクを参照してください。
data_get.pyでは、form date,to date までの日ごとの株価変動を取得しています。codeについては、上場している会社のコードを入力します。
結果をcsvファイルとして出力します。実際使ってみて改良していきます。

data_get.py
import pandas as pd
import investpy
import datetime
import os

now = datetime.datetime.now()
today = now.strftime("%d/%m/%Y")

#変数定義
code        = '6724'
company     = 'seiko_epson'
performance = 'term_price'

#フォルダ作成
os.makedirs('log/' + code + '_' + company , exist_ok=True)

#会社業績(会社業績)
term_price  = 'Ture'

if term_price:
    stock_data = investpy.get_stock_historical_data(stock=code, country='japan', from_date='01/01/2010', to_date=today)
    #csvの出力
    stock_data.to_csv('log/' + code + '_' + company + '/' + performance +'.csv')

次に、csvファイルを読み込み、グラフ化します。ここでは、単年の月ごとの変動を画像ファイルにして、さらに12月分のグラフを1つの画像ファイルにしています。
株価のmin,maxは、その年のmix,maxが含まれるようにしています。

make_graff.py
import pandas as pd
import datetime
import csv
import os
import matplotlib.pyplot as plt
import cv2
#user define 
import graff

#変数定義
code        = '6724'
company     = 'seiko_epson'
performance = 'term_price'
year        = '2021'
put_img_folder = ('log/' + code + '_' + company + '/' + year)
#month       = '01'
#m1_s=[num for num in range(13)]
infile=[num for num in range(13)]


def concat_tile(im_list_2d):
    return cv2.vconcat([cv2.hconcat(im_list_h) for im_list_h in im_list_2d])

for i in range(12):
    i = i + 1
    month = str(i).zfill(2)

    y_m         = (year + '-' +month)

    graff_fig_save_file = ( put_img_folder + '/' + y_m +'.png')

    #フォルダ作成
    os.makedirs( put_img_folder , exist_ok=True)

    df = pd.read_csv('log/' + code + '_' + company + '/' + performance +'.csv') 

    df_year_month = df[df['Date'].str.contains(year)]    
    y_min         = df_year_month['Low'].min()
    y_max         = df_year_month['High'].max()
    df_year_month = df[df['Date'].str.contains(y_m)]
    #print(df_year_month.tail(5))

    xl    = df_year_month['Date']

    yl1   = df_year_month['Open']
    yl2   = df_year_month['High']
    yl3   = df_year_month['Low']
    yl4   = df_year_month['Close']

    yl2_1 = df_year_month['Volume']

    stock_data_class = graff.stock_data_graff() #instance
    stock_data_class.d_stock(y_m, xl, yl1, yl2, yl3, yl4, yl2_1, y_min, y_max,graff_fig_save_file)

#画像ファイル

for i in range(12):
    month = str(i+1).zfill(2)
    y_m         = (year + '-' +month)
    graff_fig_save_file = ( put_img_folder + '/' + y_m +'.png')
    infile[i] = cv2.imread(graff_fig_save_file)

#サイズそのまま
im_tile = concat_tile([[ infile[0],  infile[1],  infile[2]],  
                                        [ infile[3],  infile[4],  infile[5]],
                                        [ infile[6],  infile[7],  infile[8]],
                                        [ infile[9], infile[10], infile[11]]])

cv2.imwrite(put_img_folder + '/' + year + '.png', im_tile)

graff.pyでは、単年の月ごとの変動を画像ファイルにしています。

graff.py
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import math

class  stock_data_graff:

    def __init__(self) : 
        self.stock_date  = 0        

    def d_stock(self, date_term, xxl, yyl1, yyl2, yyl3, yyl4, yyl2_1, yl3_min, yl2_max, save_file) :

        #max,minの計算
        #yl3_min = yyl3.min() 
        #yl2_max = yyl2.max() 
        y1_min = math.floor(yl3_min / 100) * 100
        y1_max = math.ceil(yl2_max  / 100) * 100

        # Figureを設定
        fig = plt.figure()
        fig = plt.figure(figsize=(8,6))

        # Axesを追加
        ax1 = fig.add_subplot(111)

        plt.xticks(rotation=45)

        ax1.set_title(date_term)
        ax1.set_xlabel('Date')
        ax1.set_ylabel('stock plice')

        ax1.plot(xxl, yyl1,color = "green",  linestyle = "solid",  label = "Open")
        ax1.plot(xxl, yyl2,color = "red",    linestyle = "dashed", label = "High")
        ax1.plot(xxl, yyl3,color = "blue",   linestyle = "dashed", label = "Low")
        ax1.plot(xxl, yyl4,color = "orange", linestyle = "solid",  label = "Close")

        #Add bar for 2rd label
        ax2 = ax1.twinx()
        ax2.bar(xxl,yyl2_1,color="lightblue",label="Volume")
        #X軸レンジ調整
        ax2.xaxis.set_major_locator(mdates.DayLocator(interval=3))
        #ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))

        #Swap before and after the graph
        ax1.set_zorder(2)
        ax2.set_zorder(1)
        ax1.patch.set_alpha(0)
        ax1.grid(True)  # grid 表示 ON
        plt.ticklabel_format(style='plain',axis='y')
        plt.rcParams['figure.subplot.bottom'] = 0.1 #下端の調整

        ax1.set_ylim(y1_min,y1_max)
        ax2.set_ylim(0,10000000)

        plt.show()

        #画像の保存
        fig.savefig(save_file)

link

参考にしたサイトは、こちらです。
https://qiita.com/matsxxx/items/f7c50b88f0b6d1c9e4d5

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