I'll help you design a stock chart visualization app using Python with Streamlit for the UI and Plotly for interactive charting. Here's a comprehensive implementation:
import streamlit as st
import yfinance as yf
import plotly.graph_objs as go
from datetime import datetime, timedelta
class StockChartApp:
def __init__(self):
# Set up the page configuration
st.set_page_config(
page_title="Stock Chart Visualizer",
page_icon=":chart_with_upwards_trend:",
layout="wide"
)
# Define a list of popular stocks
self.stock_options = [
"McDonald's (MCD)",
"Coca-Cola (KO)",
"Apple (AAPL)",
"Microsoft (MSFT)",
"Amazon (AMZN)"
]
# Mapping of display names to ticker symbols
self.stock_tickers = {
"McDonald's (MCD)": "MCD",
"Coca-Cola (KO)": "KO",
"Apple (AAPL)": "AAPL",
"Microsoft (MSFT)": "MSFT",
"Amazon (AMZN)": "AMZN"
}
def fetch_stock_data(self, ticker, start_date, end_date):
"""Fetch stock data for a given ticker and date range"""
try:
stock_data = yf.download(ticker, start=start_date, end=end_date)
return stock_data
except Exception as e:
st.error(f"Error fetching data: {e}")
return None
def create_interactive_chart(self, stock_data, ticker):
"""Create an interactive Plotly chart"""
# Create the candlestick chart
fig = go.Figure(data=[go.Candlestick(
x=stock_data.index,
open=stock_data['Open'],
high=stock_data['High'],
low=stock_data['Low'],
close=stock_data['Close'],
name=ticker
)])
# Customize the layout
fig.update_layout(
title=f'{ticker} Stock Price Over 10 Years',
yaxis_title='Stock Price (USD)',
xaxis_title='Date',
template='plotly_white',
height=600,
hovermode='x unified'
)
# Enable crosshair
fig.update_layout(
xaxis=dict(
rangeslider=dict(visible=False),
type='date'
),
hoverlabel=dict(
bgcolor='white',
font_size=12
)
)
return fig
def run(self):
"""Main app runner"""
st.title("📈 Stock Chart Visualizer")
# Sidebar for stock selection
st.sidebar.header("Stock Selection")
selected_stock_display = st.sidebar.selectbox(
"Choose a Stock",
self.stock_options
)
# Get the corresponding ticker
ticker = self.stock_tickers[selected_stock_display]
# Date range selection
end_date = datetime.now()
start_date = end_date - timedelta(days=365*10)
# Fetch stock data
stock_data = self.fetch_stock_data(ticker, start_date, end_date)
if stock_data is not None and not stock_data.empty:
# Create interactive chart
fig = self.create_interactive_chart(stock_data, ticker)
# Display the chart
st.plotly_chart(fig, use_container_width=True)
# Additional stock information
st.subheader("Stock Statistics")
col1, col2 = st.columns(2)
with col1:
st.metric("Current Price",
f"${stock_data['Close'][-1]:.2f}")
with col2:
price_change = stock_data['Close'][-1] - stock_data['Close'][0]
percent_change = (price_change / stock_data['Close'][0]) * 100
st.metric("Total 10-Year Change",
f"{percent_change:.2f}%")
else:
st.warning("Could not retrieve stock data")
# Run the app
if __name__ == "__main__":
app = StockChartApp()
app.run()
To run this app, you'll need to install the following dependencies:
pip install streamlit yfinance plotly
Key Features:
- Interactive Candlestick Chart
- 10-year historical stock data
- Crosshair functionality
- Responsive UI with Streamlit
- Multiple stock selection
- Basic stock statistics
Additional Enhancements You Could Consider:
- Add more stocks to the selection
- Implement date range picker
- Add technical indicators
- Create comparison view for multiple stocks
- Add more detailed financial metrics
Recommended Improvements:
- Error handling for stock data retrieval
- Caching mechanism for stock data
- More advanced styling and color schemes
To run the app:
streamlit run stock_chart_app.py
This implementation provides a clean, interactive way to visualize stock performance over the last 10 years with an intuitive user interface.
Would you like me to elaborate on any specific aspect of the app or discuss potential additional features?