ashwiniambastha commited on
Commit
252d445
Β·
verified Β·
1 Parent(s): 40d37cb

Upload 4 files

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. app.py +217 -0
  3. market_data.db +3 -0
  4. risk_ui_enchanced.py +936 -0
  5. streamlit_app.py +218 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ market_data.db filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from agents.market_data.agent import MarketDataAgent
4
+ from agents.market_data.storage import MarketDataStorage
5
+ import plotly.graph_objects as go
6
+ from datetime import datetime
7
+
8
+ # Initialize
9
+ symbols = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN']
10
+ agent = MarketDataAgent(symbols)
11
+ storage = MarketDataStorage()
12
+
13
+ def fetch_current_prices():
14
+ """Fetch and display current prices"""
15
+ data = agent.fetch_all_symbols()
16
+
17
+ # Save to database
18
+ for symbol, info in data.items():
19
+ storage.save_realtime_data(info)
20
+
21
+ # Create DataFrame for display
22
+ df = pd.DataFrame(data).T
23
+ df = df[['symbol', 'price', 'open', 'high', 'low', 'volume', 'pe_ratio']]
24
+ df['price'] = df['price'].apply(lambda x: f"${x:.2f}")
25
+ df['open'] = df['open'].apply(lambda x: f"${x:.2f}" if pd.notna(x) else "N/A")
26
+ df['high'] = df['high'].apply(lambda x: f"${x:.2f}" if pd.notna(x) else "N/A")
27
+ df['low'] = df['low'].apply(lambda x: f"${x:.2f}" if pd.notna(x) else "N/A")
28
+ df['volume'] = df['volume'].apply(lambda x: f"{x:,}" if pd.notna(x) else "N/A")
29
+ df['pe_ratio'] = df['pe_ratio'].apply(lambda x: f"{x:.2f}" if pd.notna(x) else "N/A")
30
+
31
+ return df
32
+
33
+ def get_historical_data(symbol, period):
34
+ """Fetch historical data and create chart"""
35
+ df = agent.fetch_historical_data(symbol, period)
36
+
37
+ if df is None or df.empty:
38
+ return None, "No data available"
39
+
40
+ # Save to database
41
+ storage.save_historical_data(symbol, df)
42
+
43
+ # Create price chart
44
+ fig = go.Figure()
45
+
46
+ # Candlestick chart
47
+ fig.add_trace(go.Candlestick(
48
+ x=df.index,
49
+ open=df['Open'],
50
+ high=df['High'],
51
+ low=df['Low'],
52
+ close=df['Close'],
53
+ name='Price'
54
+ ))
55
+
56
+ fig.update_layout(
57
+ title=f'{symbol} Price History ({period})',
58
+ yaxis_title='Price ($)',
59
+ xaxis_title='Date',
60
+ template='plotly_white',
61
+ height=500
62
+ )
63
+
64
+ # Create volume chart
65
+ fig_volume = go.Figure()
66
+ fig_volume.add_trace(go.Bar(
67
+ x=df.index,
68
+ y=df['Volume'],
69
+ name='Volume',
70
+ marker_color='lightblue'
71
+ ))
72
+
73
+ fig_volume.update_layout(
74
+ title=f'{symbol} Trading Volume ({period})',
75
+ yaxis_title='Volume',
76
+ xaxis_title='Date',
77
+ template='plotly_white',
78
+ height=300
79
+ )
80
+
81
+ # Create summary table
82
+ summary = pd.DataFrame({
83
+ 'Metric': ['Current Price', 'Period High', 'Period Low', 'Average Volume', 'Total Days'],
84
+ 'Value': [
85
+ f"${df['Close'].iloc[-1]:.2f}",
86
+ f"${df['High'].max():.2f}",
87
+ f"${df['Low'].min():.2f}",
88
+ f"{df['Volume'].mean():,.0f}",
89
+ f"{len(df)}"
90
+ ]
91
+ })
92
+
93
+ return fig, fig_volume, summary
94
+
95
+ def get_database_stats():
96
+ """Get statistics from database"""
97
+ latest = storage.get_latest_prices()
98
+
99
+ if latest.empty:
100
+ return "No data in database yet. Fetch some prices first!"
101
+
102
+ stats = f"""
103
+ πŸ“Š **Database Statistics**
104
+
105
+ - Total Symbols Tracked: {len(latest)}
106
+ - Last Update: {latest['timestamp'].max()}
107
+ - Symbols: {', '.join(latest['symbol'].tolist())}
108
+ """
109
+
110
+ return stats, latest[['symbol', 'price', 'timestamp']]
111
+
112
+ # Create Gradio Interface
113
+ with gr.Blocks(title="Market Data Agent - Demo", theme=gr.themes.Soft()) as demo:
114
+
115
+ gr.Markdown("""
116
+ # πŸ“ˆ Market Data Agent - Live Demo
117
+ ### Week 2: Multi-Agent Portfolio Optimization System
118
+ **Team:** Ashwini, Dibyendu Sarkar, Jyoti Ranjan Sethi
119
+ """)
120
+
121
+ with gr.Tab("πŸ’° Real-Time Prices"):
122
+ gr.Markdown("### Fetch current market data for tracked stocks")
123
+
124
+ with gr.Row():
125
+ fetch_btn = gr.Button("πŸ”„ Fetch Current Prices", variant="primary", size="lg")
126
+
127
+ price_output = gr.Dataframe(
128
+ headers=['Symbol', 'Price', 'Open', 'High', 'Low', 'Volume', 'P/E Ratio'],
129
+ label="Current Market Data"
130
+ )
131
+
132
+ fetch_btn.click(
133
+ fn=fetch_current_prices,
134
+ outputs=price_output
135
+ )
136
+
137
+ with gr.Tab("πŸ“Š Historical Data"):
138
+ gr.Markdown("### View historical price charts and analysis")
139
+
140
+ with gr.Row():
141
+ symbol_input = gr.Dropdown(
142
+ choices=['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN'],
143
+ value='AAPL',
144
+ label="Select Stock"
145
+ )
146
+ period_input = gr.Dropdown(
147
+ choices=['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y'],
148
+ value='1mo',
149
+ label="Select Period"
150
+ )
151
+
152
+ fetch_hist_btn = gr.Button("πŸ“ˆ Fetch Historical Data", variant="primary")
153
+
154
+ with gr.Row():
155
+ price_chart = gr.Plot(label="Price Chart")
156
+
157
+ with gr.Row():
158
+ volume_chart = gr.Plot(label="Volume Chart")
159
+
160
+ summary_table = gr.Dataframe(label="Summary Statistics")
161
+
162
+ fetch_hist_btn.click(
163
+ fn=get_historical_data,
164
+ inputs=[symbol_input, period_input],
165
+ outputs=[price_chart, volume_chart, summary_table]
166
+ )
167
+
168
+ with gr.Tab("πŸ’Ύ Database Stats"):
169
+ gr.Markdown("### View data stored in local SQLite database")
170
+
171
+ refresh_btn = gr.Button("πŸ”„ Refresh Database Stats", variant="primary")
172
+
173
+ db_stats = gr.Markdown()
174
+ db_data = gr.Dataframe(label="Latest Prices in Database")
175
+
176
+ refresh_btn.click(
177
+ fn=get_database_stats,
178
+ outputs=[db_stats, db_data]
179
+ )
180
+
181
+ with gr.Tab("ℹ️ About"):
182
+ gr.Markdown("""
183
+ ## Market Data Agent
184
+
185
+ This is the **foundation agent** of our Multi-Agent Portfolio Optimization System.
186
+
187
+ ### Features Implemented:
188
+ 1. βœ… Real-time price fetching from Yahoo Finance
189
+ 2. βœ… Historical data retrieval (1 day to 10 years)
190
+ 3. βœ… Data validation and quality checks
191
+ 4. βœ… SQLite database storage (thread-safe)
192
+ 5. βœ… REST API for other agents
193
+
194
+ ### Technologies Used:
195
+ - **Data Source:** yfinance (Yahoo Finance API)
196
+ - **Database:** SQLite with thread-safe connections
197
+ - **Charts:** Plotly for interactive visualizations
198
+ - **UI:** Gradio for web interface
199
+ - **Backend:** Python with FastAPI
200
+
201
+ ### Next Week:
202
+ We will build the **Risk Management Agent** that will use this Market Data Agent
203
+ to calculate VaR, CVaR, and portfolio risk metrics.
204
+
205
+ ---
206
+ **Project:** Intelligent Multi-Agent Portfolio Optimization System
207
+ **Week:** 2 of 16
208
+ **Date:** February 2026
209
+ """)
210
+
211
+ # Launch the app
212
+ if __name__ == "__main__":
213
+ demo.launch(
214
+ share=True, # Creates public link you can share
215
+ server_name="0.0.0.0",
216
+ server_port=7860
217
+ )
market_data.db ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e46751cf641747842d0c7370cd9953a21d72bd12d55ee10a412e73e490f5556
3
+ size 208896
risk_ui_enchanced.py ADDED
@@ -0,0 +1,936 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.graph_objects as go
5
+ from datetime import datetime
6
+ import yfinance as yf
7
+
8
+ # ─────────────────────────────────────────────
9
+ # Try importing agents; fall back gracefully
10
+ # ─────────────────────────────────────────────
11
+ try:
12
+ from agents.market_data.agent import MarketDataAgent
13
+ from agents.market_data.storage import MarketDataStorage
14
+ from agents.risk_management.agent import RiskManagementAgent
15
+ SYMBOLS = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN']
16
+ market_agent = MarketDataAgent(SYMBOLS)
17
+ storage = MarketDataStorage()
18
+ risk_agent = RiskManagementAgent()
19
+ AGENTS_LOADED = True
20
+ except Exception:
21
+ AGENTS_LOADED = False
22
+
23
+ # ─────────────────────────────────────────────
24
+ # Color Palette β€” Blue White Professional
25
+ # ─────────────────────────────────────────────
26
+ BG_PAGE = "#f0f4fb"
27
+ BG_CARD = "#ffffff"
28
+ BG_HEADER = "#1a3a6b"
29
+ BORDER = "#d0dff0"
30
+ BLUE_PRIMARY = "#1a5fca"
31
+ BLUE_DARK = "#0d2d6b"
32
+ BLUE_LIGHT = "#e8f0fe"
33
+ GREEN = "#0d9c5b"
34
+ RED = "#e03131"
35
+ GOLD = "#d4940a"
36
+ TEXT_DARK = "#0d1f3c"
37
+ TEXT_MED = "#3a5080"
38
+ TEXT_LIGHT = "#6b83a8"
39
+ WHITE = "#ffffff"
40
+
41
+ # ─────────────────────────────────────────────
42
+ # Plotly chart theme β€” clean white/blue
43
+ # ─────────────────────────────────────────────
44
+ PLOTLY_THEME = dict(
45
+ paper_bgcolor=BG_CARD,
46
+ plot_bgcolor="#f8faff",
47
+ font=dict(family="Inter, sans-serif", color=TEXT_DARK, size=12),
48
+ legend=dict(bgcolor="rgba(255,255,255,0.9)", bordercolor=BORDER,
49
+ borderwidth=1, font=dict(color=TEXT_DARK)),
50
+ margin=dict(l=55, r=30, t=55, b=45),
51
+ )
52
+
53
+ AXIS_STYLE = dict(
54
+ gridcolor="#e2eaf5",
55
+ zerolinecolor="#c5d5ea",
56
+ tickfont=dict(color=TEXT_LIGHT),
57
+ linecolor=BORDER,
58
+ )
59
+
60
+ # ─────────────────────────────────────────────
61
+ # CSS β€” Full Blue White Theme
62
+ # ─────────────────────────────────────────────
63
+ CUSTOM_CSS = """
64
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');
65
+
66
+ *, *::before, *::after { box-sizing: border-box; }
67
+
68
+ body, .gradio-container {
69
+ background: #f0f4fb !important;
70
+ font-family: 'Inter', sans-serif !important;
71
+ color: #0d1f3c !important;
72
+ }
73
+
74
+ /* Header */
75
+ .app-header {
76
+ background: linear-gradient(135deg, #0d2d6b 0%, #1a5fca 60%, #2979e8 100%);
77
+ padding: 36px 40px 28px;
78
+ text-align: center;
79
+ border-bottom: 4px solid #d4940a;
80
+ box-shadow: 0 4px 20px rgba(26,60,107,0.18);
81
+ }
82
+ .app-title {
83
+ font-family: 'Space Grotesk', sans-serif !important;
84
+ font-size: 2rem;
85
+ font-weight: 700;
86
+ color: #ffffff !important;
87
+ letter-spacing: 1px;
88
+ margin-bottom: 6px;
89
+ }
90
+ .app-subtitle {
91
+ font-size: 0.82rem;
92
+ color: rgba(255,255,255,0.75) !important;
93
+ letter-spacing: 2px;
94
+ text-transform: uppercase;
95
+ }
96
+ .app-team {
97
+ font-size: 0.75rem;
98
+ color: rgba(255,255,255,0.55) !important;
99
+ margin-top: 10px;
100
+ letter-spacing: 1.5px;
101
+ }
102
+ .header-accent {
103
+ width: 60px;
104
+ height: 3px;
105
+ background: #d4940a;
106
+ margin: 12px auto;
107
+ border-radius: 2px;
108
+ }
109
+
110
+ /* Tabs */
111
+ div[role="tablist"] {
112
+ background: #ffffff !important;
113
+ border-bottom: 2px solid #d0dff0 !important;
114
+ padding: 0 16px !important;
115
+ box-shadow: 0 2px 8px rgba(26,60,107,0.06) !important;
116
+ }
117
+ div[role="tab"] {
118
+ font-family: 'Inter', sans-serif !important;
119
+ font-size: 0.82rem !important;
120
+ font-weight: 500 !important;
121
+ color: #6b83a8 !important;
122
+ border: none !important;
123
+ border-bottom: 3px solid transparent !important;
124
+ padding: 13px 16px !important;
125
+ background: transparent !important;
126
+ transition: all 0.2s !important;
127
+ }
128
+ div[role="tab"]:hover { color: #1a5fca !important; background: #e8f0fe !important; }
129
+ div[role="tab"][aria-selected="true"] {
130
+ color: #1a5fca !important;
131
+ border-bottom: 3px solid #1a5fca !important;
132
+ background: #e8f0fe !important;
133
+ font-weight: 600 !important;
134
+ }
135
+
136
+ /* Metric cards */
137
+ .metric-grid { display: grid; gap: 14px; margin-bottom: 22px; }
138
+ .metric-grid-5 { grid-template-columns: repeat(5, 1fr); }
139
+ .metric-grid-4 { grid-template-columns: repeat(4, 1fr); }
140
+
141
+ .kpi-card {
142
+ background: #ffffff;
143
+ border: 1px solid #d0dff0;
144
+ border-radius: 12px;
145
+ padding: 18px 20px;
146
+ position: relative;
147
+ overflow: hidden;
148
+ box-shadow: 0 2px 10px rgba(26,60,107,0.07);
149
+ transition: transform 0.2s, box-shadow 0.2s;
150
+ }
151
+ .kpi-card::before {
152
+ content: '';
153
+ position: absolute;
154
+ top: 0; left: 0; right: 0;
155
+ height: 3px;
156
+ background: linear-gradient(90deg, #1a5fca, #2979e8);
157
+ }
158
+ .kpi-card.green::before { background: linear-gradient(90deg, #0d9c5b, #22c55e); }
159
+ .kpi-card.red::before { background: linear-gradient(90deg, #e03131, #f87171); }
160
+ .kpi-card.gold::before { background: linear-gradient(90deg, #d4940a, #f59e0b); }
161
+ .kpi-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(26,60,107,0.12); }
162
+
163
+ .kpi-label {
164
+ font-size: 0.70rem;
165
+ font-weight: 600;
166
+ color: #6b83a8;
167
+ text-transform: uppercase;
168
+ letter-spacing: 1.2px;
169
+ margin-bottom: 9px;
170
+ }
171
+ .kpi-value {
172
+ font-family: 'Space Grotesk', sans-serif !important;
173
+ font-size: 1.6rem;
174
+ font-weight: 700;
175
+ color: #0d1f3c;
176
+ line-height: 1.1;
177
+ }
178
+ .kpi-value.up { color: #0d9c5b; }
179
+ .kpi-value.down { color: #e03131; }
180
+ .kpi-value.warn { color: #d4940a; }
181
+ .kpi-delta {
182
+ font-size: 0.74rem;
183
+ font-weight: 500;
184
+ margin-top: 5px;
185
+ color: #6b83a8;
186
+ }
187
+ .kpi-delta.up { color: #0d9c5b; }
188
+ .kpi-delta.down { color: #e03131; }
189
+
190
+ /* Section headers */
191
+ .section-header {
192
+ margin-bottom: 18px;
193
+ padding-bottom: 12px;
194
+ border-bottom: 1px solid #d0dff0;
195
+ }
196
+ .section-title {
197
+ font-family: 'Space Grotesk', sans-serif !important;
198
+ font-size: 1rem;
199
+ font-weight: 600;
200
+ color: #0d2d6b;
201
+ }
202
+ .section-sub { font-size: 0.76rem; color: #6b83a8; margin-top: 3px; }
203
+
204
+ /* Badges */
205
+ .badge { display:inline-block; padding:4px 14px; border-radius:20px; font-size:0.71rem; font-weight:600; letter-spacing:.8px; text-transform:uppercase; }
206
+ .badge-ok { background:#d1fae5; color:#065f46; border:1px solid #6ee7b7; }
207
+ .badge-alert { background:#fee2e2; color:#991b1b; border:1px solid #fca5a5; }
208
+ .badge-warn { background:#fef3c7; color:#92400e; border:1px solid #fcd34d; }
209
+ .badge-info { background:#e8f0fe; color:#1a5fca; border:1px solid #a8c4f8; }
210
+
211
+ /* Banners */
212
+ .info-banner { background:#e8f0fe; border:1px solid #a8c4f8; border-left:4px solid #1a5fca; border-radius:8px; padding:12px 18px; font-size:.82rem; color:#1a3a6b; margin-bottom:14px; }
213
+ .alert-banner { background:#fee2e2; border:1px solid #fca5a5; border-left:4px solid #e03131; border-radius:8px; padding:12px 18px; font-size:.82rem; color:#7f1d1d; margin-bottom:14px; }
214
+ .success-banner { background:#d1fae5; border:1px solid #6ee7b7; border-left:4px solid #0d9c5b; border-radius:8px; padding:12px 18px; font-size:.82rem; color:#064e3b; margin-bottom:14px; }
215
+
216
+ /* Buttons */
217
+ button, .gr-button {
218
+ font-family: 'Inter', sans-serif !important;
219
+ font-weight: 600 !important;
220
+ font-size: 0.83rem !important;
221
+ border-radius: 8px !important;
222
+ transition: all 0.2s !important;
223
+ }
224
+ .gr-button-primary, button.primary {
225
+ background: linear-gradient(135deg, #1a5fca, #2979e8) !important;
226
+ color: #ffffff !important;
227
+ border: none !important;
228
+ box-shadow: 0 3px 12px rgba(26,95,202,0.28) !important;
229
+ }
230
+ .gr-button-primary:hover, button.primary:hover {
231
+ background: linear-gradient(135deg, #0d4fb5, #1a5fca) !important;
232
+ box-shadow: 0 5px 18px rgba(26,95,202,0.38) !important;
233
+ transform: translateY(-1px) !important;
234
+ }
235
+
236
+ /* Inputs */
237
+ input, select, textarea {
238
+ background: #ffffff !important;
239
+ border: 1.5px solid #c5d5ea !important;
240
+ border-radius: 8px !important;
241
+ color: #0d1f3c !important;
242
+ font-family: 'Inter', sans-serif !important;
243
+ font-size: 0.88rem !important;
244
+ }
245
+ input:focus, select:focus { border-color: #1a5fca !important; box-shadow: 0 0 0 3px rgba(26,95,202,0.12) !important; outline: none !important; }
246
+
247
+ label {
248
+ font-family: 'Inter', sans-serif !important;
249
+ font-size: 0.76rem !important;
250
+ font-weight: 600 !important;
251
+ color: #3a5080 !important;
252
+ text-transform: uppercase !important;
253
+ letter-spacing: 0.8px !important;
254
+ }
255
+
256
+ /* Tables */
257
+ table {
258
+ border-collapse: separate !important;
259
+ border-spacing: 0 !important;
260
+ background: #ffffff !important;
261
+ border-radius: 10px !important;
262
+ overflow: hidden !important;
263
+ border: 1px solid #d0dff0 !important;
264
+ font-size: 0.83rem !important;
265
+ box-shadow: 0 2px 10px rgba(26,60,107,0.06) !important;
266
+ }
267
+ th {
268
+ background: #1a3a6b !important;
269
+ color: #ffffff !important;
270
+ font-size: 0.72rem !important;
271
+ font-weight: 600 !important;
272
+ letter-spacing: 1px !important;
273
+ text-transform: uppercase !important;
274
+ padding: 12px 16px !important;
275
+ }
276
+ td { color: #0d1f3c !important; padding: 10px 16px !important; border-bottom: 1px solid #edf2fb !important; background: #ffffff !important; }
277
+ tr:nth-child(even) td { background: #f5f8fe !important; }
278
+ tr:hover td { background: #e8f0fe !important; }
279
+
280
+ /* Accordion */
281
+ .gr-accordion { background: #ffffff !important; border: 1px solid #d0dff0 !important; border-radius: 10px !important; }
282
+
283
+ /* Markdown */
284
+ .gr-markdown h1, .gr-markdown h2, .gr-markdown h3 { font-family: 'Space Grotesk', sans-serif !important; color: #0d2d6b !important; }
285
+ .gr-markdown p, .gr-markdown li { color: #0d1f3c !important; line-height: 1.7 !important; }
286
+ .gr-markdown strong { color: #1a5fca !important; }
287
+ .gr-markdown code { background: #e8f0fe !important; color: #1a5fca !important; border-radius: 4px !important; padding: 2px 7px !important; }
288
+ .gr-markdown table th { background: #1a3a6b !important; color: #fff !important; padding: 10px 14px !important; }
289
+ .gr-markdown table td { color: #0d1f3c !important; padding: 9px 14px !important; }
290
+
291
+ /* Slider */
292
+ input[type="range"] { accent-color: #1a5fca !important; }
293
+
294
+ /* Footer */
295
+ .app-footer {
296
+ background: #0d2d6b;
297
+ color: rgba(255,255,255,0.6);
298
+ text-align: center;
299
+ padding: 18px;
300
+ font-size: 0.72rem;
301
+ letter-spacing: 1.5px;
302
+ text-transform: uppercase;
303
+ margin-top: 40px;
304
+ }
305
+
306
+ /* Scrollbar */
307
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
308
+ ::-webkit-scrollbar-track { background: #f0f4fb; }
309
+ ::-webkit-scrollbar-thumb { background: #c5d5ea; border-radius: 3px; }
310
+ ::-webkit-scrollbar-thumb:hover { background: #1a5fca; }
311
+ """
312
+
313
+ # ─────────────────────────────────────────────
314
+ # HTML helpers
315
+ # ─────────────────────────────────────────────
316
+ def kpi_card(label, value, delta="", color="blue"):
317
+ cls_map = {"green": "up", "red": "down", "gold": "warn"}
318
+ val_cls = cls_map.get(color, "")
319
+ card_cls = color if color in ["green","red","gold"] else ""
320
+ dlt_cls = "up" if ("β–²" in delta or "+" in delta) else "down" if ("β–Ό" in delta or "-" in delta) else ""
321
+ d_html = f'<div class="kpi-delta {dlt_cls}">{delta}</div>' if delta else ""
322
+ return f"""
323
+ <div class="kpi-card {card_cls}">
324
+ <div class="kpi-label">{label}</div>
325
+ <div class="kpi-value {val_cls}">{value}</div>
326
+ {d_html}
327
+ </div>"""
328
+
329
+ def section_header(icon, title, subtitle=""):
330
+ sub = f'<div class="section-sub">{subtitle}</div>' if subtitle else ""
331
+ return f'<div class="section-header"><div class="section-title">{icon} {title}</div>{sub}</div>'
332
+
333
+ def banner(msg, kind="info"):
334
+ return f'<div class="{kind}-banner">{msg}</div>'
335
+
336
+ SYMBOLS = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN','RELIANCE']
337
+
338
+ # ─────────────────────────────────────────────
339
+ # Data helpers
340
+ # ─────────────────────────────────────────────
341
+ def get_realtime(symbols):
342
+ results = {}
343
+ for sym in symbols:
344
+ try:
345
+ info = yf.Ticker(sym).info
346
+ price = info.get('currentPrice') or info.get('regularMarketPrice') or 0
347
+ open_ = info.get('regularMarketOpen') or price
348
+ results[sym] = {
349
+ 'symbol': sym, 'price': price, 'open': open_,
350
+ 'high': info.get('dayHigh', 0), 'low': info.get('dayLow', 0),
351
+ 'volume': info.get('volume', 0), 'market_cap': info.get('marketCap', 0),
352
+ 'pe_ratio': info.get('trailingPE', 0),
353
+ 'change_pct': ((price - open_) / open_ * 100) if open_ else 0,
354
+ }
355
+ except Exception:
356
+ results[sym] = {k: 0 for k in ['price','open','high','low','volume','market_cap','pe_ratio','change_pct']}
357
+ results[sym]['symbol'] = sym
358
+ return results
359
+
360
+ def get_historical(symbol, period="1y"):
361
+ try:
362
+ df = yf.Ticker(symbol).history(period=period)
363
+ return df if not df.empty else pd.DataFrame()
364
+ except Exception:
365
+ return pd.DataFrame()
366
+
367
+ def get_returns(symbol, period="1y"):
368
+ df = get_historical(symbol, period)
369
+ if df.empty:
370
+ return pd.Series(dtype=float)
371
+ return df['Close'].pct_change().dropna()
372
+
373
+ def compute_risk(returns, portfolio_value, rf=0.04):
374
+ if returns.empty:
375
+ return {}
376
+ daily_vol = returns.std()
377
+ annual_vol = daily_vol * np.sqrt(252)
378
+ total_ret = (1 + returns).prod() - 1
379
+ years = max(len(returns) / 252, 0.01)
380
+ ann_ret = (1 + total_ret) ** (1 / years) - 1
381
+ sharpe = (ann_ret - rf) / annual_vol if annual_vol else 0
382
+ var_95 = abs(np.percentile(returns, 5))
383
+ var_99 = abs(np.percentile(returns, 1))
384
+ tail = returns[returns <= -var_95]
385
+ cvar_95 = abs(tail.mean()) if len(tail) else var_95
386
+ cum = (1 + returns).cumprod()
387
+ peak = cum.cummax()
388
+ dd = (cum - peak) / peak
389
+ max_dd = abs(dd.min())
390
+ return dict(
391
+ annual_vol=annual_vol, daily_vol=daily_vol, ann_ret=ann_ret, sharpe=sharpe,
392
+ var_95=var_95, var_99=var_99, cvar_95=cvar_95,
393
+ var_95_usd=var_95*portfolio_value, var_99_usd=var_99*portfolio_value,
394
+ cvar_95_usd=cvar_95*portfolio_value, max_dd=max_dd, drawdown=dd, returns=returns,
395
+ )
396
+
397
+ def sharpe_label(s):
398
+ if s > 3: return "Exceptional", "green"
399
+ if s > 2: return "Very Good", "green"
400
+ if s > 1: return "Good", "blue"
401
+ if s > 0.5: return "Acceptable", "gold"
402
+ if s > 0: return "Poor", "gold"
403
+ return "Losing Money", "red"
404
+
405
+ def apply_theme(fig, title_text=None, yaxis_title=None, xaxis_title=None, extra=None):
406
+ layout = dict(**PLOTLY_THEME)
407
+ layout['xaxis'] = dict(**AXIS_STYLE)
408
+ layout['yaxis'] = dict(**AXIS_STYLE)
409
+ if title_text:
410
+ layout['title'] = dict(text=title_text, font=dict(color="#1a3a6b", size=14, family="Inter, sans-serif"))
411
+ if yaxis_title:
412
+ layout['yaxis']['title'] = yaxis_title
413
+ if xaxis_title:
414
+ layout['xaxis']['title'] = xaxis_title
415
+ if extra:
416
+ layout.update(extra)
417
+ fig.update_layout(**layout)
418
+ return fig
419
+
420
+ # ═══════════════════════════════════════════════
421
+ # TAB RENDER FUNCTIONS
422
+ # ═══════════════════════════════════════════════
423
+
424
+ def render_market_overview():
425
+ data = get_realtime(SYMBOLS)
426
+ ts = datetime.now().strftime('%d %b %Y %H:%M:%S')
427
+
428
+ cards = '<div class="metric-grid metric-grid-5">'
429
+ for sym, d in data.items():
430
+ chg = d.get('change_pct', 0)
431
+ sign = "β–²" if chg >= 0 else "β–Ό"
432
+ col = "green" if chg >= 0 else "red"
433
+ cards += kpi_card(sym, f"${d['price']:.2f}" if d['price'] else "β€”",
434
+ f"{sign} {abs(chg):.2f}%", col)
435
+ cards += "</div>"
436
+
437
+ prices = {s: d['price'] for s, d in data.items() if d['price']}
438
+ changes = {s: d['change_pct'] for s, d in data.items()}
439
+ bcolors = [GREEN if changes.get(s,0) >= 0 else RED for s in prices]
440
+
441
+ fig_p = go.Figure()
442
+ fig_p.add_trace(go.Bar(
443
+ x=list(prices.keys()), y=list(prices.values()),
444
+ marker=dict(color=bcolors, line=dict(color='white', width=1)),
445
+ text=[f"${v:.2f}" for v in prices.values()],
446
+ textposition='outside', textfont=dict(size=11, color=TEXT_DARK),
447
+ hovertemplate="<b>%{x}</b><br>Price: $%{y:.2f}<extra></extra>",
448
+ ))
449
+ apply_theme(fig_p, title_text="Current Stock Prices (USD)", yaxis_title="Price ($)", extra={"showlegend": False})
450
+
451
+ vols = {s: d.get('volume', 0) for s, d in data.items()}
452
+ fig_v = go.Figure()
453
+ fig_v.add_trace(go.Bar(
454
+ x=list(vols.keys()), y=list(vols.values()),
455
+ marker=dict(color=list(vols.values()),
456
+ colorscale=[[0, BLUE_LIGHT],[1, BLUE_PRIMARY]],
457
+ showscale=False, line=dict(color='white', width=1)),
458
+ text=[f"{v/1e6:.1f}M" for v in vols.values()],
459
+ textposition='outside', textfont=dict(size=11, color=TEXT_DARK),
460
+ hovertemplate="<b>%{x}</b><br>Volume: %{y:,.0f}<extra></extra>",
461
+ ))
462
+ apply_theme(fig_v, title_text="Trading Volume", yaxis_title="Volume", extra={"showlegend": False})
463
+
464
+ rows = []
465
+ for s, d in data.items():
466
+ chg = d.get('change_pct', 0)
467
+ rows.append({
468
+ 'Symbol': s, 'Price ($)': f"${d['price']:.2f}" if d['price'] else "β€”",
469
+ 'Open ($)': f"${d['open']:.2f}" if d['open'] else "β€”",
470
+ 'High ($)': f"${d['high']:.2f}" if d['high'] else "β€”",
471
+ 'Low ($)': f"${d['low']:.2f}" if d['low'] else "β€”",
472
+ 'Volume': f"{d['volume']/1e6:.1f}M" if d['volume'] else "β€”",
473
+ 'Mkt Cap': f"${d['market_cap']/1e12:.2f}T" if d.get('market_cap') else "β€”",
474
+ 'P/E': f"{d['pe_ratio']:.1f}" if d.get('pe_ratio') else "β€”",
475
+ 'Change': f"{'β–²' if chg >= 0 else 'β–Ό'} {abs(chg):.2f}%",
476
+ })
477
+
478
+ return (cards, fig_p, fig_v, pd.DataFrame(rows),
479
+ banner(f"βœ… Data refreshed at {ts}", "success"))
480
+
481
+
482
+ def render_historical(symbol, period):
483
+ df = get_historical(symbol, period)
484
+ if df.empty:
485
+ return None, None, None, banner("⚠ No data available.", "alert")
486
+
487
+ fig_c = go.Figure()
488
+ fig_c.add_trace(go.Candlestick(
489
+ x=df.index, open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'],
490
+ increasing=dict(line=dict(color=GREEN), fillcolor="rgba(13,156,91,0.22)"),
491
+ decreasing=dict(line=dict(color=RED), fillcolor="rgba(224,49,49,0.22)"),
492
+ name="Price",
493
+ ))
494
+ ma20 = df['Close'].rolling(20).mean()
495
+ fig_c.add_trace(go.Scatter(x=df.index, y=ma20, name="MA 20",
496
+ line=dict(color=BLUE_PRIMARY, width=1.8, dash='dot')))
497
+ apply_theme(fig_c, title_text=f"{symbol} β€” Candlestick Chart ({period})", yaxis_title="Price (USD)", extra={"xaxis_rangeslider_visible": False})
498
+
499
+ returns = df['Close'].pct_change().dropna()
500
+ cum_ret = (1 + returns).cumprod() - 1
501
+ col_ret = GREEN if cum_ret.iloc[-1] >= 0 else RED
502
+ fig_r = go.Figure()
503
+ fig_r.add_trace(go.Scatter(
504
+ x=cum_ret.index, y=cum_ret * 100, fill='tozeroy',
505
+ fillcolor=f"rgba(13,156,91,0.10)" if cum_ret.iloc[-1] >= 0 else "rgba(224,49,49,0.10)",
506
+ line=dict(color=col_ret, width=2.2), name="Cumulative Return",
507
+ hovertemplate="%{x|%b %d, %Y}<br>Return: %{y:.2f}%<extra></extra>",
508
+ ))
509
+ fig_r.add_hline(y=0, line=dict(color=TEXT_LIGHT, dash='dash', width=1))
510
+ apply_theme(fig_r, title_text="Cumulative Return (%)", yaxis_title="Return (%)")
511
+
512
+ vcols = [GREEN if c >= o else RED for c, o in zip(df['Close'], df['Open'])]
513
+ fig_v = go.Figure()
514
+ fig_v.add_trace(go.Bar(x=df.index, y=df['Volume'], marker_color=vcols, name="Volume",
515
+ hovertemplate="%{x|%b %d}<br>Vol: %{y:,.0f}<extra></extra>"))
516
+ apply_theme(fig_v, title_text="Volume (Green = Up Day, Red = Down Day)", yaxis_title="Volume")
517
+
518
+ total = cum_ret.iloc[-1] * 100
519
+ sign = "β–²" if total >= 0 else "β–Ό"
520
+ col = "green" if total >= 0 else "red"
521
+ stats = f"""<div class="metric-grid metric-grid-4">
522
+ {kpi_card("Current Price", f"${df['Close'].iloc[-1]:.2f}")}
523
+ {kpi_card("Period High", f"${df['High'].max():.2f}", color="green")}
524
+ {kpi_card("Period Low", f"${df['Low'].min():.2f}", color="red")}
525
+ {kpi_card("Total Return", f"{sign} {abs(total):.2f}%", color=col)}
526
+ </div>"""
527
+
528
+ return fig_c, fig_r, fig_v, stats
529
+
530
+
531
+ def render_risk(symbol, portfolio_value):
532
+ returns = get_returns(symbol, "1y")
533
+ if returns.empty:
534
+ return banner("⚠ Could not fetch data.", "alert"), None, None, None, None
535
+
536
+ m = compute_risk(returns, portfolio_value)
537
+ slabel, scol = sharpe_label(m['sharpe'])
538
+ risk_ok = m['annual_vol'] < 0.30 and m['max_dd'] < 0.20 and m['sharpe'] > 1.0
539
+ badge = '<span class="badge badge-ok">βœ“ Within Limits</span>' if risk_ok else \
540
+ '<span class="badge badge-alert">⚠ Risk Alert</span>'
541
+
542
+ kpi_html = f"""
543
+ {section_header("πŸ›‘οΈ", f"Risk Assessment β€” {symbol}",
544
+ f"Portfolio Value: ${portfolio_value:,.0f} | {len(returns)} trading days")}
545
+ <div style="margin-bottom:14px">{badge}</div>
546
+ <div class="metric-grid metric-grid-4" style="margin-bottom:14px">
547
+ {kpi_card("VaR 95%", f"{m['var_95']:.2%}", f"βˆ’${m['var_95_usd']:,.0f}/day", "red")}
548
+ {kpi_card("VaR 99%", f"{m['var_99']:.2%}", f"βˆ’${m['var_99_usd']:,.0f}/day", "red")}
549
+ {kpi_card("CVaR 95%", f"{m['cvar_95']:.2%}", "Expected Shortfall", "red")}
550
+ {kpi_card("Annual Vol", f"{m['annual_vol']:.2%}", f"Daily: {m['daily_vol']:.2%}",
551
+ "gold" if m['annual_vol'] > 0.25 else "blue")}
552
+ </div>
553
+ <div class="metric-grid metric-grid-4">
554
+ {kpi_card("Max Drawdown", f"{m['max_dd']:.2%}", "Peak-to-Trough",
555
+ "red" if m['max_dd'] > 0.20 else "gold")}
556
+ {kpi_card("Sharpe Ratio", f"{m['sharpe']:.2f}", slabel, scol)}
557
+ {kpi_card("Annual Return", f"{m['ann_ret']:.2%}",
558
+ "β–² Positive" if m['ann_ret'] >= 0 else "β–Ό Negative",
559
+ "green" if m['ann_ret'] >= 0 else "red")}
560
+ {kpi_card("Data Points", str(len(returns)), "Trading Days")}
561
+ </div>"""
562
+
563
+ # Distribution
564
+ fig_dist = go.Figure()
565
+ fig_dist.add_trace(go.Histogram(
566
+ x=returns * 100, nbinsx=55,
567
+ marker=dict(color=BLUE_PRIMARY, opacity=0.75, line=dict(color='white', width=0.5)),
568
+ name="Daily Returns",
569
+ hovertemplate="Return: %{x:.2f}%<br>Count: %{y}<extra></extra>",
570
+ ))
571
+ fig_dist.add_vline(x=-m['var_95']*100, line=dict(color=GOLD, dash='dash', width=2),
572
+ annotation=dict(text="VaR 95%", font=dict(color=GOLD, size=10)))
573
+ fig_dist.add_vline(x=-m['var_99']*100, line=dict(color=RED, dash='dash', width=2),
574
+ annotation=dict(text="VaR 99%", font=dict(color=RED, size=10)))
575
+ apply_theme(fig_dist, title_text="Return Distribution with VaR Lines", xaxis_title="Daily Return (%)", yaxis_title="Frequency")
576
+
577
+ # Drawdown
578
+ dd = m['drawdown']
579
+ fig_dd = go.Figure()
580
+ fig_dd.add_trace(go.Scatter(
581
+ x=dd.index, y=dd * 100, fill='tozeroy',
582
+ fillcolor="rgba(224,49,49,0.13)",
583
+ line=dict(color=RED, width=1.8), name="Drawdown %",
584
+ hovertemplate="%{x|%b %d, %Y}<br>Drawdown: %{y:.2f}%<extra></extra>",
585
+ ))
586
+ fig_dd.add_hline(y=-m['max_dd']*100, line=dict(color=GOLD, dash='dot', width=1.5),
587
+ annotation=dict(text=f"Max DD {m['max_dd']:.2%}", font=dict(color=GOLD, size=10)))
588
+ apply_theme(fig_dd, title_text="Underwater Drawdown Chart", yaxis_title="Drawdown (%)")
589
+
590
+ # Rolling vol
591
+ rv = returns.rolling(21).std() * np.sqrt(252) * 100
592
+ fig_rv = go.Figure()
593
+ fig_rv.add_trace(go.Scatter(
594
+ x=rv.index, y=rv, fill='tozeroy', fillcolor="rgba(26,95,202,0.09)",
595
+ line=dict(color=BLUE_PRIMARY, width=2), name="21-day Vol",
596
+ hovertemplate="%{x|%b %d, %Y}<br>Vol: %{y:.2f}%<extra></extra>",
597
+ ))
598
+ fig_rv.add_hline(y=30, line=dict(color=RED, dash='dash', width=1.3),
599
+ annotation=dict(text="Risk Limit 30%", font=dict(color=RED, size=10)))
600
+ apply_theme(fig_rv, title_text="Rolling 21-Day Annualised Volatility", yaxis_title="Volatility (%)")
601
+
602
+ # Gauge
603
+ risk_score = min(100, m['annual_vol']/0.5*40 + m['max_dd']/0.5*40 + max(0,1-m['sharpe'])*20)
604
+ gcol = GREEN if risk_score < 40 else GOLD if risk_score < 70 else RED
605
+ fig_g = go.Figure(go.Indicator(
606
+ mode="gauge+number",
607
+ value=risk_score,
608
+ title=dict(text="RISK SCORE", font=dict(family="Inter", size=13, color=TEXT_MED)),
609
+ number=dict(font=dict(family="Space Grotesk", size=38, color=gcol)),
610
+ gauge=dict(
611
+ axis=dict(range=[0,100], tickwidth=1, tickcolor=TEXT_LIGHT,
612
+ tickfont=dict(family="Inter", size=10, color=TEXT_LIGHT)),
613
+ bar=dict(color=gcol, thickness=0.25),
614
+ bgcolor=BG_CARD, borderwidth=1, bordercolor=BORDER,
615
+ steps=[dict(range=[0,40], color="rgba(13,156,91,0.08)"),
616
+ dict(range=[40,70], color="rgba(212,148,10,0.08)"),
617
+ dict(range=[70,100],color="rgba(224,49,49,0.08)")],
618
+ threshold=dict(line=dict(color=gcol, width=3), thickness=0.75, value=risk_score),
619
+ ),
620
+ ))
621
+ fig_g.update_layout(paper_bgcolor=BG_CARD, font=dict(family="Inter", color=TEXT_DARK),
622
+ height=260, margin=dict(l=30,r=30,t=60,b=20))
623
+
624
+ return kpi_html, fig_dist, fig_dd, fig_rv, fig_g
625
+
626
+
627
+ SCENARIOS = {
628
+ "Moderate βˆ’5%": -0.05,
629
+ "Correction βˆ’10%": -0.10,
630
+ "Bear Market βˆ’20%": -0.20,
631
+ "Severe βˆ’30%": -0.30,
632
+ "2008 Crisis βˆ’50%": -0.50,
633
+ "COVID βˆ’35%": -0.35,
634
+ "Flash Crash βˆ’10%": -0.10,
635
+ "Rate Shock βˆ’15%": -0.15,
636
+ }
637
+
638
+ def render_stress(symbol, portfolio_value):
639
+ returns = get_returns(symbol, "1y")
640
+ avg_daily = returns.mean() if not returns.empty else 0.0003
641
+
642
+ rows, pcts, dloss, labels = [], [], [], []
643
+ for name, shock in SCENARIOS.items():
644
+ shocked = portfolio_value * (1 + shock)
645
+ loss = portfolio_value - shocked
646
+ days_rec = abs(shock) / avg_daily if avg_daily > 0 else float('inf')
647
+ yrs_rec = round(days_rec/252, 1) if days_rec != float('inf') else None
648
+ rows.append({'Scenario': name, 'Market Shock': f"{shock:.0%}",
649
+ 'Portfolio After': f"${shocked:,.0f}", 'Loss Amount': f"${loss:,.0f}",
650
+ 'Recovery (yrs)': str(yrs_rec) if yrs_rec else "N/A"})
651
+ pcts.append(shock * 100)
652
+ dloss.append(loss)
653
+ labels.append(name)
654
+
655
+ def sev(l):
656
+ if l < -30: return RED
657
+ if l < -15: return GOLD
658
+ return BLUE_PRIMARY
659
+
660
+ fig_pct = go.Figure()
661
+ fig_pct.add_trace(go.Bar(
662
+ x=labels, y=pcts,
663
+ marker=dict(color=[sev(l) for l in pcts], line=dict(color='white', width=1)),
664
+ text=[f"{l:.0f}%" for l in pcts], textposition='outside',
665
+ textfont=dict(size=10, color=TEXT_DARK),
666
+ hovertemplate="<b>%{x}</b><br>Loss: %{y:.1f}%<extra></extra>",
667
+ ))
668
+ apply_theme(fig_pct, title_text="Portfolio Loss % by Scenario", yaxis_title="Loss (%)", extra={"yaxis": dict(**AXIS_STYLE, range=[min(pcts)*1.3, 5])})
669
+
670
+ fig_usd = go.Figure()
671
+ fig_usd.add_trace(go.Bar(
672
+ x=labels, y=dloss,
673
+ marker=dict(color=dloss, colorscale=[[0,BLUE_LIGHT],[0.5,GOLD],[1,RED]],
674
+ showscale=False, line=dict(color='white', width=1)),
675
+ text=[f"${l:,.0f}" for l in dloss], textposition='outside',
676
+ textfont=dict(size=10, color=TEXT_DARK),
677
+ hovertemplate="<b>%{x}</b><br>Loss: $%{y:,.0f}<extra></extra>",
678
+ ))
679
+ apply_theme(fig_usd, title_text="Dollar Loss by Scenario", yaxis_title="Loss ($)")
680
+
681
+ return fig_pct, fig_usd, pd.DataFrame(rows)
682
+
683
+
684
+ def render_correlation(symbols_str):
685
+ syms = [s.strip().upper() for s in symbols_str.split(',') if s.strip()]
686
+ if len(syms) < 2:
687
+ return None, banner("⚠ Enter at least 2 comma-separated symbols.", "alert"), None
688
+
689
+ all_ret = {}
690
+ for s in syms:
691
+ r = get_returns(s, "1y")
692
+ if not r.empty:
693
+ all_ret[s] = r
694
+
695
+ if len(all_ret) < 2:
696
+ return None, banner("⚠ Could not fetch data for enough symbols.", "alert"), None
697
+
698
+ df_ret = pd.DataFrame(all_ret).dropna()
699
+ corr = df_ret.corr()
700
+
701
+ fig_h = go.Figure(go.Heatmap(
702
+ z=corr.values, x=corr.columns.tolist(), y=corr.index.tolist(),
703
+ colorscale=[[0, RED],[0.5,"#f0f4fb"],[1, BLUE_PRIMARY]],
704
+ zmid=0, zmin=-1, zmax=1,
705
+ text=corr.values.round(2), texttemplate="%{text}",
706
+ textfont=dict(family="Inter", size=13, color=TEXT_DARK),
707
+ hovertemplate="<b>%{x} vs %{y}</b><br>r = %{z:.3f}<extra></extra>",
708
+ colorbar=dict(tickfont=dict(family="Inter", color=TEXT_MED),
709
+ title=dict(text="r", font=dict(color=TEXT_MED))),
710
+ ))
711
+ apply_theme(fig_h, title_text="Correlation Matrix β€” 1 Year Daily Returns")
712
+
713
+ cum_df = (1 + df_ret).cumprod() - 1
714
+ palette = [BLUE_PRIMARY, GREEN, GOLD, RED, "#7c3aed", "#db2777", "#0891b2"]
715
+ fig_cr = go.Figure()
716
+ for i, col in enumerate(cum_df.columns):
717
+ fig_cr.add_trace(go.Scatter(
718
+ x=cum_df.index, y=cum_df[col]*100, name=col,
719
+ line=dict(color=palette[i % len(palette)], width=2.2),
720
+ hovertemplate=f"<b>{col}</b><br>%{{x|%b %d}}<br>Return: %{{y:.2f}}%<extra></extra>",
721
+ ))
722
+ apply_theme(fig_cr, title_text="Cumulative Returns Comparison (%)", yaxis_title="Return (%)")
723
+
724
+ avg_corr = corr.values[np.triu_indices_from(corr.values, k=1)].mean()
725
+ if avg_corr < 0.5:
726
+ msg, kind = f"βœ… Well Diversified β€” avg correlation: {avg_corr:.3f}", "success"
727
+ elif avg_corr < 0.7:
728
+ msg, kind = f"⚠ Moderately Correlated β€” avg correlation: {avg_corr:.3f}", "info"
729
+ else:
730
+ msg, kind = f"πŸ”΄ Highly Correlated β€” Low Diversification Benefit (r={avg_corr:.3f})", "alert"
731
+
732
+ return fig_h, banner(msg, kind), fig_cr
733
+
734
+
735
+ def render_monte_carlo(symbol, portfolio_value, days, sims):
736
+ days, sims = int(days), int(sims)
737
+ returns = get_returns(symbol, "1y")
738
+ if returns.empty:
739
+ return None, banner("⚠ Could not fetch data.", "alert")
740
+
741
+ mu, sigma = returns.mean(), returns.std()
742
+ np.random.seed(42)
743
+ sim_rets = np.random.normal(mu, sigma, (days, sims))
744
+ sim_paths = portfolio_value * np.exp(np.cumsum(np.log(1 + sim_rets), axis=0))
745
+ final_vals = sim_paths[-1]
746
+
747
+ fig = go.Figure()
748
+ x_ax = list(range(days))
749
+ for i in range(min(200, sims)):
750
+ col = "rgba(13,156,91,0.13)" if sim_paths[-1,i] >= portfolio_value else "rgba(224,49,49,0.10)"
751
+ fig.add_trace(go.Scatter(x=x_ax, y=sim_paths[:,i], mode='lines',
752
+ line=dict(color=col, width=0.5),
753
+ showlegend=False, hoverinfo='skip'))
754
+
755
+ med_path = np.median(sim_paths, axis=1)
756
+ fig.add_trace(go.Scatter(x=x_ax, y=med_path, mode='lines',
757
+ line=dict(color=BLUE_PRIMARY, width=2.8), name="Median Path"))
758
+
759
+ p5 = np.percentile(sim_paths, 5, axis=1)
760
+ p95 = np.percentile(sim_paths, 95, axis=1)
761
+ fig.add_trace(go.Scatter(
762
+ x=x_ax + x_ax[::-1], y=list(p95)+list(p5[::-1]),
763
+ fill='toself', fillcolor="rgba(26,95,202,0.07)",
764
+ line=dict(color='rgba(0,0,0,0)'), name="90% Confidence Band",
765
+ ))
766
+ fig.add_hline(y=portfolio_value, line=dict(color=TEXT_LIGHT, dash='dash', width=1.5),
767
+ annotation=dict(text="Initial Value", font=dict(color=TEXT_LIGHT, size=10)))
768
+ apply_theme(fig, title_text=f"Monte Carlo β€” {sims} Paths over {days} Trading Days", yaxis_title="Portfolio Value ($)", xaxis_title="Trading Day")
769
+
770
+ med_fin = np.median(final_vals)
771
+ p5_fin = np.percentile(final_vals, 5)
772
+ p95_fin = np.percentile(final_vals, 95)
773
+ pct_profit = (final_vals >= portfolio_value).mean() * 100
774
+ med_ret = (med_fin / portfolio_value - 1) * 100
775
+ sign = "β–²" if med_ret >= 0 else "β–Ό"
776
+
777
+ stats = f"""<div class="metric-grid metric-grid-4" style="margin-top:16px">
778
+ {kpi_card("Median Outcome", f"${med_fin:,.0f}",
779
+ f"{sign} {abs(med_ret):.1f}%", "green" if med_ret >= 0 else "red")}
780
+ {kpi_card("Best Case (95th)", f"${p95_fin:,.0f}",
781
+ f"+{(p95_fin/portfolio_value-1)*100:.1f}%", "green")}
782
+ {kpi_card("Worst Case (5th)", f"${p5_fin:,.0f}",
783
+ f"{(p5_fin/portfolio_value-1)*100:.1f}%", "red")}
784
+ {kpi_card("% Profitable", f"{pct_profit:.1f}%",
785
+ f"of {sims} simulations", "green" if pct_profit >= 50 else "red")}
786
+ </div>"""
787
+
788
+ return fig, stats
789
+
790
+ # ═══════════════════════════════════════════════
791
+ # BUILD APP
792
+ # ═══════════════════════════════════════════════
793
+
794
+ HEADER_HTML = """
795
+ <div class="app-header">
796
+ <div class="app-title">⬑ Portfolio Optimization Intelligence System</div>
797
+ <div class="header-accent"></div>
798
+ <div class="app-subtitle">Multi-Agent Risk &amp; Market Analytics Platform &nbsp;Β·&nbsp; v3.0</div>
799
+ <div class="app-team">Team: Ashwini &nbsp;|&nbsp; Dibyendu Sarkar &nbsp;|&nbsp; Jyoti Ranjan Sethi &nbsp;|&nbsp; IIT Madras 2026</div>
800
+ </div>
801
+ """
802
+
803
+ FOOTER_HTML = """
804
+ <div class="app-footer">
805
+ ⬑ Portfolio Intelligence System &nbsp;|&nbsp; IIT Madras 2026 &nbsp;|&nbsp;
806
+ Data Source: Yahoo Finance &nbsp;|&nbsp; For Educational Use Only
807
+ </div>
808
+ """
809
+
810
+ with gr.Blocks(title="Portfolio Intelligence System") as demo:
811
+
812
+ gr.HTML(HEADER_HTML)
813
+
814
+ with gr.Row():
815
+ shared_symbol = gr.Dropdown(choices=SYMBOLS, value="AAPL",
816
+ label="πŸ“Œ Stock Symbol", scale=2)
817
+ shared_period = gr.Dropdown(choices=["1mo","3mo","6mo","1y","2y","5y"],
818
+ value="1y", label="πŸ“… Period", scale=1)
819
+ shared_portfolio = gr.Number(value=100_000, label="πŸ’° Portfolio Value ($)",
820
+ minimum=1000, scale=2)
821
+
822
+ with gr.Tabs():
823
+
824
+ with gr.Tab("πŸ“‘ Market Overview"):
825
+ overview_btn = gr.Button("πŸ”„ Refresh Market Data", variant="primary", size="lg")
826
+ status_out = gr.HTML()
827
+ cards_out = gr.HTML()
828
+ with gr.Row():
829
+ price_out = gr.Plot(label="Stock Prices")
830
+ vol_out = gr.Plot(label="Trading Volume")
831
+ with gr.Accordion("πŸ“‹ Detailed Price Table", open=False):
832
+ table_out = gr.Dataframe(interactive=False)
833
+ overview_btn.click(fn=render_market_overview,
834
+ outputs=[cards_out, price_out, vol_out, table_out, status_out])
835
+
836
+ with gr.Tab("πŸ“ˆ Historical Analysis"):
837
+ hist_btn = gr.Button("πŸ“ˆ Load Historical Data", variant="primary", size="lg")
838
+ hist_stat = gr.HTML()
839
+ candle = gr.Plot(label="Candlestick + MA20")
840
+ ret_chart = gr.Plot(label="Cumulative Return")
841
+ vol_hist = gr.Plot(label="Volume")
842
+ hist_btn.click(fn=render_historical,
843
+ inputs=[shared_symbol, shared_period],
844
+ outputs=[candle, ret_chart, vol_hist, hist_stat])
845
+
846
+ with gr.Tab("πŸ›‘οΈ Risk Assessment"):
847
+ risk_btn = gr.Button("πŸ” Calculate Risk Metrics", variant="primary", size="lg")
848
+ risk_kpi = gr.HTML()
849
+ with gr.Row():
850
+ gauge_out = gr.Plot(label="Risk Score Gauge")
851
+ dist_out = gr.Plot(label="Return Distribution")
852
+ dd_out = gr.Plot(label="Drawdown Chart")
853
+ rv_out = gr.Plot(label="Rolling Volatility")
854
+ risk_btn.click(fn=render_risk,
855
+ inputs=[shared_symbol, shared_portfolio],
856
+ outputs=[risk_kpi, dist_out, dd_out, rv_out, gauge_out])
857
+
858
+ with gr.Tab("πŸ’₯ Stress Testing"):
859
+ stress_btn = gr.Button("πŸ’₯ Run Stress Tests", variant="primary", size="lg")
860
+ with gr.Row():
861
+ spct = gr.Plot(label="Loss % by Scenario")
862
+ susd = gr.Plot(label="Dollar Loss by Scenario")
863
+ with gr.Accordion("πŸ“‹ Full Stress Test Table", open=True):
864
+ stbl = gr.Dataframe(interactive=False)
865
+ stress_btn.click(fn=render_stress,
866
+ inputs=[shared_symbol, shared_portfolio],
867
+ outputs=[spct, susd, stbl])
868
+
869
+ with gr.Tab("πŸ”— Correlation"):
870
+ sym_in = gr.Textbox(value="AAPL,GOOGL,MSFT,TSLA,AMZN",
871
+ label="Symbols (comma-separated)")
872
+ corr_btn = gr.Button("πŸ”— Compute Correlations", variant="primary", size="lg")
873
+ corr_inf = gr.HTML()
874
+ heat_out = gr.Plot(label="Correlation Heatmap")
875
+ cmp_out = gr.Plot(label="Cumulative Return Comparison")
876
+ corr_btn.click(fn=render_correlation, inputs=[sym_in],
877
+ outputs=[heat_out, corr_inf, cmp_out])
878
+
879
+ with gr.Tab("🎲 Monte Carlo"):
880
+ with gr.Row():
881
+ mc_days = gr.Slider(21, 504, value=252, step=21, label="Simulation Days")
882
+ mc_sims = gr.Slider(100, 1000, value=500, step=100, label="Simulations")
883
+ mc_btn = gr.Button("🎲 Run Monte Carlo Simulation", variant="primary", size="lg")
884
+ mc_stats = gr.HTML()
885
+ mc_chart = gr.Plot(label="Simulation Paths")
886
+ mc_btn.click(fn=render_monte_carlo,
887
+ inputs=[shared_symbol, shared_portfolio, mc_days, mc_sims],
888
+ outputs=[mc_chart, mc_stats])
889
+
890
+ with gr.Tab("ℹ️ About"):
891
+ gr.Markdown("""
892
+ ## ⬑ Portfolio Intelligence System
893
+
894
+ A **multi-agent AI-powered platform** for comprehensive portfolio risk analysis.
895
+
896
+ ---
897
+
898
+ ### 🧩 Modules
899
+
900
+ | Module | Description |
901
+ |---|---|
902
+ | **Market Overview** | Real-time prices, volume, and market cap |
903
+ | **Historical Analysis** | Candlestick charts, MA20, cumulative returns |
904
+ | **Risk Assessment** | VaR, CVaR, Sharpe, Drawdown, Rolling Vol, Gauge |
905
+ | **Stress Testing** | 8 crash scenarios with loss & recovery analysis |
906
+ | **Correlation** | Heatmap + cumulative return comparison |
907
+ | **Monte Carlo** | Up to 1000-path simulation with confidence bands |
908
+
909
+ ---
910
+
911
+ ### πŸ—οΈ Architecture
912
+ ```
913
+ Yahoo Finance API β†’ Market Data Agent β†’ SQLite DB
914
+ ↓
915
+ Risk Management Agent
916
+ ↓
917
+ Gradio Dashboard UI
918
+ ```
919
+
920
+ ---
921
+ **Team:** Ashwini Β· Dibyendu Sarkar Β· Jyoti Ranjan Sethi
922
+ **Week:** 3 of 16 Β· IIT Madras Β· February 2026
923
+ ⚠️ *For educational purposes only β€” not financial advice.*
924
+ """)
925
+
926
+ gr.HTML(FOOTER_HTML)
927
+
928
+
929
+ if __name__ == "__main__":
930
+ demo.launch(
931
+ share=True,
932
+ server_name="0.0.0.0",
933
+ server_port=7862,
934
+ show_error=True,
935
+ css=CUSTOM_CSS,
936
+ )
streamlit_app.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from agents.market_data.agent import MarketDataAgent
4
+ from agents.market_data.storage import MarketDataStorage
5
+ import plotly.graph_objects as go
6
+ from datetime import datetime
7
+
8
+ # Page config
9
+ st.set_page_config(
10
+ page_title="Market Data Agent",
11
+ page_icon="πŸ“ˆ",
12
+ layout="wide"
13
+ )
14
+
15
+ # Initialize
16
+ @st.cache_resource
17
+ def get_agent():
18
+ symbols = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN']
19
+ return MarketDataAgent(symbols), MarketDataStorage()
20
+
21
+ agent, storage = get_agent()
22
+
23
+ # Title
24
+ st.title("πŸ“ˆ Market Data Agent - Live Demo")
25
+ st.markdown("### Week 2: Multi-Agent Portfolio Optimization System")
26
+ st.markdown("**Team:** Ashwini, Dibyendu Sarkar, Jyoti Ranjan Sethi")
27
+ st.divider()
28
+
29
+ # Sidebar
30
+ with st.sidebar:
31
+ st.header("βš™οΈ Settings")
32
+
33
+ st.subheader("Tracked Symbols")
34
+ st.code("AAPL, GOOGL, MSFT, TSLA, AMZN")
35
+
36
+ st.subheader("Features")
37
+ st.markdown("""
38
+ βœ… Real-time prices
39
+ βœ… Historical data
40
+ βœ… Price charts
41
+ βœ… Database storage
42
+ βœ… REST API
43
+ """)
44
+
45
+ st.divider()
46
+ st.markdown("**Project:** Multi-Agent Portfolio Optimization")
47
+ st.markdown("**Week:** 2 of 16")
48
+
49
+ # Main content - Tabs
50
+ tab1, tab2, tab3, tab4 = st.tabs(["πŸ’° Real-Time Prices", "πŸ“Š Historical Data", "πŸ’Ύ Database", "ℹ️ About"])
51
+
52
+ # Tab 1: Real-Time Prices
53
+ with tab1:
54
+ st.header("Real-Time Market Data")
55
+
56
+ if st.button("πŸ”„ Fetch Current Prices", type="primary"):
57
+ with st.spinner("Fetching data..."):
58
+ data = agent.fetch_all_symbols()
59
+
60
+ # Save to database
61
+ for symbol, info in data.items():
62
+ storage.save_realtime_data(info)
63
+
64
+ # Display as metrics
65
+ cols = st.columns(5)
66
+ for i, (symbol, info) in enumerate(data.items()):
67
+ with cols[i]:
68
+ change = ((info['price'] - info.get('open', info['price'])) / info.get('open', info['price']) * 100) if info.get('open') else 0
69
+ st.metric(
70
+ label=symbol,
71
+ value=f"${info['price']:.2f}",
72
+ delta=f"{change:.2f}%"
73
+ )
74
+
75
+ # Display as table
76
+ st.subheader("Detailed View")
77
+ df = pd.DataFrame(data).T
78
+ df = df[['symbol', 'price', 'open', 'high', 'low', 'volume', 'pe_ratio', 'market_cap']]
79
+ st.dataframe(df, use_container_width=True)
80
+
81
+ # Tab 2: Historical Data
82
+ with tab2:
83
+ st.header("Historical Price Analysis")
84
+
85
+ col1, col2 = st.columns(2)
86
+ with col1:
87
+ symbol = st.selectbox("Select Stock", ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN'])
88
+ with col2:
89
+ period = st.selectbox("Select Period", ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y'])
90
+
91
+ if st.button("πŸ“ˆ Fetch Historical Data", type="primary"):
92
+ with st.spinner(f"Fetching {period} of data for {symbol}..."):
93
+ df = agent.fetch_historical_data(symbol, period)
94
+
95
+ if df is not None and not df.empty:
96
+ # Save to database
97
+ storage.save_historical_data(symbol, df)
98
+
99
+ # Summary metrics
100
+ col1, col2, col3, col4 = st.columns(4)
101
+ with col1:
102
+ st.metric("Current Price", f"${df['Close'].iloc[-1]:.2f}")
103
+ with col2:
104
+ st.metric("Period High", f"${df['High'].max():.2f}")
105
+ with col3:
106
+ st.metric("Period Low", f"${df['Low'].min():.2f}")
107
+ with col4:
108
+ st.metric("Avg Volume", f"{df['Volume'].mean():,.0f}")
109
+
110
+ # Price chart
111
+ st.subheader("Price Chart")
112
+ fig = go.Figure()
113
+ fig.add_trace(go.Candlestick(
114
+ x=df.index,
115
+ open=df['Open'],
116
+ high=df['High'],
117
+ low=df['Low'],
118
+ close=df['Close'],
119
+ name='Price'
120
+ ))
121
+ fig.update_layout(
122
+ title=f'{symbol} Price History ({period})',
123
+ yaxis_title='Price ($)',
124
+ xaxis_title='Date',
125
+ height=500
126
+ )
127
+ st.plotly_chart(fig, use_container_width=True)
128
+
129
+ # Volume chart
130
+ st.subheader("Volume Chart")
131
+ fig_volume = go.Figure()
132
+ fig_volume.add_trace(go.Bar(
133
+ x=df.index,
134
+ y=df['Volume'],
135
+ marker_color='lightblue'
136
+ ))
137
+ fig_volume.update_layout(
138
+ title=f'{symbol} Trading Volume ({period})',
139
+ yaxis_title='Volume',
140
+ height=300
141
+ )
142
+ st.plotly_chart(fig_volume, use_container_width=True)
143
+
144
+ # Data table
145
+ with st.expander("πŸ“‹ View Raw Data"):
146
+ st.dataframe(df, use_container_width=True)
147
+
148
+ # Tab 3: Database
149
+ with tab3:
150
+ st.header("Database Statistics")
151
+
152
+ if st.button("πŸ”„ Refresh Database Stats", type="primary"):
153
+ latest = storage.get_latest_prices()
154
+
155
+ if not latest.empty:
156
+ st.success(f"βœ… Database contains {len(latest)} symbols")
157
+
158
+ col1, col2 = st.columns(2)
159
+ with col1:
160
+ st.metric("Total Symbols", len(latest))
161
+ with col2:
162
+ st.metric("Last Update", latest['timestamp'].max())
163
+
164
+ st.subheader("Latest Prices")
165
+ st.dataframe(latest, use_container_width=True)
166
+ else:
167
+ st.warning("⚠️ No data in database yet. Fetch some prices first!")
168
+
169
+ # Tab 4: About
170
+ with tab4:
171
+ st.header("About Market Data Agent")
172
+
173
+ st.markdown("""
174
+ This is the **foundation agent** of our Multi-Agent Portfolio Optimization System.
175
+
176
+ ### Features Implemented:
177
+ 1. βœ… Real-time price fetching from Yahoo Finance
178
+ 2. βœ… Historical data retrieval (1 day to 10 years)
179
+ 3. βœ… Data validation and quality checks
180
+ 4. βœ… SQLite database storage (thread-safe)
181
+ 5. βœ… REST API for other agents
182
+
183
+ ### Technologies Used:
184
+ - **Data Source:** yfinance (Yahoo Finance API)
185
+ - **Database:** SQLite with thread-safe connections
186
+ - **Charts:** Plotly for interactive visualizations
187
+ - **UI:** Streamlit for web interface
188
+ - **Backend:** Python with FastAPI
189
+
190
+ ### Architecture:
191
+ """)
192
+
193
+ st.code("""
194
+ yfinance API
195
+ ↓
196
+ Market Data Agent
197
+ ↓
198
+ Data Validator
199
+ ↓
200
+ SQLite Database
201
+ ↓
202
+ REST API β†’ Other Agents
203
+ """)
204
+
205
+ st.markdown("""
206
+ ### Next Week:
207
+ We will build the **Risk Management Agent** that will use this Market Data Agent
208
+ to calculate VaR, CVaR, and portfolio risk metrics.
209
+
210
+ ---
211
+ **Project:** Intelligent Multi-Agent Portfolio Optimization System
212
+ **Week:** 2 of 16
213
+ **Date:** February 2026
214
+ """)
215
+
216
+ # Footer
217
+ st.divider()
218
+ st.caption("Multi-Agent Portfolio Optimization System | IIT Madras | 2026")