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
6 changes: 5 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ jobs:
git diff --exit-code -- static/vendor static/css
- run: npx playwright install --with-deps chromium
- name: UI smoke test (fake data)
# Run the server with the venv's python, not `uv run`: a still-running uv process
# holds uv's cache lock and breaks setup-uv's post-job cache prune.
run: |
uv run python scripts/fake_server.py &
.venv/bin/python scripts/fake_server.py &
SERVER_PID=$!
for i in $(seq 1 30); do curl -sf http://127.0.0.1:8001/api/health && break; sleep 1; done
node scripts/ui_smoke.js
kill $SERVER_PID
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ Download the new ZIP and copy your old `data` folder into it (or `git pull`).

## What it shows

- **Home:** major indices, market news, today's biggest movers, your watchlist.
- **Home:** major indices, market news, today's biggest movers, your watchlist, and
**My Portfolio**: your positions with value, profit/loss, today's change, weights,
sector allocation, concentration warnings and expected yearly dividends.
- **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.
Expand Down
6 changes: 5 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ Browser (static/index.html + static/js/*.js, plain scripts, no build step)
watchstock/app.py FastAPI app factory, error → 502 mapping, static files
├── routes/stocks.py /api/search, /api/stocks/{t}, /api/stocks/{t}/analysis, /api/chat
├── routes/market.py /api/market/{indices,news,movers} (TTL-cached, degrade to empty)
└── routes/personal.py /api/watchlist, /api/settings
├── routes/personal.py /api/watchlist, /api/settings
└── routes/portfolio.py /api/portfolio (GET overview, PUT position, DELETE position)
│
├── services.py snapshot freshness: cache hit / live fetch / stale fallback
├── scoring.py pure scoring functions → opportunity pillars + safety, with breakdowns
├── symbols.py Yahoo ↔ TradingView ticker translation
├── portfolio.py pure portfolio math: value, P/L, weights, allocation, flags, dividends
├── analysis.py LLM prompts: report + chat (compact context)
├── store.py every SQL query
├── db.py connection + migrations (PRAGMA user_version)
Expand All @@ -34,6 +36,7 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static
| `js/scores.js` | breakdown popover + safety modal |
| `js/settings.js` | settings modal |
| `js/home.js` | indices, market news, movers, watchlist, search history |
| `js/portfolio.js` | portfolio totals/table/doughnuts, add/edit modal, "you own" sidebar line |
| `js/dashboard.js` | sidebar, finance tab, metric cards, news tab |
| `js/analysis.js` | AI report rendering/requesting, JSON export |
| `js/chat.js` | chat panel and the UI actions the model may request |
Expand Down Expand Up @@ -100,6 +103,7 @@ opens the browser. See D10.
| `watchlist` | tickers the user starred |
| `snapshots` | latest successful fetch per ticker (JSON) + `fetched_at` |
| `analyses` | every successful AI report (JSON) + model + `created_at` |
| `holdings` | one row per position: shares, avg cost, currency, notes ("why I own it") |

## Testing

Expand Down
10 changes: 10 additions & 0 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,13 @@ unpinned CDN update can't break it again (that's how the report links broke). Ta
Play CDN (a runtime compiler, not meant for production) is replaced by a precompiled
`static/css/tailwind.css`, which CI checks is up to date. Node is a developer-only tool.
All LLM markdown goes through DOMPurify, with images forbidden.

## D12 — Portfolio: one row per position, per-currency totals, no FX (2026-11-04)
The user enters each position as shares + average cost (not individual lots): that's
how a small-portfolio owner thinks about it, and it's easy to keep current. Totals,
weights and concentration are computed per currency; there is no FX conversion,
because a guessed or stale rate would make every total quietly wrong (the owner is
mostly USD). Adding a position validates the ticker by fetching and caching its
snapshot, which also gives sector/country/dividend rate for allocation. A position's
`notes` ("why I own it") is stored now so batch 5 can check the thesis against new data.
Scores are rounded half up (49, not Python's banker's 48) so people can check them by hand.
46 changes: 32 additions & 14 deletions docs/HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,30 +60,41 @@ Read this first. Update it at the end of every batch or before your context runs
- [x] `scripts/ui_smoke.js` is now a pass/fail browser test (sanitising, currencies, breakdowns,
watchlist, refresh, chat, no-key hint, failure toast) and runs in CI

### Batch 4 — Portfolio
- Holdings (ticker, shares, cost basis, currency), P/L, allocation by sector/country,
concentration warnings, projected dividend income
### Batch 4 — Portfolio *(branch `batch-4-portfolio`, PR #4, stacked on #3)* ✅
- [x] `holdings` table (migration 2), one row per position (D12)
- [x] `watchstock/portfolio.py`: value, P/L, day change, weights, sector allocation, per-currency totals
(no FX), concentration flags (position > 20%, sector > 40%, only with ≥ 3 positions),
projected annual dividends + yield on cost, missing-price handling
- [x] `/api/portfolio` GET/PUT/DELETE; PUT validates the ticker via `services.get_stock`
- [x] Home: "My Portfolio" with summary cards, holdings table (click → stock view), position and
sector doughnuts, flags; add/edit modal with autocomplete, decimal-comma input, two-click remove
- [x] Stock sidebar: "You own N @ cost, P/L" line (`holding` field on the snapshot response)
- [x] Owner feedback: long-term safety renamed "Stability (debt & volatility)" and its breakdown says
which half drags it down; scores round half up
- [x] 76 backend tests; UI smoke covers the portfolio flow

### Batch 5 — Staying on top of it
- Morning digest of holdings (earnings / ex-dividend dates, big moves, insider buys, rating changes)
- Industry peer comparison; thesis tracking ("why I bought" checked against new data)

## Status
Batches 1-3 done. PRs #1, #2, #3 (stacked) wait for the owner to merge; files are copied
to the owner's folder after each batch. Next: batch 4 (portfolio).
Batches 1-4 done. PRs #1-#4 (stacked) wait for the owner to merge; files are copied to the
owner's folder after each batch. Next: batch 5.

Notes for the next agent:
- Batch 4 plan: `holdings` table (ticker, shares, avg cost, currency, opened_at, notes) via a new
migration; `/api/portfolio` returning positions with live quotes, P/L, weights, sector/country
allocation (sector from the cached snapshot, else a light `fetch_profile`), concentration flags
(single position > 20%, sector > 40%), projected annual dividends. UI: a "Portfolio" view on the
home screen next to the watchlist; keep it to one table + two small allocation charts.
Multi-currency totals: show per-currency subtotals rather than inventing FX conversion; dad is
mostly USD.
- Batch 5 candidates, in order of value for the owner:
1. Morning digest for holdings + watchlist: earnings dates / ex-dividend dates
(`Ticker.calendar`), moves > 5%, new rating changes, new insider buys. Start as a
"Today" panel on the home screen computed on load (no scheduler needed); a
scheduled email/notification can come later.
2. Thesis check: an LLM call per position comparing `holdings.notes` with the current
snapshot and latest news ("still holds / weakening / broken" + why), on demand.
3. Peer comparison (same industry via yfinance `Industry`/`Sector`) to make P/E bands
industry-relative (see D8).
- The sidebar "you own" P/L uses the snapshot price (up to 4 h old); the portfolio table
uses live quotes. Fine for now; unify if the owner notices.
- For screenshots/tests: `scripts/fake_server.py` + `node scripts/ui_smoke.js` (needs
`PLAYWRIGHT_BROWSERS_PATH` pointing at a Chromium matching playwright 1.63.0).
- The old hackathon DB (`watchstock.db` at repo root) is not migrated; the new DB is
`data/watchstock.db`.

## Needs live testing (owner, on Windows)
Batch 1 (owner tested 2026-11-04: works; BVB chart said "symbol doesn't exist" → fixed in batch 2;
Expand All @@ -106,6 +117,13 @@ Batch 3:
- [ ] `TLV.RO` shows prices in RON (e.g. "RON 29.50"), MSFT in $
- [ ] Market cap shows compact (e.g. "$3.08T")

Batch 4:
- [ ] Add a few real positions (+ ADD POSITION): value, P/L and "Today" look right vs the broker
- [ ] Expected dividends per year look plausible (shares × annual dividend per share)
- [ ] Click a row → opens the stock; sidebar shows "You own ..."
- [ ] Edit a position, then remove it (click REMOVE twice)
- [ ] Sidebar "Stability" circle; its breakdown explains a low score from high beta

## 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.4.0"
version = "0.5.0"
description = "Personal stock analysis terminal: Yahoo Finance data, explainable scores, optional LLM analysis."
readme = "README.md"
requires-python = ">=3.12"
Expand Down
6 changes: 4 additions & 2 deletions scripts/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import copy
import json
import os
import random
import sys
import tempfile
from pathlib import Path
Expand Down Expand Up @@ -52,7 +51,10 @@ def fetch_news(ticker, count=20):


def fetch_quotes(tickers):
return {t: {"price": round(random.uniform(50, 500), 2), "change_pct": 1.2} for t in tickers}
def cur(t):
return "RON" if t.endswith(".RO") else "USD"

return {t: {"price": 100.0, "change_pct": 1.2, "currency": cur(t)} for t in tickers}


def fetch_indices():
Expand Down
40 changes: 40 additions & 0 deletions scripts/ui_smoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,53 @@ const check = (name, ok, detail = '') => { if (!ok) failures.push(`${name}${deta
check('tailwind css applied', await page.evaluate(() => getComputedStyle(document.querySelector('#initialView')).position === 'absolute'));
await shot('home');

// Portfolio: empty state, add (decimal comma), bad ticker, charts, flags
check('portfolio empty state', /No positions yet/.test(await text('#portfolioTable')));
const addPosition = async (ticker, shares, cost) => {
await page.click('#btnAddHolding');
await page.fill('#holdingTicker', ticker);
await page.fill('#holdingShares', shares);
await page.fill('#holdingCost', cost);
await page.click('#btnSaveHolding');
await page.waitForTimeout(1200);
};
await addPosition('MSFT', '10', '300,50');
await addPosition('AAPL', '5', '150');
await addPosition('NVDA', '20', '50');
await addPosition('TLV.RO', '100', '20');
const pfTable = await text('#portfolioTable');
check('portfolio rows', /MSFT/.test(pfTable) && /AAPL/.test(pfTable) && /TLV\.RO/.test(pfTable), pfTable);
check('decimal comma cost', /\$300\.50/.test(pfTable), pfTable);
check('RON position priced in RON', /RON\s?100\.00/.test(pfTable), pfTable);
check('USD summary value', /\$3,500\.00/.test(await text('#portfolioSummary')), await text('#portfolioSummary'));
check('allocation charts shown', await page.evaluate(() => getComputedStyle(document.getElementById('portfolioCharts')).display === 'grid'));
check('concentration flag', /NVDA is 57% of your USD holdings/.test(await text('#portfolioFlags')), await text('#portfolioFlags'));
await page.click('#btnAddHolding');
await page.fill('#holdingTicker', 'FAIL');
await page.fill('#holdingShares', '1');
await page.fill('#holdingCost', '1');
await page.click('#btnSaveHolding');
await page.waitForTimeout(1000);
check('bad ticker error in modal', /429/.test(await text('#holdingError')));
await page.evaluate(() => closeHoldingModal());
await shot('portfolio');
// edit prefills, two-click remove
await page.evaluate(() => openHoldingModal('AAPL'));
check('edit prefills', (await page.inputValue('#holdingShares')) === '5');
await page.click('#btnDeleteHolding');
check('remove needs confirmation', /CLICK AGAIN/.test(await text('#btnDeleteHolding')));
await page.click('#btnDeleteHolding');
await page.waitForTimeout(1000);
check('position removed', !/AAPL/.test(await text('#portfolioTable')));

// Open a stock: report renders, sanitised
await page.evaluate(() => quickSearch('Microsoft Corporation', 'MSFT'));
await page.waitForTimeout(2500);
check('ticker shown', (await text('#sbTicker')) === 'MSFT');
check('price in USD', /^\$414\.00$/.test(await text('#sbPrice')), await text('#sbPrice'));
check('market cap compact', /^\$3\.08T$/.test(await text('#sbMarketCap')), await text('#sbMarketCap'));
check('as-of label', /data /.test(await text('#asOfLabel')));
check('you-own line', /You own 10/.test(await text('#sbHolding')), await text('#sbHolding'));
const deepDive = await page.evaluate(() => document.getElementById('financialDeepDiveContent').innerHTML);
check('markdown link rendered', /<a href="https:\/\/example.com" target="_blank"/.test(deepDive), deepDive.slice(0, 200));
check('LLM HTML sanitised', !/onerror|<script|<img/i.test(deepDive) && !(await page.evaluate(() => window.__xss)), deepDive);
Expand Down
20 changes: 20 additions & 0 deletions static/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,23 @@ body {
outline: none; font-family: 'Inter', sans-serif;
}
#searchOverlay label { color: var(--text-muted); font-size: 0.7rem; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 8px; display: block; }

/* Position modal + portfolio table */
.hm-label { font-size: 0.65rem; letter-spacing: 1px; text-transform: uppercase; color: #888; display: block; margin-bottom: 6px; }
.hm-input { width: 100%; background: #111; border: 1px solid #2a2a2a; color: #e0e0e0; padding: 8px 10px; font-size: 0.8rem; outline: none; box-sizing: border-box; font-family: inherit; }
.hm-input:focus { border-color: var(--accent); }
.pf-table { width: 100%; border-collapse: collapse; font-size: 0.72rem; }
.pf-table th { text-align: right; font-weight: 600; font-size: 0.58rem; letter-spacing: 1px; color: #777; padding: 6px 8px; border-bottom: 1px solid #333; text-transform: uppercase; }
.pf-table td { text-align: right; padding: 7px 8px; border-bottom: 1px solid #222; font-family: monospace; color: #ddd; white-space: nowrap; }
.pf-table th:first-child, .pf-table td:first-child { text-align: left; }
.pf-table tbody tr:hover { background: #1e1e1e; }
.pf-stock { cursor: pointer; font-family: 'Inter', sans-serif; }
.pf-stock b { color: var(--accent); font-family: monospace; }
.pf-stock span { color: #888; font-size: 0.65rem; margin-left: 6px; }
.pf-edit { background: transparent; border: 1px solid #333; color: #888; cursor: pointer; font-size: 0.6rem; padding: 2px 7px; }
.pf-edit:hover { color: #fff; border-color: #555; }
.pf-cards { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-bottom: 12px; }
.pf-card { background: #1a1a1a; border: 1px solid #333; padding: 10px 12px; }
.pf-card .k { font-size: 0.58rem; letter-spacing: 1px; color: #888; text-transform: uppercase; }
.pf-card .v { font-size: 1.05rem; font-weight: 700; font-family: monospace; margin-top: 4px; color: #e0e0e0; }
.pf-card .s { font-size: 0.65rem; font-family: monospace; margin-top: 2px; }
Loading
Loading