File size: 1,569 Bytes
65d3158
 
a2f1a08
65d3158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2f1a08
 
65d3158
 
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
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)