From f37b8449b89ae65440226a1ca9f54a49cd8b29b7 Mon Sep 17 00:00:00 2001
From: Arvi23
Date: Wed, 4 Nov 2026 03:40:44 +0200
Subject: [PATCH] Batch 2: correct numbers + owner-reported fixes
Scoring (D8): two lenses with no metric counted twice.
- Opportunity = Quality (margins, growth, FCF yield) 30% + Valuation 30% +
Analyst 25% + Smart money 15%; Safety = Liquidity + Solvency & volatility.
- Analyst consensus with few analysts is shrunk toward 50 instead of
multiplied down (a thin Strong Buy no longer scores like a Sell).
- Loss-makers get a low valuation score instead of skipped P/E; 52-week
position labelled contrarian and down-weighted.
- FCF yield skipped when statements and price use different currencies.
- Geo risk is a flag, not a penalty; D/E skipped for financials.
- Uniform breakdown items rendered by one shared UI function.
Data:
- Dividend yield normalised to a fraction in the provider (Yahoo now
returns percent, so MSFT showed 88%).
- Snapshot schema version: old cached snapshots are refetched.
- AI report gets the previous report and returns changes_since_last.
Owner feedback:
- Browser now opens only once the server answers (first run showed
"can't connect"); second launch just opens the browser.
- Logs go to data/watchstock.log instead of the console (Windows
QuickEdit can freeze console writers).
- No API key: no auto-request, a hint is shown instead.
- TradingView symbol mapping (TLV.RO -> BVB:TLV).
- Default model nvidia/nemotron-3.5-super-vl:free; LLM timeout 150 s.
62 tests.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01TW7cJeWrcBW5SJHr4ZKtSH
---
docs/ARCHITECTURE.md | 23 +-
docs/DECISIONS.md | 24 ++
docs/HANDOFF.md | 79 +++--
pyproject.toml | 2 +-
scripts/ui_smoke.js | 17 +
start.bat | 3 +-
static/index.html | 164 ++++-----
tests/conftest.py | 2 +-
tests/test_api.py | 38 ++
tests/test_scoring.py | 195 ++++++++---
tests/test_symbols.py | 20 ++
tests/test_yahoo.py | 11 +
uv.lock | 2 +-
watchstock/__init__.py | 2 +-
watchstock/__main__.py | 74 +++-
watchstock/analysis.py | 17 +-
watchstock/config.py | 5 +-
watchstock/providers/yahoo.py | 16 +
watchstock/scoring.py | 638 +++++++++++++++-------------------
watchstock/services.py | 10 +-
watchstock/symbols.py | 43 +++
21 files changed, 841 insertions(+), 544 deletions(-)
create mode 100644 tests/test_symbols.py
create mode 100644 watchstock/symbols.py
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 32ca303..bd4aba9 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -10,7 +10,8 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static
└── routes/personal.py /api/watchlist, /api/settings
│
├── services.py snapshot freshness: cache hit / live fetch / stale fallback
- ├── scoring.py pure scoring functions → scores + breakdowns
+ ├── scoring.py pure scoring functions → opportunity pillars + safety, with breakdowns
+ ├── symbols.py Yahoo ↔ TradingView ticker translation
├── analysis.py LLM prompts: report + chat (compact context)
├── store.py every SQL query
├── db.py connection + migrations (PRAGMA user_version)
@@ -50,13 +51,25 @@ call never blocks other requests.
"upgrades_downgrades": [...], "insider_transactions": [...]
},
"news": [{"title", "url", "publisher", "published_at", "summary"}],
- "health_scores": {"short_term": {...}, "long_term": {...}},
- "scores": {"fundamental", "analyst", "valuation", "smart_money", "opportunity"},
- "risk_analysis": {...},
- "ai_analysis": null | {"executive_summary", "verdict", ..., "model", "created_at"}
+ "schema": 2, // services.SNAPSHOT_SCHEMA
+ "tradingview_symbol": "MSFT", // e.g. "BVB:TLV" for TLV.RO
+ "scores": {
+ "quality" | "valuation" | "analyst" | "smart_money": {"score", "breakdown": [item]},
+ "opportunity": {"score", "label", "color", "components": [{"key","label","score","weight"}]}
+ },
+ "safety": {"short_term": {"score","breakdown"}, "long_term": {...}, "flags": [str]},
+ "risk_analysis": {...}, // plain-language red flags for the LLM
+ // breakdown item: {"item": str, "score": 0-100|null, "weight": "25%"|null, "note": str|null}
+ "ai_analysis": null | {"executive_summary", "verdict", ..., "changes_since_last", "model", "created_at"}
}
```
+## Logging and startup
+
+`python -m watchstock` logs to `data/watchstock.log` (rotating, 1 MB × 3), opens the
+browser only once `/api/health` answers, and if an instance is already running just
+opens the browser. See D10.
+
## Database (`data/watchstock.db`)
| table | purpose |
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 8d000f9..e65d8de 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -43,3 +43,27 @@ The old "DB-first" design served data from the DB forever (a May price was shown
current in November) and also stored failed fetches. Now each ticker has one snapshot
with `fetched_at`; it's served only while younger than `SNAPSHOT_TTL`, and the UI shows
its age. AI analyses are stored separately with their own timestamp and model.
+
+## D8 — Two scoring lenses, no double counting (2026-11-04)
+The hackathon had "health" (ST/LT) and "opportunity" scores that both used current
+ratio, margins and debt/equity. Now:
+- **Opportunity** = Quality 30% (margins, growth, FCF yield) + Valuation 30% +
+ Analyst 25% + Smart money 15%.
+- **Safety** (sidebar) = Liquidity (current/quick ratio) and Solvency & volatility
+ (debt/equity, beta).
+Each metric feeds exactly one score. Missing inputs are skipped and the weights
+renormalised; no inputs gives a neutral 50. Geographic risk is a flag, not a penalty
+(HQ country says little about exposure). Analyst consensus with few analysts is shrunk
+toward 50 instead of multiplied down. Loss-makers get a low valuation score instead of
+the P/E being silently skipped. Debt/equity is skipped for financial companies. FCF yield
+is skipped when statements and price are in different currencies. P/E bands are still
+industry-agnostic, to be fixed by peer comparison (batch 5).
+
+## D9 — Snapshot schema version (2026-11-04)
+Snapshots carry `schema`. When the shape changes, bump `services.SNAPSHOT_SCHEMA` and
+cached snapshots in the old shape are refetched instead of breaking the UI.
+
+## D10 — Logs to a file, browser opens when the server is up (2026-11-04)
+Windows console QuickEdit mode blocks any process writing to a console the user has
+clicked into, which looks like a freeze. Logs go to `data/watchstock.log`; the console only
+shows the startup banner. The browser opens after `/api/health` answers.
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index b8f8f61..a1b753a 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -4,8 +4,14 @@ Read this first. Update it at the end of every batch or before your context runs
## Context
- Owner: Spartacus (GitHub `Arvi23`). End user: his dad, on Windows, non-technical,
- manages a small portfolio. Owner delegated the project ("be in charge") and wants
- progress reported in batches. **Don't touch the owner's computer**. Ask him to test.
+ manages a small portfolio, **mostly US stocks**. Owner delegated the project ("be in
+ charge") and wants progress reported in batches.
+- **Delivery:** the owner wants every batch copied straight into his local folder
+ `E:\WatchStock\WatchStock` (device file tools, `device_commit_files`) so he never has to run
+ git. Copy tracked files only; never touch its `data\`, `.venv\` or `.git\`. Don't use his
+ computer for anything else; ask him to test.
+- **Merging:** the environment blocks agents from merging their own PRs. Open the PR, get
+ CI green, and the owner merges (or stack the next batch on the open branch).
- Dev sandbox can't reach Yahoo, OpenRouter or CDNs (PyPI + npm work). Verify against
fakes and Playwright screenshots. Live behaviour goes in "Needs live testing" below.
- The original review that motivated this plan: bugs list in the batch plan below.
@@ -24,14 +30,21 @@ Read this first. Update it at the end of every batch or before your context runs
errors shown as toasts, news cards escaped, marked link renderer fixed (pulled forward from batch 3)
- [x] `scripts/fake_server.py` for UI work without network
-### Batch 2 — Correct numbers
-- Analyst score: shrink toward 50 with few analysts instead of multiplying the score down
-- Currency mismatch (`financialCurrency` ≠ `currency`, e.g. TSM) in FCF yield and similar ratios
-- Dividend yield unit (Yahoo now returns percent): normalise in the provider
-- Merge the overlapping "health" and "opportunity" scores into one explained system; geo-risk becomes a flag, not a penalty
-- Valuation: loss-makers shouldn't skip P/E penalties; label the 52-week-low = "value" assumption
-- One analysis prompt (the old "force update" used a shallower one); LLM judges news materiality; "what changed since last analysis"
-- Chat: compact context, no duplicated question
+### Batch 2 — Correct numbers + owner feedback *(branch `batch-2-numbers`, PR #2, stacked on #1)* ✅
+- [x] Analyst score shrinks toward 50 with few analysts (was multiplied down)
+- [x] Currency mismatch guard: FCF yield skipped when `financialCurrency` ≠ `currency`
+- [x] Dividend yield normalised to a fraction in the provider (Yahoo now sends percent)
+- [x] Scores restructured (D8): Opportunity = Quality/Valuation/Analyst/Smart money; Safety = Liquidity + Solvency;
+ no metric counted twice; geo-risk is a flag; D/E skipped for financials; uniform breakdown items
+- [x] Valuation: loss-makers scored low instead of skipped; 52-week position labelled "contrarian", weight 15%
+- [x] Report prompt gets the previous report and returns `changes_since_last` (new "Since the Last Report" section)
+- [x] Chat: compact context, no duplicated question (done in batch 1)
+- [x] Owner feedback: browser opened before the server was up on first run ("lost connection"), so it now waits
+ for `/api/health`; logs moved to `data/watchstock.log` (Windows QuickEdit freeze risk);
+ second launch just opens the browser; no API key → no auto-request, hint shown instead
+- [x] TradingView symbol mapping (`symbols.py`): `TLV.RO` → `BVB:TLV` etc. ("symbol doesn't exist" for BVB)
+- [x] Default model `nvidia/nemotron-3.5-super-vl:free` (owner's choice for trials); LLM timeout 150 s
+- [x] Snapshot `schema` version (D9): old cached snapshots are refetched, not rendered broken
### Batch 3 — Frontend cleanup
- Split `static/index.html` into `index.html` + `css/` + `js/` ES modules
@@ -49,34 +62,36 @@ Read this first. Update it at the end of every batch or before your context runs
- Industry peer comparison; thesis tracking ("why I bought" checked against new data)
## Status
-Batch 1 done; PR #1 green on CI (Ubuntu + Windows), **waiting for the owner to merge**
-(agents can't self-merge in this environment). Branch further batches off `main` after
-it's merged, or stack on `batch-1-foundation` if it isn't yet. Next: batch 2. Start with the analyst score + dividend unit + currency
-mismatch in `scoring.py`/`providers/yahoo.py`, updating `tests/test_scoring.py` as formulas change.
+Batches 1 and 2 done. PR #1 and PR #2 (stacked) green on CI and waiting for the owner to
+merge. Files copied to the owner's folder. Next: batch 3 (frontend cleanup).
-Batch 1 notes for the next agent:
-- Scoring formulas are deliberately unchanged from the hackathon (except: no news penalty).
- `tests/test_scoring.py` pins current behaviour; batch 2 changes it on purpose.
+Notes for the next agent:
- The chat still supports `update_tab_content` on the frontend (raw HTML). The backend
prompt no longer offers it; remove the frontend handler in batch 3 with DOMPurify.
-- The Tailwind Play CDN, Chart.js and marked still load from CDNs (unpinned). Batch 3.
- For screenshots in the sandbox: run `scripts/fake_server.py`, then `scripts/ui_smoke.js`
+- The Tailwind Play CDN, Chart.js and marked still load from CDNs (marked unpinned; the
+ link renderer uses the >=13 token API). Batch 3 vendors them into `static/vendor/`.
+- For screenshots in the sandbox: run `scripts/fake_server.py`, then `scripts/ui_smoke.js`
(header explains how it serves CDN scripts from npm copies).
+- Money is still formatted with `$` everywhere in the frontend; statement values (FCF,
+ revenue) should use `financialCurrency`, prices `currency`. Batch 3.
- The old hackathon DB (`watchstock.db` at repo root) is not migrated; the new DB is
- `data/watchstock.db`. Nothing in the old one is worth keeping.
+ `data/watchstock.db`.
## Needs live testing (owner, on Windows)
-Batch 1:
-- [ ] Fresh folder → double-click `start.bat`: uv installs, Python downloads, browser opens
-- [ ] Home: indices, market news, movers populate (they use yfinance `Search`/`screen` now)
-- [ ] Search "Microsoft" → dashboard loads; News tab shows real headlines with dates
-- [ ] AI report generates automatically once a key is set; links inside it are clickable
-- [ ] REFRESH works; "data Xm ago" label updates
-- [ ] Watchlist star add/remove, prices show
-- [ ] A European/BVB ticker (e.g. `SAP.DE`, `TLV.RO`) loads without errors (currency still shows `$`; known)
+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
+
+Batch 2:
+- [ ] First start after update: browser opens by itself once ready (no "can't connect" page)
+- [ ] Double-click start.bat again while running → just opens a tab
+- [ ] `TLV.RO` / `SNP.RO`: TradingView chart shows (if it says "only available on TradingView",
+ the free widget lacks BVB data and we'll need our own chart)
+- [ ] Remove the API key → search a stock → AI tab shows the "add a key" hint, nothing freezes
+- [ ] MSFT dividend yield shows ~0.8%, not 80%
+- [ ] Request a second report on the same stock → "Since the Last Report" section appears
+- [ ] If anything misbehaves: send `data\watchstock.log`
## Open questions for the owner
-- Does dad hold only US stocks, or also BVB (.RO) / European ones? Decides how early
- currency support lands.
-- Default LLM model id on OpenRouter: code uses `anthropic/claude-haiku-4-5`
- (worked during the hackathon); confirm or pick a newer one.
+- (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 0f05eab..e9b337a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "watchstock"
-version = "0.2.0"
+version = "0.3.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/ui_smoke.js b/scripts/ui_smoke.js
index 01a8493..6a39fa7 100644
--- a/scripts/ui_smoke.js
+++ b/scripts/ui_smoke.js
@@ -49,6 +49,23 @@ const local = {
model: document.getElementById('aiModelLabel').textContent,
link: document.querySelector('#financialDeepDiveContent a')?.outerHTML,
}));
+ // score breakdown popover + safety modal
+ await page.click('.tab-btn[data-target="tab-finance"]');
+ await page.click('[data-score-key="quality"]');
+ await page.waitForTimeout(300);
+ state.popover = await page.evaluate(() => document.getElementById('popoverContent').innerText.slice(0, 160));
+ await page.screenshot({ path: process.env.OUT + '/popover.png' });
+ await page.evaluate(() => { hideScoreBreakdown(); showScoreExplanation('long_term'); });
+ await page.waitForTimeout(300);
+ state.safetyModal = await page.evaluate(() => document.getElementById('scoreModalBody').innerText.slice(0, 160));
+ await page.screenshot({ path: process.env.OUT + '/safety.png' });
+ await page.evaluate(() => closeScoreModal());
+ state.dividendCard = await page.evaluate(() => [...document.querySelectorAll('#metricCards > div')].map(d => d.innerText).find(t => /dividend/i.test(t)));
+ // no API key: analysis must not auto-run
+ await page.evaluate(async () => { await api('/api/settings', { method: 'PUT', body: { llm_api_key: '' } }); await refreshLlmStatus(); });
+ await page.evaluate(() => quickSearch('Apple', 'AAPL'));
+ await page.waitForTimeout(1500);
+ state.noKeySummary = await page.evaluate(() => document.getElementById('aiSummary').innerText);
await page.evaluate(() => quickSearch('Fail Corp', 'FAIL'));
await page.waitForTimeout(1500);
state.toast = await page.evaluate(() => document.getElementById('toastMsg').textContent);
diff --git a/start.bat b/start.bat
index 2c7b724..d922505 100644
--- a/start.bat
+++ b/start.bat
@@ -31,6 +31,7 @@ echo Starting WatchStock... (the first start can take a few minutes)
uv run --frozen --no-dev python -m watchstock
if errorlevel 1 (
echo.
- echo [ERROR] WatchStock stopped with an error. See the messages above.
+ echo [ERROR] WatchStock stopped with an error.
+ echo Details are in data\watchstock.log
pause
)
diff --git a/static/index.html b/static/index.html
index 514e8c2..46f6eb9 100644
--- a/static/index.html
+++ b/static/index.html
@@ -292,15 +292,15 @@