Streamlitで自作株価ダッシュボードをWeb公開する方法

自動化・運用

Streamlitを使えばPythonだけで本格的なWebダッシュボードを作れます。コーディング5分、デプロイ5分で自分だけの株価分析ダッシュボードをインターネットに公開できます。

インストール

pip install streamlit yfinance pandas plotly

シンプルな株価チャートアプリ

import streamlit as st
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import numpy as np

st.set_page_config(
    page_title="株価分析ダッシュボード",
    page_icon="📈",
    layout="wide"
)

st.title("📈 株価分析ダッシュボード")
st.markdown("yfinanceを使ったリアルタイム株価分析ツール")

# サイドバー設定
with st.sidebar:
    st.header("設定")
    ticker = st.text_input("銘柄コード", value="7203.T", help="日本株: 7203.T, 米国株: AAPL")
    period = st.selectbox("取得期間", ["1mo", "3mo", "6mo", "1y", "2y", "5y"], index=3)
    interval = st.selectbox("足種", ["1d", "1wk", "1mo"], index=0)
    show_ma = st.checkbox("移動平均を表示", value=True)
    show_bb = st.checkbox("ボリンジャーバンドを表示", value=False)

# データ取得
with st.spinner("データ取得中..."):
    df = yf.download(ticker, period=period, interval=interval, progress=False, auto_adjust=True)

if df.empty:
    st.error("データを取得できませんでした")
    st.stop()

# 基本情報
info = yf.Ticker(ticker).info
col1, col2, col3, col4 = st.columns(4)
with col1:
    current = float(df["Close"].iloc[-1])
    prev = float(df["Close"].iloc[-2])
    change = (current / prev - 1) * 100
    st.metric("現在値", f"{current:,.2f}", f"{change:+.2f}%")
with col2:
    st.metric("52週高値", f"{info.get('fiftyTwoWeekHigh', 'N/A')}")
with col3:
    st.metric("52週安値", f"{info.get('fiftyTwoWeekLow', 'N/A')}")
with col4:
    per = info.get("trailingPE")
    st.metric("PER", f"{per:.1f}倍" if per else "N/A")

ローソク足チャートとテクニカル指標

# ローソク足チャート(Plotly使用)
fig = go.Figure()

# ローソク足
fig.add_trace(go.Candlestick(
    x=df.index,
    open=df["Open"], high=df["High"],
    low=df["Low"], close=df["Close"],
    name="OHLC"
))

if show_ma:
    for period_ma, color in [(25, "blue"), (75, "orange"), (200, "red")]:
        if len(df) >= period_ma:
            ma = df["Close"].rolling(period_ma).mean()
            fig.add_trace(go.Scatter(
                x=df.index, y=ma,
                name=f"MA{period_ma}", line=dict(color=color, width=1)
            ))

if show_bb:
    ma20 = df["Close"].rolling(20).mean()
    std20 = df["Close"].rolling(20).std()
    fig.add_trace(go.Scatter(x=df.index, y=ma20+2*std20, name="BB上限",
                             line=dict(color="gray", dash="dash")))
    fig.add_trace(go.Scatter(x=df.index, y=ma20-2*std20, name="BB下限",
                             line=dict(color="gray", dash="dash"),
                             fill="tonexty", fillcolor="rgba(0,0,0,0.05)"))

fig.update_layout(
    title=f"{ticker} 株価チャート",
    xaxis_rangeslider_visible=False,
    height=500
)
st.plotly_chart(fig, use_container_width=True)

# RSIチャート
delta = df["Close"].diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
rsi = 100 - (100 / (1 + gain / loss))

fig_rsi = go.Figure()
fig_rsi.add_trace(go.Scatter(x=df.index, y=rsi, name="RSI", line=dict(color="purple")))
fig_rsi.add_hline(y=70, line_dash="dash", line_color="red", annotation_text="買われすぎ(70)")
fig_rsi.add_hline(y=30, line_dash="dash", line_color="green", annotation_text="売られすぎ(30)")
fig_rsi.update_layout(title="RSI", height=250)
st.plotly_chart(fig_rsi, use_container_width=True)

複数銘柄比較タブ

st.subheader("複数銘柄比較")
compare_tickers = st.text_input("比較する銘柄(カンマ区切り)", "7203.T, 9984.T, AAPL")
tickers_list = [t.strip() for t in compare_tickers.split(",")]

if st.button("比較する"):
    with st.spinner("データ取得中..."):
        data = yf.download(tickers_list, period="1y", progress=False)["Close"]
    
    normalized = data / data.iloc[0] * 100
    fig_compare = px.line(normalized, title="累積リターン比較(初期値=100)")
    st.plotly_chart(fig_compare, use_container_width=True)
    
    returns = data.pct_change().dropna()
    stats = pd.DataFrame({
        "年率リターン": (returns.mean() * 252 * 100).round(1),
        "ボラティリティ": (returns.std() * 252**0.5 * 100).round(1),
        "シャープ比": ((returns.mean() * 252) / (returns.std() * 252**0.5)).round(2),
    })
    st.dataframe(stats)

Streamlit Cloudへのデプロイ(無料)

  1. GitHubにリポジトリを作成してコードをpush
  2. Streamlit CloudにGitHubアカウントでサインイン
  3. 「New app」→ リポジトリ・ファイル名を選択
  4. 「Deploy!」をクリックするだけで公開完了

無料枠でも無制限のアプリを公開できます(アクセスが少ないとスリープ状態になる場合あり)。

まとめ

StreamlitはPythonだけで高品質なWebダッシュボードが作れる最強ライブラリです。Streamlit Cloudへのデプロイも無料かつ数分で完了します。自分だけの株価分析ツールをWeb公開してみましょう。

タイトルとURLをコピーしました