File size: 3,985 Bytes
7e19a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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()