# Portfolio

A GNOME stock portfolio manager for shares listed on the **New York Stock Exchange**,
**Nasdaq Stockholm** and **Oslo Børs**. Written in Python with GTK 4 and libadwaita.

- Holdings grouped by exchange, each with live price, daily change and an intraday sparkline
- Portfolio total, today's change and total return in NOK, SEK, USD or EUR
- Allocation bar showing how the portfolio splits across the three markets
- Detail view with 1D / 1M / 6M / 1Y / 5Y price charts (hover for values), with your
  average price drawn as a reference line
- Ticker lookup while you type; buying more of a stock you already own merges the lots
  at a share-weighted average price
- Remove with undo, CSV export, automatic refresh every 60 seconds
- Adaptive layout down to 360 px wide (phones)

## Running from source

Requires Python ≥ 3.10, GTK ≥ 4.12, libadwaita ≥ 1.6, PyGObject and pycairo.
libsecret is optional (for storing API keys in the keyring).

```sh
# Fedora
sudo dnf install python3-gobject gtk4 libadwaita python3-cairo libsecret
# Debian / Ubuntu (24.10 or newer)
sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-4.0 gir1.2-adw-1 gir1.2-secret-1

./run
```

## Installing

```sh
meson setup _build --prefix=/usr
meson compile -C _build
meson test -C _build       # data-layer tests + desktop/metainfo validation
sudo meson install -C _build
```

### Flatpak

```sh
flatpak-builder --user --install --force-clean _flatpak \
    build-aux/flatpak/org.gnome.PortfolioManager.json
flatpak run org.gnome.PortfolioManager
```

## Entering tickers

| Exchange          | Type             | Examples                  | Currency |
|-------------------|------------------|---------------------------|----------|
| NYSE              | the plain ticker | `KO`, `JPM`, `BRK-B`      | USD      |
| Nasdaq Stockholm  | the ticker       | `VOLV-B`, `ERIC B`, `ATCO-A` | SEK   |
| Oslo Børs         | the ticker       | `EQNR`, `DNB`, `NHY`      | NOK      |

Spaces and dots in share classes are normalised (`volv b` → `VOLV-B`). Typing a Yahoo
suffix (`EQNR.OL`, `ERIC-B.ST`) switches to the matching exchange. A NYSE lookup that turns
out to be listed on Nasdaq (e.g. `AAPL`) is rejected, so each group only holds stocks from
that market. NYSE Arca and NYSE American listings are accepted under NYSE.

## Data sources

Since Yahoo! closed its official Finance API in 2017, every free source is a trade-off.
Portfolio makes the source pluggable and is honest in the UI about how fresh a price is.

| Source | Key | Markets | History | FX | Free-plan limits |
|---|---|---|---|---|---|
| Yahoo! Finance (default) | none | NYSE, Stockholm, Oslo | 1D–5Y | yes | undocumented endpoint, can change or rate-limit anytime |
| Alpha Vantage | free | NYSE | 1M–5Y (daily/weekly) | yes | 25 requests/day; unlimited for verified open-source projects |
| Finnhub | free | NYSE | — | — | 60 requests/min; international data and candles are paid |
| Stooq (experimental) | captcha-issued | NYSE | 1M–5Y (daily) | yes | key required since March 2026; a June 2026 bot check may block automated access |

Choose the primary source in **Preferences → Data Sources**. With **Use Other Sources as
Fallback** on, a stock is fetched from the primary first, then from any other source that has
a key and covers its market. None of the alternatives is verified to cover Oslo or Stockholm on
a free plan, so if Yahoo! is unavailable, Nordic stocks show their saved prices.

API keys are stored in the GNOME keyring through libsecret (the Secret portal under Flatpak).
Without libsecret they go into the settings file, which is written with mode 0600.

### Adding a source

Subclass `providers.base.Provider`, declare `markets`, `supports_history`, `supports_fx`,
`delay_minutes`, `daily_limit` and `min_quote_age`, implement `quote()` (and `history()` /
`fx_rate()` if supported), raise `RateLimited` for limits and `NotSupported` for gaps, and add
the class to `PROVIDER_CLASSES` in `providers/__init__.py`. Preferences, fallback, cooldowns
and budgets pick it up automatically. `tests/test_providers.py` shows a scriptable fake.

## Freshness, errors and rate limits

- The header shows **Delayed · Updated 22:14**; each stock's detail shows the last trade time,
  delay, source and when it was fetched. Exports include source and price time.
- Every price and exchange rate is saved to `$XDG_CACHE_HOME/gnome-portfolio/quotes.json`, so the
  app opens with the last known values, even offline, marked **Saved prices** until refreshed.
- If a source fails, holdings keep their saved price (dimmed, with a clock icon and the time),
  and a banner explains why, with a **Retry** button.
- A rate-limited source cools down using its `Retry-After`, or exponential backoff from 1 to
  30 minutes; automatic refresh retries when the cooldown ends. Sources with a daily quota
  (Alpha Vantage) count their requests and reuse recent quotes to spread them over the day.

## Storage

The portfolio is stored as JSON in `$XDG_DATA_HOME/gnome-portfolio/portfolio.json`
(normally `~/.local/share/gnome-portfolio/`). A corrupt file is moved aside to
`portfolio.json.corrupt` rather than overwritten.

**Import from CSV** reads Portfolio's own export, or any CSV with `Symbol` and `Shares`
columns (`Exchange`, `Average Price`, `Name` and `Currency` are optional; Yahoo-style
suffixes like `EQNR.OL` identify the market). Positions already held can be replaced or added to.

Total return is calculated in each stock's own currency and converted at today's rate —
historical exchange rates at purchase time aren't tracked. An average price more than 20×
away from the market price gets a warning, as it is usually a typo or the wrong currency.

## Keyboard shortcuts

| Shortcut              | Action        |
|-----------------------|---------------|
| Ctrl+N                | Add stock     |
| Ctrl+R / F5           | Refresh       |
| Ctrl+O                | Import CSV    |
| Ctrl+E                | Export CSV    |
| Ctrl+,                | Preferences   |
| Ctrl+W / Ctrl+Q       | Close / Quit  |

## Layout

```
gnome_portfolio/
  main.py        Adw.Application, actions, About dialog
  window.py      main window, banner, summary card, position rows, CSV import/export
  dialogs.py     add/edit dialog with live lookup, position detail dialog
  preferences.py general settings, data sources and API keys
  chart.py       price chart, sparkline, allocation bar (cairo)
  quotes.py      fetching service: fallback chain, cooldowns, budgets, stale tracking
  providers/     yahoo, alphavantage, finnhub, stooq — one module per source
  cache.py       saved quotes, rates and request budgets
  keystore.py    API keys in the keyring (libsecret) with a file fallback
  model.py       holdings, JSON storage, valuation, CSV import, price sanity check
  exchanges.py   NYSE / Stockholm / Oslo definitions and ticker normalisation
  formatting.py  locale-aware numbers; parses "1 234,50" and "1,234.50"
tests/test_data.py, tests/test_providers.py
```

## Notes

- `org.gnome.PortfolioManager` is used as the application ID. Publishing on Flathub under
  `org.gnome.*` requires the app to be accepted as a GNOME project; otherwise switch to an
  ID on a domain you control (e.g. `io.github.<user>.Portfolio`) in `meson.build`,
  `data/`, `main.py` and the Flatpak manifest.
- Strings are wrapped in `gettext` and ready for a `po/` directory.
- This is a tracking tool, not investment advice.

License: GPL-3.0-or-later
