From fdf5084d73e794ffbce93ae3e9dd936a1e2bba79 Mon Sep 17 00:00:00 2001 From: Arvi23 Date: Wed, 4 Nov 2026 18:54:25 +0200 Subject: [PATCH] Batch 6: industry peers, relative P/E, desktop shortcut - Industry peer comparison (D14): the snapshot includes up to 5 of the largest US companies in the stock's Yahoo industry (peers.py, yahoo.fetch_industry_peers / fetch_key_metrics, services.load_peers). US-listed stocks only; peer lists and metrics cached 24 h, fetched 4 at a time; failed peers skipped. - Valuation: trailing and forward P/E are scored against the peer median when 3+ peers have a value ("33.4 vs industry median 45.0 (-26%)"); fixed bands otherwise. - Finance tab "Industry peers" table, the stock highlighted green/orange vs median. - Snapshot schema 3; LLM context includes peer medians. - start.bat creates a Desktop shortcut on first run (once, marker file). - Debt/Equity card shows 0.30x like the breakdown (Yahoo's raw value is percent). 96 backend tests; UI smoke checks the peer table and relative P/E. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TW7cJeWrcBW5SJHr4ZKtSH --- README.md | 5 +- docs/ARCHITECTURE.md | 6 +- docs/DECISIONS.md | 10 ++++ docs/HANDOFF.md | 40 ++++++++----- pyproject.toml | 2 +- scripts/fake_server.py | 29 +++++++++- scripts/ui_smoke.js | 9 +++ start.bat | 15 +++++ static/index.html | 9 +++ static/js/dashboard.js | 41 +++++++++++++- tests/conftest.py | 19 ++++++- tests/test_peers.py | 104 ++++++++++++++++++++++++++++++++++ tests/test_yahoo.py | 21 +++++++ uv.lock | 2 +- watchstock/__init__.py | 2 +- watchstock/analysis.py | 6 ++ watchstock/config.py | 1 + watchstock/peers.py | 57 +++++++++++++++++++ watchstock/providers/yahoo.py | 39 ++++++++++++- watchstock/scoring.py | 33 ++++++++--- watchstock/services.py | 54 ++++++++++++++++-- 21 files changed, 470 insertions(+), 34 deletions(-) create mode 100644 tests/test_peers.py create mode 100644 watchstock/peers.py diff --git a/README.md b/README.md index a2b571e..b47e3af 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ an AI-written research report you can question in a chat. 2. Double-click **`start.bat`**. - The first start installs a small tool called `uv`, which downloads Python and the libraries WatchStock needs. This takes a few minutes, once. Nothing else needs to be installed. - - Your browser opens at `http://127.0.0.1:8000`. + - Your browser opens at `http://127.0.0.1:8000`, and a **WatchStock** shortcut is + put on your Desktop for next time. 3. To stop WatchStock, close the black window. Optional: for AI reports and chat, open **Settings** (gear icon) and paste an @@ -39,6 +40,8 @@ Download the new ZIP and copy your old `data` folder into it (or `git pull`). - **Finance tab:** opportunity score (fundamentals, analyst view, valuation, smart money, each with a click-for-breakdown), valuation multiples, analyst targets and rating changes, insider transactions, key metrics. +- **Industry peers** (Finance tab, US stocks): the largest companies in the same industry + side by side; the valuation score compares P/E with the industry median. - **AI Analysis tab:** verdict, deep dive, news impact, bull/base/bear scenarios, charts. Reports are saved with their date and model. - **News tab:** recent headlines for the stock. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 564cdaa..1938c04 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -16,12 +16,13 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static ├── symbols.py Yahoo ↔ TradingView ticker translation ├── portfolio.py pure portfolio math: value, P/L, weights, allocation, flags, dividends ├── today.py pure "Today" event builder (earnings, ex-div, moves, ratings, insider buys) + ├── peers.py pure industry-peer comparison (medians, relative %, table rows) ├── analysis.py LLM prompts: report, chat, thesis check (compact context) ├── store.py every SQL query ├── db.py connection + migrations (PRAGMA user_version) ├── ttl_cache.py in-memory TTL cache for widgets └── providers/ the only code that touches the network - ├── yahoo.py yfinance: profile, news, quotes, events (calendar), search, screeners + ├── yahoo.py yfinance: profile, news, quotes, events, industry peers, search, screeners └── openrouter.py chat completions ``` @@ -79,7 +80,8 @@ call never blocks other requests. "upgrades_downgrades": [...], "insider_transactions": [...] }, "news": [{"title", "url", "publisher", "published_at", "summary"}], - "schema": 2, // services.SNAPSHOT_SCHEMA + "schema": 3, // services.SNAPSHOT_SCHEMA + "peers": null | {"industry", "rows": [{"ticker","name","is_self", P/E...}], "medians", "relative", "peer_count"}, "tradingview_symbol": "MSFT", // e.g. "BVB:TLV" for TLV.RO "scores": { "quality" | "valuation" | "analyst" | "smart_money": {"score", "breakdown": [item]}, diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 4f05a06..7bf56d7 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -98,3 +98,13 @@ and fetched at most 4 tickers at a time, to stay gentle with Yahoo. Thesis check explicit button per position (one LLM call each) and are stored with the thesis text as it was, so a later check can say what changed. Insider sales are skipped (routine diversification); purchases are signal. + +## D14 — Industry peers make P/E relative; US-listed stocks only (2026-11-04) +Fixed P/E bands judged a software company and a bank by the same yardstick (D8). The +snapshot now includes up to 5 of the largest companies in the stock's Yahoo industry +(`yf.Industry(key).top_companies`). When at least 3 have a usable value, trailing and +forward P/E are scored against the peer median (ratio bands), and the breakdown says +e.g. "33.4 vs industry median 45.0 (-26%)". Otherwise the fixed bands still apply. Yahoo's +industry lists are US companies, so non-USD stocks get no peers rather than a misleading +comparison. Peer lists and peer metrics (one `info` call each) are cached in memory for +24 h and fetched 4 at a time; a failed peer is skipped. Snapshot schema 3. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 643b75b..ce3cf89 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -83,21 +83,27 @@ Read this first. Update it at the end of every batch or before your context runs portfolio table; previous check passed to the next one - [x] 88 backend tests; UI smoke covers the Today panel and thesis flow -### Batch 6 — Next (not started) -1. **Peer comparison** (deferred from batch 5): fetch 4-6 industry peers (yfinance - `Ticker.info["industryKey"]` → `yf.Industry(key).top_companies`), show a small - peer table (P/E, fwd P/E, PEG, margin, growth) on the Finance tab, and make the valuation - P/E bands relative to the peer median (see D8). Cache peers per industry for a day. -2. **Price chart fallback** if TradingView's free widget lacks BVB data (owner to confirm): - `Ticker.history(period="1y")` → Chart.js line chart. -3. **Desktop shortcut** created by `start.bat` on first run (dad-friendliness). -4. Optional: scheduled morning digest (email or Windows toast) once the panel proves useful. +### Batch 6 — Peers + polish *(branch `batch-6-peers`, PR #6, stacked on #5)* ✅ +- [x] Industry peer comparison (D14): `peers.py`, `yahoo.fetch_industry_peers` / `fetch_key_metrics`, + `services.load_peers` (US-listed only, 24 h cache, 4 parallel); Finance tab "Industry peers" table + with the stock highlighted vs the median; P/E and forward P/E scored relative to the peer median +- [x] Snapshot schema 3 (old cached snapshots refetch); LLM context includes peer medians +- [x] `start.bat` creates a Desktop shortcut on first run (once; marker `data\.shortcut-created`) +- [x] Debt/Equity card shows "0.30x" like the breakdown (Yahoo's raw value is percent) +- [x] 96 backend tests; UI smoke checks the peer table and relative P/E + +### Ideas for later (not planned) +- Own price chart (`Ticker.history`) if TradingView ever fails for a market the owner uses + (owner confirmed TradingView works, including BVB, on 2026-11-04). +- Scheduled morning digest (email / Windows toast) if the "Your stocks" panel proves useful. +- Peer comparison for non-US stocks (would need a different peer source). +- Portfolio history (value over time) — needs a daily snapshot job. ## Status -**Paused 2026-11-04 after batch 5** (owner: "we'll stop for today"). Batches 1-5 done; -PRs #1-#5 are stacked, CI-green, and wait for the owner to merge in order. The owner's folder -`E:\WatchStock\WatchStock` has everything through batch 5. Next session: start with -batch 6 (plan above), after checking the "Needs live testing" boxes the owner has reported back on. +Batches 1-6 done. PR #1 merged by the owner; #2-#6 are stacked and CI-green. **Owner action:** +on PR #2 change the base to `main` (Edit next to the title), merge, click "Delete branch"; +GitHub then retargets #3 to `main`, and so on. (Agents may not merge or retarget PRs here.) +The owner's folder `E:\WatchStock\WatchStock` has everything through batch 6. Notes for the next agent: - The sidebar "you own" P/L uses the snapshot price (up to 4 h old); the portfolio table @@ -106,6 +112,8 @@ Notes for the next agent: `PLAYWRIGHT_BROWSERS_PATH` pointing at a Chromium matching playwright 1.63.0). ## Needs live testing (owner, on Windows) +Owner reported 2026-11-04 evening: batches 1-5 tested, "it all seems to work" (incl. TradingView on BVB). + Batch 1 (owner tested 2026-11-04: works; BVB chart said "symbol doesn't exist" → fixed in batch 2; first run without key "froze / lost connection" → likely browser opened too early, fixed in batch 2): - [x] start.bat first run, search, news, AI report with the free nemotron model @@ -139,6 +147,12 @@ Batch 5: - [ ] Add a "why I own it" note to a position → CHECK → verdict with evidence appears; badge in table - [ ] The free model returns valid JSON for the thesis check (if not: note the error text) +Batch 6: +- [ ] Finance tab "Industry peers" table appears for a US stock (e.g. MSFT, JPM) with sensible peers +- [ ] Valuation breakdown shows "P/E ... vs industry median ..." +- [ ] First start after the update creates a "WatchStock" shortcut on the Desktop, and it launches the app +- [ ] Opening a stock for the first time is still reasonably fast (peers add up to 5 Yahoo calls, cached a day) + ## Open questions for the owner - (answered) Dad holds mostly US stocks → currency formatting stays in batch 3, no rush. - (answered) Default model: `nvidia/nemotron-3.5-super-vl:free` for now. diff --git a/pyproject.toml b/pyproject.toml index 0a23e33..7820160 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "watchstock" -version = "0.6.0" +version = "0.7.0" description = "Personal stock analysis terminal: Yahoo Finance data, explainable scores, optional LLM analysis." readme = "README.md" requires-python = ">=3.12" diff --git a/scripts/fake_server.py b/scripts/fake_server.py index 6e4d710..d578879 100644 --- a/scripts/fake_server.py +++ b/scripts/fake_server.py @@ -29,6 +29,7 @@ def fetch_profile(ticker): raise yahoo.MarketDataError("429 Too Many Requests (fake)") p = copy.deepcopy(SAMPLE_PROFILE) m = p["metrics"] + m["industryKey"] = "software-infrastructure" if ticker.endswith(".RO"): # Bucharest: everything in RON p["name"] = "Banca Transilvania S.A." m.update(currency="RON", financialCurrency="RON", currentPrice=29.5, marketCap=2.4e10) @@ -60,6 +61,32 @@ def chg(t): return {t: {"price": 100.0, "change_pct": chg(t), "currency": cur(t)} for t in tickers} +def fetch_industry_peers(industry_key, limit=8): + return [ + {"ticker": t, "name": n} + for t, n in [ + ("MSFT", "Microsoft"), + ("ORCL", "Oracle"), + ("ADBE", "Adobe"), + ("CRM", "Salesforce"), + ] + ][:limit] + + +def fetch_key_metrics(ticker): + pe = {"ORCL": 40.0, "ADBE": 45.0, "CRM": 50.0}.get(ticker, 30.0) + return { + "name": ticker, + "trailingPE": pe, + "forwardPE": pe * 0.8, + "pegRatio": 2.0, + "profitMargins": 0.2, + "revenueGrowth": 0.1, + "marketCap": 2e11, + "currency": "USD", + } + + def fetch_events(ticker): from datetime import date, timedelta @@ -147,7 +174,7 @@ def complete(messages, *, api_key, model, json_mode=True): def install_fakes(): for fn in (fetch_profile, fetch_news, fetch_quotes, fetch_indices, fetch_market_news, - fetch_movers, search, fetch_events): # fmt: skip + fetch_movers, search, fetch_events, fetch_industry_peers, fetch_key_metrics): # fmt: skip setattr(yahoo, fn.__name__, fn) openrouter.complete = complete diff --git a/scripts/ui_smoke.js b/scripts/ui_smoke.js index 2df0210..0aa6330 100644 --- a/scripts/ui_smoke.js +++ b/scripts/ui_smoke.js @@ -115,6 +115,15 @@ const check = (name, ok, detail = '') => { if (!ok) failures.push(`${name}${deta await page.click('.tab-btn[data-target="tab-finance"]'); await page.click('[data-score-key="quality"]'); check('quality breakdown', /Net margin 36\.0%/.test(await text('#popoverContent')), await text('#popoverContent')); + await page.evaluate(() => hideScoreBreakdown()); + await page.click('[data-score-key="valuation"]'); + check('relative P/E in valuation', /Trailing P\/E 33\.4 vs industry median 45\.0 \(-26%\)/.test(await text('#popoverContent')), await text('#popoverContent')); + await page.evaluate(() => hideScoreBreakdown()); + const peersText = await text('#peersTable'); + check('peer table', /ORCL/.test(peersText) && /CRM/.test(peersText) && /Peer median/.test(peersText), peersText); + await page.evaluate(() => document.getElementById('peersSection').scrollIntoView()); + await shot('peers'); + await page.click('[data-score-key="quality"]'); await shot('popover'); await page.evaluate(() => { hideScoreBreakdown(); showScoreExplanation('long_term'); }); check('safety modal', /Debt\/Equity 0\.30x/.test(await text('#scoreModalBody'))); diff --git a/start.bat b/start.bat index d922505..8bed98a 100644 --- a/start.bat +++ b/start.bat @@ -27,6 +27,10 @@ if errorlevel 1 ( exit /b 1 ) +rem First run only: put a WatchStock shortcut on the Desktop. The marker file means +rem a shortcut the user deleted on purpose doesn't come back. Delete the marker to redo. +if not exist "data\.shortcut-created" call :make_shortcut + echo Starting WatchStock... (the first start can take a few minutes) uv run --frozen --no-dev python -m watchstock if errorlevel 1 ( @@ -35,3 +39,14 @@ if errorlevel 1 ( echo Details are in data\watchstock.log pause ) +exit /b + +:make_shortcut +if not exist "data" mkdir "data" +set "APPDIR=%CD%" +powershell -NoProfile -ExecutionPolicy ByPass -Command "$s = (New-Object -ComObject WScript.Shell).CreateShortcut([Environment]::GetFolderPath('Desktop') + '\WatchStock.lnk'); $s.TargetPath = $env:APPDIR + '\start.bat'; $s.WorkingDirectory = $env:APPDIR; $s.Description = 'Start WatchStock'; $s.Save()" >nul 2>&1 +if not errorlevel 1 ( + type nul > "data\.shortcut-created" + echo Created a WatchStock shortcut on your Desktop. +) +exit /b 0 diff --git a/static/index.html b/static/index.html index a9930c5..2d80943 100644 --- a/static/index.html +++ b/static/index.html @@ -327,6 +327,15 @@

+
+
INDUSTRY PEERS
+
Largest US companies in the same industry · median excludes this stock
+
+
+ +
FUNDAMENTALS
diff --git a/static/js/dashboard.js b/static/js/dashboard.js index e8c49f7..8472f49 100644 --- a/static/js/dashboard.js +++ b/static/js/dashboard.js @@ -14,7 +14,7 @@ const METRIC_DESCRIPTIONS = { earningsGrowth: { label: 'Earnings Growth', desc: 'Year-over-year earnings change.', format: fmtPct }, trailingEps: { label: 'EPS (Trailing)', desc: 'Earnings per share over the last 12 months.', format: v => fmtMoney(v, priceCurrency()) }, forwardEps: { label: 'EPS (Forward)', desc: 'Analyst-estimated earnings per share for next 12 months.', format: v => fmtMoney(v, priceCurrency()) }, - debtToEquity: { label: 'Debt / Equity', desc: 'Total debt relative to shareholders equity. Lower = less leverage risk.', format: fmtNum(2) }, + debtToEquity: { label: 'Debt / Equity', desc: 'Total debt relative to shareholders equity. Lower = less leverage risk.', format: v => v != null ? (v / 100).toFixed(2) + 'x' : 'N/A' }, // Yahoo sends percent freeCashflow: { label: 'Free Cash Flow', desc: 'Cash generated after capex. Positive = company funds itself without borrowing.', format: v => fmtBig(v, statementCurrency()) }, dividendYield: { label: 'Dividend Yield', desc: 'Annual dividend as % of current price.', format: v => v != null ? (v * 100).toFixed(2) + '%' : 'N/A' }, // backend sends a fraction @@ -412,6 +412,7 @@ function populateDashboard(data) { renderValuationSection(metrics, data.scores?.valuation); renderAnalystSection(data.financial_data?.analyst_data, data.scores?.analyst, data.financial_data?.upgrades_downgrades); renderSmartMoneySection(metrics, data.scores?.smart_money, data.financial_data?.insider_transactions); + renderPeersSection(data.peers); // ---- Fundamentals metric cards ---- const metricCards = document.getElementById('metricCards'); @@ -493,3 +494,41 @@ function populateDashboard(data) { newsContent.appendChild(card); }); } + +// ---- Industry peers ---- +// Lower is "better" for valuation multiples, higher for margins/growth; colour the +// stock's own cells against the peer median accordingly. +const PEER_COLUMNS = [ + { key: 'trailingPE', label: 'P/E', fmt: v => v?.toFixed(1), lowerIsBetter: true }, + { key: 'forwardPE', label: 'Fwd P/E', fmt: v => v?.toFixed(1), lowerIsBetter: true }, + { key: 'pegRatio', label: 'PEG', fmt: v => v?.toFixed(2), lowerIsBetter: true }, + { key: 'profitMargins', label: 'Net margin', fmt: v => v != null ? (v * 100).toFixed(1) + '%' : null }, + { key: 'revenueGrowth', label: 'Rev growth', fmt: v => v != null ? (v * 100).toFixed(1) + '%' : null }, + { key: 'marketCap', label: 'Mkt cap', fmt: v => v != null ? fmtBig(v, 'USD') : null }, +]; + +function renderPeersSection(peers) { + const section = document.getElementById('peersSection'); + if (!peers || !peers.rows?.length) { section.style.display = 'none'; return; } + section.style.display = 'block'; + document.getElementById('peersIndustry').textContent = peers.industry ? `· ${peers.industry}` : ''; + + const cell = (col, row) => { + const text = col.fmt(row[col.key]) ?? '—'; + const med = peers.medians?.[col.key]; + if (!row.is_self || med == null || row[col.key] == null || col.key === 'marketCap') return `${esc(text)}`; + const better = col.lowerIsBetter ? row[col.key] < med : row[col.key] > med; + return `${esc(text)}`; + }; + const rows = peers.rows.map(r => ` + + + ${esc(r.ticker)}${esc((r.name || '').slice(0, 22))} + ${PEER_COLUMNS.map(c => cell(c, r)).join('')} + `).join(''); + const medianRow = `Peer median + ${PEER_COLUMNS.map(c => `${c.key === 'marketCap' ? '' : esc(c.fmt(peers.medians?.[c.key]) ?? '—')}`).join('')}`; + document.getElementById('peersTable').innerHTML = ` + ${PEER_COLUMNS.map(c => ``).join('')} + ${rows}${medianRow}
Company${c.label}
`; +} diff --git a/tests/conftest.py b/tests/conftest.py index 0aea0a2..dc3a3fe 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -94,6 +94,22 @@ def fetch_movers(self, count=20): return self._market("movers", {"gainers": [], "losers": []}) events: dict = {} + # industry key -> list of peers; peer ticker -> key metrics. Empty = no peers. + industries: dict = {} + peer_metrics: dict = {} + peers_error: Exception | None = None + + def fetch_industry_peers(self, industry_key, limit=8): + self.calls.append(("industry", industry_key)) + if self.peers_error: + raise self.peers_error + return copy.deepcopy(self.industries.get(industry_key, []))[:limit] + + def fetch_key_metrics(self, ticker): + self.calls.append(("peer", ticker)) + if ticker not in self.peer_metrics: + raise yahoo.MarketDataError(f"No data found for ticker {ticker!r}") + return copy.deepcopy(self.peer_metrics[ticker]) def fetch_events(self, ticker): self.calls.append(("events", ticker)) @@ -141,7 +157,8 @@ def _isolated(tmp_path, monkeypatch): def fake_yahoo(monkeypatch): fake = FakeYahoo() for name in ("fetch_profile", "fetch_news", "fetch_quotes", "fetch_indices", - "fetch_market_news", "fetch_movers", "search", "fetch_events"): # fmt: skip + "fetch_market_news", "fetch_movers", "search", "fetch_events", + "fetch_industry_peers", "fetch_key_metrics"): # fmt: skip monkeypatch.setattr(yahoo, name, getattr(fake, name)) return fake diff --git a/tests/test_peers.py b/tests/test_peers.py new file mode 100644 index 0000000..9183234 --- /dev/null +++ b/tests/test_peers.py @@ -0,0 +1,104 @@ +"""Industry peer comparison: pure math, relative P/E scoring, snapshot integration.""" + +import pytest + +from watchstock import peers, scoring +from watchstock.providers.yahoo import MarketDataError + + +def peer(t, pe, fpe=None, margin=0.2, growth=0.1): + return { + "ticker": t, + "name": t, + "trailingPE": pe, + "forwardPE": fpe, + "pegRatio": None, + "profitMargins": margin, + "revenueGrowth": growth, + "marketCap": 1e11, + } + + +def test_medians_need_three_valid_peers_and_ignore_bad_values(): + rows = [peer("A", 20), peer("B", 30), peer("C", -5), peer("D", 900)] + med = peers.peer_medians(rows) + assert med["trailingPE"] is None # only 2 valid P/Es + assert med["profitMargins"] == 0.2 + med = peers.peer_medians([peer("A", 20), peer("B", 30), peer("C", 40)]) + assert med["trailingPE"] == 30 + + +def test_comparison_excludes_self_and_computes_relative(): + rows = [peer("MSFT", 99), peer("A", 20), peer("B", 30), peer("C", 40)] + out = peers.build_comparison("MSFT", "Microsoft", {"trailingPE": 36.0}, rows, "Software") + assert out["peer_count"] == 3 + assert [r["ticker"] for r in out["rows"]] == ["MSFT", "A", "B", "C"] + assert out["rows"][0]["is_self"] is True + assert out["relative"]["trailingPE"] == 20.0 # 36 vs median 30 + + +def test_valuation_uses_peer_median_when_available(): + absolute = scoring.score_valuation({"trailingPE": 33.4}) + cheap_vs_peers = scoring.score_valuation({"trailingPE": 33.4}, {"trailingPE": 60.0}) + pricey_vs_peers = scoring.score_valuation({"trailingPE": 33.4}, {"trailingPE": 15.0}) + assert absolute["breakdown"][0]["item"] == "Trailing P/E 33.4" + assert "vs industry median 60.0 (-44%)" in cheap_vs_peers["breakdown"][0]["item"] + assert cheap_vs_peers["score"] > absolute["score"] > pricey_vs_peers["score"] + + +# --------------------------------------------------------------- snapshots + + +@pytest.fixture +def with_peers(fake_yahoo, monkeypatch): + from tests.conftest import SAMPLE_PROFILE + + monkeypatch.setitem(SAMPLE_PROFILE["metrics"], "industryKey", "software-infrastructure") + fake_yahoo.industries = {"software-infrastructure": [ + {"ticker": "MSFT", "name": "Microsoft"}, {"ticker": "ORCL", "name": "Oracle"}, + {"ticker": "ADBE", "name": "Adobe"}, {"ticker": "CRM", "name": "Salesforce"}, + {"ticker": "GONE", "name": "Delisted"}, + ]} # fmt: skip + fake_yahoo.peer_metrics = { + "ORCL": peer("ORCL", 40, 30), + "ADBE": peer("ADBE", 45, 28), + "CRM": peer("CRM", 50, 32), + } + return fake_yahoo + + +def test_snapshot_includes_peers_and_relative_valuation(client, with_peers): + body = client.get("/api/stocks/MSFT").json() + p = body["peers"] + assert p["industry"] == "Software" + assert [r["ticker"] for r in p["rows"]] == [ + "MSFT", + "ORCL", + "ADBE", + "CRM", + ] # GONE failed, skipped + assert p["medians"]["trailingPE"] == 45 + pe_item = body["scores"]["valuation"]["breakdown"][0]["item"] + assert "vs industry median 45.0" in pe_item + + +def test_peer_data_is_cached_across_stocks(client, with_peers): + client.get("/api/stocks/MSFT") + client.get("/api/stocks/MSFT?refresh=true") + assert with_peers.calls.count(("industry", "software-infrastructure")) == 1 + assert with_peers.calls.count(("peer", "ORCL")) == 1 + + +def test_no_peers_for_non_usd_stocks(client, with_peers, monkeypatch): + from tests.conftest import SAMPLE_PROFILE + + monkeypatch.setitem(SAMPLE_PROFILE["metrics"], "currency", "RON") + assert client.get("/api/stocks/TLV.RO").json()["peers"] is None + assert ("industry", "software-infrastructure") not in with_peers.calls + + +def test_peer_failure_falls_back_to_absolute_bands(client, with_peers): + with_peers.peers_error = MarketDataError("blocked") + body = client.get("/api/stocks/MSFT").json() + assert body["peers"] is None + assert body["scores"]["valuation"]["breakdown"][0]["item"] == "Trailing P/E 33.4" diff --git a/tests/test_yahoo.py b/tests/test_yahoo.py index 40a60a1..5b2734a 100644 --- a/tests/test_yahoo.py +++ b/tests/test_yahoo.py @@ -77,3 +77,24 @@ def test_dividend_yield_is_a_fraction(monkeypatch): info = {"longName": "X", "currentPrice": 400.0, "dividendYield": 0.88} monkeypatch.setattr(yahoo.yf, "Ticker", lambda t: _StubTicker(info)) assert yahoo.fetch_profile("X")["metrics"]["dividendYield"] == pytest.approx(0.0088) + + +def test_fetch_industry_peers_and_key_metrics(monkeypatch): + import pandas as pd + + class StubIndustry: + def __init__(self, key): + self.top_companies = pd.DataFrame( + [("MSFT", "Microsoft", "Buy", 0.4), ("ORCL", "Oracle", "Buy", 0.1)], + columns=["symbol", "name", "rating", "market weight"], + ).set_index("symbol") + + monkeypatch.setattr(yahoo.yf, "Industry", StubIndustry) + assert yahoo.fetch_industry_peers("software-infrastructure", limit=1) == [ + {"ticker": "MSFT", "name": "Microsoft"} + ] + + info = {"shortName": "Oracle", "trailingPE": 40.0, "forwardPE": float("nan"), "currency": "USD"} + monkeypatch.setattr(yahoo.yf, "Ticker", lambda t: _StubTicker(info)) + m = yahoo.fetch_key_metrics("ORCL") + assert m["name"] == "Oracle" and m["trailingPE"] == 40.0 and m["forwardPE"] is None diff --git a/uv.lock b/uv.lock index 73ea8c4..034260d 100644 --- a/uv.lock +++ b/uv.lock @@ -1020,7 +1020,7 @@ wheels = [ [[package]] name = "watchstock" -version = "0.6.0" +version = "0.7.0" source = { editable = "." } dependencies = [ { name = "fastapi" }, diff --git a/watchstock/__init__.py b/watchstock/__init__.py index c242578..604e9c1 100644 --- a/watchstock/__init__.py +++ b/watchstock/__init__.py @@ -1,3 +1,3 @@ """WatchStock: personal stock analysis terminal.""" -__version__ = "0.6.0" +__version__ = "0.7.0" diff --git a/watchstock/analysis.py b/watchstock/analysis.py index 4bdb802..d4f3e27 100644 --- a/watchstock/analysis.py +++ b/watchstock/analysis.py @@ -50,6 +50,11 @@ def compact_context(stock: dict[str, Any]) -> dict[str, Any]: "key_officers": (stock.get("financial_data", {}).get("key_officers") or [])[:3], "risk_analysis": stock.get("risk_analysis", {}), "safety": stock.get("safety"), + "industry_peers": ( + {k: stock["peers"][k] for k in ("industry", "medians", "relative", "peer_count")} + if stock.get("peers") + else None + ), "scores": stock.get("scores"), "news": [ {k: n.get(k) for k in ("title", "publisher", "published_at", "summary")} @@ -70,6 +75,7 @@ def compact_context(stock: dict[str, Any]) -> dict[str, Any]: "- `scores`: opportunity (0-100) built from quality, valuation, analyst and smart-money " "pillars, each with a breakdown of what drove it\n" "- `safety`: short_term (liquidity) and long_term (solvency & volatility) 0-100, plus flags\n" + "- `industry_peers` (may be null): industry peer medians and this stock's % difference\n" "- `previous_report` (may be absent): your last report on this stock and its date\n" "- `news`: recent headlines. Decide yourself which ones are material.\n\n" "INSTRUCTIONS:\n" diff --git a/watchstock/config.py b/watchstock/config.py index 05aff3f..0132f0c 100644 --- a/watchstock/config.py +++ b/watchstock/config.py @@ -18,6 +18,7 @@ MARKET_NEWS_TTL_SECONDS = 5 * 60 MOVERS_TTL_SECONDS = 10 * 60 EVENTS_TTL_SECONDS = 6 * 60 * 60 # calendar / ratings / insider data per ticker +PEERS_TTL_SECONDS = 24 * 60 * 60 # industry peer lists and peer metrics # Free model the owner chose for trials; any OpenRouter model id works (set in Settings). DEFAULT_LLM_MODEL = "nvidia/nemotron-3.5-super-vl:free" diff --git a/watchstock/peers.py b/watchstock/peers.py new file mode 100644 index 0000000..ee8c6ba --- /dev/null +++ b/watchstock/peers.py @@ -0,0 +1,57 @@ +"""Industry peer comparison: pure functions. Covered by tests/test_peers.py. + +Peers are the largest US companies in the stock's Yahoo industry. Medians are taken over +the peers only (not the stock itself) and only when at least MIN_PEERS have a usable value. +""" + +from statistics import median +from typing import Any + +MIN_PEERS = 3 + +# field -> (label, valid range); values outside the range (e.g. negative or absurd P/E) +# are ignored for medians. +COMPARE_FIELDS: dict[str, tuple[str, tuple[float, float] | None]] = { + "trailingPE": ("P/E", (0, 500)), + "forwardPE": ("Fwd P/E", (0, 500)), + "pegRatio": ("PEG", (0, 20)), + "profitMargins": ("Net margin", None), + "revenueGrowth": ("Revenue growth", None), +} + + +def _valid(field: str, value: Any) -> bool: + if not isinstance(value, int | float): + return False + bounds = COMPARE_FIELDS[field][1] + return bounds is None or bounds[0] < value < bounds[1] + + +def peer_medians(peers: list[dict]) -> dict[str, float | None]: + out: dict[str, float | None] = {} + for field in COMPARE_FIELDS: + values = [p[field] for p in peers if _valid(field, p.get(field))] + out[field] = round(median(values), 4) if len(values) >= MIN_PEERS else None + return out + + +def build_comparison( + ticker: str, name: str, metrics: dict, peers: list[dict], industry: str | None +) -> dict[str, Any]: + peers = [p for p in peers if p.get("ticker") != ticker] + medians = peer_medians(peers) + relative = {} + for field, med in medians.items(): + value = metrics.get(field) + if med and _valid(field, value): + relative[field] = round((value / med - 1) * 100, 1) + self_row = {"ticker": ticker, "name": name, "is_self": True, + **{f: metrics.get(f) for f in (*COMPARE_FIELDS, "marketCap")}} # fmt: skip + rows = [self_row] + [{**p, "is_self": False} for p in peers] + return { + "industry": industry, + "rows": rows, + "medians": medians, + "relative": relative, + "peer_count": len(peers), + } diff --git a/watchstock/providers/yahoo.py b/watchstock/providers/yahoo.py index 87b0774..641ada2 100644 --- a/watchstock/providers/yahoo.py +++ b/watchstock/providers/yahoo.py @@ -49,7 +49,8 @@ class MarketDataError(Exception): # Ownership / short interest "shortPercentOfFloat", "shortRatio", "heldPercentInstitutions", "heldPercentInsiders", # Meta - "country", "website", "sector", "industry", "currency", "financialCurrency", "exchange", + "country", "website", "sector", "industry", "industryKey", "currency", "financialCurrency", + "exchange", ] # fmt: skip _ANALYST_FIELDS = [ @@ -213,6 +214,42 @@ def fetch_market_news(count: int = 10) -> list[dict[str, Any]]: return [n for n in (normalize_news_item(i) for i in raw or []) if n] +# -------------------------------------------------------------------- peers + +# The few fields the peer table and relative valuation need. +PEER_FIELDS = [ + "trailingPE", "forwardPE", "pegRatio", "priceToBook", "profitMargins", + "revenueGrowth", "marketCap", "currency", +] # fmt: skip + + +def fetch_industry_peers(industry_key: str, limit: int = 8) -> list[dict[str, Any]]: + """Largest US companies in a Yahoo industry (e.g. "software-infrastructure").""" + try: + df = yf.Industry(industry_key).top_companies + except Exception as exc: + raise MarketDataError(f"Could not load industry {industry_key!r}: {exc}") from exc + if df is None or df.empty: + return [] + return [ + {"ticker": str(symbol), "name": str(row.get("name") or symbol)} + for symbol, row in df.head(limit).iterrows() + ] + + +def fetch_key_metrics(ticker: str) -> dict[str, Any]: + """Only `info` (one request), not the full profile: used for each peer.""" + try: + info = yf.Ticker(ticker).info or {} + except Exception as exc: + raise MarketDataError(f"Yahoo Finance request failed for {ticker}: {exc}") from exc + if not info.get("longName") and not info.get("shortName"): + raise MarketDataError(f"No data found for ticker {ticker!r}") + out = {k: _clean(info.get(k)) for k in PEER_FIELDS} + out["name"] = info.get("shortName") or info.get("longName") + return out + + # ------------------------------------------------------------------- events diff --git a/watchstock/scoring.py b/watchstock/scoring.py index 40efbc5..18f05f7 100644 --- a/watchstock/scoring.py +++ b/watchstock/scoring.py @@ -105,12 +105,27 @@ def score_quality(metrics: dict) -> dict: # ------------------------------------------------------------------- valuation -def score_valuation(metrics: dict) -> dict: +# P/E relative to the industry median: ratio -> score (cheaper than peers scores higher). +_RELATIVE_PE_BANDS = [(0.6, 90), (0.8, 78), (0.95, 64), (1.05, 55), (1.25, 42), (1.6, 28)] + + +def _pe_component(label: str, pe: float, median: float | None, abs_bands, abs_else: float, + weight: float) -> tuple[str, float, float]: # fmt: skip + """P/E vs industry peers when a median exists, else fixed bands for all industries.""" + if median: + ratio = pe / median + return (f"{label} {pe:.1f} vs industry median {median:.1f} ({(ratio - 1) * 100:+.0f}%)", + _bucket(ratio, _RELATIVE_PE_BANDS, 15), weight) # fmt: skip + return (f"{label} {pe:.1f}", _bucket(pe, abs_bands, abs_else), weight) + + +def score_valuation(metrics: dict, peer_medians: dict | None = None) -> dict: """How cheap the stock is vs earnings, book value and its own 52-week range. - Higher = cheaper. P/E bands are the same for every industry (a known - simplification until peer comparison exists). + Higher = cheaper. With industry peers (peers.py), P/E and forward P/E are judged + against the peer median; without them, against fixed bands for all industries. """ + peer_medians = peer_medians or {} comps: list[tuple[str, float, float]] = [] extra: Breakdown = [] pos_pct = None @@ -118,14 +133,18 @@ def score_valuation(metrics: dict) -> dict: pe, eps = metrics.get("trailingPE"), metrics.get("trailingEps") if pe is not None and 0 < pe < 500: bands = [(10, 90), (15, 80), (20, 68), (25, 55), (35, 40), (50, 25)] - comps.append((f"Trailing P/E {pe:.1f}", _bucket(pe, bands, 12), 0.25)) + comps.append( + _pe_component("Trailing P/E", pe, peer_medians.get("trailingPE"), bands, 12, 0.25) + ) elif eps is not None and eps <= 0: comps.append(("Trailing P/E: losses over last 12 months", 10, 0.25)) fpe, feps = metrics.get("forwardPE"), metrics.get("forwardEps") if fpe is not None and 0 < fpe < 500: bands = [(10, 90), (15, 80), (20, 68), (25, 55), (35, 38)] - comps.append((f"Forward P/E {fpe:.1f}", _bucket(fpe, bands, 18), 0.20)) + comps.append( + _pe_component("Forward P/E", fpe, peer_medians.get("forwardPE"), bands, 18, 0.20) + ) elif feps is not None and feps <= 0: comps.append(("Forward P/E: losses expected", 10, 0.20)) @@ -354,11 +373,11 @@ def check(key: str, label: str, bad: float, weak: float, fmt: str) -> None: # ------------------------------------------------------------------------ all -def compute_all(metrics: dict, analyst_data: dict) -> dict: +def compute_all(metrics: dict, analyst_data: dict, peer_medians: dict | None = None) -> dict: """Every score for one stock, in the shape the UI expects.""" pillars = { "quality": score_quality(metrics), - "valuation": score_valuation(metrics), + "valuation": score_valuation(metrics, peer_medians), "analyst": score_analyst(metrics, analyst_data), "smart_money": score_smart_money(metrics), } diff --git a/watchstock/services.py b/watchstock/services.py index f64f83e..58074a1 100644 --- a/watchstock/services.py +++ b/watchstock/services.py @@ -5,11 +5,12 @@ """ import logging +from concurrent.futures import ThreadPoolExecutor from datetime import UTC, datetime from typing import Any from urllib.parse import urlparse -from watchstock import config, scoring, store, symbols +from watchstock import config, peers, scoring, store, symbols, ttl_cache from watchstock.providers import yahoo from watchstock.providers.yahoo import MarketDataError @@ -17,7 +18,7 @@ # Bump when the snapshot shape changes; older cached snapshots are then refetched # instead of being sent to a UI that no longer understands them. -SNAPSHOT_SCHEMA = 2 +SNAPSHOT_SCHEMA = 3 # 3: industry peers + industryKey def normalize_ticker(ticker: str) -> str: @@ -35,6 +36,46 @@ def _domain(website: str | None) -> str | None: return netloc.removeprefix("www.") or None +PEER_LIMIT = 5 + + +def load_peers(ticker: str, name: str, metrics: dict) -> dict[str, Any] | None: + """Industry peer comparison, or None when unavailable. + + US-listed stocks only: Yahoo's industry lists are US companies, so comparing a + Bucharest bank with them would mislead. Industry lists and peer metrics are cached + for a day in memory; peers are fetched 4 at a time. + """ + key = metrics.get("industryKey") + if not key or (metrics.get("currency") or "USD") != "USD": + return None + try: + candidates = ttl_cache.get_or_set( + f"industry:{key}", config.PEERS_TTL_SECONDS, + lambda: yahoo.fetch_industry_peers(key, limit=PEER_LIMIT + 3), + ) # fmt: skip + except MarketDataError as exc: + log.warning("peer list unavailable for %s (%s): %s", ticker, key, exc) + return None + chosen = [c for c in candidates if c["ticker"] != ticker][:PEER_LIMIT] + + def one(candidate: dict) -> dict | None: + t = candidate["ticker"] + try: + m = ttl_cache.get_or_set( + f"peer:{t}", config.PEERS_TTL_SECONDS, lambda: yahoo.fetch_key_metrics(t) + ) + except MarketDataError: + return None + return {**m, "ticker": t, "name": m.get("name") or candidate["name"]} + + with ThreadPoolExecutor(max_workers=4) as pool: + rows = [r for r in pool.map(one, chosen) if r] + if not rows: + return None + return peers.build_comparison(ticker, name, metrics, rows, metrics.get("industry")) + + def build_snapshot(ticker: str, fallback_name: str = "") -> dict[str, Any]: """Fetch everything live. Raises MarketDataError if the core data is unavailable.""" profile = yahoo.fetch_profile(ticker) @@ -46,10 +87,12 @@ def build_snapshot(ticker: str, fallback_name: str = "") -> dict[str, Any]: news, warnings = [], ["News could not be loaded."] metrics = profile["metrics"] + name = profile.get("name") or fallback_name or ticker + comparison = load_peers(ticker, name, metrics) return { "schema": SNAPSHOT_SCHEMA, "ticker": ticker, - "company_name": profile.get("name") or fallback_name or ticker, + "company_name": name, "company_domain": _domain(metrics.get("website")), "as_of": store.utcnow_iso(), "financial_data": { @@ -61,7 +104,10 @@ def build_snapshot(ticker: str, fallback_name: str = "") -> dict[str, Any]: }, "news": news, "warnings": warnings, - **scoring.compute_all(metrics, profile["analyst_data"]), + "peers": comparison, + **scoring.compute_all( + metrics, profile["analyst_data"], comparison["medians"] if comparison else None + ), }