Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down Expand Up @@ -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]},
Expand Down
10 changes: 10 additions & 0 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
40 changes: 27 additions & 13 deletions docs/HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
29 changes: 28 additions & 1 deletion scripts/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
9 changes: 9 additions & 0 deletions scripts/ui_smoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')));
Expand Down
15 changes: 15 additions & 0 deletions start.bat
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
9 changes: 9 additions & 0 deletions static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,15 @@ <h2 class="text-2xl font-bold tracking-widest pulse-loader" style="color: var(--
</div>
</div>

<!-- Industry peers -->
<div id="peersSection" style="display:none; padding:20px 28px; border-bottom:1px solid var(--border-color);">
<div style="display:flex; justify-content:space-between; align-items:baseline; margin-bottom:12px;">
<div style="font-size:0.58rem; letter-spacing:2px; color:var(--text-muted);">INDUSTRY PEERS <span id="peersIndustry" style="letter-spacing:0; text-transform:none; color:#888;"></span></div>
<div style="font-size:0.6rem; color:#555;">Largest US companies in the same industry · median excludes this stock</div>
</div>
<div id="peersTable"></div>
</div>

<!-- Fundamentals grid -->
<div style="padding:20px 28px; border-bottom:1px solid var(--border-color);">
<div style="font-size:0.58rem; letter-spacing:2px; color:var(--text-muted); margin-bottom:14px;">FUNDAMENTALS</div>
Expand Down
41 changes: 40 additions & 1 deletion static/js/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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 `<td>${esc(text)}</td>`;
const better = col.lowerIsBetter ? row[col.key] < med : row[col.key] > med;
return `<td style="color:${better ? '#4caf50' : '#ff9800'}; font-weight:700;">${esc(text)}</td>`;
};
const rows = peers.rows.map(r => `
<tr style="${r.is_self ? 'background:#1c2633;' : ''}">
<td class="pf-stock" ${r.is_self ? '' : `onclick="quickSearch(${esc(JSON.stringify(r.name || r.ticker))}, ${esc(JSON.stringify(r.ticker))})" title="Open ${esc(r.name || r.ticker)}"`}>
<b>${esc(r.ticker)}</b><span>${esc((r.name || '').slice(0, 22))}</span></td>
${PEER_COLUMNS.map(c => cell(c, r)).join('')}
</tr>`).join('');
const medianRow = `<tr style="border-top:1px solid #444;"><td style="color:#888; font-family:'Inter',sans-serif;">Peer median</td>
${PEER_COLUMNS.map(c => `<td style="color:#888;">${c.key === 'marketCap' ? '' : esc(c.fmt(peers.medians?.[c.key]) ?? '—')}</td>`).join('')}</tr>`;
document.getElementById('peersTable').innerHTML = `<table class="pf-table">
<thead><tr><th>Company</th>${PEER_COLUMNS.map(c => `<th>${c.label}</th>`).join('')}</tr></thead>
<tbody>${rows}${medianRow}</tbody></table>`;
}
19 changes: 18 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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

Expand Down
Loading
Loading