Intermediate

Live Dashboard

Create a Streamlit dashboard with real-time stock data, prediction charts, technical indicator overlays, and configurable price alerts.

Streamlit Dashboard

# app/dashboard.py
import streamlit as st
import plotly.graph_objects as go
import pandas as pd
from app.data_collector import StockDataCollector
from app.indicators import TechnicalIndicators
from app.model import StockPredictor

st.set_page_config(page_title="Stock Predictor", layout="wide")
st.title("📈 Stock Prediction Dashboard")

# Sidebar controls
ticker = st.sidebar.text_input("Ticker Symbol", "AAPL")
days = st.sidebar.slider("History (days)", 90, 730, 365)
show_indicators = st.sidebar.checkbox("Show Indicators", True)

@st.cache_data(ttl=3600)
def load_data(ticker, days):
    collector = StockDataCollector()
    df = collector.fetch_history(ticker, days)
    ti = TechnicalIndicators()
    df = ti.add_all(df)
    return df

df = load_data(ticker, days)

# Price chart
fig = go.Figure()
fig.add_trace(go.Candlestick(
    x=df.index, open=df["Open"], high=df["High"],
    low=df["Low"], close=df["Close"], name="Price"
))

if show_indicators:
    fig.add_trace(go.Scatter(x=df.index, y=df["sma_20"],
        name="SMA 20", line=dict(color="orange", width=1)))
    fig.add_trace(go.Scatter(x=df.index, y=df["bb_upper"],
        name="BB Upper", line=dict(color="gray", dash="dash", width=1)))
    fig.add_trace(go.Scatter(x=df.index, y=df["bb_lower"],
        name="BB Lower", line=dict(color="gray", dash="dash", width=1)))

fig.update_layout(title=f"{ticker} Price Chart", xaxis_rangeslider_visible=False)
st.plotly_chart(fig, use_container_width=True)

# Metrics
col1, col2, col3, col4 = st.columns(4)
col1.metric("Current Price", f"${df['Close'].iloc[-1]:.2f}",
    f"{df['daily_return'].iloc[-1]*100:.2f}%")
col2.metric("RSI (14)", f"{df['rsi'].iloc[-1]:.1f}")
col3.metric("20d Volatility", f"{df['volatility_20d'].iloc[-1]*100:.2f}%")
col4.metric("Volume Ratio", f"{df.get('volume_ratio', pd.Series([0])).iloc[-1]:.2f}x")

# RSI Chart
st.subheader("RSI Indicator")
fig_rsi = go.Figure()
fig_rsi.add_trace(go.Scatter(x=df.index, y=df["rsi"], name="RSI"))
fig_rsi.add_hline(y=70, line_dash="dash", line_color="red")
fig_rsi.add_hline(y=30, line_dash="dash", line_color="green")
st.plotly_chart(fig_rsi, use_container_width=True)

# Prediction (if model exists)
if st.sidebar.button("Run Prediction"):
    with st.spinner("Training model..."):
        predictor = StockPredictor()
        metrics = predictor.train(df, epochs=30)
        preds = predictor.predict(df)
        st.success(f"Model trained. Val loss: {metrics['val_loss']:.6f}")
        st.line_chart(pd.DataFrame({
            "Actual": df["Close"].values[-len(preds):],
            "Predicted": preds
        }))

Running the Dashboard

# Start the dashboard
streamlit run app/dashboard.py

# Access at http://localhost:8501
💡
Caching: @st.cache_data(ttl=3600) caches data for 1 hour, preventing redundant API calls on every interaction. Use ttl=0 during development for fresh data.

Key Takeaways

  • Streamlit creates interactive dashboards with just Python — no frontend framework needed.
  • Plotly candlestick charts provide professional-quality financial visualizations.
  • Caching prevents redundant API calls and speeds up dashboard interactions.
  • Sidebar controls let users explore different tickers and timeframes interactively.