File size: 4,709 Bytes
54e930d
 
 
 
 
 
 
 
4018845
54e930d
 
 
 
 
 
 
92aeff5
 
 
 
 
 
 
 
54e930d
 
a80abfa
00c2ebd
a80abfa
00c2ebd
54e930d
 
00c2ebd
 
54e930d
 
 
 
 
92aeff5
54e930d
4333cf4
54e930d
 
4333cf4
54e930d
 
 
 
00c2ebd
54e930d
 
00c2ebd
 
54e930d
 
 
 
4333cf4
54e930d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00c2ebd
 
54e930d
 
 
 
 
 
 
 
 
 
dd6ec15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00c2ebd
dd6ec15
54e930d
 
dd6ec15
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
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
import tempfile

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

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

# Sector Averages (Hardcoded for now)
sector_averages = {
    "Technology": {"P/E Ratio": 25, "P/S Ratio": 5, "P/B Ratio": 6},
    "Healthcare": {"P/E Ratio": 20, "P/S Ratio": 4, "P/B Ratio": 3},
    "Financials": {"P/E Ratio": 15, "P/S Ratio": 2, "P/B Ratio": 1.5},
    "Energy": {"P/E Ratio": 12, "P/S Ratio": 1.2, "P/B Ratio": 1.3},
}

# Helper Functions
def get_company_info(symbol):
    api_key = os.getenv("POLYGON_API_KEY")
    print(f"DEBUG: Using API Key: {api_key}")
    url = f"https://api.polygon.io/v3/reference/tickers/{symbol}?apiKey={api_key}"
    print(f"DEBUG: Fetching company info from URL: {url}")
    try:
        response = requests.get(url)
        print(f"DEBUG: Company Info Status Code: {response.status_code}")
        print(f"DEBUG: Company Info Response: {response.text}")
        response.raise_for_status()
        data = response.json()['results']
        return {
            'Name': data.get('name', 'N/A'),
            'Industry': data.get('sic_description', 'N/A'),
            'Sector': data.get('market', '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 from URL: {url}")
    try:
        response = requests.get(url)
        print(f"DEBUG: Current Price Status Code: {response.status_code}")
        print(f"DEBUG: Current Price Response: {response.text}")
        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}"
    try:
        response = requests.get(url)
        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}"
    try:
        response = requests.get(url)
        print(f"DEBUG: Historical Prices Status Code: {response.status_code}")
        print(f"DEBUG: Historical Prices Response: {response.text}")
        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 generate_summary(info, ratios):
    recommendation = "Hold"
    if ratios['P/E Ratio'] < 15 and ratios['P/B Ratio'] < 2:
        recommendation = "Buy"
    elif ratios['P/E Ratio'] > 30 and ratios['P/B Ratio'] > 5:
        recommendation = "Sell"

    prompt = (
        f"Write a professional financial analysis about the company {info['Name']}. "
        f"{info['Name']} operates in the {info['Industry']} industry within the {info['Sector']} sector. "
        f"It has a market capitalization of approximately ${info['Market Cap']:,.2f}. "
        f"The Price-to-Earnings (P/E) ratio is {ratios['P/E Ratio']:.2f}, "
        f"Price-to-Sales (P/S) ratio is {ratios['P/S Ratio']:.2f}, "
        f"Price-to-Book (P/B) ratio is {ratios['P/B Ratio']:.2f}, "
        f"PEG ratio is {ratios['PEG Ratio']:.2f}, and dividend yield is {ratios['Dividend Yield (%)']:.2f}%. "
        f"Based on these metrics, the recommended investment action is: {recommendation}."
    )
    summary = summarizer(prompt, max_length=180, min_length=80, do_sample=False)[0]['summary_text']
    return summary

# (Rest of the code remains the same)