File size: 6,413 Bytes
54e930d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4333cf4
 
 
54e930d
 
4333cf4
 
54e930d
 
 
 
 
 
4333cf4
54e930d
 
4333cf4
54e930d
 
 
 
4333cf4
54e930d
 
4333cf4
 
54e930d
 
 
 
4333cf4
54e930d
 
 
 
4333cf4
54e930d
 
4333cf4
 
54e930d
 
 
 
 
 
 
 
 
 
 
 
 
 
4333cf4
54e930d
 
4333cf4
 
54e930d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcb6654
 
 
 
 
 
 
 
54e930d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcb6654
 
 
54e930d
 
 
 
 
 
 
 
 
 
 
 
4333cf4
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import pandas as pd
import numpy as np
import gradio as gr
import matplotlib.pyplot as plt
import requests
import os
from transformers import pipeline
import datetime

# Initialize Summarizer
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")

# Polygon API Key
POLYGON_API_KEY = os.getenv("POLYGON_API_KEY")

# Helper Functions
def get_company_info(symbol):
    print(f"DEBUG: Using API Key: {POLYGON_API_KEY}")
    url = f"https://api.polygon.io/v3/reference/tickers/{symbol}?apiKey={POLYGON_API_KEY}"
    print(f"DEBUG: Fetching company info URL: {url}")
    try:
        response = requests.get(url)
        print(f"DEBUG: Response Status: {response.status_code}")
        print(f"DEBUG: Response JSON: {response.json()}")
        response.raise_for_status()
        data = response.json()['results']
        return {
            'Name': data.get('name', 'N/A'),
            'Industry': data.get('sic_description', 'N/A'),
            'Market Cap': data.get('market_cap', 0),
            'Total Revenue': data.get('total_employees', 0) * 100000
        }
    except Exception as e:
        print(f"DEBUG: Error fetching company info: {e}")
        return None

def get_current_price(symbol):
    url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/prev?adjusted=true&apiKey={POLYGON_API_KEY}"
    print(f"DEBUG: Fetching current price URL: {url}")
    try:
        response = requests.get(url)
        print(f"DEBUG: Response Status: {response.status_code}")
        print(f"DEBUG: Response JSON: {response.json()}")
        response.raise_for_status()
        data = response.json()['results'][0]
        return float(data['c'])
    except Exception as e:
        print(f"DEBUG: Error fetching current price: {e}")
        return None

def get_dividends(symbol):
    url = f"https://api.polygon.io/v3/reference/dividends?ticker={symbol}&apiKey={POLYGON_API_KEY}"
    print(f"DEBUG: Fetching dividends URL: {url}")
    try:
        response = requests.get(url)
        print(f"DEBUG: Response Status: {response.status_code}")
        print(f"DEBUG: Response JSON: {response.json()}")
        response.raise_for_status()
        data = response.json()['results'][0]
        return {
            'Dividend Amount': data.get('cash_amount', 0),
            'Ex-Dividend Date': data.get('ex_dividend_date', 'N/A')
        }
    except Exception as e:
        print(f"DEBUG: Error fetching dividends: {e}")
        return {'Dividend Amount': 0, 'Ex-Dividend Date': 'N/A'}

def get_historical_prices(symbol):
    end = datetime.date.today()
    start = end - datetime.timedelta(days=365)
    url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/range/1/day/{start}/{end}?adjusted=true&sort=asc&apiKey={POLYGON_API_KEY}"
    print(f"DEBUG: Fetching historical prices URL: {url}")
    try:
        response = requests.get(url)
        print(f"DEBUG: Response Status: {response.status_code}")
        print(f"DEBUG: Response JSON: {response.json()}")
        response.raise_for_status()
        results = response.json()['results']
        dates = [datetime.datetime.fromtimestamp(r['t']/1000) for r in results]
        prices = [r['c'] for r in results]
        return dates, prices
    except Exception as e:
        print(f"DEBUG: Error fetching historical prices: {e}")
        return [], []

def calculate_ratios(market_cap, total_revenue, price, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
    pe_ratio = price / assumed_eps if assumed_eps else 0
    ps_ratio = market_cap / total_revenue if total_revenue else 0
    pb_ratio = market_cap / book_value if book_value else 0
    peg_ratio = pe_ratio / (growth_rate * 100) if growth_rate else 0
    return {
        'P/E Ratio': pe_ratio,
        'P/S Ratio': ps_ratio,
        'P/B Ratio': pb_ratio,
        'PEG Ratio': peg_ratio
    }

def generate_summary(info, ratios):
    text = (f"{info['Name']} operates in the {info['Industry']} sector. It has a market capitalization of "
            f"${info['Market Cap']:,.2f}. The company exhibits a P/E ratio of {ratios['P/E Ratio']:.2f}, "
            f"P/S ratio of {ratios['P/S Ratio']:.2f}, and P/B ratio of {ratios['P/B Ratio']:.2f}. "
            f"This suggests a {'potential undervaluation' if ratios['P/E Ratio'] < 20 else 'higher valuation'} relative to the market.")
    summary = summarizer(text, max_length=120, min_length=30, do_sample=False)[0]['summary_text']
    return summary

def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
    # Safeguard against None values
    if assumed_eps is None:
        assumed_eps = 5.0
    if growth_rate is None:
        growth_rate = 0.1
    if book_value is None:
        book_value = 500000000

    info = get_company_info(symbol)
    price = get_current_price(symbol)
    dividends = get_dividends(symbol)
    dates, prices = get_historical_prices(symbol)

    if not info or not price:
        return "Error fetching stock information.", None, None, None

    ratios = calculate_ratios(info['Market Cap'], info['Total Revenue'], price, assumed_eps, growth_rate, book_value)
    summary = generate_summary(info, ratios)

    # Create historical price chart
    fig, ax = plt.subplots()
    ax.plot(dates, prices, label=f"{symbol} Price")
    ax.set_title(f"{symbol} Historical Price (1 Year)")
    ax.set_xlabel("Date")
    ax.set_ylabel("Price ($)")
    ax.legend()
    ax.grid(True)

    info_table = pd.DataFrame({"Metric": list(info.keys()), "Value": list(info.values())})
    ratios_table = pd.DataFrame({"Ratio": list(ratios.keys()), "Value": list(ratios.values())})

    return summary, info_table, ratios_table, fig

iface = gr.Interface(
    fn=stock_research,
    inputs=[
        gr.Textbox(label="Stock Symbol (e.g., AAPL)"),
        gr.Number(label="Assumed EPS", value=5.0),
        gr.Number(label="Assumed Growth Rate", value=0.1),
        gr.Number(label="Assumed Book Value", value=500000000)
    ],
    outputs=[
        gr.Textbox(label="AI Research Summary"),
        gr.Dataframe(label="Company Snapshot"),
        gr.Dataframe(label="Valuation Ratios"),
        gr.Plot(label="Historical Price Chart")
    ],
    title="AI-Powered Stock Researcher",
    description="Enter a stock symbol to get company info, valuation ratios, a 1-year price chart, and an AI-generated research summary based on live Polygon.io data."
)

if __name__ == "__main__":
    iface.launch()