mr601s commited on
Commit
8e82e74
·
verified ·
1 Parent(s): f518f63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -14
app.py CHANGED
@@ -7,28 +7,30 @@ import time
7
  import random
8
  from datetime import datetime, timedelta
9
  import pandas as pd
 
10
 
11
  # === POLYGON CONFIG ===
12
- # Insert your key here:
13
- POLYGON_API_KEY = "fAhg47wPlf4FT6U2Hn23kQoQCQIyW0G_"
14
 
15
- # === POLYGON QUOTE UTILITY ===
16
  def fetch_polygon_quote(ticker, polygon_api_key=POLYGON_API_KEY):
17
- url = f"https://api.polygon.io/v2/last/trade/{ticker.upper()}?apiKey={polygon_api_key}"
18
  try:
19
  response = requests.get(url, timeout=10)
20
  response.raise_for_status()
21
  data = response.json()
22
- if "results" in data and "p" in data["results"]:
23
- price = data["results"]["p"] # last trade price
24
- ts = data["results"]["t"] # timestamp (optional, could convert)
25
- return f"💰 **Stock Quote for {ticker.upper()}**\n\n• **Current Price**: ${price:.2f}\n\n[More details on Polygon](https://polygon.io/stock/{ticker.upper()}/quote)"
 
 
26
  else:
27
  return f"❌ Quote data unavailable for {ticker.upper()}."
28
  except Exception as e:
29
  return f"❌ Error: {str(e)}"
30
 
31
-
32
  # === SEC Utilities (no change) ===
33
  class SECUtils:
34
  def __init__(self):
@@ -107,7 +109,6 @@ class NewsUtils:
107
  return f"📰 **Latest News for {ticker}**\n\n❌ Error fetching news: {str(e)}\n\n💡 Try these alternatives:\n• [Yahoo Finance News](https://finance.yahoo.com/quote/{ticker}/news)\n• [Google Finance](https://www.google.com/finance/quote/{ticker}:NASDAQ)\n• [MarketWatch](https://www.marketwatch.com/investing/stock/{ticker})"
108
 
109
  # === Chart Utilities (keeps using yfinance for now) ===
110
- # If you want Polygon-powered charts, you can request that snippet.
111
  import yfinance as yf
112
  class ChartUtils:
113
  def create_price_chart(self, ticker, period="3mo"):
@@ -143,7 +144,6 @@ class ChartUtils:
143
  return None
144
 
145
  # === Financial Summary Placeholder ===
146
- # You could call Polygon's /vX/company endpoint, but not all summary info is available for free.
147
  def get_financial_summary_placeholder(ticker):
148
  return f"📊 **Financial Summary for {ticker.upper()}**\n\n❌ Detailed financials unavailable in the free Polygon tier.\n\n💡 Try [Yahoo Finance Financials](https://finance.yahoo.com/quote/{ticker}/financials) for more."
149
 
@@ -152,14 +152,13 @@ sec_utils = SECUtils()
152
  news_utils = NewsUtils()
153
  chart_utils = ChartUtils()
154
 
155
- # --- APP LOGIC ---
156
  def update_stock_info(ticker):
157
  """Update all sections when ticker changes"""
158
  if not ticker or not ticker.strip():
159
  empty_msg = "Enter a ticker symbol to see data"
160
  return empty_msg, empty_msg, empty_msg, empty_msg, None
161
  ticker = ticker.upper().strip()
162
- # 1. Fetch quote via Polygon
163
  quote_data = fetch_polygon_quote(ticker)
164
  time.sleep(0.3)
165
  # 2. News
@@ -194,7 +193,7 @@ with gr.Blocks(css=css, theme=gr.themes.Soft(), title="Stock Research Platform")
194
 
195
  🎯 Enter a stock ticker symbol (like **AAPL**, **TSLA**, **MSFT**, **GOOGL**) to explore detailed information.
196
 
197
- ⚠️ **Note**: Stock quote data provided by Polygon. News and SEC filings remain free. Charts may still be subject to Yahoo limits.
198
  """)
199
  with gr.Row():
200
  with gr.Column(scale=3):
 
7
  import random
8
  from datetime import datetime, timedelta
9
  import pandas as pd
10
+ import os
11
 
12
  # === POLYGON CONFIG ===
13
+ # If using Hugging Face "Secrets", leave as os.getenv; otherwise you may hardcode.
14
+ POLYGON_API_KEY = os.getenv("POLYGON_API_KEY") or "fAhg47wPlf4FT6U2Hn23kQoQCQIyW0G_"
15
 
16
+ # === POLYGON QUOTE for Free Tier (uses Previous Close) ===
17
  def fetch_polygon_quote(ticker, polygon_api_key=POLYGON_API_KEY):
18
+ url = f"https://api.polygon.io/v2/aggs/ticker/{ticker.upper()}/prev?adjusted=true&apiKey={polygon_api_key}"
19
  try:
20
  response = requests.get(url, timeout=10)
21
  response.raise_for_status()
22
  data = response.json()
23
+ if data.get("results"):
24
+ last = data["results"][0]
25
+ price = last["c"] # close price
26
+ # Polygon gives epoch ms; convert to readable date
27
+ close_dt = datetime.utcfromtimestamp(last["t"] / 1000).strftime('%Y-%m-%d')
28
+ return f"💰 **Previous Close for {ticker.upper()} (as of {close_dt})**\n\n• **Close Price:** ${price:.2f}\n\n_(Free Polygon plan only provides prior close)_"
29
  else:
30
  return f"❌ Quote data unavailable for {ticker.upper()}."
31
  except Exception as e:
32
  return f"❌ Error: {str(e)}"
33
 
 
34
  # === SEC Utilities (no change) ===
35
  class SECUtils:
36
  def __init__(self):
 
109
  return f"📰 **Latest News for {ticker}**\n\n❌ Error fetching news: {str(e)}\n\n💡 Try these alternatives:\n• [Yahoo Finance News](https://finance.yahoo.com/quote/{ticker}/news)\n• [Google Finance](https://www.google.com/finance/quote/{ticker}:NASDAQ)\n• [MarketWatch](https://www.marketwatch.com/investing/stock/{ticker})"
110
 
111
  # === Chart Utilities (keeps using yfinance for now) ===
 
112
  import yfinance as yf
113
  class ChartUtils:
114
  def create_price_chart(self, ticker, period="3mo"):
 
144
  return None
145
 
146
  # === Financial Summary Placeholder ===
 
147
  def get_financial_summary_placeholder(ticker):
148
  return f"📊 **Financial Summary for {ticker.upper()}**\n\n❌ Detailed financials unavailable in the free Polygon tier.\n\n💡 Try [Yahoo Finance Financials](https://finance.yahoo.com/quote/{ticker}/financials) for more."
149
 
 
152
  news_utils = NewsUtils()
153
  chart_utils = ChartUtils()
154
 
 
155
  def update_stock_info(ticker):
156
  """Update all sections when ticker changes"""
157
  if not ticker or not ticker.strip():
158
  empty_msg = "Enter a ticker symbol to see data"
159
  return empty_msg, empty_msg, empty_msg, empty_msg, None
160
  ticker = ticker.upper().strip()
161
+ # 1. Fetch quote via Polygon (previous close)
162
  quote_data = fetch_polygon_quote(ticker)
163
  time.sleep(0.3)
164
  # 2. News
 
193
 
194
  🎯 Enter a stock ticker symbol (like **AAPL**, **TSLA**, **MSFT**, **GOOGL**) to explore detailed information.
195
 
196
+ ⚠️ **Note**: Stock quote data provided by Polygon (Previous Close for free plans). News and SEC filings remain free. Charts may still be subject to Yahoo limits.
197
  """)
198
  with gr.Row():
199
  with gr.Column(scale=3):