stockbot / app.py
decodingdatascience's picture
Upload 2 files
7e19a0b verified
import gradio as gr
import requests
import os
from dotenv import load_dotenv
from openai import OpenAI
# Load environment variables from .env file
load_dotenv()
# Get API keys from environment variables
ALPHA_VANTAGE_API_KEY = os.getenv('ALPHA_VANTAGE_API_KEY')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
# Validate API keys
if not ALPHA_VANTAGE_API_KEY or not OPENAI_API_KEY:
raise ValueError("Missing API keys. Please check your .env file.")
# Configure OpenAI
client = OpenAI(api_key=OPENAI_API_KEY)
def get_stock_price(symbol):
"""Fetch stock price from Alpha Vantage API"""
if not symbol:
return "Please enter a stock symbol"
url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={ALPHA_VANTAGE_API_KEY}"
response = requests.get(url)
data = response.json()
if "Global Quote" in data and "05. price" in data["Global Quote"]:
return float(data["Global Quote"]["05. price"])
elif "Note" in data: # API rate limit message
return "API rate limit reached. Please try again in a minute."
return "Stock symbol not found"
def get_ai_analysis(company_name):
"""Get AI analysis using GPT-3.5"""
prompt = f"""
Provide a brief analysis of {company_name} as a long-term investment.
Consider historical milestones, recent announcements, and market position.
Keep the response under 150 words.
"""
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a financial analyst providing brief stock analyses."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
def get_stock_symbol(company_name):
"""Convert company name to stock symbol using GPT-3.5"""
prompt = f"""
What is the stock symbol for {company_name}?
Provide only the symbol without any additional text or explanation.
For example, if asked about Apple, respond with: AAPL
"""
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a financial expert. Respond only with stock symbols in capital letters."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content.strip()
except Exception as e:
return None
def analyze_stock(company_input):
"""Main function to process user input and return results"""
try:
# Convert company name to symbol if needed
if not company_input.isupper() or len(company_input.split()) > 1:
symbol = get_stock_symbol(company_input)
if not symbol:
return "Could not determine stock symbol", "Please try entering the stock symbol directly"
else:
symbol = company_input
# Get stock price
price = get_stock_price(symbol)
# Get AI analysis
analysis = get_ai_analysis(company_input)
return f"${price:.2f}" if isinstance(price, float) else price, analysis
except Exception as e:
return str(e), "Error occurred while analyzing the stock"
# Update Gradio interface
iface = gr.Interface(
fn=analyze_stock,
inputs=[
gr.Textbox(label="Enter Company Name or Symbol (e.g., 'Apple' or 'AAPL')", placeholder="Enter company name or stock symbol...")
],
outputs=[
gr.Textbox(label="Current Stock Price"),
gr.Textbox(label="AI Analysis", lines=5)
],
title="Stock Analysis Assistant",
description="Get real-time stock prices and AI-powered investment analysis",
theme=gr.themes.Soft()
)
# Launch the application
if __name__ == "__main__":
iface.launch()