|
import gradio as gr |
|
import os |
|
from openai import OpenAI |
|
from stock_utils import get_multi_stock_data |
|
|
|
|
|
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) |
|
|
|
def analyze_stocks(ticker_input): |
|
try: |
|
|
|
tickers = [t.strip().upper() for t in ticker_input.split(',') if t.strip()] |
|
if not tickers: |
|
return "Please enter at least one valid stock ticker." |
|
|
|
|
|
stock_data_list = get_multi_stock_data(tickers) |
|
|
|
|
|
formatted_data = "\n\n".join([str(data) for data in stock_data_list]) |
|
prompt = ( |
|
"You are a financial analyst. Analyze the following stock data for multiple companies and for each, 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{formatted_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_stocks, |
|
inputs=gr.Textbox(label="Enter Stock Tickers (comma-separated, e.g., AAPL, MSFT, TSLA)"), |
|
outputs=gr.Textbox(label="Agent Recommendations"), |
|
title="π Multi-Stock AI Advisor Agent", |
|
description="Enter multiple stock tickers to get GPT-4o-powered insights and recommendations over multiple timeframes." |
|
) |
|
|
|
demo.launch() |