2019年5月16日木曜日

JupyterとYahoo! Finance Fix for Pandas Datareaderでダウ平均、S&P500、NASDAQ総合指数、日経平均を取得してグラフを描画する

以下のコードでYahoo! Finance Fix for Pandas Datareaderを使用してダウ平均、S&P500、NASDAQ総合指数、日経平均を取得して、グラフを描画する事ができます。

〇出力グラフ


〇サンプルコード
import matplotlib.pyplot as plt
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
import numpy as np
from datetime import datetime
import fix_yahoo_finance as yf
print("fix_yahoo_finance:" +yf.__version__)


df = yf.download("^DJI ^GSPC ^IXIC ^N225", start="2019-01-01", end="2019-05-10")
df = df['Adj Close'].reset_index()
df['datenum'] = df['Date'].apply(lambda date: mdates.date2num(date.to_pydatetime()))

numrows = len(df)
offset_mon = (5-mdates.num2date(df['datenum'][0]).weekday())%5
plt.plot(df.index, df['^DJI'], color = 'red', label = 'Dow Jones Industrial Average')
plt.plot(df.index, df['^GSPC'], color = 'blue', label = 'S&P 500 Index')
plt.plot(df.index, df['^IXIC'], color = 'green', label = 'NASDAQ Composite Index')
plt.plot(df.index, df['^N225'], color = 'yellow', label = 'Nikkei 225')
plt.xticks(range(offset_mon,numrows,5), [mdates.num2date(x).strftime("%Y-%m-%d") for x in df['datenum'][offset_mon::5]], rotation=50)
plt.legend(bbox_to_anchor=(0.5, -0.3))
ax = plt.subplot(1,1,1)
ax.grid(True)

〇必要パッケージのインストール
pip install mpl_finance
pip install fix_yahoo_finance --upgrade --no-cache-dir

0 件のコメント:

コメントを投稿