From 98aadcc3197fb7f56ff84f6cf50f350c5aa2417d Mon Sep 17 00:00:00 2001 From: Arvi23 Date: Wed, 4 Nov 2026 19:38:10 +0200 Subject: [PATCH] Batch 8a: import the portfolio from a Tradeville export - IMPORT button next to "+ ADD POSITION": pick a file, review a preview, confirm - watchstock/importers.py: Tradeville export parser (SEP= line, simbol/sold/costm/..., class suffixes, cash rows skipped) + generic CSV (ticker/shares/avg_cost) - Preview verifies every ticker (batch quotes, ISIN search fallback, no duplicates); unknown rows are editable and re-checked before they can be imported - Replace (default) or merge; "why I own it" notes are kept - company_info table (migration 4): light sector/country/dividend fetch in the background for never-opened stocks, resumed on the next portfolio load - Tests on a synthetic fixture; UI smoke covers the flow in English and Romanian - Docs: HANDOFF, ARCHITECTURE, DECISIONS D16; version 0.9.0 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TW7cJeWrcBW5SJHr4ZKtSH --- docs/ARCHITECTURE.md | 6 +- docs/DECISIONS.md | 14 ++ docs/HANDOFF.md | 33 +++-- pyproject.toml | 2 +- scripts/fake_server.py | 12 +- scripts/ui_smoke.js | 31 +++++ static/css/app.css | 7 + static/index.html | 31 +++++ static/js/i18n.js | 40 ++++++ static/js/import.js | 189 +++++++++++++++++++++++++++ static/js/main.js | 1 + static/js/portfolio.js | 13 +- tests/conftest.py | 25 +++- tests/fixtures/tradeville_sample.csv | 9 ++ tests/test_i18n.py | 2 + tests/test_import.py | 148 +++++++++++++++++++++ uv.lock | 2 +- watchstock/__init__.py | 2 +- watchstock/db.py | 9 ++ watchstock/i18n.py | 3 + watchstock/importers.py | 162 +++++++++++++++++++++++ watchstock/providers/yahoo.py | 22 ++++ watchstock/routes/portfolio.py | 142 +++++++++++++++++++- watchstock/store.py | 44 +++++++ 24 files changed, 921 insertions(+), 28 deletions(-) create mode 100644 static/js/import.js create mode 100644 tests/fixtures/tradeville_sample.csv create mode 100644 tests/test_import.py create mode 100644 watchstock/importers.py diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c83755f..49de75b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -8,13 +8,15 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static ├── 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/portfolio.py /api/portfolio (GET overview, PUT/DELETE position, GET/POST {t}/thesis) + ├── routes/portfolio.py /api/portfolio (GET overview, PUT/DELETE position, GET/POST {t}/thesis, + │ POST import/preview, import/commit) └── routes/today.py /api/today (events for held + watched stocks) │ ├── services.py snapshot freshness: cache hit / live fetch / stale fallback ├── scoring.py pure scoring functions → opportunity pillars + safety, with breakdowns ├── i18n.py English/Romanian: tr(), num(), request language (cookie → ContextVar) ├── symbols.py Yahoo ↔ TradingView ticker translation + ├── importers.py pure file parsing: Tradeville export, generic CSV → positions ├── portfolio.py pure portfolio math: value, P/L, weights, allocation, flags, dividends ├── today.py pure "Today" event builder (earnings, ex-div, moves, ratings, insider buys) ├── peers.py pure industry-peer comparison (medians, relative %, table rows) @@ -42,6 +44,7 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static | `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, thesis check, "you own" line | +| `js/import.js` | import modal: read file, preview table, ticker fixes, replace/merge, commit | | `js/today.js` | "Your stocks · next 2 weeks" panel | | `js/dashboard.js` | sidebar, finance tab, metric cards, news tab | | `js/analysis.js` | AI report rendering/requesting, JSON export | @@ -113,6 +116,7 @@ opens the browser. See D10. | `analyses` | every successful AI report (JSON) + model + `created_at` | | `holdings` | one row per position: shares, avg cost, currency, notes ("why I own it") | | `thesis_checks` | every thesis check (JSON: status, summary, supporting, against, watch) + the thesis text | +| `company_info` | light facts (name, sector, country, currency, dividend rate) for positions never opened; snapshots win | ## Testing diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 75c6365..e8a93e6 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -122,3 +122,17 @@ now computed at serve time from the cached snapshot (cheap, language-aware, and changes apply without refetching). Switching language reloads the page. Numbers and dates follow the locale (1.234,56 in Romanian). Stored AI reports stay in the language they were written in. Tests enforce dictionary completeness. + +## D16 — Portfolio import: preview first, verify every ticker, light background info (2026-11-04) +The owner's dad keeps his positions in Tradeville, so typing ~36 positions by hand was the +real obstacle. Import is two calls: `preview` parses the file and checks every ticker (one +batch quote call; an ISIN search for the ones that fail; an ISIN hit that would duplicate +another row is rejected) and saves nothing; `commit` writes the rows the user kept. Rows that +can't be verified can't be imported until the user types a ticker that verifies, so the +portfolio never holds an unpriced typo. "Replace" is the default because a broker export is +the full portfolio; "why I own it" notes survive either mode. Opening all 36 stocks just to get +sectors would cost ~10 Yahoo calls each, so the import fetches one light `info` call per new +ticker in the background (`company_info` table, migration 4) and the portfolio re-polls while +`info_pending > 0`; if the app was closed mid-way, the next portfolio load resumes it. Failed +fetches are not saved. Parsing is pure (`importers.py`) and tested on a synthetic fixture: the +real export contains the family's holdings and stays out of the repo. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 7a0ce85..08e2b76 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -103,15 +103,19 @@ Read this first. Update it at the end of every batch or before your context runs leftover English. Caught: a MutationObserver infinite loop on identical translations, and the logo turning into "WatchAcțiune" -### Batch 8 — History, Tradeville import, highlights, model presets (next) -- **Tradeville import** (owner sent a real export 2026-11-04; NOT in the repo, keep it that way; - build a synthetic fixture). Format: first line `SEP=\t`, then a tab-separated header. Columns: - `simbol` (e.g. `US.APLD`, `US.COHRn`, `US.OUSTc`: strip the `US.` prefix and trailing lowercase - class letters; BVB symbols presumably have no prefix → `.RO`), `sold` = shares, - `costm` = average cost, `ppiata` = market price, `valuta` = currency, `nume` = name, - `isin`, `tsim` = `actiuni` (shares) or `bani` (cash row; skip, maybe show cash). Decimal point - is `.`. Use the ISIN (`yf.Search(isin)`) as a fallback when a ticker doesn't resolve. Preview - before saving; replace vs merge choice. The owner's dad has ~36 US positions. +### Batch 8a — Portfolio import *(branch `batch-8-import`, PR #8, stacked on #7)* ✅ +- [x] IMPORT button next to "+ ADD POSITION" → pick file → preview (nothing saved) → confirm (D16) +- [x] `watchstock/importers.py`: Tradeville export parser (format notes in its docstring) + + generic CSV (ticker/shares/avg_cost, `,` or `;`, decimal comma ok); cash rows skipped +- [x] Preview checks every ticker with one batch quote call; unknown ones fall back to an ISIN + search; still-unknown rows are red and editable ("CHECK AGAIN" re-runs with overrides) +- [x] Replace (default, the file is the whole portfolio) or merge; notes are kept either way +- [x] Sector/country/dividend for never-opened stocks: one light `info` call each, in the + background, saved in `company_info` (migration 4); resumed on the next portfolio load +- [x] Tests on a **synthetic** fixture `tests/fixtures/tradeville_sample.csv`. The owner's real + export is NOT in the repo; keep it that way. Parsed fine locally: 36 positions + 1 cash row. + +### Batch 8b — History, highlights, model presets, lighter Today panel (next) - **Today panel with ~36 holdings**: currently fetches calendar + ratings + insider per ticker (3 Yahoo requests each, cached 6 h, 4 in parallel): fine but slow on first load. Consider calendar-only for the first pass and loading ratings/insider lazily. @@ -129,10 +133,10 @@ Read this first. Update it at the end of every batch or before your context runs - Portfolio history (value over time) — needs a daily snapshot job. ## Status -Batches 1-7 done. PR #1 merged by the owner; #2-#7 stacked, CI-green. **Owner action:** on PR #2 +Batches 1-7 and 8a (import) done. PR #1 merged by the owner; #2-#8 stacked, CI-green. **Owner action:** on PR #2 change the base to `main` (Edit next to the title), merge, click "Delete branch"; GitHub then retargets #3 to `main`, and so on. (Agents may not merge or retarget PRs here.) -The owner's folder `E:\WatchStock\WatchStock` has everything through batch 7. Next: batch 8. +The owner's folder `E:\WatchStock\WatchStock` has everything through batch 8a. Next: batch 8b. Notes for the next agent: - The sidebar "you own" P/L uses the snapshot price (up to 4 h old); the portfolio table @@ -189,6 +193,13 @@ Batch 7: - [ ] A new AI report / thesis check / chat answer comes back in Romanian (free model quality varies) - [ ] Romanian wording reads naturally to the dad (send any odd phrases; they're in static/js/i18n.js) +Batch 8a (import): +- [ ] IMPORT → pick the Tradeville export → preview lists ~36 positions, all "OK" (send the names + of any red "Not found" rows: their Tradeville symbol needs a new mapping rule) +- [ ] After importing: values and P/L match Tradeville (avg cost = Tradeville's `costm`) +- [ ] Sector doughnut fills in within a minute or two ("Loading sector and dividend info..." line) +- [ ] The "Your stocks" panel with ~36 holdings: how long does the first load take? + ## Open questions for the owner - (answered) Dad holds mostly US stocks → currency formatting stays in batch 3, no rush. - (answered) Default model: `nvidia/nemotron-3.5-super-vl:free` for now. diff --git a/pyproject.toml b/pyproject.toml index a850c11..bd9d9aa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "watchstock" -version = "0.8.0" +version = "0.9.0" description = "Personal stock analysis terminal: Yahoo Finance data, explainable scores, optional LLM analysis." readme = "README.md" requires-python = ">=3.12" diff --git a/scripts/fake_server.py b/scripts/fake_server.py index d578879..1350633 100644 --- a/scripts/fake_server.py +++ b/scripts/fake_server.py @@ -58,7 +58,14 @@ def cur(t): def chg(t): return -6.5 if t == "NVDA" else 1.2 # NVDA: a "big move" for the Today panel - return {t: {"price": 100.0, "change_pct": chg(t), "currency": cur(t)} for t in tickers} + # OLDNAME: a symbol Yahoo doesn't know (tests the import's "not found" path) + return {t: {"price": 100.0, "change_pct": chg(t), "currency": cur(t)} + for t in tickers if t != "OLDNAME"} # fmt: skip + + +def fetch_company_basics(ticker): + return {"name": f"{ticker} Inc", "sector": "Industrials", "country": "United States", + "currency": "USD", "dividend_rate": 0.5} # fmt: skip def fetch_industry_peers(industry_key, limit=8): @@ -174,7 +181,8 @@ def complete(messages, *, api_key, model, json_mode=True): def install_fakes(): for fn in (fetch_profile, fetch_news, fetch_quotes, fetch_indices, fetch_market_news, - fetch_movers, search, fetch_events, fetch_industry_peers, fetch_key_metrics): # fmt: skip + fetch_movers, search, fetch_events, fetch_industry_peers, fetch_key_metrics, + fetch_company_basics): # fmt: skip setattr(yahoo, fn.__name__, fn) openrouter.complete = complete diff --git a/scripts/ui_smoke.js b/scripts/ui_smoke.js index ba4e88f..9157e7f 100644 --- a/scripts/ui_smoke.js +++ b/scripts/ui_smoke.js @@ -5,6 +5,7 @@ // // Exits non-zero if any check fails or the page throws. All app assets are local, so // only external extras (TradingView, logos, favicons) are blocked. +const path = require('path'); const { chromium } = require('playwright'); const BASE = process.env.BASE_URL || 'http://127.0.0.1:8001'; @@ -97,6 +98,29 @@ const check = (name, ok, detail = '') => { if (!ok) failures.push(`${name}${deta await page.waitForTimeout(500); check('thesis badge in table', /INTACT/.test(await text('#portfolioTable'))); + // Import a (synthetic) Tradeville export: preview, fix an unknown ticker, merge + const SAMPLE_CSV = path.join(__dirname, '..', 'tests', 'fixtures', 'tradeville_sample.csv'); + await page.click('#btnImport'); + await page.setInputFiles('#importFile', SAMPLE_CSV); + await page.waitForSelector('.imp-table'); + check('import preview summary', /Tradeville export: 5 positions found/.test(await text('#importPreview')), await text('#importPreview')); + check('import skips cash', /USD cash \(43\.06\) is not imported/.test(await text('#importPreview'))); + check('unknown ticker needs a fix', await page.evaluate(() => document.querySelector('.imp-fix')?.value === 'OLDNAME')); + check('import button counts rows', /IMPORT 4 POSITIONS/.test(await text('#btnCommitImport')), await text('#btnCommitImport')); + check('replace warns about removals', /will be removed/.test(await text('#importRemoved')), await text('#importRemoved')); + await page.fill('.imp-fix', 'newname'); + await page.click('#importPreview button:has-text("CHECK AGAIN")'); + await page.waitForFunction(() => /IMPORT 5 POSITIONS/.test(document.getElementById('btnCommitImport').innerText)); + await shot('import_preview'); + await page.check('input[name="importMode"][value="merge"]'); + check('merge removes nothing', (await text('#importRemoved')) === ''); + await page.click('#btnCommitImport'); + await page.waitForTimeout(1200); + const afterImport = await text('#portfolioTable'); + check('imported positions shown', /COHR/.test(afterImport) && /BRK-B/.test(afterImport) && /NEWNAME/.test(afterImport), afterImport); + check('merge kept other positions', /NVDA/.test(afterImport)); + check('import modal closed', await page.evaluate(() => document.getElementById('importModal').style.display === 'none')); + // Open a stock: report renders, sanitised await page.evaluate(() => quickSearch('Microsoft Corporation', 'MSFT')); await page.waitForTimeout(2500); @@ -211,6 +235,13 @@ const check = (name, ok, detail = '') => { if (!ok) failures.push(`${name}${deta check('[ro] decimal comma in indices', /6\.012,30/.test(await roText('#indicesBar')), await roText('#indicesBar')); check('[ro] today panel in Romanian', /Rezultate financiare în 3 zile/.test(await roText('#todayList')), await roText('#todayList')); await leftovers('home'); + await ro.click('#btnImport'); + await ro.setInputFiles('#importFile', path.join(__dirname, '..', 'tests', 'fixtures', 'tradeville_sample.csv')); + await ro.waitForSelector('.imp-table'); + check('[ro] import preview', /Export Tradeville: 5 poziții găsite/.test(await roText('#importPreview')), await roText('#importPreview')); + await leftovers('import'); + OUT && await ro.screenshot({ path: `${OUT}/ro_import.png` }); + await ro.evaluate(() => closeImportModal()); await ro.evaluate(() => quickSearch('Microsoft Corporation', 'MSFT')); await ro.waitForTimeout(2000); await ro.click('.tab-btn[data-target="tab-finance"]'); diff --git a/static/css/app.css b/static/css/app.css index 29efac6..3da1bfa 100644 --- a/static/css/app.css +++ b/static/css/app.css @@ -150,6 +150,13 @@ body { .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; } +/* import modal */ +.imp-file { display: inline-block; border: 1px dashed var(--accent); color: var(--accent); padding: 12px 22px; font-size: 0.72rem; font-weight: 700; letter-spacing: 1px; cursor: pointer; } +.imp-file:hover { background: #1f1f1f; } +.imp-table td { vertical-align: top; } +.imp-mode { display: flex; gap: 10px; align-items: flex-start; font-size: 0.74rem; color: #ddd; margin: 8px 0; cursor: pointer; line-height: 1.4; } +.imp-mode input { margin-top: 3px; accent-color: var(--accent); } +.imp-sub { font-size: 0.65rem; color: #777; } .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; } diff --git a/static/index.html b/static/index.html index 9ec4769..de89282 100644 --- a/static/index.html +++ b/static/index.html @@ -104,6 +104,7 @@ MY PORTFOLIO
+
@@ -543,6 +544,35 @@

+
+
+

Import positions

+ +
+
+
+
    +
  1. In Tradeville, open your portfolio and export it to a file.
  2. +
  3. Pick that file below. You will see a preview first; nothing is saved until you confirm.
  4. +
+ +
Any CSV with ticker, shares and avg_cost columns works too.
+
+ + +
+
+ + +
+
+ +