Poojashetty357's picture
Update app.py
157bd28 verified
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()