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
+
+
+
+
+
+
In Tradeville, open your portfolio and export it to a file.
+
Pick that file below. You will see a preview first; nothing is saved until you confirm.
+
+
+
Any CSV with ticker, shares and avg_cost columns works too.
+
+
+
+
+
+
+
+
+
+
+
@@ -573,6 +603,7 @@
+
diff --git a/static/js/i18n.js b/static/js/i18n.js
index 1534cda..2c1ef77 100644
--- a/static/js/i18n.js
+++ b/static/js/i18n.js
@@ -307,6 +307,46 @@ const RO = {
'+{n} more': 'încă {n}',
'Value · {cur}': 'Valoare · {cur}',
'BY POSITION ({cur})': 'PE POZIȚII ({cur})',
+ // ---- import
+ 'Import positions': 'Importă poziții',
+ 'Load positions from a Tradeville export or a CSV file': 'Încarcă pozițiile dintr-un export Tradeville sau dintr-un fișier CSV',
+ 'In Tradeville, open your portfolio and export it to a file.': 'În Tradeville, deschide portofoliul și exportă-l într-un fișier.',
+ 'Pick that file below. You will see a preview first; nothing is saved until you confirm.': 'Alege fișierul mai jos. Vei vedea întâi o previzualizare; nimic nu se salvează până nu confirmi.',
+ 'CHOOSE FILE': 'ALEGE FIȘIERUL',
+ 'Any CSV with ticker, shares and avg_cost columns works too.': 'Merge și orice CSV cu coloanele ticker, shares și avg_cost.',
+ 'That file is too big for a portfolio export.': 'Fișierul e prea mare pentru un export de portofoliu.',
+ 'Reading the file and checking each stock...': 'Citesc fișierul și verific fiecare acțiune...',
+ 'Matched by ISIN (file: {ticker})': 'Găsită după ISIN (în fișier: {ticker})',
+ 'Not found': 'Negăsită',
+ 'already in portfolio': 'deja în portofoliu',
+ '{cur} cash ({amount}) is not imported.': 'Numerarul în {cur} ({amount}) nu se importă.',
+ '{symbol}: no shares or cost, skipped.': '{symbol}: fără acțiuni sau cost, omisă.',
+ '{symbol}: skipped ({reason}).': '{symbol}: omisă ({reason}).',
+ '{n} stock was not found on Yahoo Finance.': '{n} acțiune nu a fost găsită pe Yahoo Finance.',
+ '{n} stocks were not found on Yahoo Finance.': '{n} acțiuni nu au fost găsite pe Yahoo Finance.',
+ 'Type the Yahoo ticker in the red rows (e.g. BRK-B, TLV.RO), then check again. Rows that stay red are left out.': 'Scrie simbolul Yahoo pe rândurile roșii (de ex. BRK-B, TLV.RO), apoi verifică din nou. Rândurile care rămân roșii nu se importă.',
+ 'CHECK AGAIN': 'VERIFICĂ DIN NOU',
+ 'Replace my portfolio with this file': 'Înlocuiește portofoliul cu acest fișier',
+ 'Best for a full Tradeville export. Your "why I own it" notes are kept for stocks that stay.': 'Potrivit pentru un export Tradeville complet. Notițele „de ce o dețin” se păstrează pentru acțiunile care rămân.',
+ 'Add and update only': 'Doar adaugă și actualizează',
+ 'Positions that are not in the file stay as they are.': 'Pozițiile care nu sunt în fișier rămân neschimbate.',
+ 'Tradeville export: {n} positions found.': 'Export Tradeville: {n} poziții găsite.',
+ 'CSV file: {n} positions found.': 'Fișier CSV: {n} poziții găsite.',
+ 'PICK ANOTHER FILE': 'ALT FIȘIER',
+ 'In the file': 'În fișier',
+ 'Ticker': 'Simbol',
+ 'Name': 'Nume',
+ 'Status': 'Stare',
+ 'IMPORT {n} POSITION': 'IMPORTĂ {n} POZIȚIE',
+ 'IMPORT {n} POSITIONS': 'IMPORTĂ {n} POZIȚII',
+ '1 position you hold now is not selected and will be removed.': 'O poziție pe care o deții acum nu e selectată și va fi ștearsă.',
+ '{n} positions you hold now are not selected and will be removed.': '{n} poziții pe care le deții acum nu sunt selectate și vor fi șterse.',
+ 'SAVING...': 'SE SALVEAZĂ...',
+ 'Imported {n} position.': 'Am importat {n} poziție.',
+ 'Imported {n} positions.': 'Am importat {n} poziții.',
+ 'Using Tradeville? Click IMPORT and pick your portfolio export.': 'Folosești Tradeville? Apasă IMPORT și alege exportul portofoliului.',
+ 'Loading sector and dividend info for {n} stock...': 'Se încarcă sectorul și dividendele pentru {n} acțiune...',
+ 'Loading sector and dividend info for {n} stocks...': 'Se încarcă sectorul și dividendele pentru {n} acțiuni...',
};
function t(text, params) {
diff --git a/static/js/import.js b/static/js/import.js
new file mode 100644
index 0000000..c77421b
--- /dev/null
+++ b/static/js/import.js
@@ -0,0 +1,189 @@
+// Portfolio import from a broker export (Tradeville) or a simple CSV.
+// Flow: pick file -> POST /api/portfolio/import/preview (nothing is saved; tickers are
+// checked against Yahoo) -> the user reviews / fixes tickers -> POST .../import/commit.
+// Parsing lives in watchstock/importers.py; this file only shows the result.
+
+let _import = null; // { content, overrides: {fileSymbol: ticker}, preview }
+
+function openImportModal() {
+ _import = null;
+ document.getElementById('importPick').style.display = 'block';
+ document.getElementById('importPreview').style.display = 'none';
+ document.getElementById('importPreview').innerHTML = '';
+ document.getElementById('importFile').value = '';
+ importError('');
+ updateImportButton();
+ document.getElementById('importModal').style.display = 'flex';
+}
+
+function closeImportModal() {
+ document.getElementById('importModal').style.display = 'none';
+}
+
+function importError(msg) {
+ const el = document.getElementById('importError');
+ el.textContent = msg;
+ el.style.display = msg ? 'block' : 'none';
+}
+
+// Tradeville exports are UTF-8; older Romanian Windows files can be Windows-1250.
+async function readFileText(file) {
+ const buf = await file.arrayBuffer();
+ try {
+ return new TextDecoder('utf-8', { fatal: true }).decode(buf);
+ } catch (e) {
+ return new TextDecoder('windows-1250').decode(buf);
+ }
+}
+
+async function onImportFile(input) {
+ const file = input.files[0];
+ if (!file) return;
+ importError('');
+ if (file.size > 2_000_000) return importError(t('That file is too big for a portfolio export.'));
+ _import = { content: await readFileText(file), overrides: {}, preview: null };
+ await runImportPreview();
+}
+
+async function runImportPreview() {
+ const box = document.getElementById('importPreview');
+ box.style.display = 'block';
+ box.innerHTML = `
${t('Reading the file and checking each stock...')}
+ ${esc(t(notFound === 1 ? '{n} stock was not found on Yahoo Finance.' : '{n} stocks were not found on Yahoo Finance.', { n: notFound }))}
+ ${t('Type the Yahoo ticker in the red rows (e.g. BRK-B, TLV.RO), then check again. Rows that stay red are left out.')}
+
+
- No positions yet. Add the stocks you own to see their value, profit/loss, allocation and expected dividends in one place.
`;
+ No positions yet. Add the stocks you own to see their value, profit/loss, allocation and expected dividends in one place.
+ Using Tradeville? Click IMPORT and pick your portfolio export.
${esc(t(
+ p.info_pending === 1 ? 'Loading sector and dividend info for {n} stock...' : 'Loading sector and dividend info for {n} stocks...', { n: p.info_pending }))}
` : '');
}
function doughnut(canvasId, items) {
diff --git a/tests/conftest.py b/tests/conftest.py
index 7ae4732..1998f59 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,6 +1,7 @@
"""Shared fixtures. Tests never touch the network: providers are replaced by fakes."""
import copy
+import re
import pytest
from fastapi.testclient import TestClient
@@ -72,9 +73,24 @@ def fetch_news(self, ticker, count=20):
raise self.news_error
return copy.deepcopy(SAMPLE_NEWS)
+ unknown_tickers: set = set() # fetch_quotes returns nothing for these
+ isin_map: dict = {} # ISIN -> ticker, for search()
+
def fetch_quotes(self, tickers):
self.calls.append(("quotes", tuple(tickers)))
- return {t: {"price": 100.0, "change_pct": 1.5} for t in tickers}
+ return {
+ t: {"price": 100.0, "change_pct": 1.5} for t in tickers if t not in self.unknown_tickers
+ }
+
+ def fetch_company_basics(self, ticker):
+ self.calls.append(("basics", ticker))
+ return {
+ "name": f"{ticker} Inc",
+ "sector": "Technology",
+ "country": "United States",
+ "currency": "USD",
+ "dividend_rate": 1.0,
+ }
def _market(self, name, value):
self.calls.append((name,))
@@ -117,6 +133,11 @@ def fetch_events(self, ticker):
def search(self, query, limit=6):
self.calls.append(("search", query))
+ if query in self.isin_map:
+ t = self.isin_map[query]
+ return [{"name": t, "ticker": t, "exchange": "NYSE", "type": "EQUITY"}]
+ if re.fullmatch(r"[A-Z]{2}[A-Z0-9]{9}\d", query):
+ return [] # unknown ISIN
return [
{
"name": "Microsoft Corporation",
@@ -160,7 +181,7 @@ def fake_yahoo(monkeypatch):
fake = FakeYahoo()
for name in ("fetch_profile", "fetch_news", "fetch_quotes", "fetch_indices",
"fetch_market_news", "fetch_movers", "search", "fetch_events",
- "fetch_industry_peers", "fetch_key_metrics"): # fmt: skip
+ "fetch_industry_peers", "fetch_key_metrics", "fetch_company_basics"): # fmt: skip
monkeypatch.setattr(yahoo, name, getattr(fake, name))
return fake
diff --git a/tests/fixtures/tradeville_sample.csv b/tests/fixtures/tradeville_sample.csv
new file mode 100644
index 0000000..7ed91b5
--- /dev/null
+++ b/tests/fixtures/tradeville_sample.csv
@@ -0,0 +1,9 @@
+SEP=
+simbol cont sold costm ppiata ba valuta pproc market nume pretref bid ask pasmin isin stare tsim tcont nrzec porbid pret eval comis profit evalron profitron valutaSauPrc crest varcost tipcash valcump investitie nrzecFractionar nrzecDynamic pondere
+US.MSFT TEST01.US 10 300.123456 414 USD US Microsoft Corp US5949181045 actiuni
+US.COHRn TEST01.US 2 207.265635 192.41 USD US Coherent Corp US19247G1076 actiuni
+US.BRK.B TEST01.US 1 400 450 USD US Berkshire Hathaway B US0846707026 actiuni
+TLV TEST01.US 100 20.5 29.5 RON RO Banca Transilvania ROTLVAACNOR1 actiuni
+US.OLDNAME TEST01.US 5 10 12 USD US Renamed Inc US0000000001 actiuni
+US.ZERO TEST01.US 0 10 12 USD US Sold out US0000000002 actiuni
+USD TEST01.US 43.06 1 USD RO USD bani
diff --git a/tests/test_i18n.py b/tests/test_i18n.py
index f0e5965..13e3b81 100644
--- a/tests/test_i18n.py
+++ b/tests/test_i18n.py
@@ -22,6 +22,8 @@
"Trailing P/E", "Forward P/E", "Strong Buy", "Buy", "Hold", "Underperform", "Sell",
*scoring.PILLAR_LABELS.values(), "Strong Opportunity", "Moderate Opportunity", "Neutral", "Weak", "Avoid",
"conflict-exposed region", "emerging market",
+ "The file is empty or not a table.",
+ "Unrecognised file. Use a Tradeville portfolio export, or a CSV with ticker, shares and avg_cost columns.",
] # fmt: skip
diff --git a/tests/test_import.py b/tests/test_import.py
new file mode 100644
index 0000000..dd5f66e
--- /dev/null
+++ b/tests/test_import.py
@@ -0,0 +1,148 @@
+"""Portfolio import: Tradeville parsing (synthetic fixture), ticker resolution, commit."""
+
+from pathlib import Path
+
+import pytest
+
+from watchstock import importers
+
+SAMPLE = (Path(__file__).parent / "fixtures" / "tradeville_sample.csv").read_bytes()
+
+
+@pytest.mark.parametrize(
+ ("symbol", "market", "expected"),
+ [("US.APLD", "US", "APLD"), ("US.COHRn", "US", "COHR"), ("US.OUSTc", "US", "OUST"),
+ ("US.BRK.B", "US", "BRK-B"), ("TLV", "RO", "TLV.RO"), ("SNP", "BVB", "SNP.RO")],
+) # fmt: skip
+def test_tradeville_symbol_mapping(symbol, market, expected):
+ assert importers.tradeville_to_yahoo(symbol, market) == expected
+
+
+@pytest.mark.parametrize(("text", "value"), [("1234.56", 1234.56), ("1.234,56", 1234.56),
+ ("1,234.56", 1234.56), ("182,50", 182.5), ("", None)]) # fmt: skip
+def test_parse_number(text, value):
+ assert importers.parse_number(text) == value
+
+
+def test_parse_tradeville_export():
+ out = importers.parse(importers.decode(SAMPLE))
+ assert out["format"] == "tradeville"
+ assert [r["ticker"] for r in out["rows"]] == ["MSFT", "COHR", "BRK-B", "TLV.RO", "OLDNAME"]
+ msft = out["rows"][0]
+ assert msft["shares"] == 10 and msft["avg_cost"] == pytest.approx(300.123456)
+ assert msft["currency"] == "USD" and msft["isin"] == "US5949181045"
+ reasons = {s["symbol"]: s["reason"] for s in out["skipped"]}
+ assert reasons == {"USD": "cash", "US.ZERO": "no shares or cost"}
+
+
+def test_parse_generic_csv_with_semicolons_and_decimal_commas():
+ out = importers.parse("Ticker;Shares;Avg_Cost\nAAPL;10;182,50\nmsft;2;300\n")
+ assert out["format"] == "generic"
+ assert [(r["ticker"], r["shares"], r["avg_cost"]) for r in out["rows"]] == [
+ ("AAPL", 10, 182.5),
+ ("MSFT", 2, 300),
+ ]
+
+
+def test_unrecognised_file_is_rejected():
+ with pytest.raises(importers.ImportError_):
+ importers.parse("foo,bar\n1,2\n")
+
+
+# ---------------------------------------------------------------------- API
+
+
+def test_preview_resolves_tickers_with_isin_fallback(client, fake_yahoo):
+ fake_yahoo.unknown_tickers = {"OLDNAME"}
+ fake_yahoo.isin_map = {"US0000000001": "NEWNAME"}
+ body = client.post("/api/portfolio/import/preview", json={"content": SAMPLE.decode()}).json()
+ status = {r["ticker"]: r["status"] for r in body["rows"]}
+ assert status == {"MSFT": "ok", "COHR": "ok", "BRK-B": "ok", "TLV.RO": "ok", "NEWNAME": "isin"}
+ assert next(r for r in body["rows"] if r["ticker"] == "NEWNAME")["original_ticker"] == "OLDNAME"
+ assert client.get("/api/portfolio").json()["positions"] == [] # preview saves nothing
+
+
+def test_preview_marks_unresolvable_rows(client, fake_yahoo):
+ fake_yahoo.unknown_tickers = {"OLDNAME"}
+ rows = client.post("/api/portfolio/import/preview", json={"content": SAMPLE.decode()}).json()[
+ "rows"
+ ]
+ assert next(r for r in rows if r["ticker"] == "OLDNAME")["status"] == "not_found"
+
+
+def test_preview_applies_user_corrections(client, fake_yahoo):
+ fake_yahoo.unknown_tickers = {"OLDNAME"}
+ body = {"content": SAMPLE.decode(), "overrides": {"US.OLDNAME": " newname "}}
+ rows = client.post("/api/portfolio/import/preview", json=body).json()["rows"]
+ fixed = next(r for r in rows if r["source_symbol"] == "US.OLDNAME")
+ assert fixed["ticker"] == "NEWNAME" and fixed["status"] == "ok"
+
+
+def test_preview_rejects_garbage(client):
+ r = client.post("/api/portfolio/import/preview", json={"content": "hello"})
+ assert r.status_code == 422
+
+
+def test_commit_replace_keeps_notes_and_fills_company_info(client, fake_yahoo):
+ client.put(
+ "/api/portfolio", json={"ticker": "MSFT", "shares": 1, "avg_cost": 1, "notes": "Cloud"}
+ )
+ client.put("/api/portfolio", json={"ticker": "OLD", "shares": 1, "avg_cost": 1})
+ rows = [{"ticker": "MSFT", "shares": 10, "avg_cost": 300, "currency": "USD"},
+ {"ticker": "COHR", "shares": 2, "avg_cost": 207.27, "currency": "USD"}] # fmt: skip
+ r = client.post("/api/portfolio/import/commit", json={"rows": rows, "mode": "replace"})
+ assert r.json() == {"ok": True, "imported": 2, "mode": "replace"}
+ positions = {p["ticker"]: p for p in client.get("/api/portfolio").json()["positions"]}
+ assert set(positions) == {"MSFT", "COHR"} # OLD removed by "replace"
+ assert positions["MSFT"]["shares"] == 10 and positions["MSFT"]["notes"] == "Cloud"
+ # COHR was never opened: sector comes from the light company-info fetch after import
+ assert positions["COHR"]["sector"] == "Technology"
+ assert ("basics", "COHR") in fake_yahoo.calls
+ assert ("basics", "MSFT") not in fake_yahoo.calls # had a snapshot already
+
+
+def test_commit_merge_adds_and_updates(client):
+ client.put("/api/portfolio", json={"ticker": "MSFT", "shares": 1, "avg_cost": 1})
+ client.put("/api/portfolio", json={"ticker": "AAPL", "shares": 3, "avg_cost": 100})
+ rows = [
+ {"ticker": "MSFT", "shares": 10, "avg_cost": 300},
+ {"ticker": "COHR", "shares": 2, "avg_cost": 200},
+ ]
+ client.post("/api/portfolio/import/commit", json={"rows": rows, "mode": "merge"})
+ shares = {p["ticker"]: p["shares"] for p in client.get("/api/portfolio").json()["positions"]}
+ assert shares == {"MSFT": 10, "AAPL": 3, "COHR": 2}
+
+
+def test_commit_validation(client):
+ bad = {"rows": [{"ticker": "MSFT", "shares": 0, "avg_cost": 1}], "mode": "replace"}
+ assert client.post("/api/portfolio/import/commit", json=bad).status_code == 422
+ assert (
+ client.post(
+ "/api/portfolio/import/commit", json={"rows": [], "mode": "replace"}
+ ).status_code
+ == 422
+ )
+
+
+def test_portfolio_load_fills_missing_company_info(client, fake_yahoo):
+ from watchstock import store
+
+ store.holding_upsert("COHR", 2, 200, "USD", "") # e.g. app closed mid warm-up
+ first = client.get("/api/portfolio").json()
+ assert first["info_pending"] == 1
+ second = client.get("/api/portfolio").json() # background task ran after the first
+ assert second["info_pending"] == 0 and second["positions"][0]["sector"] == "Technology"
+
+
+def test_failed_company_info_is_not_saved(client, fake_yahoo, monkeypatch):
+ from watchstock import store
+ from watchstock.providers import yahoo
+ from watchstock.providers.yahoo import MarketDataError
+
+ def boom(ticker):
+ raise MarketDataError("offline")
+
+ monkeypatch.setattr(yahoo, "fetch_company_basics", boom)
+ store.holding_upsert("COHR", 2, 200, "USD", "")
+ client.get("/api/portfolio")
+ assert store.get_company_info("COHR") is None
diff --git a/uv.lock b/uv.lock
index 8f7c158..8f0941d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1020,7 +1020,7 @@ wheels = [
[[package]]
name = "watchstock"
-version = "0.8.0"
+version = "0.9.0"
source = { editable = "." }
dependencies = [
{ name = "fastapi" },
diff --git a/watchstock/__init__.py b/watchstock/__init__.py
index eced2b9..928d9bf 100644
--- a/watchstock/__init__.py
+++ b/watchstock/__init__.py
@@ -1,3 +1,3 @@
"""WatchStock: personal stock analysis terminal."""
-__version__ = "0.8.0"
+__version__ = "0.9.0"
diff --git a/watchstock/db.py b/watchstock/db.py
index 65eba87..3c33940 100644
--- a/watchstock/db.py
+++ b/watchstock/db.py
@@ -63,6 +63,15 @@
);
CREATE INDEX idx_thesis_ticker ON thesis_checks (ticker, created_at);
""",
+ # 4 — light company facts (sector, country, dividend rate) for positions that were
+ # imported without opening the stock; snapshots take precedence when they exist
+ """
+ CREATE TABLE company_info (
+ ticker TEXT PRIMARY KEY,
+ data TEXT NOT NULL,
+ fetched_at TEXT NOT NULL
+ );
+ """,
]
diff --git a/watchstock/i18n.py b/watchstock/i18n.py
index 5cac6e9..9f6e797 100644
--- a/watchstock/i18n.py
+++ b/watchstock/i18n.py
@@ -140,6 +140,9 @@ def llm_language_instruction() -> str:
"An analyst": "Un analist",
"Insider buy: {who}{amount}": "Cumpărare de insider: {who}{amount}",
"An insider": "Un insider",
+ # ---- import
+ "The file is empty or not a table.": "Fișierul e gol sau nu e un tabel.",
+ "Unrecognised file. Use a Tradeville portfolio export, or a CSV with ticker, shares and avg_cost columns.": "Fișier nerecunoscut. Folosește exportul de portofoliu din Tradeville sau un CSV cu coloanele ticker, shares și avg_cost.",
# ---- services / routes / analysis
"News could not be loaded.": "Știrile nu au putut fi încărcate.",
"Live data unavailable ({err}). Showing the last saved data.": "Datele live nu sunt disponibile ({err}). Se afișează ultimele date salvate.",
diff --git a/watchstock/importers.py b/watchstock/importers.py
new file mode 100644
index 0000000..af5b308
--- /dev/null
+++ b/watchstock/importers.py
@@ -0,0 +1,162 @@
+"""Portfolio file import: Tradeville export, plus a simple generic CSV. Pure parsing.
+
+Tradeville "Portofoliu" export (observed 2026-11-04):
+- first line `SEP=` (an Excel hint), then a tab-separated header
+- `simbol`: market prefix + symbol + optional lowercase venue/class letter,
+ e.g. `US.APLD`, `US.COHRn`, `US.OUSTc`; cash rows are e.g. `USD`
+- `sold` = shares, `costm` = average cost per share, `ppiata` = market price,
+ `valuta` = currency, `nume` = name, `isin`, `market`, `tsim` = `actiuni` (shares) / `bani` (cash)
+- decimal point is `.`
+
+Generic CSV: a header with ticker/symbol, shares/quantity and avg_cost/cost columns,
+comma or semicolon separated. Resolving tickers against Yahoo happens in the route.
+"""
+
+import csv
+import io
+import re
+from typing import Any
+
+
+class ImportError_(ValueError): # noqa: N801 (avoid shadowing the builtin ImportError)
+ """The file couldn't be understood."""
+
+
+def decode(raw: bytes) -> str:
+ for encoding in ("utf-8-sig", "cp1250"): # cp1250: older Romanian Windows exports
+ try:
+ return raw.decode(encoding)
+ except UnicodeDecodeError:
+ continue
+ return raw.decode("latin-1")
+
+
+def parse_number(text: Any) -> float | None:
+ """'1234.56', '1.234,56', '1,234.56', '182,50' -> float."""
+ s = str(text or "").strip().replace(" ", "").replace(" ", "")
+ if not s:
+ return None
+ if "," in s and "." in s:
+ s = (
+ s.replace(".", "").replace(",", ".")
+ if s.rfind(",") > s.rfind(".")
+ else s.replace(",", "")
+ )
+ elif "," in s:
+ s = s.replace(",", ".")
+ try:
+ return float(s)
+ except ValueError:
+ return None
+
+
+# Tradeville market prefix -> Yahoo suffix ("" = US, no suffix).
+_MARKET_SUFFIX = {"US": "", "RO": ".RO", "BVB": ".RO"}
+
+
+def tradeville_to_yahoo(symbol: str, market: str | None = None) -> str:
+ """`US.COHRn` -> `COHR`, `US.BRK.B` -> `BRK-B`, `TLV` (market RO) -> `TLV.RO`."""
+ symbol = symbol.strip()
+ prefix, dot, rest = symbol.partition(".")
+ if dot and prefix.isupper() and 1 < len(prefix) <= 3 and rest:
+ code, base = prefix, rest
+ else:
+ code, base = (market or "").strip().upper(), symbol
+ base = re.sub(r"[a-z]+$", "", base) # venue/class letter: COHRn -> COHR
+ suffix = _MARKET_SUFFIX.get(code)
+ if suffix is None:
+ return base.upper() # unknown market: the ISIN fallback will have to resolve it
+ if suffix == "":
+ return base.upper().replace(".", "-") # Yahoo writes share classes with '-'
+ return base.upper() + suffix
+
+
+def _rows(text: str) -> tuple[list[dict[str, str]], str]:
+ lines = text.lstrip("").splitlines()
+ sep = None
+ if lines and lines[0].upper().startswith("SEP="):
+ sep = lines[0][4:5] or "\t"
+ lines = lines[1:]
+ body = "\n".join(lines)
+ if sep is None:
+ first = lines[0] if lines else ""
+ sep = max(("\t", ";", ","), key=first.count)
+ reader = csv.DictReader(io.StringIO(body), delimiter=sep)
+ rows = [{(k or "").strip().lower(): (v or "").strip() for k, v in r.items()} for r in reader]
+ return rows, sep
+
+
+def _pick(row: dict[str, str], *names: str) -> str:
+ for n in names:
+ if row.get(n):
+ return row[n]
+ return ""
+
+
+def parse(text: str) -> dict[str, Any]:
+ """-> {"format", "rows": [position], "skipped": [{"symbol", "reason"}]}."""
+ rows, _ = _rows(text)
+ if not rows:
+ raise ImportError_("The file is empty or not a table.")
+ headers = set(rows[0])
+ positions: list[dict[str, Any]] = []
+ skipped: list[dict[str, Any]] = []
+
+ if {"simbol", "sold", "costm"} <= headers:
+ fmt = "tradeville"
+ for r in rows:
+ symbol = r.get("simbol", "")
+ if not symbol:
+ continue
+ kind = r.get("tsim", "").lower()
+ if kind and kind != "actiuni":
+ reason = "cash" if kind == "bani" else kind
+ amount = parse_number(r.get("sold"))
+ skipped.append({"symbol": symbol, "reason": reason, "amount": amount,
+ "currency": r.get("valuta")}) # fmt: skip
+ continue
+ positions.append({
+ "source_symbol": symbol,
+ "ticker": tradeville_to_yahoo(symbol, r.get("market")),
+ "name": r.get("nume", ""),
+ "isin": r.get("isin", ""),
+ "shares": parse_number(r.get("sold")),
+ "avg_cost": parse_number(r.get("costm")),
+ "currency": r.get("valuta") or None,
+ "broker_price": parse_number(r.get("ppiata")),
+ }) # fmt: skip
+ else:
+
+ def column(*names: str) -> str | None:
+ return next((c for c in names if c in headers), None)
+
+ ticker_col = column("ticker", "symbol", "simbol")
+ shares_col = column("shares", "quantity", "qty", "sold", "cantitate")
+ cost_col = column("avg_cost", "average_cost", "cost", "avg price", "costm", "pret mediu")
+ if not (ticker_col and shares_col and cost_col):
+ raise ImportError_(
+ "Unrecognised file. Use a Tradeville portfolio export, or a CSV with "
+ "ticker, shares and avg_cost columns."
+ )
+ fmt = "generic"
+ for r in rows:
+ if not r.get(ticker_col):
+ continue
+ positions.append({
+ "source_symbol": r[ticker_col],
+ "ticker": r[ticker_col].strip().upper(),
+ "name": _pick(r, "name", "nume", "company"),
+ "isin": _pick(r, "isin"),
+ "shares": parse_number(r.get(shares_col)),
+ "avg_cost": parse_number(r.get(cost_col)),
+ "currency": _pick(r, "currency", "valuta") or None,
+ "broker_price": None,
+ }) # fmt: skip
+
+ valid = []
+ for p in positions:
+ if not p["shares"] or p["shares"] <= 0 or p["avg_cost"] is None or p["avg_cost"] < 0:
+ skipped.append({"symbol": p["source_symbol"], "reason": "no shares or cost"})
+ else:
+ valid.append(p)
+ return {"format": fmt, "rows": valid, "skipped": skipped}
diff --git a/watchstock/providers/yahoo.py b/watchstock/providers/yahoo.py
index 641ada2..38ed2ba 100644
--- a/watchstock/providers/yahoo.py
+++ b/watchstock/providers/yahoo.py
@@ -250,6 +250,28 @@ def fetch_key_metrics(ticker: str) -> dict[str, Any]:
return out
+def fetch_company_basics(ticker: str) -> dict[str, Any]:
+ """Name, sector, country, currency and dividend rate: one `info` request.
+
+ Used to fill in portfolio allocation for imported positions without fetching the
+ full stock profile (news, ratings, insiders, peers) for every holding.
+ """
+ try:
+ info = yf.Ticker(ticker).info or {}
+ except Exception as exc:
+ raise MarketDataError(f"Yahoo Finance request failed for {ticker}: {exc}") from exc
+ name = info.get("longName") or info.get("shortName")
+ if not name:
+ raise MarketDataError(f"No data found for ticker {ticker!r}")
+ return {
+ "name": name,
+ "sector": info.get("sector"),
+ "country": info.get("country"),
+ "currency": info.get("currency"),
+ "dividend_rate": _clean(info.get("dividendRate")),
+ }
+
+
# ------------------------------------------------------------------- events
diff --git a/watchstock/routes/portfolio.py b/watchstock/routes/portfolio.py
index 72c8e10..96222ac 100644
--- a/watchstock/routes/portfolio.py
+++ b/watchstock/routes/portfolio.py
@@ -1,16 +1,20 @@
"""Portfolio: holdings CRUD and the computed overview."""
import asyncio
-from typing import Any
+import logging
+import threading
+from typing import Any, Literal
-from fastapi import APIRouter, HTTPException
+from fastapi import APIRouter, BackgroundTasks, HTTPException
from pydantic import BaseModel, Field
-from watchstock import analysis, portfolio, services, store
+from watchstock import analysis, importers, portfolio, services, store
from watchstock.i18n import tr
from watchstock.providers import yahoo
+from watchstock.providers.yahoo import MarketDataError
router = APIRouter(prefix="/api/portfolio", tags=["portfolio"])
+log = logging.getLogger(__name__)
class HoldingIn(BaseModel):
@@ -21,17 +25,26 @@ class HoldingIn(BaseModel):
@router.get("")
-async def get_portfolio() -> dict[str, Any]:
+async def get_portfolio(background: BackgroundTasks) -> dict[str, Any]:
holdings = store.holdings_list()
if not holdings:
return portfolio.build_portfolio([], {}, {})
tickers = [h["ticker"] for h in holdings]
quotes = await asyncio.to_thread(yahoo.fetch_quotes, tickers)
- info = {}
+ info, missing = {}, []
for t in tickers:
- snap = store.get_snapshot(t)
- info[t] = portfolio.info_from_snapshot(snap["data"] if snap else None)
+ # Full snapshot when the stock was opened; else light facts saved after an import.
+ if snap := store.get_snapshot(t):
+ info[t] = portfolio.info_from_snapshot(snap["data"])
+ elif basics := store.get_company_info(t):
+ info[t] = basics
+ else:
+ info[t] = {}
+ missing.append(t)
+ if missing: # e.g. the app was closed before the post-import fetch finished
+ background.add_task(_warm_company_info, missing)
result = portfolio.build_portfolio(holdings, quotes, info)
+ result["info_pending"] = len(missing) # the UI re-polls while sector info is loading
for pos in result["positions"]:
check = store.latest_thesis_check(pos["ticker"])
pos["thesis_check"] = (
@@ -72,3 +85,118 @@ async def run_thesis_check(ticker: str) -> dict[str, Any]:
async def delete_holding(ticker: str) -> dict[str, bool]:
store.holding_delete(services.normalize_ticker(ticker))
return {"ok": True}
+
+
+# ------------------------------------------------------------------- import
+
+
+class ImportPreviewIn(BaseModel):
+ content: str = Field(min_length=1, max_length=2_000_000)
+ # The user's corrections from the preview: file symbol -> ticker to use instead.
+ overrides: dict[str, str] = Field(default_factory=dict, max_length=500)
+
+
+def _resolve(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Check each ticker with one cheap quote lookup; fall back to the ISIN via Yahoo search."""
+ quotes = yahoo.fetch_quotes(sorted({r["ticker"] for r in rows}))
+ taken = {r["ticker"] for r in rows}
+ for r in rows:
+ if q := quotes.get(r["ticker"]):
+ r.update(status="ok", price=q["price"])
+ continue
+ r.update(status="not_found", price=None)
+ if not r.get("isin"):
+ continue
+ try:
+ hits = yahoo.search(r["isin"], limit=3)
+ except MarketDataError:
+ hits = []
+ for hit in hits:
+ if hit["ticker"] in taken: # never turn one position into a duplicate of another
+ continue
+ if q := yahoo.fetch_quotes([hit["ticker"]]).get(hit["ticker"]):
+ r.update(
+ status="isin",
+ original_ticker=r["ticker"],
+ ticker=hit["ticker"],
+ price=q["price"],
+ )
+ taken.add(hit["ticker"])
+ break
+ return rows
+
+
+@router.post("/import/preview")
+async def import_preview(body: ImportPreviewIn) -> dict[str, Any]:
+ """Parse an uploaded file and check every ticker. Nothing is saved."""
+ try:
+ parsed = importers.parse(body.content)
+ except importers.ImportError_ as exc:
+ raise HTTPException(422, tr(str(exc))) from exc
+ for r in parsed["rows"]:
+ if fixed := body.overrides.get(r["source_symbol"], "").strip():
+ r["ticker"] = services.normalize_ticker(fixed)
+ r["isin"] = "" # the user chose the ticker; don't second-guess it via the ISIN
+ rows = await asyncio.to_thread(_resolve, parsed["rows"])
+ held = {h["ticker"] for h in store.holdings_list()}
+ for r in rows:
+ r["in_portfolio"] = r["ticker"] in held
+ return {
+ "format": parsed["format"],
+ "rows": rows,
+ "skipped": parsed["skipped"],
+ "currently_held": len(held),
+ }
+
+
+class ImportRow(BaseModel):
+ ticker: str = Field(min_length=1, max_length=20)
+ shares: float = Field(gt=0)
+ avg_cost: float = Field(ge=0)
+ currency: str | None = None
+
+
+class ImportCommitIn(BaseModel):
+ rows: list[ImportRow] = Field(min_length=1, max_length=500)
+ mode: Literal["replace", "merge"]
+
+
+_warming = threading.Lock()
+
+
+def _warm_company_info(tickers: list[str]) -> None:
+ """Fetch sector/country/dividend for positions that were never opened, one ticker at a
+ time (kind to Yahoo). Only one warm-up runs at once; failures are retried on a later
+ portfolio load and never saved."""
+ if not _warming.acquire(blocking=False):
+ return
+ try:
+ for t in tickers:
+ if store.get_snapshot(t) or store.get_company_info(t):
+ continue
+ try:
+ store.save_company_info(t, yahoo.fetch_company_basics(t))
+ except MarketDataError as exc:
+ log.warning("company info unavailable for %s: %s", t, exc)
+ finally:
+ _warming.release()
+
+
+@router.post("/import/commit")
+async def import_commit(body: ImportCommitIn, background: BackgroundTasks) -> dict[str, Any]:
+ """Save imported positions. "replace" makes the file the whole portfolio; "merge" adds
+ and updates. "Why I own it" notes of positions that stay are kept either way."""
+ existing = {h["ticker"]: h for h in store.holdings_list()}
+ rows = {}
+ for r in body.rows:
+ t = services.normalize_ticker(r.ticker)
+ notes = existing.get(t, {}).get("notes", "")
+ rows[t] = {"ticker": t, "shares": r.shares, "avg_cost": r.avg_cost,
+ "currency": r.currency, "notes": notes} # fmt: skip
+ if body.mode == "replace":
+ store.replace_holdings(list(rows.values()))
+ else:
+ for r in rows.values():
+ store.holding_upsert(r["ticker"], r["shares"], r["avg_cost"], r["currency"], r["notes"])
+ background.add_task(_warm_company_info, list(rows))
+ return {"ok": True, "imported": len(rows), "mode": body.mode}
diff --git a/watchstock/store.py b/watchstock/store.py
index 5e634cb..9a214b4 100644
--- a/watchstock/store.py
+++ b/watchstock/store.py
@@ -188,3 +188,47 @@ def latest_thesis_check(ticker: str) -> dict[str, Any] | None:
return None
return {**json.loads(row["content"]), "created_at": row["created_at"],
"model": row["model"], "thesis": row["thesis"]} # fmt: skip
+
+
+# ------------------------------------------------------------- company info
+
+
+def get_company_info(ticker: str) -> dict[str, Any] | None:
+ with db.session() as conn:
+ row = conn.execute("SELECT data FROM company_info WHERE ticker = ?", (ticker,)).fetchone()
+ return json.loads(row["data"]) if row else None
+
+
+def save_company_info(ticker: str, data: dict[str, Any]) -> None:
+ with db.session() as conn:
+ conn.execute(
+ "INSERT INTO company_info (ticker, data, fetched_at) VALUES (?, ?, ?) "
+ "ON CONFLICT(ticker) DO UPDATE SET "
+ "data = excluded.data, fetched_at = excluded.fetched_at",
+ (ticker, json.dumps(data, default=str), utcnow_iso()),
+ )
+
+
+def replace_holdings(rows: list[dict[str, Any]]) -> None:
+ """Replace the whole portfolio in one transaction (import with "replace")."""
+ now = utcnow_iso()
+ with db.session() as conn:
+ conn.execute("DELETE FROM holdings")
+ values = [
+ (
+ r["ticker"],
+ r["shares"],
+ r["avg_cost"],
+ r.get("currency"),
+ r.get("notes", ""),
+ now,
+ now,
+ )
+ for r in rows
+ ]
+ conn.executemany(
+ "INSERT INTO holdings "
+ "(ticker, shares, avg_cost, currency, notes, added_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ values,
+ )