import os import requests import gradio as gr import openai # ๐Ÿ” Load secrets from environment client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")) STOCK_API_KEY = os.getenv("STOCK_API_KEY") # ๐Ÿ” Get stock symbol from company name def get_stock_symbol(company_name): url = 'https://www.alphavantage.co/query' params = { 'function': 'SYMBOL_SEARCH', 'keywords': company_name, 'apikey': STOCK_API_KEY } r = requests.get(url, params=params).json() try: return r['bestMatches'][0]['1. symbol'] except (KeyError, IndexError): return None # ๐Ÿ“ˆ Get real-time stock price and last trading date def get_stock_quote(symbol): url = 'https://www.alphavantage.co/query' params = { 'function': 'GLOBAL_QUOTE', 'symbol': symbol, 'apikey': STOCK_API_KEY } r = requests.get(url, params=params).json() try: quote = r['Global Quote'] return quote['05. price'], quote['07. latest trading day'] except KeyError: return None, None # ๐Ÿงพ Get company financial info (overview) def get_financial_overview(symbol): url = 'https://www.alphavantage.co/query' params = { 'function': 'OVERVIEW', 'symbol': symbol, 'apikey': STOCK_API_KEY } r = requests.get(url, params=params).json() try: return { "P/E Ratio": r.get("PERatio", "N/A"), "EPS": r.get("EPS", "N/A"), "Market Cap": r.get("MarketCapitalization", "N/A"), "Description": r.get("Description", "No description available.") } except KeyError: return None # ๐Ÿ’ฌ Ask GPT for investment insight def ask_gpt_summary(company_name, financial_data): prompt = ( f"Provide a short summary and investment insight for {company_name}.\n" f"Here is some financial data:\n" f"P/E Ratio: {financial_data['P/E Ratio']}\n" f"EPS: {financial_data['EPS']}\n" f"Market Cap: {financial_data['Market Cap']}" ) try: response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a stock market assistant providing brief insights."}, {"role": "user", "content": prompt} ], max_tokens=250, temperature=0.3 ) return response.choices[0].message.content.strip() except Exception as e: return f"GPT Error: {e}" # ๐ŸŽฏ Main function def stock_insight(company_name): symbol = get_stock_symbol(company_name) if not symbol: return f"โŒ Could not find stock symbol for '{company_name}'.", "", "", "", "", "" price, last_trade = get_stock_quote(symbol) if not price: return f"โŒ Could not fetch price for symbol {symbol}.", "", "", "", "", "" overview = get_financial_overview(symbol) if not overview: return f"โŒ Could not fetch financial data for {symbol}.", "", "", "", "", "" summary = ask_gpt_summary(company_name, overview) return ( f"โœ… Symbol: {symbol}", f"๐Ÿ’ฒ Price: ${price}", f"๐Ÿ—“๏ธ Last Trading Day: {last_trade}", f"๐Ÿ“Š P/E Ratio: {overview['P/E Ratio']}\nEPS: {overview['EPS']}\nMarket Cap: ${overview['Market Cap']}", f"๐Ÿ“ Company Summary: {overview['Description'][:300]}...", f"๐Ÿค– GPT Insight: {summary}" ) # ๐Ÿ–ฅ๏ธ Gradio Interface demo = gr.Interface( fn=stock_insight, inputs=gr.Textbox(label="Enter Company Name"), outputs=[ gr.Textbox(label="Symbol"), gr.Textbox(label="Stock Price"), gr.Textbox(label="Last Trading Day"), gr.Textbox(label="Financial Overview"), gr.Textbox(label="Company Summary"), gr.Textbox(label="AI Insight") ], title="๐Ÿ“ˆ Stock Market Assistant", description="Search by company name to get stock symbol, live price, financial info, last trade date, and AI-based insight." ) demo.launch()