ラベル fix_yahoo_finance の投稿を表示しています。 すべての投稿を表示
ラベル fix_yahoo_finance の投稿を表示しています。 すべての投稿を表示

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

2019年5月13日月曜日

DockerでJupyter LabとYahoo! Finance Fix for Pandas Datareader、ipython-sql、PostgreSQL11がインストールされたコンテナを作成する

Jupyter LabとYahoo! Finance Fix for Pandas Datareader、ipython-sql、PostgreSQLでPythonとSQLが使用できる環境を提供する事ができます。

〇Jupyter Labの実行画面


〇構築方法
1. イメージの作成
docker build -t jupyter-pg-yf .

Dockerfile
FROM jupyter/scipy-notebook
ENV TZ=Asia/Tokyo
USER root
RUN apt-get update \
  && apt-get -y install libpq-dev python-dev \
  && pip install psycopg2-binary \
  && pip install ipython-sql \
  && pip install mpl_finance \
  && pip install fix_yahoo_finance --upgrade --no-cache-dir \
  && apt-get clean
USER $NB_UID

2. Jupyter NotebookとPostgreSQLコンテナの構築・実行(docker-compose.ymlがあるフォルダで実行)
docker-compose up -d

docker-compose.yml
version: "2"
services:
  jupyter-pg-iexfinance:
    image: jupyter-pg-yf
    container_name: "jupyter-pg-yf"
    volumes:
      - "jupyter-data:/home/jovyan/work"
    ports:
      - "8888:8888"
    environment:
      JUPYTER_TOKEN: jupyter
      JUPYTER_ENABLE_LAB: 1
    depends_on:
      - db
  db:
    image: postgres:11-alpine
    container_name: "test-db"
    ports:
      - "5432:5432"
    volumes:
      - "db-data:/var/lib/postgresql/data"
    environment:
        POSTGRES_DB: test
        POSTGRES_PASSWORD: test
volumes:
  db-data:
    driver: local
  jupyter-data:
    driver: local

3.ブラウザから以下のURLにアクセス
http://<Dockerホスト名またはIP>:8888/?token=jupyter

〇動作検証用コード
%load_ext sql
dsl = 'postgres://postgres:test@db:5432/test'
%sql $dsl

%%sql
select * from pg_database;


○関連情報
・psycopg2に関する他の記事はこちらを参照してください。

jupyterとYahoo! Finance Fix for Pandas Datareaderで米国株価データを取得して、ローソク足グラフを描画する

以下のコードでYahoo! Finance Fix for Pandas Datareaderを使用して米国株価データを取得して、ローソク足グラフを描画する事ができます。

〇出力グラフ


〇コード
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("AAPL", start="2019-01-01", end="2019-05-10")
df = df.reset_index()
df['datenum'] = df['Date'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
df = df.set_index('datenum').drop(columns="Date")

fig = plt.figure()
ax = plt.subplot()

numrows = len(df)
ohlc = np.vstack((range(numrows), df.values.T)).T
candlestick_ohlc(ax, ohlc, width=0.8, colorup='g', colordown='r')
offset_mon = (5-mdates.num2date(df.index[0]).weekday())%5
plt.xticks(range(offset_mon,numrows,5), [mdates.num2date(x).strftime("%Y-%m-%d") for x in df.index][offset_mon::5])
ax.grid(True)
ax.set_xlim(-1, numrows)
fig.autofmt_xdate()

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