Stock-Analyser / app.py
CCockrum's picture
Update app.py
59c465c verified
Raw History Blame Contribute Delete
15.8 kB
# file: app.py
# Hugging Face Spaces–friendly stock research app (FULL FILE)
# Fixes included:
# - Uses HF Router via huggingface_hub.InferenceClient
# - Robust LLM call: tries chat.completions, falls back to text_generation if model isn't chat
# - Reads token from Spaces Secrets: HF_TOKEN / HUGGING_FACE_HUB_TOKEN / HUGGINGFACEHUB_API_TOKEN
# - queue() enabled for proxy stability
# - Avoids duplicate functions and duplicate reset handler
# - Closes matplotlib figures to prevent leaks on Spaces
from __future__ import annotations
import os
import datetime
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import gradio as gr
import requests
from huggingface_hub import InferenceClient
# -----------------------------
# Hugging Face token (Spaces)
# -----------------------------
def get_hf_token() -> str:
"""
On Hugging Face Spaces, store your token in:
Space Settings -> Secrets -> HF_TOKEN
Token must have: 'Make calls to Inference Providers'
"""
candidates = [
os.getenv("HF_TOKEN"),
os.getenv("HUGGING_FACE_HUB_TOKEN"),
os.getenv("HUGGINGFACEHUB_API_TOKEN"),
]
tok = next((t for t in candidates if t and t.strip()), None)
if not tok:
raise RuntimeError(
"[LLM auth error] Hugging Face token required. "
"Add a Space Secret named HF_TOKEN and enable 'Make calls to Inference Providers'."
)
return tok.strip()
# -----------------------------
# HF Router LLM call (chat->text fallback)
# -----------------------------
DEFAULT_CHAT_MODEL = os.getenv("HF_CHAT_MODEL_ID", "meta-llama/Llama-3.1-8B-Instruct")
DEFAULT_TEXT_MODEL = os.getenv("HF_TEXT_MODEL_ID", "mistralai/Mistral-7B-Instruct-v0.3")
def query_llm(prompt: str, model_id: Optional[str] = None, max_tokens: int = 256) -> str:
"""
Try chat first (for chat-capable models). If model isn't chat, fall back to text_generation.
Works well on Hugging Face Spaces + Router.
"""
try:
token = get_hf_token()
client = InferenceClient(api_key=token)
# If user specified a model, try it; otherwise prefer chat model then text model.
candidates = [model_id] if (model_id and model_id.strip()) else [DEFAULT_CHAT_MODEL, DEFAULT_TEXT_MODEL]
candidates = [m.strip() for m in candidates if m and m.strip()]
last_err: Optional[Exception] = None
for m in candidates:
# 1) Try chat.completions (only works for chat models)
try:
resp = client.chat.completions.create(
model=m,
messages=[
{"role": "system", "content": "You are a helpful financial assistant. Be concise and clear."},
{"role": "user", "content": prompt},
],
max_tokens=int(max_tokens),
temperature=0.3,
top_p=0.9,
)
return resp.choices[0].message.content
except Exception as e:
last_err = e
msg = str(e)
# If model isn't a chat model, fall back to text_generation for the SAME model
if ("not a chat model" in msg) or ("model_not_supported" in msg) or ("not supported" in msg):
try:
out = client.text_generation(
model=m,
prompt=prompt,
max_new_tokens=int(max_tokens),
temperature=0.3,
top_p=0.9,
do_sample=True,
return_full_text=False,
)
return out
except Exception as e2:
last_err = e2
continue
# Other error: try next candidate
continue
raise last_err or RuntimeError("Unknown LLM error")
except Exception as e:
msg = str(e)
if any(x in msg for x in ("401", "403", "Unauthorized", "permission")):
return (
"[LLM auth error] Your HF token is missing or lacks permission. "
"On Spaces: Settings → Secrets → HF_TOKEN, and enable 'Make calls to Inference Providers'."
)
if "model_not_found" in msg or "does not exist" in msg:
return "[LLM model error] Model not found/accessible for your token. Try a different model ID."
return f"[LLM error] {msg}"
# -----------------------------
# Polygon / finance helpers
# -----------------------------
POLYGON_API_KEY = os.getenv("POLYGON_API_KEY")
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},
}
def safe_request(url: str):
try:
r = requests.get(url, timeout=20)
r.raise_for_status()
return r
except Exception:
return None
def get_company_info(symbol: str) -> Optional[Dict]:
if not POLYGON_API_KEY:
return None
url = f"https://api.polygon.io/v3/reference/tickers/{symbol}?apiKey={POLYGON_API_KEY}"
r = safe_request(url)
if not r:
return None
data = r.json().get("results", {}) or {}
sector = data.get("market", "Technology")
if isinstance(sector, str) and sector.lower() == "stocks":
sector = "Technology"
return {
"Name": data.get("name", symbol),
"Industry": data.get("sic_description", "N/A"),
"Sector": sector,
"Market Cap": data.get("market_cap", 0) or 0,
# Polygon "total_employees" isn't revenue; leaving your original rough proxy:
"Total Revenue": (data.get("total_employees", 0) or 0) * 100000,
}
def get_current_price(symbol: str) -> Optional[float]:
if not POLYGON_API_KEY:
return None
url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/prev?adjusted=true&apiKey={POLYGON_API_KEY}"
r = safe_request(url)
if not r:
return None
results = r.json().get("results") or []
if not results:
return None
return results[0].get("c")
def get_dividends(symbol: str) -> float:
if not POLYGON_API_KEY:
return 0.0
url = f"https://api.polygon.io/v3/reference/dividends?ticker={symbol}&apiKey={POLYGON_API_KEY}"
r = safe_request(url)
if not r:
return 0.0
results = r.json().get("results") or []
if not results:
return 0.0
return float(results[0].get("cash_amount", 0) or 0)
def get_historical_prices(symbol: str):
if not POLYGON_API_KEY:
return [], []
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}"
r = safe_request(url)
if not r:
return [], []
results = r.json().get("results") or []
if not results:
return [], []
dates = [datetime.datetime.fromtimestamp(x["t"] / 1000) for x in results if "t" in x]
prices = [x.get("c") for x in results]
return dates, prices
# -----------------------------
# Ratios / comparisons
# -----------------------------
def calculate_ratios(
market_cap: float,
total_revenue: float,
price: float,
dividend_amount: float,
eps: float = 5.0,
growth: float = 0.1,
book_value: float = 500000000,
) -> Dict[str, float]:
pe = price / eps if eps else 0.0
ps = market_cap / total_revenue if total_revenue else 0.0
pb = market_cap / book_value if book_value else 0.0
peg = pe / (growth * 100) if growth else 0.0
div_yield = (dividend_amount / price) * 100 if price else 0.0
return {
"P/E Ratio": pe,
"P/S Ratio": ps,
"P/B Ratio": pb,
"PEG Ratio": peg,
"Dividend Yield": div_yield,
}
def compare_to_sector(sector: str, ratios: Dict[str, float]) -> pd.DataFrame:
if isinstance(sector, str) and sector.lower() == "stocks":
sector = "Technology"
averages = sector_averages.get(sector, {})
if not averages:
return pd.DataFrame({"Ratio": ["Sector data not available"], "Stock Value": ["N/A"], "Sector Average": ["N/A"], "Difference": ["N/A"]})
rows = []
for key, sector_value in averages.items():
stock_value = float(ratios.get(key, 0) or 0)
diff = stock_value - float(sector_value or 0)
if diff < 0:
diff_display = f"{diff:.2f} 🟢"
elif diff > 0:
diff_display = f"{diff:.2f} 🔴"
else:
diff_display = f"{diff:.2f} ⚪"
rows.append({
"Ratio": key,
"Stock Value": round(stock_value, 2),
"Sector Average": round(float(sector_value), 2),
"Difference": diff_display,
})
return pd.DataFrame(rows)
def generate_summary(info: Dict, ratios: Dict[str, float]) -> str:
recommendation = "Hold"
if ratios["P/E Ratio"] < 15 and ratios["P/B Ratio"] < 2 and ratios["PEG Ratio"] < 1.0 and ratios["Dividend Yield"] > 2:
recommendation = "Buy"
elif ratios["P/E Ratio"] > 30 and ratios["P/B Ratio"] > 5 and ratios["PEG Ratio"] > 2.0:
recommendation = "Sell"
report = (
f"Company Overview:\n"
f"Name: {info.get('Name','N/A')}\n"
f"Industry: {info.get('Industry','N/A')}\n"
f"Sector: {info.get('Sector','N/A')}\n"
f"Market Cap: ${float(info.get('Market Cap',0) or 0):,.2f}\n\n"
f"Financial Metrics:\n"
f"P/E Ratio: {ratios['P/E Ratio']:.2f}\n"
f"P/S Ratio: {ratios['P/S Ratio']:.2f}\n"
f"P/B Ratio: {ratios['P/B Ratio']:.2f}\n"
f"PEG Ratio: {ratios['PEG Ratio']:.2f}\n"
f"Dividend Yield: {ratios['Dividend Yield']:.2f}%\n\n"
f"Recommended Investment Action: {recommendation}.\n"
)
prompt = f"Summarize the following financial report clearly and briefly:\n\n{report}"
return query_llm(prompt, max_tokens=220)
# -----------------------------
# Main analysis function (wired to Gradio)
# -----------------------------
def stock_research(symbol: str, eps: float = 5.0, growth: float = 0.1, book: float = 500000000):
symbol = (symbol or "").strip().upper()
if not symbol:
return "Please enter a stock symbol.", pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), None
info = get_company_info(symbol) or {
"Name": symbol,
"Industry": "N/A",
"Sector": "Technology",
"Market Cap": 0,
"Total Revenue": 0,
}
price = get_current_price(symbol)
if price is None:
price = float(np.random.uniform(100, 300))
dividends = float(get_dividends(symbol) or 0)
dates, prices = get_historical_prices(symbol)
if not dates or not prices:
dates = pd.date_range(datetime.date.today() - datetime.timedelta(days=365), periods=365).to_pydatetime().tolist()
prices = np.random.uniform(100, 300, size=365).tolist()
ratios = calculate_ratios(
market_cap=float(info.get("Market Cap", 0) or 0),
total_revenue=float(info.get("Total Revenue", 0) or 0),
price=float(price),
dividend_amount=dividends,
eps=float(eps),
growth=float(growth),
book_value=float(book),
)
ratios_rounded = {k: round(float(v), 2) for k, v in ratios.items()}
info_table = pd.DataFrame(list(info.items()), columns=["Metric", "Value"])
ratios_table = pd.DataFrame(list(ratios_rounded.items()), columns=["Metric", "Value"])
sector_comp = compare_to_sector(str(info.get("Sector", "Technology")), ratios)
recommendation = "Hold"
if ratios["P/E Ratio"] < 15 and ratios["P/B Ratio"] < 2 and ratios["PEG Ratio"] < 1.0 and ratios["Dividend Yield"] > 2:
recommendation = "Buy"
elif ratios["P/E Ratio"] > 30 and ratios["P/B Ratio"] > 5 and ratios["PEG Ratio"] > 2.0:
recommendation = "Sell"
financial_health = ratios_table[ratios_table["Metric"].isin(["P/E Ratio", "P/B Ratio", "PEG Ratio", "Dividend Yield"])].copy()
financial_health = pd.concat(
[financial_health, pd.DataFrame([{"Metric": "Recommendation", "Value": recommendation}])],
ignore_index=True
)
smooth_prices = np.convolve(np.array(prices, dtype=float), np.ones(5) / 5, mode="valid")
fig, ax = plt.subplots()
ax.plot(dates[: len(smooth_prices)], smooth_prices)
ax.set_title(f"{symbol} Historical Price (Smoothed)")
ax.set_xlabel("Date")
ax.set_ylabel("Price ($)")
ax.grid(True)
plt.tight_layout()
ai_summary = generate_summary(info, ratios)
plt.close(fig)
return ai_summary, info_table, ratios_table, financial_health, sector_comp, fig
# -----------------------------
# Gradio UI
# -----------------------------
selected_theme = os.getenv("APP_THEME", "light")
theme = gr.themes.Base() if selected_theme == "dark" else gr.themes.Soft(primary_hue="blue")
with gr.Blocks(theme=theme) as iface:
gr.Markdown("## Stock Research + AI Summary (Hugging Face Spaces Ready)")
with gr.Row():
symbol = gr.Textbox(label="Stock Symbol (e.g., AAPL)")
eps = gr.Number(label="Assumed EPS", value=5.0)
growth = gr.Number(label="Assumed Growth Rate", value=0.1)
book = gr.Number(label="Assumed Book Value", value=500000000)
with gr.Tabs():
with gr.Tab("AI Research Summary"):
output_summary = gr.Textbox(label="AI Summary", lines=10)
with gr.Tab("Company Snapshot"):
output_info = gr.Dataframe(label="Company Info", wrap=True)
with gr.Tab("Valuation Ratios"):
output_ratios = gr.Dataframe(label="Valuation Ratios", wrap=True)
with gr.Tab("Financial Health"):
output_health = gr.Dataframe(label="Financial Health", wrap=True)
with gr.Tab("Sector Comparison"):
output_sector = gr.Dataframe(label="Sector Comparison", wrap=True)
with gr.Tab("Historical Price Chart"):
output_chart = gr.Plot(label="Chart")
with gr.Tab("Ask About Investing"):
user_question = gr.Textbox(label="Ask about investing...")
answer_box = gr.Textbox(label="Answer", lines=6)
ask_button = gr.Button("Get Answer")
def ask(q: str) -> str:
q = (q or "").strip()
if not q:
return "Ask a question first."
return query_llm(q, max_tokens=220)
ask_button.click(fn=ask, inputs=[user_question], outputs=[answer_box]).then(
lambda: "",
inputs=[],
outputs=[user_question]
)
with gr.Row():
submit_btn = gr.Button("Run Analysis")
reset_btn = gr.Button("Reset All Fields")
submit_btn.click(
fn=stock_research,
inputs=[symbol, eps, growth, book],
outputs=[output_summary, output_info, output_ratios, output_health, output_sector, output_chart],
)
def reset_fields():
return "", 5.0, 0.1, 500000000, "", pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), None
reset_btn.click(
fn=reset_fields,
inputs=[],
outputs=[
symbol, eps, growth, book,
output_summary, output_info, output_ratios, output_health, output_sector, output_chart
],
)
# Recommended on Spaces
iface = iface.queue()
if __name__ == "__main__":
iface.launch(server_name="0.0.0.0", server_port=7860, share=False)