0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Streamlitによる為替チャートの作成

0
Posted at

UdemyでStreamlitの講座を受講しました。
講座内では、簡単な株価のグラフ表示アプリの説明でしたが
応用として為替のチャートの作成をしてみました。

Streamlitのインストール

インストールについては、以下の記事が参考になるかと思います。

為替データの取得

為替データは、Yahooファイナンスより、yfinanceにて取得します。
(以前紹介したDataReaderより、少し詳しいデータが取れますが為替データについてはあまり違いがないようです。)

↓20日間のUSDJPYの為替データの取得


import yfinance as yf

usd = yf.Ticker('USDJPY=X')
days = 20
hist = usd.history(period=f'{days}d')

為替データの整形

取得する日数(days)、通過ペア(countries)を画面で指定できるようにした上で、以下の関数の整形を行う。

def get_data(days, countries,targets):
    df2 = pd.DataFrame()
    for target in targets:
        df = pd.DataFrame()
        for country in countries:
            tkr = yf.Ticker(tickers[country])
            hist = tkr.history(period=f'{days}d')
            hist.index = hist.index.strftime('%d %B %Y')
            hist = hist[[target]]
            hist.columns = [country]
            hist = hist.T
            hist.index.name = 'Name'
            df = pd.concat([df, hist])
        
        df = df.T.reset_index()
        
        df = pd.melt(df, id_vars=['index']).rename(
            columns={'value': target}
        )
        if target == 'Open':
            df2 = df
        else:
            df2 = pd.concat([df2,df[target]],axis=1)
        
    return df2

チャートの描写

チャートの描写には、altairを使いチャートを作成する。


        open_close_color = alt.condition("datum.Open <= datum.Close",
                                 alt.value("#06982d"),
                                 alt.value("#ae1325"))

        base = alt.Chart(df).encode(
            alt.X('Date:T',
                axis=alt.Axis(
                    format='%m/%d',
                    labelAngle=-45,
                    title='Date in 2021'
                )
            ),
            color=open_close_color
        )

        rule = base.mark_rule().encode(
            alt.Y(
                'Low:Q',
                title='Price',
                scale=alt.Scale(zero=False),
            ),
            alt.Y2('High:Q')
        )       

        bar = base.mark_bar().encode(
            alt.Y('Open:Q'),
            alt.Y2('Close:Q')
        )
        st.altair_chart(rule+bar, use_container_width=True)

作成した画面は、下のような感じです。
streamlit.jpg

とりあえず、今回は試してみましたというところです。
時間があれば、分析用の機能などつけて見ようと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?