import gradio as gr import os from openai import OpenAI from stock_utils import get_multi_stock_data # Initialize OpenAI client using Hugging Face secret client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def analyze_stocks(ticker_input): try: # Split input into a list of tickers 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." # Get stock data for all tickers stock_data_list = get_multi_stock_data(tickers) # Format prompt for the agent 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}" ) # Call GPT-4o to analyze all stocks 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)}" # Gradio app UI 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()