koyelia commited on
Commit
d4b8525
Β·
verified Β·
1 Parent(s): 84dbef5

Upload 3 files

Browse files

App.py, Readme and requirement txt file uploaded

Files changed (3) hide show
  1. app.py +313 -0
  2. readme_md.txt +142 -0
  3. requirements_txt.txt +3 -0
app.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import pandas as pd
5
+ from datetime import datetime
6
+
7
+ # Your Modal MCP Server URL
8
+ MODAL_MCP_URL = "https://koyeliaghoshroy1--mcp-stock-analysis-server-web-app.modal.run"
9
+
10
+ def test_connection():
11
+ """Test connection to Modal MCP server"""
12
+ try:
13
+ response = requests.get(f"{MODAL_MCP_URL}/health", timeout=10)
14
+ if response.status_code == 200:
15
+ return "βœ… Connected to Modal MCP Server", response.json()
16
+ else:
17
+ return f"❌ Connection failed: {response.status_code}", {}
18
+ except Exception as e:
19
+ return f"❌ Connection error: {str(e)}", {}
20
+
21
+ def get_available_tools():
22
+ """Get available MCP tools from Modal server"""
23
+ try:
24
+ response = requests.get(f"{MODAL_MCP_URL}/tools", timeout=10)
25
+ if response.status_code == 200:
26
+ data = response.json()
27
+ tools = data.get("tools", [])
28
+ return "βœ… Tools loaded successfully", tools
29
+ else:
30
+ return f"❌ Failed to load tools: {response.status_code}", []
31
+ except Exception as e:
32
+ return f"❌ Tools error: {str(e)}", []
33
+
34
+ def get_stock_price(symbol):
35
+ """Call Modal MCP server to get stock price"""
36
+ if not symbol.strip():
37
+ return "❌ Please enter a stock symbol", {}
38
+
39
+ try:
40
+ response = requests.post(
41
+ f"{MODAL_MCP_URL}/call",
42
+ json={
43
+ "name": "get_stock_price",
44
+ "arguments": {"symbol": symbol.strip().upper()}
45
+ },
46
+ timeout=30
47
+ )
48
+
49
+ if response.status_code == 200:
50
+ data = response.json()
51
+ if data.get("success"):
52
+ # Parse the result from the MCP server
53
+ result_str = data.get("result", ["{}"])[0]
54
+ result = json.loads(result_str)
55
+
56
+ if "error" in result:
57
+ return f"❌ {result['error']}", result
58
+ else:
59
+ status = f"βœ… Stock data retrieved for {result.get('symbol', symbol)}"
60
+ return status, result
61
+ else:
62
+ return f"❌ {data.get('error', 'Unknown error')}", data
63
+ else:
64
+ return f"❌ Request failed: {response.status_code}", {}
65
+
66
+ except Exception as e:
67
+ return f"❌ Error: {str(e)}", {}
68
+
69
+ def analyze_stock_comprehensive(symbol):
70
+ """Call Modal MCP server for comprehensive stock analysis"""
71
+ if not symbol.strip():
72
+ return "❌ Please enter a stock symbol", {}
73
+
74
+ try:
75
+ response = requests.post(
76
+ f"{MODAL_MCP_URL}/call",
77
+ json={
78
+ "name": "analyze_stock_comprehensive",
79
+ "arguments": {"symbol": symbol.strip().upper()}
80
+ },
81
+ timeout=30
82
+ )
83
+
84
+ if response.status_code == 200:
85
+ data = response.json()
86
+ if data.get("success"):
87
+ # Parse the result from the MCP server
88
+ result_str = data.get("result", ["{}"])[0]
89
+ result = json.loads(result_str)
90
+
91
+ if "error" in result:
92
+ return f"❌ {result['error']}", result
93
+ else:
94
+ status = f"βœ… Analysis complete for {result.get('symbol', symbol)}"
95
+ return status, result
96
+ else:
97
+ return f"❌ {data.get('error', 'Unknown error')}", data
98
+ else:
99
+ return f"❌ Request failed: {response.status_code}", {}
100
+
101
+ except Exception as e:
102
+ return f"❌ Error: {str(e)}", {}
103
+
104
+ def format_stock_data(data):
105
+ """Format stock data for better display"""
106
+ if not data or "error" in data:
107
+ return data
108
+
109
+ # Create a formatted summary
110
+ summary = {
111
+ "Company": data.get("company_name", "N/A"),
112
+ "Symbol": data.get("symbol", "N/A"),
113
+ "Current Price": f"${data.get('current_price', 0):.2f}",
114
+ "Market Cap": f"${data.get('market_cap', 0):,}" if data.get('market_cap') else "N/A",
115
+ "Sector": data.get("sector", "N/A")
116
+ }
117
+
118
+ # Add analysis-specific fields if they exist
119
+ if "investment_score" in data:
120
+ summary.update({
121
+ "Investment Score": f"{data.get('investment_score', 0)}/100",
122
+ "Recommendation": data.get("recommendation", "N/A"),
123
+ "YTD Return": f"{data.get('ytd_return', 0):.2f}%",
124
+ "P/E Ratio": data.get("pe_ratio", "N/A")
125
+ })
126
+
127
+ return summary
128
+
129
+ # Custom CSS for better styling
130
+ custom_css = """
131
+ .gradio-container {
132
+ font-family: 'Arial', sans-serif;
133
+ }
134
+ .tab-nav button {
135
+ font-weight: bold;
136
+ }
137
+ .json-display {
138
+ background-color: #f8f9fa;
139
+ border: 1px solid #e9ecef;
140
+ border-radius: 0.375rem;
141
+ padding: 1rem;
142
+ }
143
+ """
144
+
145
+ # Create the Gradio interface
146
+ with gr.Blocks(
147
+ title="MCP Stock Analysis - Hackathon Entry",
148
+ theme=gr.themes.Soft(),
149
+ css=custom_css
150
+ ) as demo:
151
+
152
+ # Header
153
+ gr.Markdown("""
154
+ # πŸš€ MCP Stock Analysis Server
155
+ ## Hugging Face Gradio MCP Hackathon Entry
156
+
157
+ **Architecture**: Gradio Frontend (Hugging Face Spaces) + Modal MCP Backend
158
+
159
+ This application demonstrates the **Model Context Protocol (MCP)** by connecting a Gradio interface
160
+ to a Modal-hosted MCP server for real-time stock analysis.
161
+ """)
162
+
163
+ # Connection Status
164
+ with gr.Row():
165
+ connection_btn = gr.Button("πŸ”— Test Connection", variant="secondary")
166
+ connection_status = gr.Textbox(label="Connection Status", interactive=False)
167
+
168
+ # Main Interface Tabs
169
+ with gr.Tabs():
170
+
171
+ # Stock Price Tab
172
+ with gr.TabItem("πŸ“ˆ Stock Price Lookup"):
173
+ gr.Markdown("Get real-time stock price and basic company information.")
174
+
175
+ with gr.Row():
176
+ with gr.Column(scale=2):
177
+ price_symbol = gr.Textbox(
178
+ label="Stock Symbol",
179
+ placeholder="Enter symbol (e.g., AAPL, TSLA, GOOGL)",
180
+ value="AAPL"
181
+ )
182
+ with gr.Column(scale=1):
183
+ price_btn = gr.Button("Get Price", variant="primary", size="lg")
184
+
185
+ price_status = gr.Textbox(label="Status", interactive=False)
186
+ price_result = gr.JSON(label="Stock Price Data")
187
+ price_summary = gr.JSON(label="Formatted Summary")
188
+
189
+ # Stock Analysis Tab
190
+ with gr.TabItem("πŸ“Š Comprehensive Analysis"):
191
+ gr.Markdown("Get detailed stock analysis with investment scoring and recommendations.")
192
+
193
+ with gr.Row():
194
+ with gr.Column(scale=2):
195
+ analysis_symbol = gr.Textbox(
196
+ label="Stock Symbol",
197
+ placeholder="Enter symbol (e.g., AAPL, TSLA, GOOGL)",
198
+ value="TSLA"
199
+ )
200
+ with gr.Column(scale=1):
201
+ analysis_btn = gr.Button("Analyze Stock", variant="primary", size="lg")
202
+
203
+ analysis_status = gr.Textbox(label="Status", interactive=False)
204
+ analysis_result = gr.JSON(label="Full Analysis Data")
205
+ analysis_summary = gr.JSON(label="Investment Summary")
206
+
207
+ # MCP Tools Tab
208
+ with gr.TabItem("πŸ› οΈ MCP Tools"):
209
+ gr.Markdown("View available MCP tools and server information.")
210
+
211
+ tools_btn = gr.Button("Load Available Tools", variant="secondary")
212
+ tools_status = gr.Textbox(label="Status", interactive=False)
213
+ tools_result = gr.JSON(label="Available MCP Tools")
214
+
215
+ # About Tab
216
+ with gr.TabItem("ℹ️ About"):
217
+ gr.Markdown("""
218
+ ## About This Project
219
+
220
+ ### πŸ† Hackathon Entry
221
+ - **Event**: Hugging Face Gradio MCP Hackathon
222
+ - **Architecture**: Distributed MCP implementation
223
+ - **Frontend**: Gradio on Hugging Face Spaces
224
+ - **Backend**: Modal MCP Server with stock analysis tools
225
+
226
+ ### πŸ”§ Technical Implementation
227
+ - **MCP Protocol**: Implements Model Context Protocol for tool discovery and execution
228
+ - **Real-time Data**: Uses yfinance for live stock market data
229
+ - **Cloud Architecture**: Scalable backend on Modal with Gradio frontend
230
+ - **RESTful API**: Standard HTTP/JSON communication between components
231
+
232
+ ### πŸ“ˆ Features
233
+ - **Stock Price Lookup**: Real-time price, market cap, sector information
234
+ - **Investment Analysis**: Scoring algorithm with buy/hold/sell recommendations
235
+ - **Smart Ticker Search**: Company name to ticker symbol mapping
236
+ - **Error Handling**: Robust error handling and user feedback
237
+
238
+ ### πŸ› οΈ MCP Tools Available
239
+ 1. `get_stock_price` - Retrieve current stock price and basic info
240
+ 2. `analyze_stock_comprehensive` - Full analysis with investment scoring
241
+ 3. `smart_ticker_search` - Convert company names to ticker symbols
242
+
243
+ ### 🌐 Live Endpoints
244
+ - **Modal MCP Server**: `{MODAL_MCP_URL}`
245
+ - **Health Check**: `{MODAL_MCP_URL}/health`
246
+ - **Tools Discovery**: `{MODAL_MCP_URL}/tools`
247
+ - **Tool Execution**: `{MODAL_MCP_URL}/call`
248
+
249
+ ### πŸ’‘ Usage Examples
250
+ Try these stock symbols: **AAPL**, **TSLA**, **GOOGL**, **MSFT**, **AMZN**, **META**
251
+
252
+ Or company names: **apple**, **tesla**, **microsoft**, **amazon**
253
+ """)
254
+
255
+ # Event Handlers
256
+
257
+ # Connection test
258
+ def handle_connection_test():
259
+ status, data = test_connection()
260
+ return status
261
+
262
+ connection_btn.click(
263
+ fn=handle_connection_test,
264
+ outputs=connection_status
265
+ )
266
+
267
+ # Stock price lookup
268
+ def handle_price_lookup(symbol):
269
+ status, data = get_stock_price(symbol)
270
+ summary = format_stock_data(data) if data else {}
271
+ return status, data, summary
272
+
273
+ price_btn.click(
274
+ fn=handle_price_lookup,
275
+ inputs=price_symbol,
276
+ outputs=[price_status, price_result, price_summary]
277
+ )
278
+
279
+ # Stock analysis
280
+ def handle_analysis(symbol):
281
+ status, data = analyze_stock_comprehensive(symbol)
282
+ summary = format_stock_data(data) if data else {}
283
+ return status, data, summary
284
+
285
+ analysis_btn.click(
286
+ fn=handle_analysis,
287
+ inputs=analysis_symbol,
288
+ outputs=[analysis_status, analysis_result, analysis_summary]
289
+ )
290
+
291
+ # Tools discovery
292
+ def handle_tools_discovery():
293
+ status, tools = get_available_tools()
294
+ return status, tools
295
+
296
+ tools_btn.click(
297
+ fn=handle_tools_discovery,
298
+ outputs=[tools_status, tools_result]
299
+ )
300
+
301
+ # Auto-test connection on load
302
+ demo.load(
303
+ fn=handle_connection_test,
304
+ outputs=connection_status
305
+ )
306
+
307
+ # Launch the app
308
+ if __name__ == "__main__":
309
+ demo.launch(
310
+ share=False,
311
+ server_name="0.0.0.0",
312
+ server_port=7860
313
+ )
readme_md.txt ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # πŸš€ MCP Stock Analysis - Hackathon Entry
2
+
3
+ ## Hugging Face Gradio MCP Hackathon Submission
4
+
5
+ A distributed Model Context Protocol (MCP) implementation for real-time stock analysis, showcasing the power of connecting Gradio frontends with cloud-hosted MCP servers.
6
+
7
+ ## πŸ† Hackathon Details
8
+
9
+ - **Event**: Hugging Face Gradio MCP Hackathon
10
+ - **Track**: Track 1: MCP Tool / Server
11
+ - **Submission Date**: 10th June 2025
12
+
13
+ ## πŸ—οΈ Architecture
14
+
15
+ ```
16
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” HTTP/JSON β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
17
+ β”‚ Gradio Frontend β”‚ ◄─────────────► β”‚ Modal MCP Server β”‚
18
+ β”‚ (Hugging Face) β”‚ REST API β”‚ (Backend) β”‚
19
+ β”‚ β”‚ β”‚ β”‚
20
+ β”‚ - User Interface β”‚ β”‚ - MCP Protocol β”‚
21
+ β”‚ - Stock Lookup β”‚ β”‚ - Stock Analysis β”‚
22
+ β”‚ - Results Display β”‚ β”‚ - yfinance Data β”‚
23
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
24
+ ```
25
+
26
+ ## ✨ Features
27
+
28
+ ### πŸ” MCP Tools Available
29
+ 1. **Stock Price Lookup** - Real-time price, market cap, and company info
30
+ 2. **Comprehensive Analysis** - Investment scoring with buy/hold/sell recommendations
31
+ 3. **Smart Ticker Search** - Company name to ticker symbol conversion
32
+
33
+ ### πŸ“Š User Interface
34
+ - **Intuitive Gradio Interface** - Easy-to-use web interface
35
+ - **Real-time Data** - Live stock market information
36
+ - **Error Handling** - Robust error handling and user feedback
37
+ - **Multiple Views** - Tabbed interface for different functionalities
38
+
39
+ ### πŸ› οΈ Technical Implementation
40
+ - **MCP Protocol** - Full Model Context Protocol implementation
41
+ - **Cloud Architecture** - Scalable backend on Modal
42
+ - **RESTful API** - Standard HTTP/JSON communication
43
+ - **Real-time Data** - Uses yfinance for live market data
44
+
45
+ ## πŸš€ Live Demo
46
+
47
+ Try the live application: [Your Hugging Face Space URL]
48
+
49
+ **Backend MCP Server**: https://koyeliaghoshroy1--mcp-stock-analysis-server-web-app.modal.run
50
+
51
+ ## πŸ“‹ Example Usage
52
+
53
+ ### Stock Symbols to Try:
54
+ - **Tech**: AAPL, GOOGL, MSFT, TSLA, META, NVDA
55
+ - **Finance**: JPM, BAC, WFC, GS
56
+ - **Consumer**: WMT, KO, PEP, NKE
57
+
58
+ ### Company Names:
59
+ - apple, microsoft, tesla, amazon, netflix, nvidia
60
+
61
+ ## πŸ”§ Technical Stack
62
+
63
+ ### Frontend (Gradio)
64
+ - **Framework**: Gradio 4.0+
65
+ - **Hosting**: Hugging Face Spaces
66
+ - **Language**: Python
67
+ - **UI Components**: Tabs, JSON displays, status indicators
68
+
69
+ ### Backend (Modal MCP Server)
70
+ - **Framework**: FastAPI + Modal
71
+ - **Protocol**: Model Context Protocol (MCP)
72
+ - **Data Source**: yfinance
73
+ - **Analysis**: Custom investment scoring algorithm
74
+ - **Hosting**: Modal cloud platform
75
+
76
+ ## πŸ“‘ API Endpoints
77
+
78
+ ### MCP Server Endpoints:
79
+ - `GET /health` - Server health check
80
+ - `GET /tools` - Available MCP tools discovery
81
+ - `POST /call` - Execute MCP tools
82
+ - `GET /` - Server information
83
+
84
+ ### Tool Execution Format:
85
+ ```json
86
+ {
87
+ "name": "get_stock_price",
88
+ "arguments": {
89
+ "symbol": "AAPL"
90
+ }
91
+ }
92
+ ```
93
+
94
+ ## πŸ… Hackathon Innovation
95
+
96
+ ### What Makes This Special:
97
+ 1. **Distributed MCP Architecture** - Separates frontend and backend for scalability
98
+ 2. **Cloud-Native Design** - Leverages Modal for compute and HF Spaces for interface
99
+ 3. **Real-World Application** - Practical stock analysis with investment recommendations
100
+ 4. **User-Friendly Interface** - Makes MCP accessible to non-technical users
101
+ 5. **Robust Error Handling** - Graceful handling of network and data issues
102
+
103
+ ### MCP Protocol Demonstration:
104
+ - **Tool Discovery** - Dynamic loading of available tools
105
+ - **Tool Execution** - Remote tool execution via HTTP
106
+ - **Error Handling** - Proper error propagation and user feedback
107
+ - **Real-time Communication** - Live data exchange between components
108
+
109
+ ## πŸ”„ Development Workflow
110
+
111
+ 1. **Backend Development** - Modal MCP server with stock analysis tools
112
+ 2. **API Testing** - Validation of MCP protocol implementation
113
+ 3. **Frontend Creation** - Gradio interface development
114
+ 4. **Integration Testing** - End-to-end functionality verification
115
+ 5. **Deployment** - Production deployment on both platforms
116
+
117
+ ## πŸ“ˆ Investment Analysis Algorithm
118
+
119
+ The comprehensive analysis includes:
120
+ - **YTD Return Calculation** - Year-to-date performance analysis
121
+ - **PE Ratio Evaluation** - Price-to-earnings ratio assessment
122
+ - **Scoring System** - 0-100 investment score
123
+ - **Recommendations** - Buy/Hold/Sell suggestions based on analysis
124
+
125
+ ## 🀝 Contributing
126
+
127
+ This is a hackathon submission, but feedback and suggestions are welcome!
128
+
129
+ ## πŸ“„ License
130
+
131
+ MIT License - Feel free to use and modify for your own projects.
132
+
133
+ ## πŸ™ Acknowledgments
134
+
135
+ - **Hugging Face** - For hosting the Gradio frontend and organizing the hackathon
136
+ - **Modal** - For providing cloud compute credits and hosting the MCP server
137
+ - **yfinance** - For real-time stock market data
138
+ - **MCP Community** - For the Model Context Protocol specification
139
+
140
+ ---
141
+
142
+ **Built with ❀️ for the Hugging Face Gradio MCP Hackathon**
requirements_txt.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=4.0.0
2
+ requests>=2.25.0
3
+ pandas>=1.3.0