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