Spaces:
Running
Running
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) | |