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 matplotlib.pyplot as plt
from datetime import datetime, timedelta
# Generate mock stock data
def generate_mock_data(tickers, start_date, end_date):
date_range = pd.date_range(start_date, end_date)
data = {}
for ticker in tickers:
prices = np.random.rand(len(date_range)) * 100
data[ticker] = pd.DataFrame({
'Date': date_range,
'Open': prices,
'Close': prices + (np.random.rand(len(date_range)) - 0.5) * 10,
'High': prices + np.random.rand(len(date_range)) * 5,
'Low': prices - np.random.rand(len(date_range)) * 5,
'Volume': np.random.randint(1000, 5000, len(date_range))
}).set_index('Date')
return data
# Define stock tickers
stock_tickers = ['AAPL', 'TSLA', 'GOOGL', 'MSFT', 'AMZN']
# Generate mock data for the past year
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
mock_data = generate_mock_data(stock_tickers, start_date, end_date)
# Streamlit app
st.title('Stock Analysis App')
# Stock selector
selected_stock = st.selectbox('Select a stock:', stock_tickers)
df = mock_data[selected_stock]
# Date range picker
start, end = st.date_input('Select date range:', [start_date, end_date])
filtered_df = df[(df.index >= pd.to_datetime(start)) & (df.index <= pd.to_datetime(end))]
# Chart type toggle
chart_type = st.selectbox('Select chart type:', ['Line', 'Bar'])
# Plotting
plt.figure(figsize=(10, 5))
if chart_type == 'Line':
plt.plot(filtered_df.index, filtered_df['Close'], label='Close Price')
else:
plt.bar(filtered_df.index, filtered_df['Close'], label='Close Price')
plt.title(f'{selected_stock} Price Trend')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid()
st.pyplot(plt)
# Basic stats
mean_price = filtered_df['Close'].mean()
volatility = filtered_df['Close'].std()
st.write(f'Mean Price: ${mean_price:.2f}')
st.write(f'Volatility: ${volatility:.2f}')
# Moving averages
moving_avg_period = st.number_input('Moving average period:', min_value=1, value=30)
df['Moving_Average'] = df['Close'].rolling(window=moving_avg_period).mean()
st.line_chart(df[['Close', 'Moving_Average']].loc[filtered_df.index])
# Volume analysis
st.bar_chart(filtered_df['Volume'])
# Stock comparison
comparison_tickers = st.multiselect('Select stocks for comparison:', stock_tickers, default=[selected_stock])
comparison_data = pd.concat([mock_data[ticker]['Close'].loc[filtered_df.index] for ticker in comparison_tickers], axis=1)
comparison_data.columns = comparison_tickers
st.line_chart(comparison_data)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?