File size: 1,873 Bytes
13b15cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import os
from openai import OpenAI
from stock_utils import get_stock_data

# Initialize OpenAI client using Hugging Face secret
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def analyze_stock(ticker):
    try:
        # Get stock data using yfinance
        data = get_stock_data(ticker)
        if "error" in data:
            return f"Data fetch error: {data['error']}"

        # Construct prompt
        prompt = (
            "You are a financial analyst. Analyze the following stock data and provide:\n"
            "1. A BUY / HOLD / SELL recommendation\n"
            "2. Reason for the recommendation\n"
            "3. Summary in bullet points\n\n"
            f"Stock Data:\n{data}"
        )

        # Call OpenAI chat model
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": prompt}]
        )

        raw_text = response.choices[0].message.content.strip()

        # Clean markdown artifacts (if model wraps in ``` or quotes)
        if raw_text.startswith("```") and raw_text.endswith("```"):
            raw_text = raw_text[3:-3].strip()
        elif raw_text.startswith("'''") and raw_text.endswith("'''"):
            raw_text = raw_text[3:-3].strip()
        elif raw_text.startswith('"') and raw_text.endswith('"'):
            raw_text = raw_text[1:-1].strip()

        return raw_text

    except Exception as e:
        return f"❌ Unexpected error: {str(e)}"

# Gradio app UI
demo = gr.Interface(
    fn=analyze_stock,
    inputs=gr.Textbox(label="Enter Stock Ticker (e.g., AAPL)"),
    outputs=gr.Textbox(label="Agent Recommendation"),
    title="πŸ“ˆ AI Stock Advisor Agent",
    description="Enter a stock ticker to get GPT-4o-powered insights and a recommendation"
)

demo.launch()