Delete app.py
Browse files
app.py
DELETED
|
@@ -1,217 +0,0 @@
|
|
| 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 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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