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 @@
| Company | ${PEER_COLUMNS.map(c => `${c.label} | `).join('')}
|---|