I want an dashboard where I can visualise stocks and monitor trading strategies
To upload files, please first save the app
import streamlit as st
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime, timedelta
import numpy as np
import ta
# Page config
st.set_page_config(page_title="Stock Trading Dashboard", layout="wide")
# Title
st.title("📈 Stock Trading Dashboard")
# Sidebar
st.sidebar.header("Dashboard Settings")
# Stock symbol input
symbol = st.sidebar.text_input("Enter Stock Symbol (e.g., AAPL)", value="AAPL")
# Date range selection
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
date_range = st.sidebar.date_input(
"Select Date Range",
value=(start_date, end_date),
max_value=end_date
)
# Technical indicators selection
st.sidebar.subheader("Technical Indicators")
show_sma = st.sidebar.checkbox("Show SMA", value=True)
show_ema = st.sidebar.checkbox("Show EMA", value=True)
show_bollinger = st.sidebar.checkbox("Show Bollinger Bands", value=True)
show_rsi = st.sidebar.checkbox("Show RSI", value=True)
# Fetch data
@st.cache_data(ttl=3600)
def fetch_stock_data(symbol, start_date, end_date):
try:
stock = yf.Ticker(symbol)
df = stock.history(start=start_date, end=end_date)
return df
except Exception as e:
st.error(f"Error fetching data: {e}")
return None
# Main content
col1, col2 = st.columns([2, 1])
with col1:
df = fetch_stock_data(symbol, date_range[0], date_range[1])
if df is not None and not df.empty:
# Create candlestick chart
fig = go.Figure(data=[go.Candlestick(x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'])])
# Add technical indicators
if show_sma:
sma_20 = ta.trend.sma_indicator(df['Close'], window=20)
sma_50 = ta.trend.sma_indicator(df['Close'], window=50)
fig.add_trace(go.Scatter(x=df.index, y=sma_20, name='SMA 20', line=dict(color='orange')))
fig.add_trace(go.Scatter(x=df.index, y=sma_50, name='SMA 50', line=dict(color='blue')))
if show_ema:
ema_20 = ta.trend.ema_indicator(df['Close'], window=20)
fig.add_trace(go.Scatter(x=df.index, y=ema_20, name='EMA 20', line=dict(color='purple')))
if show_bollinger:
bollinger = ta.volatility.BollingerBands(df['Close'])
fig.add_trace(go.Scatter(x=df.index, y=bollinger.bollinger_hband(), name='Bollinger High',
line=dict(color='gray', dash='dash')))
fig.add_trace(go.Scatter(x=df.index, y=bollinger.bollinger_lband(), name='Bollinger Low',
line=dict(color='gray', dash='dash')))
fig.update_layout(title=f'{symbol} Stock Price',
yaxis_title='Price',
xaxis_title='Date',
template='plotly_white')
st.plotly_chart(fig, use_container_width=True)
if show_rsi:
rsi = ta.momentum.RSIIndicator(df['Close']).rsi()
fig_rsi = go.Figure()
fig_rsi.add_trace(go.Scatter(x=df.index, y=rsi, name='RSI'))
fig_rsi.add_hline(y=70, line_color='red', line_dash='dash')
fig_rsi.add_hline(y=30, line_color='green', line_dash='dash')
fig_rsi.update_layout(title='RSI Indicator',
yaxis_title='RSI',
template='plotly_white')
st.plotly_chart(fig_rsi, use_container_width=True)
with col2:
if df is not None and not df.empty:
# Summary statistics
st.subheader("Summary Statistics")
# Current price and daily change
current_price = df['Close'].iloc[-1]
previous_price = df['Close'].iloc[-2]
price_change = current_price - previous_price
price_change_pct = (price_change / previous_price) * 100
st.metric(
"Current Price",
f"${current_price:.2f}",
f"{price_change_pct:.2f}%"
)
# Trading volume
st.metric(
"Trading Volume",
f"{df['Volume'].iloc[-1]:,.0f}",
f"{((df['Volume'].iloc[-1] / df['Volume'].iloc[-2]) - 1) * 100:.2f}%"
)
# Basic statistics
st.write("Price Statistics:")
stats_df = pd.DataFrame({
'Metric': ['High', 'Low', 'Average', 'Std Dev'],
'Value': [
f"${df['High'].max():.2f}",
f"${df['Low'].min():.2f}",
f"${df['Close'].mean():.2f}",
f"${df['Close'].std():.2f}"
]
})
st.table(stats_df)
# Recent trades
st.subheader("Recent Price Data")
recent_data = df.tail().reset_index()
recent_data['Date'] = recent_data['Date'].dt.date
st.dataframe(recent_data[['Date', 'Open', 'High', 'Low', 'Close', 'Volume']])
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?