koyelia commited on
Commit
2d4f6a1
Β·
verified Β·
1 Parent(s): f2b57fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +270 -4
app.py CHANGED
@@ -1,7 +1,273 @@
1
  import gradio as gr
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import requests
5
+ import json
6
+ from datetime import datetime, timedelta
7
+ import plotly.graph_objects as go
8
+ import plotly.express as px
9
 
10
+ # Tool 1: Get Stock Price
11
+ def get_stock_price(symbol):
12
+ """Get real-time stock price and basic info"""
13
+ try:
14
+ stock = yf.Ticker(symbol.upper())
15
+ hist = stock.history(period="1d")
16
+ info = stock.info
17
+
18
+ if hist.empty:
19
+ return f"Error: Could not find stock data for {symbol}"
20
+
21
+ current_price = hist['Close'].iloc[-1]
22
+ prev_close = info.get('previousClose', hist['Close'].iloc[-1])
23
+ change = current_price - prev_close
24
+ change_percent = (change / prev_close) * 100
25
+
26
+ result = f"""
27
+ πŸ“ˆ **{symbol.upper()} Stock Price**
28
+ πŸ’° Current Price: ${current_price:.2f}
29
+ πŸ“Š Change: ${change:.2f} ({change_percent:+.2f}%)
30
+ πŸ“… Previous Close: ${prev_close:.2f}
31
+ 🏒 Company: {info.get('longName', 'N/A')}
32
+ πŸ“ˆ Market Cap: ${info.get('marketCap', 0):,}
33
+ """
34
+ return result
35
+ except Exception as e:
36
+ return f"Error fetching stock price for {symbol}: {str(e)}"
37
 
38
+ # Tool 2: Get Stock Fundamentals
39
+ def get_stock_fundamentals(symbol):
40
+ """Get fundamental analysis data"""
41
+ try:
42
+ stock = yf.Ticker(symbol.upper())
43
+ info = stock.info
44
+
45
+ # Key fundamental metrics
46
+ pe_ratio = info.get('trailingPE', 'N/A')
47
+ forward_pe = info.get('forwardPE', 'N/A')
48
+ price_to_book = info.get('priceToBook', 'N/A')
49
+ debt_to_equity = info.get('debtToEquity', 'N/A')
50
+ roe = info.get('returnOnEquity', 'N/A')
51
+ profit_margin = info.get('profitMargins', 'N/A')
52
+ revenue_growth = info.get('revenueGrowth', 'N/A')
53
+
54
+ # Format percentages
55
+ if isinstance(roe, (int, float)):
56
+ roe = f"{roe*100:.2f}%"
57
+ if isinstance(profit_margin, (int, float)):
58
+ profit_margin = f"{profit_margin*100:.2f}%"
59
+ if isinstance(revenue_growth, (int, float)):
60
+ revenue_growth = f"{revenue_growth*100:.2f}%"
61
+
62
+ result = f"""
63
+ πŸ” **{symbol.upper()} Fundamental Analysis**
64
+
65
+ πŸ“Š **Valuation Metrics:**
66
+ β€’ P/E Ratio: {pe_ratio}
67
+ β€’ Forward P/E: {forward_pe}
68
+ β€’ Price-to-Book: {price_to_book}
69
+
70
+ πŸ’° **Financial Health:**
71
+ β€’ Debt-to-Equity: {debt_to_equity}
72
+ β€’ Return on Equity: {roe}
73
+ β€’ Profit Margin: {profit_margin}
74
+ β€’ Revenue Growth: {revenue_growth}
75
+
76
+ 🏒 **Company Info:**
77
+ β€’ Sector: {info.get('sector', 'N/A')}
78
+ β€’ Industry: {info.get('industry', 'N/A')}
79
+ β€’ Employees: {info.get('fullTimeEmployees', 'N/A'):,}
80
+ β€’ Market Cap: ${info.get('marketCap', 0):,}
81
+ """
82
+ return result
83
+ except Exception as e:
84
+ return f"Error fetching fundamentals for {symbol}: {str(e)}"
85
+
86
+ # Tool 3: Compare Stocks
87
+ def compare_stocks(symbol1, symbol2, symbol3=""):
88
+ """Compare 2-3 stocks side by side"""
89
+ try:
90
+ symbols = [s.upper().strip() for s in [symbol1, symbol2, symbol3] if s.strip()]
91
+
92
+ if len(symbols) < 2:
93
+ return "Please provide at least 2 stock symbols"
94
+
95
+ comparison_data = []
96
+
97
+ for symbol in symbols:
98
+ stock = yf.Ticker(symbol)
99
+ info = stock.info
100
+ hist = stock.history(period="1d")
101
+
102
+ if not hist.empty:
103
+ current_price = hist['Close'].iloc[-1]
104
+ comparison_data.append({
105
+ 'Symbol': symbol,
106
+ 'Company': info.get('longName', 'N/A')[:30],
107
+ 'Price': f"${current_price:.2f}",
108
+ 'P/E Ratio': info.get('trailingPE', 'N/A'),
109
+ 'Market Cap': f"${info.get('marketCap', 0)/1e9:.1f}B",
110
+ 'Sector': info.get('sector', 'N/A'),
111
+ 'ROE': f"{info.get('returnOnEquity', 0)*100:.1f}%" if info.get('returnOnEquity') else 'N/A'
112
+ })
113
+
114
+ if not comparison_data:
115
+ return "Could not fetch data for any of the provided symbols"
116
+
117
+ # Create comparison table
118
+ result = "πŸ“Š **Stock Comparison**\n\n"
119
+ result += "| Metric | " + " | ".join([data['Symbol'] for data in comparison_data]) + " |\n"
120
+ result += "|" + "---|" * (len(comparison_data) + 1) + "\n"
121
+
122
+ metrics = ['Company', 'Price', 'P/E Ratio', 'Market Cap', 'Sector', 'ROE']
123
+
124
+ for metric in metrics:
125
+ result += f"| **{metric}** | "
126
+ result += " | ".join([str(data.get(metric, 'N/A')) for data in comparison_data])
127
+ result += " |\n"
128
+
129
+ return result
130
+
131
+ except Exception as e:
132
+ return f"Error comparing stocks: {str(e)}"
133
+
134
+ # Tool 4: AI-Powered Investment Analysis
135
+ def analyze_stock_ai(symbol, analysis_type="comprehensive"):
136
+ """AI-powered investment insights"""
137
+ try:
138
+ stock = yf.Ticker(symbol.upper())
139
+ info = stock.info
140
+ hist = stock.history(period="3mo") # 3 months of data
141
+
142
+ if hist.empty:
143
+ return f"Could not fetch data for {symbol}"
144
+
145
+ # Calculate technical indicators
146
+ current_price = hist['Close'].iloc[-1]
147
+ price_change_3m = ((current_price - hist['Close'].iloc[0]) / hist['Close'].iloc[0]) * 100
148
+ avg_volume = hist['Volume'].mean()
149
+ volatility = hist['Close'].pct_change().std() * 100
150
+
151
+ # Get fundamental data
152
+ pe_ratio = info.get('trailingPE', 0)
153
+ market_cap = info.get('marketCap', 0)
154
+ sector = info.get('sector', 'Unknown')
155
+
156
+ # AI Analysis Logic
157
+ analysis = f"""
158
+ πŸ€– **AI Investment Analysis for {symbol.upper()}**
159
+
160
+ πŸ“ˆ **Technical Analysis:**
161
+ β€’ 3-Month Performance: {price_change_3m:+.2f}%
162
+ β€’ Current Price: ${current_price:.2f}
163
+ β€’ Volatility: {volatility:.2f}%
164
+ β€’ Average Volume: {avg_volume:,.0f}
165
+
166
+ 🎯 **Investment Signals:**
167
+ """
168
+
169
+ # Simple AI-like decision logic
170
+ signals = []
171
+
172
+ if price_change_3m > 10:
173
+ signals.append("🟒 Strong upward momentum")
174
+ elif price_change_3m > 0:
175
+ signals.append("🟑 Positive trend")
176
+ else:
177
+ signals.append("πŸ”΄ Declining trend")
178
+
179
+ if pe_ratio and 10 < pe_ratio < 25:
180
+ signals.append("🟒 Reasonable valuation")
181
+ elif pe_ratio and pe_ratio > 30:
182
+ signals.append("🟑 High valuation - growth expected")
183
+ elif pe_ratio and pe_ratio < 10:
184
+ signals.append("🟑 Low valuation - value opportunity")
185
+
186
+ if volatility < 20:
187
+ signals.append("🟒 Low volatility - stable")
188
+ elif volatility > 40:
189
+ signals.append("πŸ”΄ High volatility - risky")
190
+
191
+ for signal in signals:
192
+ analysis += f"\nβ€’ {signal}"
193
+
194
+ # Risk Assessment
195
+ risk_level = "Low"
196
+ if volatility > 30 or (pe_ratio and pe_ratio > 40):
197
+ risk_level = "High"
198
+ elif volatility > 20 or (pe_ratio and pe_ratio > 25):
199
+ risk_level = "Medium"
200
+
201
+ analysis += f"""
202
+
203
+ ⚠️ **Risk Assessment:** {risk_level}
204
+ 🏒 **Sector:** {sector}
205
+ πŸ’Ό **Market Cap:** ${market_cap/1e9:.1f}B
206
+
207
+ πŸ“ **AI Recommendation:**
208
+ Based on technical and fundamental analysis, this stock shows {signals[0].split()[1]} characteristics.
209
+ Consider your risk tolerance and portfolio diversification before making investment decisions.
210
+
211
+ ⚠️ *This is AI-generated analysis for educational purposes only. Not financial advice.*
212
+ """
213
+
214
+ return analysis
215
+
216
+ except Exception as e:
217
+ return f"Error in AI analysis for {symbol}: {str(e)}"
218
+
219
+ # Create Gradio Interface
220
+ def create_interface():
221
+ with gr.Blocks(title="Financial Analyst MCP Tools", theme=gr.themes.Soft()) as demo:
222
+ gr.Markdown("# 🏦 Financial Analyst - MCP Tools")
223
+ gr.Markdown("Professional stock analysis tools powered by real-time data and AI insights")
224
+
225
+ with gr.Tabs():
226
+ # Tool 1: Stock Price
227
+ with gr.Tab("πŸ“ˆ Stock Price"):
228
+ gr.Markdown("### Get Real-time Stock Price")
229
+ with gr.Row():
230
+ price_input = gr.Textbox(label="Stock Symbol", placeholder="e.g., AAPL, TSLA, GOOGL")
231
+ price_btn = gr.Button("Get Price", variant="primary")
232
+ price_output = gr.Markdown()
233
+ price_btn.click(get_stock_price, inputs=price_input, outputs=price_output)
234
+
235
+ # Tool 2: Fundamentals
236
+ with gr.Tab("πŸ” Fundamentals"):
237
+ gr.Markdown("### Stock Fundamental Analysis")
238
+ with gr.Row():
239
+ fund_input = gr.Textbox(label="Stock Symbol", placeholder="e.g., AAPL, MSFT")
240
+ fund_btn = gr.Button("Analyze Fundamentals", variant="primary")
241
+ fund_output = gr.Markdown()
242
+ fund_btn.click(get_stock_fundamentals, inputs=fund_input, outputs=fund_output)
243
+
244
+ # Tool 3: Compare Stocks
245
+ with gr.Tab("βš–οΈ Compare Stocks"):
246
+ gr.Markdown("### Side-by-side Stock Comparison")
247
+ with gr.Row():
248
+ with gr.Column():
249
+ comp_input1 = gr.Textbox(label="Stock 1", placeholder="e.g., AAPL")
250
+ comp_input2 = gr.Textbox(label="Stock 2", placeholder="e.g., MSFT")
251
+ comp_input3 = gr.Textbox(label="Stock 3 (Optional)", placeholder="e.g., GOOGL")
252
+ comp_btn = gr.Button("Compare Stocks", variant="primary")
253
+ comp_output = gr.Markdown()
254
+ comp_btn.click(compare_stocks, inputs=[comp_input1, comp_input2, comp_input3], outputs=comp_output)
255
+
256
+ # Tool 4: AI Analysis
257
+ with gr.Tab("πŸ€– AI Analysis"):
258
+ gr.Markdown("### AI-Powered Investment Insights")
259
+ with gr.Row():
260
+ ai_input = gr.Textbox(label="Stock Symbol", placeholder="e.g., NVDA, AMD")
261
+ ai_btn = gr.Button("AI Analysis", variant="primary")
262
+ ai_output = gr.Markdown()
263
+ ai_btn.click(analyze_stock_ai, inputs=ai_input, outputs=ai_output)
264
+
265
+ gr.Markdown("---")
266
+ gr.Markdown("*⚠️ Disclaimer: This tool provides educational information only. Not financial advice. Always consult with financial professionals before making investment decisions.*")
267
+
268
+ return demo
269
+
270
+ # Launch the app
271
+ if __name__ == "__main__":
272
+ demo = create_interface()
273
+ demo.launch()