"""Deterministic finance tools. Every number shown to users comes from here, never from the LLM.""" import datetime import io import logging import re from functools import lru_cache import pandas as pd logger = logging.getLogger(__name__) YFINANCE_TIMEOUT = 10 def sanitize_ticker(ticker): if not ticker or not isinstance(ticker, str): return None cleaned = re.sub(r"[^A-Z0-9.^-]", "", ticker.upper().strip().lstrip("$")) return cleaned if 0 < len(cleaned) <= 10 else None def validate_year_range(start_year, end_year): try: start, end = int(start_year), int(end_year) except (TypeError, ValueError): return False, "Years must be valid integers" now = datetime.datetime.now().year if not 1900 <= start <= now: return False, f"Start year must be between 1900 and {now}" if not 1900 <= end <= now + 1: return False, f"End year must be between 1900 and {now + 1}" if end <= start: return False, "End year must be after start year" return True, "Valid" def _hour_key(): return datetime.datetime.now().strftime("%Y%m%d%H") @lru_cache(maxsize=128) def _download(ticker, start, end, _cache_key): import yfinance as yf try: data = yf.download(ticker, start=start, end=end, progress=False, auto_adjust=False, timeout=YFINANCE_TIMEOUT) except Exception as e: # network / API errors logger.error("yfinance error for %s: %s", ticker, e) return None if data is not None and isinstance(data.columns, pd.MultiIndex): data.columns = data.columns.droplevel(1) return data def cagr_value(ticker, start_year, end_year): """Return dict(ticker, cagr_pct, start, end) or dict(ticker, error).""" t = sanitize_ticker(ticker) if not t: return {"ticker": ticker, "error": "Invalid ticker format"} ok, msg = validate_year_range(start_year, end_year) if not ok: return {"ticker": t, "error": msg} data = _download(t, f"{start_year}-01-01", f"{end_year}-12-31", _hour_key()) if data is None: return {"ticker": t, "error": "Error fetching data (API timeout or network issue)"} if data.empty or "Adj Close" not in data.columns: return {"ticker": t, "error": f"Data is not available for {t} between {start_year} and {end_year}"} s = data["Adj Close"].dropna() if s.empty or s.iloc[0] <= 0 or s.iloc[-1] <= 0: return {"ticker": t, "error": "Missing or invalid price data"} years = (s.index[-1] - s.index[0]).days / 365.25 if years <= 0: return {"ticker": t, "error": "Invalid time period"} cagr = ((s.iloc[-1] / s.iloc[0]) ** (1 / years) - 1) * 100 return {"ticker": t, "cagr_pct": float(cagr), "start": s.index[0].strftime("%Y-%m-%d"), "end": s.index[-1].strftime("%Y-%m-%d")} def cagr_report(tickers, start, end): ok, msg = validate_year_range(start, end) if not ok: return f"Error: {msg}", [] if len(tickers) > 10: return "Error: Too many tickers requested. Please limit to 10 tickers per query.", [] results = [cagr_value(t, start, end) for t in tickers] lines = [] for r in results: if "error" in r: lines.append(f"- {r['ticker']}: {r['error']}") else: lines.append(f"- {r['ticker']}: ~{r['cagr_pct']:.2f}% per year (data: {r['start']} to {r['end']})") text = (f"**CAGR Analysis ({start} - {end})**\n\n" + "\n".join(lines) + "\n\n*Notes:* CAGR is the average annual return with compounding, based on adjusted " "closing prices (includes dividends/splits). Past performance is not indicative of future results.") return text, results def compound_interest(principal, rate_pct, years, contribution=0.0): """Annual compounding; optional contribution added at the end of each year.""" r = rate_pct / 100 growth = (1 + r) ** years fv = principal * growth + (contribution * ((growth - 1) / r if r else years)) paid_in = principal + contribution * years return fv, fv - paid_in, paid_in def compound_report(principal, rate_pct, years, contribution=0.0): try: principal, rate_pct, years = float(principal), float(rate_pct), int(years) contribution = float(contribution or 0) except (TypeError, ValueError): return "Error: amount, rate and years must be numbers." if principal < 0 or contribution < 0 or principal + contribution <= 0: return "Error: amounts must be positive." if not 0 <= rate_pct <= 100: return "Error: Interest rate must be between 0% and 100%." if not 0 < years <= 100: return "Error: Years must be between 1 and 100." fv, interest, paid_in = compound_interest(principal, rate_pct, years, contribution) extra = f"- Yearly Contribution: ${contribution:,.2f}\n" if contribution else "" return (f"**Compound Interest Calculation**\n\n- Starting Principal: ${principal:,.2f}\n{extra}" f"- Annual Interest Rate: {rate_pct:.2f}%\n- Time Period: {years} years\n- Compounding: Annually\n\n" f"**Results:**\n- Final Balance (Year {years}): ${fv:,.2f}\n- Total Contributed: ${paid_in:,.2f}\n" f"- Total Interest Earned: ${interest:,.2f}\n\n" "*Assumes annual compounding" + (", contributions at year end" if contribution else ", no additional deposits") + ".*") def current_price(ticker): import yfinance as yf t = sanitize_ticker(ticker) if not t: return None for attempt in range(2): try: tk = yf.Ticker(t) p = None try: p = tk.fast_info.last_price except Exception: pass if not p or p <= 0: # fallback: last daily close h = tk.history(period="5d")["Close"].dropna() p = float(h.iloc[-1]) if len(h) else None if p and p > 0: return round(float(p), 2) except Exception as e: logger.warning("Price fetch failed for %s (try %d): %s", t, attempt + 1, e) return None def prices_report(tickers): tickers = [sanitize_ticker(t) or str(t) for t in (tickers or [])][:10] if not tickers: return "Error: no ticker given." lines = [] for t in tickers: p = current_price(t) lines.append(f"- {t}: ${p:,.2f}" if p else f"- {t}: Data is not available for {t}") return "**Latest Prices** (Yahoo Finance, may be delayed)\n\n" + "\n".join(lines) # ---------------- Portfolio ---------------- PORTFOLIO_COLS = ["Ticker", "Shares", "Avg Cost", "Current Price"] def _to_df(df): if df is None: return None if not isinstance(df, pd.DataFrame): df = pd.DataFrame(df, columns=PORTFOLIO_COLS) return df.copy() def portfolio_has_rows(df): df = _to_df(df) return df is not None and any(sanitize_ticker(str(t)) for t in df["Ticker"] if pd.notna(t) and str(t).strip()) def process_portfolio(df, growth_rate): """Returns (markdown_report, PIL image or None).""" df = _to_df(df) if df is None or len(df) == 0: return "", None for c in PORTFOLIO_COLS[1:]: df[c] = pd.to_numeric(df[c], errors="coerce") holdings, errors = {}, [] for _, row in df.iterrows(): t = sanitize_ticker(str(row["Ticker"])) if pd.notna(row["Ticker"]) else None if not t: continue sh = row["Shares"] if pd.notna(row["Shares"]) else 0 cost = row["Avg Cost"] if pd.notna(row["Avg Cost"]) else 0 price = row["Current Price"] if pd.notna(row["Current Price"]) else 0 if sh <= 0: errors.append(f"{t}: Invalid shares count"); continue if price < 0 or cost < 0: errors.append(f"{t}: Negative prices not allowed"); continue value, basis = sh * price, sh * cost holdings[t] = dict(shares=sh, cost=cost, price=price, value=value, basis=basis, pct=((value - basis) / basis * 100) if basis > 0 else 0) if not holdings: return "No valid portfolio entries found. Please check your data.", None total = sum(h["value"] for h in holdings.values()) basis = sum(h["basis"] for h in holdings.values()) gl = total - basis out = "**📊 Portfolio Analysis**\n\n**Current Holdings:**\n" for t, h in holdings.items(): out += (f"- {t}: {h['shares']:.2f} shares @ ${h['price']:.2f} (Cost: ${h['cost']:.2f}) " f"= ${h['value']:,.2f} [{h['pct']:+.2f}%]\n") out += (f"\n**Portfolio Summary:**\n- Total Value: ${total:,.2f}\n- Total Cost Basis: ${basis:,.2f}\n" f"- Total Gain/Loss: ${gl:+,.2f} ({(gl / basis * 100) if basis > 0 else 0:+.2f}%)\n" f"\n**Projected Values (at {growth_rate}% annual growth):**\n") for y in (1, 2, 5, 10): v = total * (1 + growth_rate / 100) ** y out += f"- {y} year{'s' if y > 1 else ''}: ${v:,.2f} (+${v - total:,.2f})\n" if errors: out += "\n**⚠️ Warnings:**\n" + "".join(f"- {e}\n" for e in errors) out += "\n*Projections assume a constant growth rate and no additional contributions.*" return out, _pie(holdings, total) def _pie(holdings, total): if total <= 0: return None import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from PIL import Image fig, ax = plt.subplots(figsize=(6, 5)) ax.pie([h["value"] for h in holdings.values()], labels=list(holdings), autopct="%1.1f%%", startangle=90) ax.set_title("Portfolio Allocation by Value") buf = io.BytesIO() fig.savefig(buf, format="png", bbox_inches="tight", dpi=100) plt.close(fig) buf.seek(0) return Image.open(buf) def fetch_current_prices(df): df = _to_df(df) if df is None or len(df) == 0: return df for i in df.index: t = sanitize_ticker(str(df.at[i, "Ticker"])) if pd.notna(df.at[i, "Ticker"]) else None if not t: continue price = current_price(t) if price: df.at[i, "Current Price"] = price return df # ---------------- Dividends ---------------- @lru_cache(maxsize=64) def _div_data(ticker, _cache_key): import yfinance as yf try: tk = yf.Ticker(ticker) hist = tk.history(period="1y")["Close"].dropna() divs = tk.dividends except Exception as e: logger.warning("dividend fetch failed for %s: %s", ticker, e) return None, None return hist, divs def ticker_has_data(ticker): t = sanitize_ticker(ticker) if not t: return False hist, _ = _div_data(t, _hour_key()) return hist is not None and len(hist) > 0 def dividend_stats(ticker, years=5): """dict with price, ttm dividend/yield, annual dividends by full calendar year, dividend CAGR; or dict(error).""" t = sanitize_ticker(ticker) if not t: return {"ticker": ticker, "error": f"Data is not available for {ticker}"} hist, divs = _div_data(t, _hour_key()) if hist is None or len(hist) == 0: return {"ticker": t, "error": f"Data is not available for {t}"} price = float(hist.iloc[-1]) if divs is None or len(divs) == 0: return {"ticker": t, "price": price, "error": f"Dividend data is not available for {t} (it may not pay dividends)"} divs = divs.copy() divs.index = pd.to_datetime(divs.index).tz_localize(None) last_date = pd.Timestamp(hist.index[-1]).tz_localize(None) ttm = float(divs[divs.index > last_date - pd.Timedelta(days=365)].sum()) annual = divs.groupby(divs.index.year).sum() full = annual[annual.index < last_date.year] out = {"ticker": t, "price": price, "ttm_div": ttm, "ttm_yield": ttm / price * 100, "as_of": last_date.strftime("%Y-%m-%d")} if len(full) >= years + 1 and full.iloc[-(years + 1)] > 0: y0, y1 = int(full.index[-(years + 1)]), int(full.index[-1]) out.update(div_cagr=((full.iloc[-1] / full.iloc[-(years + 1)]) ** (1 / years) - 1) * 100, cagr_from=y0, cagr_to=y1, div_start=float(full.iloc[-(years + 1)]), div_end=float(full.iloc[-1])) return out def dividend_report(ticker, amount=None, years=5, gain_pct=None, price_growth=None, div_growth=None): try: years = int(years or 5) amount = float(amount) if amount not in (None, "", 0) else None gain_pct = float(gain_pct) if gain_pct not in (None, "") else None price_growth = float(price_growth) if price_growth not in (None, "") else None div_growth = float(div_growth) if div_growth not in (None, "") else None except (TypeError, ValueError): return "Error: amount, years and percentages must be numbers." years = min(max(years, 1), 30) s = dividend_stats(ticker, 5) if "error" in s: return s["error"] + "." t = s["ticker"] out = (f"**Dividend Analysis: {t}** (Yahoo Finance, as of {s['as_of']})\n\n" f"- Price: ${s['price']:,.2f}\n- Trailing 12-month dividends: ${s['ttm_div']:,.4f} per share\n" f"- Trailing 12-month yield: {s['ttm_yield']:.2f}%\n") g = s.get("div_cagr") if g is not None: out += (f"- 5-year dividend growth (CAGR of annual dividends {s['cagr_from']}→{s['cagr_to']}, " f"${s['div_start']:,.4f}→${s['div_end']:,.4f}): {g:.2f}% per year\n") else: out += "- 5-year dividend growth: not available (fewer than 6 full years of dividend history)\n" if amount is None: return out + "\n*Past dividends do not guarantee future dividends.*" shares = amount / s["price"] pay0 = shares * s["ttm_div"] out += (f"\n**On ${amount:,.2f} of {t}** (assumed to be today's market value ≈ {shares:,.2f} shares)\n" f"- Estimated annual dividend payment now: ${pay0:,.2f}\n") if gain_pct is not None: basis = amount / (1 + gain_pct / 100) out += (f"- With a {gain_pct:g}% gain, your cost basis would be ≈ ${basis:,.2f}, so yield on cost ≈ " f"{pay0 / basis * 100:.2f}% (vs {s['ttm_yield']:.2f}% on market value)\n" f"- Alternative reading: if ${amount:,.2f} is what you *paid* and the position is up {gain_pct:g}%, " f"market value ≈ ${amount * (1 + gain_pct / 100):,.2f} and the annual payment ≈ " f"${pay0 * (1 + gain_pct / 100):,.2f} (yield on cost ≈ {s['ttm_yield'] * (1 + gain_pct / 100):.2f}%)\n") gr = (div_growth if div_growth is not None else (g or 0.0)) / 100 rows, total = [], 0.0 for k in range(1, years + 1): p = pay0 * (1 + gr) ** k total += p rows.append(f" - Year {k}: ${p:,.2f} (yield on ${amount:,.0f}: {p / amount * 100:.2f}%)") if div_growth is not None: hist_txt = f"; historical 5-yr CAGR was {g:.2f}%" if g is not None else "" basis_txt = f"{div_growth:g}%/yr (YOUR assumed dividend growth rate{hist_txt})" else: basis_txt = f"{g:.2f}%/yr (historical 5-yr dividend CAGR)" if g is not None else "0%/yr (no growth history)" out += (f"\n**{years}-year projection** — dividends grow at {basis_txt}, dividends not reinvested:\n" + "\n".join(rows) + f"\n- Total dividends over {years} years: ${total:,.2f}\n" f"- Weighted {years}-year dividend return: {total / amount * 100:.2f}% total, " f"≈ {total / amount / years * 100:.2f}% per year on ${amount:,.0f}\n") if price_growth is not None: end_val = amount * (1 + price_growth / 100) ** years out += (f"- With {price_growth:g}%/yr price growth: value ≈ ${end_val:,.2f} after {years} years; " f"total return incl. dividends ≈ {(end_val + total - amount) / amount * 100:.2f}%\n") note = "your assumed rate" if div_growth is not None else "the past rate" return out + f"\n*Projection assumes dividends keep growing at {note}; actual dividends can be cut. Not advice.*"