|
import gradio as gr
|
|
import os
|
|
from openai import OpenAI
|
|
from stock_utils import get_stock_data
|
|
|
|
|
|
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
|
|
|
def analyze_stock(ticker):
|
|
try:
|
|
|
|
data = get_stock_data(ticker)
|
|
if "error" in data:
|
|
return f"Data fetch error: {data['error']}"
|
|
|
|
|
|
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}"
|
|
)
|
|
|
|
|
|
response = client.chat.completions.create(
|
|
model="gpt-4o",
|
|
messages=[{"role": "user", "content": prompt}]
|
|
)
|
|
|
|
raw_text = response.choices[0].message.content.strip()
|
|
|
|
|
|
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)}"
|
|
|
|
|
|
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() |