Here's a design for a stock chart viewer app with a clean UI, 10-year historical data, and crosshair functionality:
python Copy code
import streamlit as st
import yfinance as yf
import plotly.graph_objects as go
from datetime import datetime, timedelta
import pandas as pd
# App configuration
st.set_page_config(
page_title="Stock Chart Viewer",
page_icon="📈",
layout="wide"
)
# Custom CSS for styling
st.markdown("""
<style>
.main {
background-color: #f8f9fa;
}
.stSelectbox div[data-baseweb="select"] {
background-color: white;
}
.stButton>button {
background-color: #4CAF50;
color: white;
border-radius: 4px;
border: none;
padding: 8px 16px;
}
.stButton>button:hover {
background-color: #45a049;
}
.title {
color: #2c3e50;
font-size: 2.5em;
text-align: center;
margin-bottom: 20px;
}
.chart-container {
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
padding: 20px;
background-color: white;
}
.info-box {
background-color: #e8f4f8;
border-left: 4px solid #3498db;
padding: 12px;
border-radius: 4px;
margin-bottom: 20px;
}
</style>
""", unsafe_allow_html=True)
# App title
st.markdown('<div class="title">📈 Stock Chart Viewer</div>', unsafe_allow_html=True)
# Stock selection
stocks = {
"McDonald's": "MCD",
"Coca-Cola": "KO",
"Apple": "AAPL",
"Microsoft": "MSFT",
"Amazon": "AMZN",
"Google": "GOOGL",
"Tesla": "TSLA",
"NVIDIA": "NVDA",
"Walmart": "WMT",
"Disney": "DIS"
}
col1, col2 = st.columns([3, 1])
with col1:
selected_stock = st.selectbox(
"Select a stock:",
list(stocks.keys()),
index=0
)
with col2:
st.write("") # Spacer
st.write("") # Spacer
if st.button("Update Chart"):
st.experimental_rerun()
# Date range (last 10 years)
end_date = datetime.today()
start_date = end_date - timedelta(days=365*10)
# Fetch stock data
@st.cache_data(ttl=3600) # Cache for 1 hour
def get_stock_data(ticker, start, end):
data = yf.download(ticker, start=start, end=end)
return data
ticker = stocks[selected_stock]
data = get_stock_data(ticker, start_date, end_date)
# Create interactive chart with crosshair
fig = go.Figure()
# Add candlestick chart
fig.add_trace(go.Candlestick(
x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
name='Price',
increasing_line_color='#2ecc71', # Green for up
decreasing_line_color='#e74c3c' # Red for down
))
# Add moving averages
data['MA50'] = data['Close'].rolling(window=50).mean()
data['MA200'] = data['Close'].rolling(window=200).mean()
fig.add_trace(go.Scatter(
x=data.index,
y=data['MA50'],
line=dict(color='#3498db', width=1.5),
name='50-day MA'
))
fig.add_trace(go.Scatter(
x=data.index,
y=data['MA200'],
line=dict(color='#9b59b6', width=1.5),
name='200-day MA'
))
# Layout configuration
fig.update_layout(
title=f"{selected_stock} ({ticker}) - 10 Year Price History",
xaxis_title="Date",
yaxis_title="Price (USD)",
template="plotly_white",
hovermode="x unified",
height=600,
margin=dict(l=50, r=50, t=80, b=50),
xaxis=dict(
rangeslider=dict(visible=False),
type="date"
),
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
)
# Crosshair configuration
fig.update_xaxes(
showspikes=True,
spikecolor="grey",
spikesnap="cursor",
spikemode="across",
spikethickness=0.5
)
fig.update_yaxes(
showspikes=True,
spikecolor="grey",
spikethickness=0.5
)
# Display the chart
st.markdown('<div class="chart-container">', unsafe_allow_html=True)
st.plotly_chart(fig, use_container_width=True)
st.markdown('</div>', unsafe_allow_html=True)
# Display current stock info
current_price = data['Close'].iloc[-1]
prev_close = data['Close'].iloc[-2]
price_change = current_price - prev_close
percent_change = (price_change / prev_close) * 100
st.markdown(f"""
<div class="info-box">
<h3>{selected_stock} ({ticker}) - Current Info</h3>
<p><strong>Current Price:</strong> ${current_price:.2f}</p>
<p><strong>Change:</strong> <span style="color: {'#2ecc71' if price_change >= 0 else '#e74c3c'}">{price_change:.2f} ({percent_change:.2f}%)</span></p>
<p><strong>52-Week Range:</strong> ${data['Close'].tail(252).min():.2f} - ${data['Close'].tail(252).max():.2f}</p>
</div>
""", unsafe_allow_html=True)