koyelia's picture
Update app.py
2d4f6a1 verified
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()