-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
218 lines (177 loc) · 7 KB
/
app.py
File metadata and controls
218 lines (177 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import streamlit as st
import yfinance as yf
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from utils.database import init_db
# Configure the page
st.set_page_config(
page_title="Stock Market Analysis",
page_icon="📈",
layout="wide",
initial_sidebar_state="expanded"
)
# Initialize database
if 'db_initialized' not in st.session_state:
st.session_state.db_initialized = init_db()
# Main page content
st.title("📈 Stock Market Analysis Dashboard")
st.markdown("---")
# Introduction
st.markdown("""
### Welcome to the Stock Market Analysis Dashboard
This comprehensive platform provides:
- **Real-time stock data** and historical analysis
- **Interactive charts** with multiple timeframes
- **Technical indicators** (Moving Averages, RSI, MACD, etc.)
- **Portfolio tracking** and performance monitoring
- **Stock comparison** tools
Navigate through the sidebar to explore different features.
""")
# Quick market overview
st.subheader("📊 Market Overview")
# Mixed portfolio for global overview
popular_stocks = ['AAPL', 'GOOGL', 'MSFT', 'RELIANCE.NS', 'TCS.NS', 'HDFCBANK.NS', 'TSLA', 'NVDA']
try:
with st.spinner("Loading market overview..."):
# Create columns for displaying stock cards
cols = st.columns(4)
for i, symbol in enumerate(popular_stocks[:8]):
with cols[i % 4]:
try:
stock = yf.Ticker(symbol)
info = stock.info
hist = stock.history(period="2d")
if len(hist) >= 2:
current_price = hist['Close'].iloc[-1]
prev_price = hist['Close'].iloc[-2]
change = current_price - prev_price
change_pct = (change / prev_price) * 100
# Color based on performance
color = "green" if change >= 0 else "red"
arrow = "↗️" if change >= 0 else "↘️"
# Format currency based on market
currency_symbol = "₹" if ".NS" in symbol else "$"
st.metric(
label=f"{symbol}",
value=f"{currency_symbol}{current_price:.2f}",
delta=f"{change_pct:.2f}%"
)
except Exception as e:
st.error(f"Error loading {symbol}: {str(e)}")
except Exception as e:
st.error(f"Error loading market overview: {str(e)}")
st.markdown("---")
# Quick stock lookup
st.subheader("🔍 Quick Stock Lookup")
col1, col2 = st.columns([2, 1])
with col1:
symbol_input = st.text_input(
"Enter a stock symbol (e.g., AAPL, GOOGL, MSFT):",
placeholder="AAPL"
).upper()
with col2:
st.write("") # Spacing
lookup_button = st.button("🔍 Lookup Stock", type="primary")
if lookup_button and symbol_input:
try:
with st.spinner(f"Fetching data for {symbol_input}..."):
stock = yf.Ticker(symbol_input)
info = stock.info
hist = stock.history(period="1mo")
if not hist.empty:
col1, col2, col3 = st.columns(3)
with col1:
# Format currency for quick lookup
current_lookup_price = hist['Close'].iloc[-1]
prev_lookup_price = hist['Close'].iloc[-2] if len(hist) > 1 else current_lookup_price
lookup_change_pct = ((current_lookup_price - prev_lookup_price) / prev_lookup_price * 100) if prev_lookup_price != 0 else 0
lookup_currency = "₹" if ".NS" in symbol_input else "$"
st.metric(
"Current Price",
f"{lookup_currency}{current_lookup_price:.2f}",
f"{lookup_change_pct:.2f}%"
)
with col2:
st.metric("Volume", f"{hist['Volume'].iloc[-1]:,}")
with col3:
st.metric("Market Cap", info.get('marketCap', 'N/A'))
# Simple price chart
fig = go.Figure()
fig.add_trace(go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name='Close Price',
line=dict(color='#1f77b4', width=2)
))
fig.update_layout(
title=f"{symbol_input} - 1 Month Price Chart",
xaxis_title="Date",
yaxis_title="Price ($)",
height=400,
showlegend=False
)
st.plotly_chart(fig, use_container_width=True)
# Company info
if 'longName' in info:
st.write(f"**Company:** {info['longName']}")
if 'sector' in info:
st.write(f"**Sector:** {info['sector']}")
if 'industry' in info:
st.write(f"**Industry:** {info['industry']}")
else:
st.error(f"No data found for symbol: {symbol_input}")
except Exception as e:
st.error(f"Error fetching data for {symbol_input}: {str(e)}")
st.markdown("---")
# Navigation guide
st.subheader("🧭 Navigation Guide")
nav_col1, nav_col2 = st.columns(2)
with nav_col1:
st.markdown("""
**📈 Stock Analysis**
- View detailed stock information
- Interactive price charts
- Multiple timeframes
- Company fundamentals
- Support for US and NSE stocks
**📊 Technical Indicators**
- Moving Averages (SMA, EMA)
- RSI, MACD, Bollinger Bands
- Volume analysis
- Custom indicator settings
""")
with nav_col2:
st.markdown("""
**💼 Portfolio Tracker**
- Track your investments
- Portfolio performance
- Profit/Loss calculations
- Diversification analysis
**🔍 Stock Comparison**
- Compare multiple stocks
- Side-by-side analysis
- Performance correlation
- Relative strength
**🔮 Price Prediction**
- AI-powered weekly forecasts
- Machine learning analysis
- Confidence intervals
- Technical factor insights
**🇮🇳 NSE Stocks**
- Indian stock market analysis
- NSE-specific features
- Currency in Indian Rupees
- Major Indian companies
""")
# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; color: #666;'>
<p>📊 Stock Market Analysis Dashboard | Built with Streamlit & yfinance</p>
<p><small>⚠️ This is for educational purposes only. Not financial advice.</small></p>
</div>
""", unsafe_allow_html=True)