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 @@
--
- Short-Term Safety - Liquidity & Shock + Liquidity + Short-term safety
--
- Long-Term Safety - Solvency & Geo + Solvency + Debt & volatility
@@ -462,6 +462,10 @@

+
@@ -767,39 +771,37 @@

+ // ---- Score breakdowns ---- + // Items with a score get a bar; items without one are explanations (skipped inputs, flags). + function renderBreakdownItems(items) { + return (items || []).map(item => { + if (item.score !== null && item.score !== undefined) { + const c = scoreColor(item.score); + return `
- ${item.item} - ${s}/100 - ${item.weight ? `${item.weight}` : ''} + ${esc(item.item)} + ${item.score}/100 + ${item.weight ? `${esc(item.weight)}` : ''}
-
+
`; - } else if (item.impact !== undefined) { - const c = item.impact >= 0 ? '#4caf50' : '#f44336'; - html += `
- ${item.item} ${item.impact > 0 ? '+' : ''}${item.impact} -
`; - } else { - html += `
${item.item || ''}
`; } - }); + return `
${esc(item.item)}${item.note ? ` · ${esc(item.note)}` : ''}
`; + }).join(''); + } + + // ---- Score Breakdown Popover ---- + function showScoreBreakdown(key, event) { + event.stopPropagation(); + if (!currentRawData?.scores) return; + const data = currentRawData.scores[key]; + if (!data) return; + const comp = currentRawData.scores.opportunity?.components?.find(c => c.key === key); + document.getElementById('popoverTitle').textContent = (comp?.label || key).toUpperCase() + ' — BREAKDOWN'; + + let html = renderBreakdownItems(data.breakdown); if (key === 'smart_money' && data.flags?.length) { html += `
`; @@ -967,6 +969,7 @@

- ${b.item} - ${sign}${b.impact} -

`; - }); - html += `
- Final Score - ${data.score} -
`; - - body.innerHTML = html; - modal.style.display = 'flex'; + const safety = currentRawData?.safety; + if (!safety?.[type]) return; + const data = safety[type]; + const label = type === 'short_term' ? 'Liquidity (short term)' : 'Solvency & Volatility (long term)'; + document.getElementById('scoreModalTitle').innerText = `${label} — ${data.score}/100`; + document.getElementById('scoreModalBody').innerHTML = renderBreakdownItems(data.breakdown) + + `
The score is the weighted average of the items with a bar. Lines without a bar explain what was skipped or flagged.
`; + document.getElementById('scoreModal').style.display = 'flex'; } function closeScoreModal() { @@ -1155,7 +1138,7 @@

` +
-
${v}
-
${labels[k]}
-
${weights[k]}
+
${c.score}
+
${esc(c.label)}
+
${esc(c.weight)}
click for breakdown
`).join(''); } @@ -1577,9 +1557,9 @@

50, beta 1.5 -> 50 - assert h["long_term"]["score"] == 50 + sell_wide = scoring.score_analyst( + {}, {"recommendationMean": 4.0, "numberOfAnalystOpinions": 20} + ) + assert strong_buy_thin["score"] > 50 > sell_wide["score"] + # raw 87.5 -> 50 + 37.5 * 0.5 + assert strong_buy_thin["score"] == 69 -def test_geo_penalty_applies_to_long_term_only(): - base = scoring.calculate_health_scores( - {"debtToEquity": 0, "beta": 0.5, "country": "United States"} +def test_analyst_upside_adjustment(): + a = scoring.score_analyst( + {"currentPrice": 100}, + {"recommendationMean": 3.0, "numberOfAnalystOpinions": 10, "targetMeanPrice": 140}, ) - risky = scoring.calculate_health_scores({"debtToEquity": 0, "beta": 0.5, "country": "Russia"}) - assert base["long_term"]["score"] - risky["long_term"]["score"] == 40 - assert base["short_term"] == risky["short_term"] + assert a["upside_pct"] == 40.0 + assert a["score"] == 60 # neutral 50 + 10 for >30% upside + + +def test_analyst_no_coverage(): + assert scoring.score_analyst({}, {})["score"] == 50 + + +# --------------------------------------------------------------------- quality -def test_valuation_position_in_52w_range(): +def test_quality_skips_fcf_yield_on_currency_mismatch(): + metrics = { + "freeCashflow": 900e9, + "marketCap": 1e12, + "financialCurrency": "TWD", + "currency": "USD", + } + q = scoring.score_quality(metrics) + assert q["score"] == 50 # nothing else to score + assert any("skipped" in b["item"] for b in q["breakdown"]) + + +def test_quality_fcf_yield_when_currencies_match(): + q = scoring.score_quality( + {"freeCashflow": 50e9, "marketCap": 1e12, "currency": "USD", "financialCurrency": "USD"} + ) + assert q["score"] == 100 # 5% yield + + +def test_quality_profitable_grower_beats_shrinking_loss_maker(): + good = scoring.score_quality( + {"profitMargins": 0.3, "revenueGrowth": 0.2, "earningsGrowth": 0.2} + ) + bad = scoring.score_quality( + {"profitMargins": -0.1, "revenueGrowth": -0.15, "earningsGrowth": -0.3} + ) + assert good["score"] > 80 and bad["score"] < 20 + + +# ------------------------------------------------------------------- valuation + + +def test_valuation_penalises_loss_makers_instead_of_skipping(): + loss = scoring.score_valuation({"trailingEps": -1.2, "forwardEps": -0.5}) + assert loss["score"] == 10 + assert "losses" in loss["breakdown"][0]["item"] + + +def test_valuation_52w_position_is_labelled_contrarian(): v = scoring.score_valuation( {"currentPrice": 150, "fiftyTwoWeekLow": 100, "fiftyTwoWeekHigh": 200} ) assert v["position_pct"] == 50.0 + assert "contrarian" in v["breakdown"][0]["item"] -def test_analyst_upside(): - a = scoring.score_analyst( - {"currentPrice": 100}, - {"recommendationMean": 2.0, "numberOfAnalystOpinions": 10, "targetMeanPrice": 120}, +def test_valuation_cheap_beats_expensive(): + cheap = scoring.score_valuation( + {"trailingPE": 9, "forwardPE": 8, "pegRatio": 0.8, "priceToBook": 0.9} + ) + pricey = scoring.score_valuation( + {"trailingPE": 80, "forwardPE": 60, "pegRatio": 4, "priceToBook": 12} ) - assert a["upside_pct"] == 20.0 + assert cheap["score"] > 80 and pricey["score"] < 25 + +# ---------------------------------------------------------------------- safety -def test_opportunity_label_thresholds(): - s = lambda v: {"score": v} # noqa: E731 - assert ( - scoring.calculate_opportunity_score(s(80), s(80), s(80), s(80))["label"] - == "Strong Opportunity" + +def test_safety_known_values(): + s = scoring.calculate_safety( + {"currentRatio": 2.0, "quickRatio": 1.5, "debtToEquity": 100, "beta": 1.5} ) - assert scoring.calculate_opportunity_score(s(10), s(10), s(10), s(10))["label"] == "Avoid" + assert s["short_term"]["score"] == 100 + assert s["long_term"]["score"] == 50 # D/E 1.0x -> 50, beta 1.5 -> 50 + +def test_geo_is_a_flag_not_a_penalty(): + base = {"debtToEquity": 0, "beta": 0.5} + us = scoring.calculate_safety({**base, "country": "United States"}) + ru = scoring.calculate_safety({**base, "country": "Russia"}) + assert us["long_term"]["score"] == ru["long_term"]["score"] == 100 + assert ru["flags"] and not us["flags"] -def test_risk_flags_for_missing_metrics(): - r = scoring.calculate_financial_risk({}) - assert r["total_risk_points"] == 3 - assert r["severity_level"] == "Medium" +def test_debt_to_equity_skipped_for_financials(): + s = scoring.calculate_safety({"sector": "Financial Services", "debtToEquity": 900, "beta": 1.0}) + assert s["long_term"]["score"] == 75 # beta only + assert any("skipped" in b["item"] for b in s["long_term"]["breakdown"]) -def test_no_nan_leaks(): - out = scoring.compute_all({"marketCap": 0, "freeCashflow": 1e9}, {}) - fcf = [b for b in out["scores"]["fundamental"]["breakdown"] if b["item"] == "Free Cash Flow"] - assert fcf and not math.isnan(fcf[0]["score"]) + +def test_breakdown_items_have_uniform_shape(): + out = scoring.compute_all(SAMPLE_METRICS, SAMPLE_PROFILE["analyst_data"]) + pillars = [out["scores"][k] for k in scoring.OPPORTUNITY_WEIGHTS] + for block in [*pillars, out["safety"]["short_term"], out["safety"]["long_term"]]: + for item in block["breakdown"]: + assert set(item) == {"item", "score", "weight", "note"} + + +def test_risk_flags(): + r = scoring.calculate_financial_risk( + {"currentRatio": 0.8, "revenueGrowth": -0.1, "profitMargins": -0.02} + ) + assert r["total_risk_points"] == 6 + assert r["severity_level"] == "High" + assert scoring.calculate_financial_risk({})["total_risk_points"] == 0 diff --git a/tests/test_symbols.py b/tests/test_symbols.py new file mode 100644 index 0000000..cd01a2a --- /dev/null +++ b/tests/test_symbols.py @@ -0,0 +1,20 @@ +import pytest + +from watchstock.symbols import tradingview_symbol + + +@pytest.mark.parametrize( + ("yahoo", "tv"), + [ + ("TLV.RO", "BVB:TLV"), + ("snp.ro", "BVB:SNP"), + ("SAP.DE", "XETR:SAP"), + ("VOD.L", "LSE:VOD"), + ("0700.HK", "HKEX:700"), + ("MSFT", "MSFT"), + ("BRK-B", "BRK.B"), + ("FOO.XX", "FOO.XX"), + ], +) +def test_tradingview_symbol(yahoo, tv): + assert tradingview_symbol(yahoo) == tv diff --git a/tests/test_yahoo.py b/tests/test_yahoo.py index e278c0c..40a60a1 100644 --- a/tests/test_yahoo.py +++ b/tests/test_yahoo.py @@ -66,3 +66,14 @@ def boom(_t): monkeypatch.setattr(yahoo.yf, "Ticker", boom) with pytest.raises(yahoo.MarketDataError): yahoo.fetch_profile("MSFT") + + +def test_dividend_yield_is_a_fraction(monkeypatch): + # Yahoo 2025+: dividendYield 0.88 means 0.88% + info = {"longName": "X", "currentPrice": 400.0, "dividendYield": 0.88, "dividendRate": 3.6} + monkeypatch.setattr(yahoo.yf, "Ticker", lambda t: _StubTicker(info)) + assert yahoo.fetch_profile("X")["metrics"]["dividendYield"] == pytest.approx(0.009) + + 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) diff --git a/uv.lock b/uv.lock index ee8accd..f812cc8 100644 --- a/uv.lock +++ b/uv.lock @@ -1020,7 +1020,7 @@ wheels = [ [[package]] name = "watchstock" -version = "0.2.0" +version = "0.3.0" source = { editable = "." } dependencies = [ { name = "fastapi" }, diff --git a/watchstock/__init__.py b/watchstock/__init__.py index 6d8c77b..103e026 100644 --- a/watchstock/__init__.py +++ b/watchstock/__init__.py @@ -1,3 +1,3 @@ """WatchStock: personal stock analysis terminal.""" -__version__ = "0.2.0" +__version__ = "0.3.0" diff --git a/watchstock/__main__.py b/watchstock/__main__.py index 22b9c40..1535534 100644 --- a/watchstock/__main__.py +++ b/watchstock/__main__.py @@ -1,8 +1,22 @@ -"""`python -m watchstock` — start the server and open the browser.""" +"""`python -m watchstock` — start the server and open the browser. + +Windows notes: +- The browser is opened only once the server actually answers. On a first run, + importing pandas/yfinance can take 10-30 s, and opening the page earlier shows + "can't connect". +- Logs go to data/watchstock.log, not the console. If the user clicks inside a + Windows console window (QuickEdit mode), every write to it blocks until they press + a key, which looks like the app froze. +- Double-clicking start.bat while WatchStock is already running just opens the browser. +""" import argparse import logging +import logging.handlers +import sys import threading +import time +import urllib.request import webbrowser import uvicorn @@ -10,20 +24,64 @@ from watchstock import config +def _already_running(url: str) -> bool: + try: + with urllib.request.urlopen(f"{url}/api/health", timeout=1) as resp: + return b'"ok":true' in resp.read().replace(b" ", b"") + except OSError: + return False + + +def _open_when_ready(url: str, timeout: float = 120) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if _already_running(url): + webbrowser.open(url) + return + time.sleep(0.5) + logging.getLogger(__name__).error("server did not come up within %ss", timeout) + + +def _setup_logging() -> None: + handler = logging.handlers.RotatingFileHandler( + config.data_dir() / "watchstock.log", maxBytes=1_000_000, backupCount=2, encoding="utf-8" + ) + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")) + root = logging.getLogger() + root.setLevel(logging.INFO) + root.addHandler(handler) + # Keep yfinance's chatter out of the log unless it's a real problem. + logging.getLogger("yfinance").setLevel(logging.ERROR) + + def main() -> None: parser = argparse.ArgumentParser(prog="watchstock") parser.add_argument("--no-browser", action="store_true", help="don't open a browser tab") parser.add_argument("--port", type=int, default=config.PORT) args = parser.parse_args() - - logging.basicConfig( - level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s" - ) url = f"http://{config.HOST}:{args.port}" - print(f"\n WatchStock is running at {url}\n Close this window to stop it.\n") + + if _already_running(url): + print(f"WatchStock is already running at {url}. Opening it.") + if not args.no_browser: + webbrowser.open(url) + return + + _setup_logging() + print(f"\n WatchStock is starting at {url}") + print(" Your browser opens when it's ready. Close this window to stop WatchStock.") + print(f" Log file: {config.data_dir() / 'watchstock.log'}\n") + sys.stdout.flush() + if not args.no_browser: - threading.Timer(1.5, webbrowser.open, args=(url,)).start() - uvicorn.run("watchstock.app:app", host=config.HOST, port=args.port, log_level="warning") + threading.Thread(target=_open_when_ready, args=(url,), daemon=True).start() + uvicorn.run( + "watchstock.app:app", + host=config.HOST, + port=args.port, + log_config=None, # use our file logging + access_log=False, + ) if __name__ == "__main__": diff --git a/watchstock/analysis.py b/watchstock/analysis.py index 7c60b9c..695963e 100644 --- a/watchstock/analysis.py +++ b/watchstock/analysis.py @@ -49,7 +49,7 @@ def compact_context(stock: dict[str, Any]) -> dict[str, Any]: "analyst_data": stock.get("financial_data", {}).get("analyst_data", {}), "key_officers": (stock.get("financial_data", {}).get("key_officers") or [])[:3], "risk_analysis": stock.get("risk_analysis", {}), - "health_scores": stock.get("health_scores"), + "safety": stock.get("safety"), "scores": stock.get("scores"), "news": [ {k: n.get(k) for k in ("title", "publisher", "published_at", "summary")} @@ -67,8 +67,10 @@ def compact_context(stock: dict[str, Any]) -> dict[str, Any]: "- `metrics`: ratios and valuation multiples (P/E, PEG, P/B, margins, debt/equity " "(Yahoo reports it in percent, 150 = 1.5x), beta, marketCap, EPS, revenue growth)\n" "- `analyst_data`: Wall Street consensus, price targets, recommendation rating\n" - "- `scores`: opportunity, fundamental, analyst, valuation, smart money (0-100)\n" - "- `health_scores`: short_term (liquidity) and long_term (solvency) 0-100\n" + "- `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" + "- `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" "1. Interpret the numbers, don't just list them.\n" @@ -84,6 +86,8 @@ def compact_context(stock: dict[str, Any]) -> dict[str, Any]: ' "financial_deep_dive": "Rich markdown analysis, min 200 words.",\n' ' "news_impact_analysis": "Rich markdown analysis, min 150 words.",\n' ' "risk_scenarios": "Rich markdown with ## Bull Case, ## Base Case, ## Bear Case.",\n' + ' "changes_since_last": "If previous_report exists: short markdown on what changed ' + 'since then and whether the verdict changed and why. Otherwise null.",\n' ' "charts": [\n' ' {"chart_type": "bar", "labels": ["P/E", "P/B", "EV/EBITDA"], ' '"values": [28.5, 4.2, 18.1], "title": "Valuation Multiples"}\n' @@ -99,10 +103,15 @@ def compact_context(stock: dict[str, Any]) -> dict[str, Any]: def run_analysis(stock: dict[str, Any]) -> dict[str, Any]: """Generate, validate and store an analysis report. Raises LLMError.""" api_key, model = llm_settings() + context = compact_context(stock) + if previous := store.latest_analysis(stock["ticker"]): + context["previous_report"] = { + k: previous.get(k) for k in ("created_at", "verdict", "executive_summary") + } reply = openrouter.complete( [ {"role": "system", "content": ANALYSIS_SYSTEM_PROMPT}, - {"role": "user", "content": json.dumps(compact_context(stock), default=str)}, + {"role": "user", "content": json.dumps(context, default=str)}, ], api_key=api_key, model=model, diff --git a/watchstock/config.py b/watchstock/config.py index 928e1bf..68abee3 100644 --- a/watchstock/config.py +++ b/watchstock/config.py @@ -18,8 +18,9 @@ MARKET_NEWS_TTL_SECONDS = 5 * 60 MOVERS_TTL_SECONDS = 10 * 60 -DEFAULT_LLM_MODEL = "anthropic/claude-haiku-4-5" -LLM_TIMEOUT_SECONDS = 90.0 +# 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" +LLM_TIMEOUT_SECONDS = 150.0 # free OpenRouter endpoints can be slow def data_dir() -> Path: diff --git a/watchstock/providers/yahoo.py b/watchstock/providers/yahoo.py index 2e92e6a..c1e31da 100644 --- a/watchstock/providers/yahoo.py +++ b/watchstock/providers/yahoo.py @@ -9,6 +9,12 @@ - News comes in two shapes: `{"content": {...}}` (Ticker.get_news, 2025+) and the older flat shape (Search.news). `normalize_news_item` accepts both. - Insider-transaction "Transaction" is often NaN; infer buy/sell from "Text". +- `dividendYield` switched from a fraction to a percent in 2025 (0.88 means 0.88%). + We expose it as a fraction like every other ratio: dividendRate / price when + both exist, else dividendYield / 100. +- For foreign companies listed in the US, statement values (freeCashflow, + totalRevenue...) are in `financialCurrency` while price/marketCap are in + `currency`. Both are exposed; scoring skips ratios that would mix them. """ import math @@ -66,6 +72,15 @@ def _is_blank(value: Any) -> bool: # ------------------------------------------------------------------ profile +def _dividend_yield(info: dict[str, Any], price: float | None) -> float | None: + """Dividend yield as a fraction (0.0088 = 0.88%). See module docstring.""" + rate = _clean(info.get("dividendRate")) + if rate and price: + return round(rate / price, 6) + raw = _clean(info.get("dividendYield")) + return None if raw is None else round(raw / 100, 6) + + def fetch_profile(ticker: str) -> dict[str, Any]: """Fundamentals, analyst consensus, officers, rating changes, insider trades.""" try: @@ -81,6 +96,7 @@ def fetch_profile(ticker: str) -> dict[str, Any]: metrics = {k: _clean(info.get(k)) for k in _METRIC_FIELDS} metrics["currentPrice"] = _clean(price) + metrics["dividendYield"] = _dividend_yield(info, metrics["currentPrice"]) analyst = {k: _clean(info.get(k)) for k in _ANALYST_FIELDS} officers = [ diff --git a/watchstock/scoring.py b/watchstock/scoring.py index ec4a722..4f67207 100644 --- a/watchstock/scoring.py +++ b/watchstock/scoring.py @@ -1,424 +1,356 @@ """Scoring: pure functions from Yahoo metrics to explainable 0-100 scores. -No I/O here. Every score returns a `breakdown` list the UI shows on click, so -any formula change must keep the breakdown honest. Covered by tests/test_scoring.py. +No I/O here. Covered by tests/test_scoring.py. -NOTE (batch 1): formulas are ported unchanged from the hackathon version except -that the news penalty in the health scores is gone (it depended on the removed -embedding model). Known formula problems are listed in docs/HANDOFF.md, batch 2. -""" +Two separate lenses, so no metric is counted twice: +* **Opportunity** (is it worth buying?) = weighted mix of four pillars: + Quality (profitability, growth, cash), Valuation, Analyst view, Smart money. +* **Safety** (how fragile is it?) = Liquidity (short-term) and Solvency & + volatility (long-term). Shown in the sidebar. -def calculate_financial_risk(metrics: dict): - """ - Compute a simple risk score based on key financial ratios. - Each missing or unhealthy metric adds risk points. - """ - risk_points = 0 - flags = [] - - cr = metrics.get("currentRatio") - if cr is None: - risk_points += 1 - flags.append("currentRatio missing (1 pt)") - elif cr < 1.0: - risk_points += 2 - flags.append(f"currentRatio < 1.0 ({cr}) (2 pts)") - elif 1.0 <= cr <= 1.2: - risk_points += 1 - flags.append(f"currentRatio between 1.0 and 1.2 ({cr}) (1 pt)") - - rg = metrics.get("revenueGrowth") - if rg is None: - risk_points += 1 - flags.append("revenueGrowth missing (1 pt)") - elif rg < -0.05: - risk_points += 2 - flags.append(f"revenueGrowth < -0.05 ({rg}) (2 pts)") - elif -0.05 <= rg <= 0: - risk_points += 1 - flags.append(f"revenueGrowth between -0.05 and 0 ({rg}) (1 pt)") - - pm = metrics.get("profitMargins") - if pm is None: - risk_points += 1 - flags.append("profitMargins missing (1 pt)") - elif pm < 0: - risk_points += 2 - flags.append(f"profitMargins < 0 ({pm}) (2 pts)") - elif 0 <= pm <= 0.05: - risk_points += 1 - flags.append(f"profitMargins between 0 and 0.05 ({pm}) (1 pt)") - - if risk_points <= 1: - severity = "Low" - elif risk_points <= 3: - severity = "Medium" - else: - severity = "High" +Every score returns a `breakdown`: a list of +`{"item": label, "score": 0-100 | None, "weight": "25%" | None, "note": str | None}`. +Items with `score: None` are explanations (skipped inputs, flags) and don't count. +Missing data is skipped, never guessed. With no usable inputs a score is a neutral 50. - return { - "total_risk_points": risk_points, - "severity_level": severity, - "flags": flags, - } +Units: Yahoo reports debtToEquity in percent (150 = 1.5x). Ratios like margins and +growth are fractions (0.25 = 25%). dividendYield is normalised to a fraction in +providers/yahoo.py. +""" +from typing import Any -def norm_cr(val): - return max(0, min(100, (val / 2.0) * 100)) +Breakdown = list[dict[str, Any]] -def norm_qr(val): - return max(0, min(100, (val / 1.5) * 100)) +def _clamp(x: float) -> float: + return max(0.0, min(100.0, x)) -def norm_margin(val): - return max(0, min(100, (val / 0.25) * 100)) +def _item(label: str, score: float | None = None, weight: float | None = None, + note: str | None = None) -> dict[str, Any]: # fmt: skip + return { + "item": label, + "score": None if score is None else round(score), + "weight": None if weight is None else f"{weight * 100:.0f}%", + "note": note, + } -def norm_de(val): - return max(0, min(100, 100 - (val / 2.0))) +def _combine(components: list[tuple[str, float, float]], extra: Breakdown | None = None) -> dict: + """Weighted average of (label, score, weight); weights renormalised over present inputs.""" + breakdown = [_item(label, s, w) for label, s, w in components] + (extra or []) + total = sum(w for _, _, w in components) + if total == 0: + return {"score": 50, "breakdown": breakdown + [_item("Not enough data: neutral 50")]} + score = sum(s * w for _, s, w in components) / total + return {"score": round(score), "breakdown": breakdown} -def norm_beta(val): - return max(0, min(100, 100 - ((val - 0.5) * 50))) +def _bucket(value: float, thresholds: list[tuple[float, float]], otherwise: float) -> float: + """First score whose upper bound exceeds `value`.""" + for upper, score in thresholds: + if value < upper: + return score + return otherwise -def _weighted(components: list) -> float: - total_w = sum(w for _, _, w in components) - return sum(s * (w / total_w) for _, s, w in components) if total_w > 0 else 50.0 +# --------------------------------------------------------------------- quality -def score_fundamental(metrics: dict) -> dict: - """Liquidity, profitability, and solvency — 0-100.""" - comps = [] - cr = metrics.get("currentRatio") - if cr is not None: - comps.append(("Current Ratio", norm_cr(cr), 0.20)) - qr = metrics.get("quickRatio") - if qr is not None: - comps.append(("Quick Ratio", norm_qr(qr), 0.15)) - pm = metrics.get("profitMargins") - if pm is not None: - comps.append(("Profit Margins", norm_margin(pm), 0.20)) - rg = metrics.get("revenueGrowth") - if rg is not None: - comps.append(("Revenue Growth", max(0, min(100, (rg + 0.2) / 0.5 * 100)), 0.15)) - de = metrics.get("debtToEquity") - if de is not None: - comps.append(("Debt/Equity", norm_de(de), 0.15)) - fcf = metrics.get("freeCashflow") - mc = metrics.get("marketCap") or 1 - if fcf is not None: - fcf_s = max(0, min(100, 50 + (fcf / mc) * 1000)) if mc > 0 else (60 if fcf > 0 else 30) - comps.append(("Free Cash Flow", fcf_s, 0.15)) - eg = metrics.get("earningsGrowth") - if eg is not None: - comps.append(("Earnings Growth", max(0, min(100, 50 + eg * 150)), 0.10)) - if not comps: - return {"score": 50, "breakdown": []} - score = round(_weighted(comps)) - return { - "score": score, - "breakdown": [ - {"item": n, "score": round(s), "weight": f"{w * 100:.0f}%"} for n, s, w in comps - ], - } +def currency_mismatch(metrics: dict) -> str | None: + """Return a note if financial statements and the share price use different currencies. + Happens for foreign companies listed in the US (e.g. TSM: statements in TWD, + price and market cap in USD). Ratios we compute by mixing the two are skipped. + """ + fin, px = metrics.get("financialCurrency"), metrics.get("currency") + if fin and px and fin != px: + return f"statements in {fin}, price in {px}" + return None -def score_analyst(metrics: dict, analyst_data: dict) -> dict: - """Analyst consensus and price-target upside — 0-100.""" - rec = analyst_data.get("recommendationMean") - n = analyst_data.get("numberOfAnalystOpinions") or 0 - tgt = analyst_data.get("targetMeanPrice") - cur = metrics.get("currentPrice") - if rec is None: - return {"score": 50, "breakdown": [], "upside_pct": None} +def score_quality(metrics: dict) -> dict: + """Profitability, growth and cash generation.""" + comps: list[tuple[str, float, float]] = [] + extra: Breakdown = [] - base = max(0, min(100, (5 - rec) / 4 * 100)) - confidence = 1.0 if n >= 8 else (0.75 if n >= 3 else 0.5) - score = base * confidence + if (pm := metrics.get("profitMargins")) is not None: + comps.append((f"Net margin {pm * 100:.1f}%", _clamp(pm / 0.25 * 100), 0.25)) + if (om := metrics.get("operatingMargins")) is not None: + comps.append((f"Operating margin {om * 100:.1f}%", _clamp(om / 0.30 * 100), 0.15)) + if (rg := metrics.get("revenueGrowth")) is not None: + # -20% -> 0, +30% -> 100 + comps.append((f"Revenue growth {rg * 100:+.1f}%", _clamp((rg + 0.2) / 0.5 * 100), 0.25)) + if (eg := metrics.get("earningsGrowth")) is not None: + comps.append((f"Earnings growth {eg * 100:+.1f}%", _clamp(50 + eg * 150), 0.15)) + + fcf, mcap = metrics.get("freeCashflow"), metrics.get("marketCap") + if fcf is not None and mcap: + if note := currency_mismatch(metrics): + extra.append(_item("Free-cash-flow yield skipped", note=note)) + else: + fcf_yield = fcf / mcap + # 0% -> 50, +5% -> 100, -5% -> 0 + comps.append((f"FCF yield {fcf_yield * 100:.1f}%", _clamp(50 + fcf_yield * 1000), 0.20)) + return _combine(comps, extra) - upside_pct = None - consensus = (analyst_data.get("recommendationKey") or "N/A").replace("_", " ").title() - breakdown = [ - { - "item": f"Consensus: {consensus}", - "score": round(base), - } - ] - if tgt and cur and cur > 0: - upside_pct = round((tgt - cur) / cur * 100, 1) - delta = ( - 10 if upside_pct > 30 else (5 if upside_pct > 10 else (-10 if upside_pct < 0 else 0)) - ) - score = max(0, min(100, score + delta)) - breakdown.append({"item": f"Price-target upside: {upside_pct:+.1f}%", "impact": delta}) - if n > 0: - breakdown.append({"item": f"{n} analysts · {confidence * 100:.0f}% confidence weight"}) - return {"score": round(score), "breakdown": breakdown, "upside_pct": upside_pct} +# ------------------------------------------------------------------- valuation def score_valuation(metrics: dict) -> dict: - """How cheap/expensive vs earnings and its own 52-week range. 0-100, higher = cheaper.""" - comps = [] + """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). + """ + comps: list[tuple[str, float, float]] = [] + extra: Breakdown = [] pos_pct = None - pe = metrics.get("trailingPE") + pe, eps = metrics.get("trailingPE"), metrics.get("trailingEps") if pe is not None and 0 < pe < 500: - pe_s = ( - 90 - if pe < 10 - else 80 - if pe < 15 - else 68 - if pe < 20 - else 55 - if pe < 25 - else 40 - if pe < 35 - else 25 - if pe < 50 - else 12 - ) - comps.append(("Trailing P/E", pe_s, 0.25)) - fpe = metrics.get("forwardPE") + 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)) + 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: - fpe_s = ( - 90 - if fpe < 10 - else 80 - if fpe < 15 - else 68 - if fpe < 20 - else 55 - if fpe < 25 - else 38 - if fpe < 35 - else 18 - ) - comps.append(("Forward P/E", fpe_s, 0.20)) + 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)) + elif feps is not None and feps <= 0: + comps.append(("Forward P/E: losses expected", 10, 0.20)) + peg = metrics.get("pegRatio") if peg is not None and 0 < peg < 20: - peg_s = ( - 95 - if peg < 0.5 - else 82 - if peg < 1.0 - else 65 - if peg < 1.5 - else 50 - if peg < 2.0 - else 32 - if peg < 3.0 - else 15 - ) - comps.append(("PEG Ratio", peg_s, 0.25)) - high52 = metrics.get("fiftyTwoWeekHigh") - low52 = metrics.get("fiftyTwoWeekLow") - cur = metrics.get("currentPrice") - if high52 and low52 and cur and high52 > low52: - pos_pct = round((cur - low52) / (high52 - low52) * 100, 1) - pos_s = ( - 85 - if pos_pct < 20 - else 72 - if pos_pct < 40 - else 55 - if pos_pct < 60 - else 38 - if pos_pct < 80 - else 20 - ) - comps.append(("52-Week Position", pos_s, 0.20)) + bands = [(0.5, 95), (1.0, 82), (1.5, 65), (2.0, 50), (3.0, 32)] + comps.append((f"PEG {peg:.2f}", _bucket(peg, bands, 15), 0.25)) + pb = metrics.get("priceToBook") if pb is not None and pb > 0: - pb_s = 88 if pb < 1 else 72 if pb < 2 else 58 if pb < 3 else 42 if pb < 5 else 22 - comps.append(("Price/Book", pb_s, 0.10)) + comps.append( + (f"Price/Book {pb:.2f}", _bucket(pb, [(1, 88), (2, 72), (3, 58), (5, 42)], 22), 0.15) + ) - if not comps: - return {"score": 50, "breakdown": [], "position_pct": None} - score = round(_weighted(comps)) - return { - "score": score, - "breakdown": [ - {"item": n, "score": round(s), "weight": f"{w * 100:.0f}%"} for n, s, w in comps - ], - "position_pct": pos_pct, - } + high, low, cur = ( + metrics.get(k) for k in ("fiftyTwoWeekHigh", "fiftyTwoWeekLow", "currentPrice") + ) + if high and low and cur and high > low: + pos_pct = round((cur - low) / (high - low) * 100, 1) + bands = [(20, 85), (40, 72), (60, 55), (80, 38)] + comps.append( + (f"52-week position {pos_pct:.0f}% (contrarian: lower = cheaper)", + _bucket(pos_pct, bands, 20), 0.15) + ) # fmt: skip + + result = _combine(comps, extra) + result["position_pct"] = pos_pct + return result + + +# --------------------------------------------------------------------- analyst + + +def score_analyst(metrics: dict, analyst_data: dict) -> dict: + """Wall Street consensus and price-target upside. + + With few analysts the consensus is pulled toward neutral (50) rather than + scaled down, so a thinly covered Strong Buy isn't scored like a Sell. + """ + rec = analyst_data.get("recommendationMean") # 1 = strong buy ... 5 = strong sell + n = analyst_data.get("numberOfAnalystOpinions") or 0 + target, cur = analyst_data.get("targetMeanPrice"), metrics.get("currentPrice") + + if rec is None: + return { + "score": 50, + "breakdown": [_item("No analyst coverage: neutral 50")], + "upside_pct": None, + } + + raw = _clamp((5 - rec) / 4 * 100) + confidence = 1.0 if n >= 8 else 0.75 if n >= 3 else 0.5 + score = 50 + (raw - 50) * confidence + consensus = (analyst_data.get("recommendationKey") or "n/a").replace("_", " ").title() + breakdown = [ + _item(f"Consensus: {consensus} ({rec:.1f} on a 1-5 scale)", raw), + _item(f"{n} analyst{'s' if n != 1 else ''}: {confidence * 100:.0f}% trust in consensus", + note="few analysts pull the score toward 50"), + ] # fmt: skip + + upside = None + if target and cur and cur > 0: + upside = round((target - cur) / cur * 100, 1) + delta = 10 if upside > 30 else 5 if upside > 10 else -10 if upside < 0 else 0 + score += delta + breakdown.append(_item(f"Price-target upside {upside:+.1f}%", note=f"{delta:+d} points")) + return {"score": round(_clamp(score)), "breakdown": breakdown, "upside_pct": upside} + + +# ----------------------------------------------------------------- smart money def score_smart_money(metrics: dict) -> dict: - """Insider ownership, institutional positioning, short interest — 0-100.""" - comps = [] - flags = [] - - ins_pct = metrics.get("heldPercentInsiders") - if ins_pct is not None: - ins_s = ( - 85 - if ins_pct > 0.20 - else 72 - if ins_pct > 0.10 - else 58 - if ins_pct > 0.05 - else 44 - if ins_pct > 0.01 - else 30 - ) - comps.append(("Insider Ownership", ins_s, 0.35)) - - inst_pct = metrics.get("heldPercentInstitutions") - if inst_pct is not None: - if inst_pct > 0.90: - inst_s = 40 - flags.append("Heavily institutionally owned — crowded trade risk") - elif inst_pct > 0.80: - inst_s = 55 - elif inst_pct >= 0.50: - inst_s = 72 - elif inst_pct >= 0.20: - inst_s = 60 + """Insider ownership, institutional positioning, short interest.""" + comps: list[tuple[str, float, float]] = [] + flags: list[str] = [] + + if (ins := metrics.get("heldPercentInsiders")) is not None: + bands = [(0.01, 30), (0.05, 44), (0.10, 58), (0.20, 72)] + comps.append((f"Insider ownership {ins * 100:.1f}%", _bucket(ins, bands, 85), 0.35)) + + if (inst := metrics.get("heldPercentInstitutions")) is not None: + if inst > 0.90: + s = 40 + flags.append("Heavily institutionally owned: crowded-trade risk") else: - inst_s = 52 - comps.append(("Institutional Ownership", inst_s, 0.30)) + s = _bucket(inst, [(0.20, 52), (0.50, 60), (0.80, 72)], 55) + comps.append((f"Institutional ownership {inst * 100:.1f}%", s, 0.30)) - short_pct = metrics.get("shortPercentOfFloat") - if short_pct is not None: - if short_pct > 0.20: - short_s = 22 - flags.append( - f"Very high short interest ({short_pct * 100:.1f}%) — heavy bearish conviction " - "or extreme squeeze candidate" - ) - elif short_pct > 0.10: - short_s = 35 + if (short := metrics.get("shortPercentOfFloat")) is not None: + if short > 0.20: + s = 22 flags.append( - f"High short interest ({short_pct * 100:.1f}%) — watch for squeeze " - "or continued selling" + f"Very high short interest ({short * 100:.1f}%): " + "strong bearish bets or squeeze risk" ) - elif short_pct > 0.05: - short_s = 52 - elif short_pct > 0.02: - short_s = 62 + elif short > 0.10: + s = 35 + flags.append(f"High short interest ({short * 100:.1f}%)") else: - short_s = 72 - comps.append(("Short Interest", short_s, 0.35)) + s = _bucket(short, [(0.02, 72), (0.05, 62)], 52) + comps.append((f"Short interest {short * 100:.1f}% of float", s, 0.35)) - if not comps: - return {"score": 50, "breakdown": [], "flags": []} - score = round(_weighted(comps)) - return { - "score": score, - "breakdown": [ - {"item": n, "score": round(s), "weight": f"{w * 100:.0f}%"} for n, s, w in comps - ], - "flags": flags, - } + result = _combine(comps) + result["flags"] = flags + return result -def calculate_opportunity_score(f: dict, a: dict, v: dict, s: dict) -> dict: - """Composite opportunity score from all four dimensions.""" - score = round(f["score"] * 0.25 + a["score"] * 0.30 + v["score"] * 0.30 + s["score"] * 0.15) - label, color = ( - ("Strong Opportunity", "#4caf50") - if score >= 75 - else ("Moderate Opportunity", "#8bc34a") - if score >= 60 - else ("Neutral", "#ffc107") - if score >= 45 - else ("Weak", "#ff9800") - if score >= 30 - else ("Avoid", "#f44336") - ) - return { - "score": score, - "label": label, - "color": color, - "sub": { - "fundamental": f["score"], - "analyst": a["score"], - "valuation": v["score"], - "smart_money": s["score"], - }, - } +# ----------------------------------------------------------------- opportunity +OPPORTUNITY_WEIGHTS = {"quality": 0.30, "valuation": 0.30, "analyst": 0.25, "smart_money": 0.15} +PILLAR_LABELS = { + "quality": "Quality", + "valuation": "Valuation", + "analyst": "Analyst", + "smart_money": "Smart Money", +} -def get_geo_risk_penalty(country: str): - if not country: - return 0, "No data" - tier_3_tax_havens = [ - "Bermuda", - "Cayman Islands", - "British Virgin Islands", - "Cyprus", - "Bahamas", + +def calculate_opportunity_score(pillars: dict[str, dict]) -> dict: + score = round(sum(pillars[k]["score"] * w for k, w in OPPORTUNITY_WEIGHTS.items())) + label, color = ( + ("Strong Opportunity", "#4caf50") if score >= 75 else + ("Moderate Opportunity", "#8bc34a") if score >= 60 else + ("Neutral", "#ffc107") if score >= 45 else + ("Weak", "#ff9800") if score >= 30 else + ("Avoid", "#f44336") + ) # fmt: skip + components = [ + { + "key": k, + "label": PILLAR_LABELS[k], + "score": pillars[k]["score"], + "weight": f"{w * 100:.0f}%", + } + for k, w in OPPORTUNITY_WEIGHTS.items() ] - tier_4_conflict = ["Israel", "Ukraine", "Russia", "Iran", "Yemen", "Syria"] - tier_2_emerging = ["Brazil", "India", "Mexico", "South Africa", "China"] + return {"score": score, "label": label, "color": color, "components": components} - if country in tier_4_conflict: - return 40, "High geopolitical risk / Conflict" - elif country in tier_3_tax_havens: - return 20, "Tax Haven / Regulatory scrutiny" - elif country in tier_2_emerging: - return 10, "Emerging Market Volatility" - return 0, "Safe/Tier 1" +# ---------------------------------------------------------------------- safety -def calculate_health_scores(metrics: dict): - """ - Compute Short-Term (ST) and Long-Term (LT) health scores (0-100). +_GEO_FLAGS = { + **dict.fromkeys( + ["Israel", "Ukraine", "Russia", "Iran", "Yemen", "Syria"], "conflict-exposed region" + ), + **dict.fromkeys( + ["Brazil", "India", "Mexico", "South Africa", "China", "Turkey"], "emerging market" + ), +} - Short-Term: weighted average of Current Ratio, Quick Ratio, Profit Margins. - Long-Term: weighted average of Debt/Equity, Beta, minus a geo-risk penalty. - """ - st_components = [] + +def calculate_safety(metrics: dict) -> dict: + """Liquidity (short term) and solvency & volatility (long term).""" + financial = (metrics.get("sector") or "") == "Financial Services" + + st: list[tuple[str, float, float]] = [] + st_extra: Breakdown = [] if (cr := metrics.get("currentRatio")) is not None: - st_components.append(("Current Ratio", norm_cr(cr), 0.4)) + st.append((f"Current ratio {cr:.2f}", _clamp(cr / 2.0 * 100), 0.55)) if (qr := metrics.get("quickRatio")) is not None: - st_components.append(("Quick Ratio", norm_qr(qr), 0.3)) - if (pm := metrics.get("profitMargins")) is not None: - st_components.append(("Profit Margins", norm_margin(pm), 0.3)) - st_base = _weighted(st_components) if st_components else 50.0 + st.append((f"Quick ratio {qr:.2f}", _clamp(qr / 1.5 * 100), 0.45)) + if financial and not st: + st_extra.append(_item("Liquidity ratios aren't reported for banks/insurers")) - lt_components = [] - if (de := metrics.get("debtToEquity")) is not None: - lt_components.append(("Debt to Equity", norm_de(de), 0.5)) + lt: list[tuple[str, float, float]] = [] + lt_extra: Breakdown = [] + flags: list[str] = [] + de = metrics.get("debtToEquity") + if de is not None and not financial: + # Yahoo: percent. 0% -> 100, 200% (2x) -> 0 + lt.append((f"Debt/Equity {de / 100:.2f}x", _clamp(100 - de / 2.0), 0.5)) + elif de is not None: + lt_extra.append(_item("Debt/Equity skipped", note="not meaningful for financial companies")) if (beta := metrics.get("beta")) is not None: - lt_components.append(("Beta", norm_beta(beta), 0.5)) - lt_base = _weighted(lt_components) if lt_components else 50.0 - - geo_pen, geo_reason = get_geo_risk_penalty(metrics.get("country") or "") - lt_final = max(0, lt_base - geo_pen) + # beta 0.5 -> 100, 1.5 -> 50, 2.5 -> 0 + lt.append((f"Beta {beta:.2f}", _clamp(100 - (beta - 0.5) * 50), 0.5)) - st_breakdown = [{"item": "Short-Term Base (Liquidity & Margins)", "impact": round(st_base, 1)}] - lt_breakdown = [{"item": "Long-Term Base (Solvency & Volatility)", "impact": round(lt_base, 1)}] - if geo_pen > 0: - lt_breakdown.append({"item": f"Geo-Risk Penalty ({geo_reason})", "impact": -geo_pen}) + country = metrics.get("country") + if country in _GEO_FLAGS: + flag = f"Headquartered in {country} ({_GEO_FLAGS[country]})" + flags.append(flag) + lt_extra.append(_item(flag, note="informational, not scored")) return { - "short_term": {"score": round(st_base), "breakdown": st_breakdown}, - "long_term": {"score": round(lt_final), "breakdown": lt_breakdown}, + "short_term": _combine(st, st_extra), + "long_term": _combine(lt, lt_extra), + "flags": flags, } +# ------------------------------------------------------------------- red flags + + +def calculate_financial_risk(metrics: dict) -> dict: + """Plain-language red flags, fed to the LLM as hints.""" + points, flags = 0, [] + + def check(key: str, label: str, bad: float, weak: float, fmt: str) -> None: + nonlocal points + v = metrics.get(key) + if v is None: + return + if v < bad: + points += 2 + flags.append(f"{label} {fmt.format(v)} (bad)") + elif v <= weak: + points += 1 + flags.append(f"{label} {fmt.format(v)} (weak)") + + check("currentRatio", "Current ratio", 1.0, 1.2, "{:.2f}") + check("revenueGrowth", "Revenue growth", -0.05, 0.0, "{:+.1%}") + check("profitMargins", "Net margin", 0.0, 0.05, "{:.1%}") + severity = "Low" if points <= 1 else "Medium" if points <= 3 else "High" + return {"total_risk_points": points, "severity_level": severity, "flags": flags} + + +# ------------------------------------------------------------------------ all + + def compute_all(metrics: dict, analyst_data: dict) -> dict: """Every score for one stock, in the shape the UI expects.""" - f = score_fundamental(metrics) - a = score_analyst(metrics, analyst_data) - v = score_valuation(metrics) - s = score_smart_money(metrics) + pillars = { + "quality": score_quality(metrics), + "valuation": score_valuation(metrics), + "analyst": score_analyst(metrics, analyst_data), + "smart_money": score_smart_money(metrics), + } return { - "health_scores": calculate_health_scores(metrics), - "scores": { - "fundamental": f, - "analyst": a, - "valuation": v, - "smart_money": s, - "opportunity": calculate_opportunity_score(f, a, v, s), - }, + "scores": {**pillars, "opportunity": calculate_opportunity_score(pillars)}, + "safety": calculate_safety(metrics), "risk_analysis": calculate_financial_risk(metrics), } diff --git a/watchstock/services.py b/watchstock/services.py index 7e6c56d..98111fb 100644 --- a/watchstock/services.py +++ b/watchstock/services.py @@ -9,12 +9,16 @@ from typing import Any from urllib.parse import urlparse -from watchstock import config, scoring, store +from watchstock import config, scoring, store, symbols from watchstock.providers import yahoo from watchstock.providers.yahoo import MarketDataError log = logging.getLogger(__name__) +# 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 + def normalize_ticker(ticker: str) -> str: return ticker.strip().upper() @@ -43,6 +47,7 @@ def build_snapshot(ticker: str, fallback_name: str = "") -> dict[str, Any]: metrics = profile["metrics"] return { + "schema": SNAPSHOT_SCHEMA, "ticker": ticker, "company_name": profile.get("name") or fallback_name or ticker, "company_domain": _domain(metrics.get("website")), @@ -68,6 +73,8 @@ def get_stock(ticker: str, *, name: str = "", refresh: bool = False) -> dict[str """ ticker = normalize_ticker(ticker) cached = store.get_snapshot(ticker) + if cached and cached["data"].get("schema") != SNAPSHOT_SCHEMA: + cached = None # incompatible shape from an older version fresh_enough = cached and _age_seconds(cached["fetched_at"]) < config.SNAPSHOT_TTL_SECONDS if cached and fresh_enough and not refresh: @@ -90,4 +97,5 @@ def get_stock(ticker: str, *, name: str = "", refresh: bool = False) -> dict[str stock = {**stock, "source": "live", "stale": False} stock["ai_analysis"] = store.latest_analysis(ticker) + stock["tradingview_symbol"] = symbols.tradingview_symbol(ticker) return stock diff --git a/watchstock/symbols.py b/watchstock/symbols.py new file mode 100644 index 0000000..91db867 --- /dev/null +++ b/watchstock/symbols.py @@ -0,0 +1,43 @@ +"""Ticker symbol translation between Yahoo Finance and other services.""" + +# Yahoo suffix -> TradingView exchange prefix. Yahoo: "TLV.RO", TradingView: "BVB:TLV". +_TRADINGVIEW_EXCHANGES = { + "RO": "BVB", # Bucharest + "DE": "XETR", # Xetra + "F": "FWB", # Frankfurt + "L": "LSE", + "PA": "EURONEXT", + "AS": "EURONEXT", + "BR": "EURONEXT", + "LS": "EURONEXT", + "MI": "MIL", + "MC": "BME", + "SW": "SIX", + "VI": "VIE", + "WA": "GPW", + "ST": "OMXSTO", + "CO": "OMXCOP", + "HE": "OMXHEX", + "OL": "OSL", + "TO": "TSX", + "V": "TSXV", + "HK": "HKEX", + "T": "TSE", + "AX": "ASX", + "NS": "NSE", + "BO": "BSE", + "KS": "KRX", + "SA": "BMFBOVESPA", +} + + +def tradingview_symbol(yahoo_ticker: str) -> str: + """Best-effort TradingView symbol for a Yahoo ticker. Unknown suffixes pass through.""" + ticker = yahoo_ticker.strip().upper() + base, dot, suffix = ticker.rpartition(".") + if not dot or suffix not in _TRADINGVIEW_EXCHANGES: + # US share classes: Yahoo "BRK-B" is TradingView "BRK.B". + return ticker.replace("-", ".") + if suffix == "HK": + base = base.lstrip("0") or "0" # Yahoo "0700.HK" -> "HKEX:700" + return f"{_TRADINGVIEW_EXCHANGES[suffix]}:{base}"