Create an app for stock analysis with mock data. Generate mock daily price data for 5 tech stocks over the past year with standard fields (Open, Close, etc). Features: - Stock selector dropdown - Price trend charts - Basic stats (mean, volatility) - Moving averages - Volume analysis - Stock comparison Interactive elements: - Date range picker - Technical indicators - Chart type toggle Focus on clean visualization of realistic mock data.
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from datetime import datetime, timedelta
import time
# Set page config
st.set_page_config(layout="wide", page_title="Stock Analysis Dashboard")
# Generate mock data
def generate_stock_data():
tickers = ["AAPL", "GOOGL", "MSFT", "AMZN", "META"]
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
dates = pd.date_range(start=start_date, end=end_date, freq='D')
all_stocks_data = {}
for ticker in tickers:
np.random.seed(hash(ticker) % 32) # Consistent random data per ticker
# Generate base price trend with random walk
price = 100 * (1 + np.random.normal(0, 0.02, len(dates)))
price = np.exp(np.cumsum(np.random.normal(0.0002, 0.02, len(dates))))
# Generate OHLC data
data = pd.DataFrame({
'Date': dates,
'Open': price * (1 + np.random.normal(0, 0.015, len(dates))),
'High': price * (1 + abs(np.random.normal(0, 0.02, len(dates)))),
'Low': price * (1 - abs(np.random.normal(0, 0.02, len(dates)))),
'Close': price * (1 + np.random.normal(0, 0.015, len(dates))),
'Volume': np.random.normal(1000000, 200000, len(dates)).astype(int),
'Ticker': ticker
})
# Ensure High > Low
data['High'] = np.maximum(data['High'], data[['Open', 'Close', 'Low']].max(axis=1))
data['Low'] = np.minimum(data['Low'], data[['Open', 'Close', 'High']].min(axis=1))
all_stocks_data[ticker] = data
return all_stocks_data
# Calculate technical indicators
def calculate_indicators(df, window_short=20, window_long=50):
df = df.copy()
df['SMA_short'] = df['Close'].rolling(window=window_short).mean()
df['SMA_long'] = df['Close'].rolling(window=window_long).mean()
df['Volatility'] = df['Close'].rolling(window=window_short).std()
return df
# Main app
st.title('Stock Analysis Dashboard')
# Initialize session state
if 'stock_data' not in st.session_state:
st.session_state.stock_data = generate_stock_data()
# Sidebar controls
st.sidebar.header('Controls')
selected_stock = st.sidebar.selectbox('Select Stock', ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META'])
chart_type = st.sidebar.selectbox('Chart Type', ['Candlestick', 'Line'])
show_indicators = st.sidebar.checkbox('Show Technical Indicators', True)
# Date range selector
df = st.session_state.stock_data[selected_stock]
min_date = df['Date'].min()
max_date = df['Date'].max()
col1, col2 = st.sidebar.columns(2)
start_date = col1.date_input('Start Date', min_date)
end_date = col2.date_input('End Date', max_date)
# Filter data based on date range
mask = (df['Date'].dt.date >= start_date) & (df['Date'].dt.date <= end_date)
df_filtered = df.loc[mask].copy()
# Calculate indicators
if show_indicators:
df_filtered = calculate_indicators(df_filtered)
# Main charts
st.subheader(f'{selected_stock} Stock Analysis')
# Price chart
fig = make_subplots(rows=2, cols=1, row_heights=[0.7, 0.3],
vertical_spacing=0.03,
subplot_titles=(f'{selected_stock} Price', 'Volume'))
if chart_type == 'Candlestick':
fig.add_trace(
go.Candlestick(x=df_filtered['Date'],
open=df_filtered['Open'],
high=df_filtered['High'],
low=df_filtered['Low'],
close=df_filtered['Close'],
name='OHLC'),
row=1, col=1
)
else:
fig.add_trace(
go.Scatter(x=df_filtered['Date'],
y=df_filtered['Close'],
name='Close Price',
line=dict(color='blue')),
row=1, col=1
)
if show_indicators:
fig.add_trace(
go.Scatter(x=df_filtered['Date'],
y=df_filtered['SMA_short'],
name='20-day SMA',
line=dict(color='orange', dash='dash')),
row=1, col=1
)
fig.add_trace(
go.Scatter(x=df_filtered['Date'],
y=df_filtered['SMA_long'],
name='50-day SMA',
line=dict(color='green', dash='dash')),
row=1, col=1
)
# Volume chart
fig.add_trace(
go.Bar(x=df_filtered['Date'],
y=df_filtered['Volume'],
name='Volume'),
row=2, col=1
)
fig.update_layout(
height=800,
showlegend=True,
xaxis_rangeslider_visible=False,
template='plotly_white'
)
st.plotly_chart(fig, use_container_width=True)
# Statistics
st.subheader('Key Statistics')
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric('Current Price', f"${df_filtered['Close'].iloc[-1]:.2f}")
with col2:
returns = (df_filtered['Close'].iloc[-1] / df_filtered['Close'].iloc[0] - 1) * 100
st.metric('Period Return', f"{returns:.1f}%")
with col3:
volatility = df_filtered['Close'].pct_change().std() * np.sqrt(252) * 100
st.metric('Annualized Volatility', f"{volatility:.1f}%")
with col4:
avg_volume = df_filtered['Volume'].mean()
st.metric('Avg Daily Volume', f"{avg_volume:,.0f}")
# Stock comparison
st.subheader('Stock Comparison')
comparison_df = pd.DataFrame()
for ticker in st.session_state.stock_data.keys():
temp_df = st.session_state.stock_data[ticker].loc[mask]
comparison_df[ticker] = temp_df['Close'] / temp_df['Close'].iloc[0] * 100
fig_comparison = go.Figure()
for ticker in comparison_df.columns:
fig_comparison.add_trace(
go.Scatter(x=df_filtered['Date'],
y=comparison_df[ticker],
name=ticker)
)
fig_comparison.update_layout(
title='Relative Performance (Normalized to 100)',
yaxis_title='Normalized Price',
template='plotly_white',
height=400
)
st.plotly_chart(fig_comparison, use_container_width=True)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?