株のシステムトレードをしよう - 1から始める株自動取引システムの作り方

株式をコンピュータに売買させる仕組みを少しずつ作っていきます。できあがってから公開ではなく、書いたら途中でも記事として即掲載して、後から固定ページにして体裁を整える方式で進めていきます。

kaleidoのインポートができず、plotlyのグラフ画像をエクスポートできない

下記のようなエラーが出て困っている。kaleidoはpipでインストールしてあると思ってるんだけどなぁ。

ValueError: 
Image export using the "kaleido" engine requires the kaleido package,
which can be installed using pip:
    $ pip install -U kaleido
# %%
filepath = './data/日経225mini 歩み値(ティック) (2022 08).zip'

# %%
%pip install mplfinance
import mplfinance as mpf

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

%pip install plotly
%pip install kaleido
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
 
tips = sns.load_dataset('tips')

# %%
import pandas as pd

# %%


# %%
reset_df = '_df_original' in globals()

dtype = {
  'trade_date': str,
  'make_date': str,
  'index_type': 'uint8',
  'security_code': str,
  'time': str,
  'trade_price': 'float32',
  'price_type': str,
  'trade_volume': 'uint32',
  'no': 'uint32',
  'contract_month': str,
}

if not reset_df:
  _df_original = pd.read_csv(filepath, dtype=dtype)
df = _df_original.copy()

# %%
def parse_date(df):
  df.trade_date = pd.to_datetime(df.trade_date + 'T' + df.time, format='%Y%m%dT%H%M%S%f')
  df.make_date = pd.to_datetime(df.make_date + 'T' + df.time, format='%Y%m%dT%H%M%S%f')
  df.index = df.make_date
  return df
df = parse_date(df)

# %%
df

# %%
def convert_into_ohlcv(df, frequency: str) -> pd.DataFrame:
  ohlcv = df.trade_price.resample(frequency).ohlc()
  ohlcv['volume'] = df.trade_volume.resample(frequency).sum()
  return ohlcv
ohlcv = convert_into_ohlcv(df, 'S')
ohlcv

# %%
def show_by_seaborn(df, x, y, hue=None, kind='line', **kwargs):
  sns.scatterplot(data=df, x=x, y=y, hue=hue, **kwargs)
  #sns.lineplot(data=df, x=x, y=y, hue=hue, **kwargs)
  plt.show()
# show_by_seaborn(df, df.index, df.trade_price)
show_by_seaborn(ohlcv, 'make_date', 'open')

# %%
ohlcv_H = convert_into_ohlcv(df, 'H')
ohlcv_H

# %%
df.sort_index().loc['2022-08-01':'2022-08-07', :]

# %%
def plotly_candlestick(df, title=None, save_fig=False, filename=None):
  '''
  https://stackoverflow.com/a/65997291/15983717
  '''
  # plotly = go.Figure(data=go.Candlestick(x=df.index, open=df.open, high=df.high, low=df.low, close=df.close))
  # Plot OHLC on 1st row
  plotly = make_subplots(rows=2, cols=1, shared_xaxes=True, 
            vertical_spacing=0.03, subplot_titles=('OHLC', 'Volume'), 
            row_width=[0.2, 0.7])
  plotly.add_trace(go.Candlestick(
    x=df.index, open=df.open, high=df.high, low=df.low, close=df.close, name='OHLC'), row=1, col=1)
  # Bar trace for volumes on 2nd row without legend
  plotly.add_trace(go.Bar(x=df.index, y=df.volume, showlegend=False), row=2, col=1)
  plotly.update_layout(  # https://qiita.com/Ringa_hyj/items/b13e3e721519c2842cc9
      xaxis=dict(
          rangeselector=dict(
              buttons=list([
                  dict(count=1,
                       label="1m",
                       step="month",
                       stepmode="backward"),
                  dict(count=6,
                       label="6m",
                       step="month",
                       stepmode="backward"),
                  dict(count=1,
                       label="YTD",
                       step="year",
                       stepmode="todate"),
                  dict(count=1,
                       label="1y",
                       step="year",
                       stepmode="backward"),
                  dict(step="all")
              ])
          ),
          rangeslider=dict(
              visible=True
          ),
          type="date"
      )
  )
  #plotly.update(layout_xaxis_rangeslider_visible=True)
  if save_fig:
    plotly.write_html(f'figures/figure_{filename}.html')
    # https://zenn.dev/ganariya/articles/plotly-high-resolution
    plotly.write_image(f'figures/figure_{filename}.png', engine="kaleido", scale=10)
  else:
    plotly.show()
# plotly_candlestick(convert_into_ohlcv(df.sort_index().loc['2022-08-01':'2022-08-07', :], '1min'))
for date in range(1, 31 + 1):
  fulldate = f'2022-08-{date:02}'
  print(f'{date:02}')
  plotly_candlestick(
    convert_into_ohlcv(
      df.sort_index().loc[fulldate], '2S'
    ),
    save_fig=True, title=fulldate, filename=fulldate
  )

(C) 2020 dogwood008 禁無断転載 不許複製 Reprinting, reproducing are prohibited.