yfinance-mcp / app.py
serverdaun's picture
add mcp server
65d3158
from typing import Dict
import gradio as gr
import yfinance as yf
def get_stocks_info(ticker: str) -> Dict[str, str]:
"""
Fetches the current stock price and daily change for a stock ticker.
Args:
ticker: The stock ticker to get information for.
Returns:
A dictionary containing the stock price and daily change.
"""
financial_data: Dict[str, str] = {}
# Filter out invalid tickers upfront
ticker = ticker.upper().strip()
if not ticker or ticker in ["N/A", "NA", ""]:
return {ticker: "No financial data"}
try:
stock = yf.Ticker(ticker)
info = stock.info
price = info.get("currentPrice") or info.get("regularMarketPrice")
change_percent = info.get("regularMarketChangePercent")
if price is not None and change_percent is not None:
change_str = f"{change_percent * 100:+.2f}%"
financial_data[ticker] = f"${price:.2f} ({change_str})"
else:
financial_data[ticker] = "Price data not available."
return financial_data
except Exception:
return {ticker: "Invalid Ticker or Data Error"}
demo = gr.Interface(
fn=get_stocks_info,
inputs=gr.Textbox(placeholder="Enter a stock ticker", label="Stock Ticker"),
outputs=gr.JSON(label="Output"),
title="YFinance MCP",
description="Get the current stock price and daily change for a stock ticker",
examples=[
["AAPL"],
["GOOG"],
["MSFT"],
],
)
if __name__ == "__main__":
demo.launch(mcp_server=True)