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 docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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

Expand Down
14 changes: 14 additions & 0 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
33 changes: 22 additions & 11 deletions docs/HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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.
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.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"
Expand Down
12 changes: 10 additions & 2 deletions scripts/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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

Expand Down
31 changes: 31 additions & 0 deletions scripts/ui_smoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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"]');
Expand Down
7 changes: 7 additions & 0 deletions static/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
31 changes: 31 additions & 0 deletions static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
<span style="font-size:0.7rem; letter-spacing:1.5px; color:var(--text-muted);">MY PORTFOLIO</span>
<div style="display:flex; gap:8px; align-items:center;">
<button onclick="loadPortfolio()" title="Refresh prices" style="background:transparent; border:none; color:#666; cursor:pointer; font-size:0.85rem; padding:0 4px;">↻</button>
<button id="btnImport" onclick="openImportModal()" title="Load positions from a Tradeville export or a CSV file" style="background:transparent; border:1px solid #444; color:#aaa; padding:4px 10px; font-size:0.65rem; font-weight:700; letter-spacing:1px; cursor:pointer;">IMPORT</button>
<button id="btnAddHolding" onclick="openHoldingModal()" style="background:transparent; border:1px solid var(--accent); color:var(--accent); padding:4px 10px; font-size:0.65rem; font-weight:700; letter-spacing:1px; cursor:pointer;">+ ADD POSITION</button>
</div>
</div>
Expand Down Expand Up @@ -543,6 +544,35 @@ <h3 id="holdingModalTitle" style="font-size:0.75rem; font-weight:700; color:#fff
</div>
</div>

<!-- Import positions from a file (static/js/import.js) -->
<div id="importModal" style="display:none; position:fixed; inset:0; z-index:2000; background:rgba(0,0,0,0.75); backdrop-filter:blur(4px); align-items:center; justify-content:center;">
<div style="background:#1a1a1a; border:1px solid #333; width:820px; max-width:94vw; max-height:90vh; display:flex; flex-direction:column;">
<div style="padding:16px 20px; border-bottom:1px solid #333; display:flex; justify-content:space-between; align-items:center;">
<h3 style="font-size:0.75rem; font-weight:700; color:#fff; letter-spacing:2px; margin:0; text-transform:uppercase;">Import positions</h3>
<button onclick="closeImportModal()" style="color:#666; font-size:1.1rem; background:none; border:none; cursor:pointer; padding:4px; line-height:1;">✕</button>
</div>
<div style="padding:20px 24px; overflow-y:auto;">
<div id="importPick">
<ol style="margin:0 0 16px 18px; padding:0; font-size:0.75rem; color:#bbb; line-height:1.7; list-style:decimal;">
<li>In Tradeville, open your portfolio and export it to a file.</li>
<li>Pick that file below. You will see a preview first; nothing is saved until you confirm.</li>
</ol>
<label class="imp-file">
<input id="importFile" type="file" accept=".csv,.txt,.tsv,text/csv,text/plain" onchange="onImportFile(this)" style="display:none;">
<span>CHOOSE FILE</span>
</label>
<div style="font-size:0.62rem; color:#555; margin-top:10px;">Any CSV with ticker, shares and avg_cost columns works too.</div>
</div>
<div id="importPreview" style="display:none;"></div>
<div id="importError" style="display:none; color:#ff6b6b; font-size:0.72rem; margin-top:10px;"></div>
</div>
<div style="padding:14px 24px; border-top:1px solid #333; display:flex; justify-content:flex-end; gap:10px;">
<button onclick="closeImportModal()" style="background:transparent; border:1px solid #333; color:#666; padding:8px 18px; font-size:0.7rem; letter-spacing:1px; cursor:pointer;">CANCEL</button>
<button id="btnCommitImport" onclick="commitImport()" disabled style="background:var(--accent); border:none; color:#fff; padding:8px 20px; font-size:0.7rem; font-weight:700; letter-spacing:1px; cursor:pointer; opacity:0.4;">IMPORT</button>
</div>
</div>
</div>

<!-- Score Breakdown Popover -->
<div id="scoreBreakdownPopover" style="display:none; position:fixed; z-index:3000; background:#1e1e1e; border:1px solid #444; padding:16px; width:290px; box-shadow:0 8px 32px rgba(0,0,0,0.7); pointer-events:all;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; border-bottom:1px solid #333; padding-bottom:10px;">
Expand Down Expand Up @@ -573,6 +603,7 @@ <h3 id="scoreModalTitle" style="font-size:1rem; font-weight:700; color:#fff; let
<script src="/static/js/settings.js"></script>
<script src="/static/js/home.js"></script>
<script src="/static/js/portfolio.js"></script>
<script src="/static/js/import.js"></script>
<script src="/static/js/today.js"></script>
<script src="/static/js/dashboard.js"></script>
<script src="/static/js/analysis.js"></script>
Expand Down
Loading
Loading