Value positions from a daily price feed
A position was a share count. An instrument now carries a market symbol and the last close fetched for it, so Wealth and the dashboard report cash plus market value instead of cash alone. The symbol is chosen by hand and never derived: one ISIN lists on several exchanges in different currencies, and a price from the wrong listing misstates wealth without failing any check. The refresh refuses a quote whose currency differs from the instrument's, keeps the previous quote when a symbol cannot be priced, and counts an instrument with no symbol as unpriced - naming it in a check and leaving it out of every total, because cost is not value. The quote belongs to the job: saving an instrument can neither set nor erase it, and changing the symbol discards it. Two things the provider forced. It answers HTTP 429 to every request whose User-Agent names a programming language, so the client identifies as a browser; without that header the first call of the day fails. Its closes are 32-bit floats widened to 64 - 165.26 arrives as 165.25999450683594 - so a figure is rounded to seven significant digits, which is what 24 mantissa bits carry; eight would have stored 165.25999 as a price. Accepted quotes are written in one commit against a revision re-read after the fetches, and nothing is committed when no quote changed. The automatic run starts shortly after launch and repeats daily on its own timer, so a sync backoff cannot delay it and prices arrive with no bank connected. Verified against live quotes end to end: 80 shares at 125.45 and 40 at 165.26 on 6000.00 cash report 22646.40 with one holding named as unpriced; giving that holding a symbol through the UI moves the figure to 23530.50, and a second refresh leaves the revision untouched.
This commit is contained in:
+49
-9
@@ -497,6 +497,45 @@ instrument that already exists. The name is editable display text; the ISIN is
|
|||||||
identity and cannot be changed. Crypto is held under the ISIN-shaped identifier
|
identity and cannot be changed. Crypto is held under the ISIN-shaped identifier
|
||||||
the broker issues for it, so it needs no separate identity scheme.
|
the broker issues for it, so it needs no separate identity scheme.
|
||||||
|
|
||||||
|
Market prices and valuation
|
||||||
|
---------------------------
|
||||||
|
An instrument carries an optional market symbol, which is the listing its price
|
||||||
|
is read from, and the last quote fetched for it with the day that quote closed.
|
||||||
|
The symbol is set by hand and never derived: one ISIN lists on several exchanges
|
||||||
|
in different currencies, an ISIN search returns the wrong one often enough to
|
||||||
|
matter, and a price from the wrong listing misstates wealth without failing any
|
||||||
|
check. A quote whose currency differs from the instrument's is refused and not
|
||||||
|
stored.
|
||||||
|
|
||||||
|
The quote belongs to the price job. Saving an instrument can neither set it nor
|
||||||
|
erase it; changing the symbol discards it, because the stored price belongs to
|
||||||
|
the previous listing. A symbol that cannot be priced keeps its last quote and is
|
||||||
|
reported as a failure, so the failure mode is a stale figure with a visible
|
||||||
|
date, never a wrong one. An instrument with no symbol is counted as unpriced,
|
||||||
|
named in the report, and excluded from every total: cost is not value, and
|
||||||
|
substituting it would report a number the journal cannot support.
|
||||||
|
|
||||||
|
A quote is a rate, not money: money holds four decimal places, while a unit
|
||||||
|
price can need more. Quotes are therefore stored at the share count's eight-
|
||||||
|
place precision, and a provider figure is rounded to seven significant digits
|
||||||
|
before it is stored. Seven is what a 32-bit float carries, and the provider's
|
||||||
|
closes are 32-bit floats widened to 64: 165.26 arrives as 165.25999450683594,
|
||||||
|
and rounding at eight would preserve 165.25999 as though it were a price.
|
||||||
|
|
||||||
|
The provider is an undocumented, unauthenticated endpoint, and it refuses any
|
||||||
|
request whose User-Agent names a programming language, so the client sends a
|
||||||
|
browser agent; without it every fetch answers HTTP 429 on the first call. Runs
|
||||||
|
are paced, fetches are bounded and never follow redirects, and no response text
|
||||||
|
reaches an error message. The automatic run starts shortly after launch and
|
||||||
|
repeats daily. Nothing is committed when no quote changed.
|
||||||
|
|
||||||
|
A holding's value is its share count times its quote, rounded half away from
|
||||||
|
zero to money's four places. Positions is that value summed per account, wealth
|
||||||
|
is cash plus positions, and result is value plus everything the position
|
||||||
|
returned less everything put into it - the outcome to date, realised and not.
|
||||||
|
None of these figures are read from the DuckDB index: the report is recomputed
|
||||||
|
from the journal so it can be checked against a broker's own screen.
|
||||||
|
|
||||||
A broker reuses one reference across every leg of an economic event: the cash
|
A broker reuses one reference across every leg of an economic event: the cash
|
||||||
and position sides of a corporate action arrive with the same reference byte for
|
and position sides of a corporate action arrive with the same reference byte for
|
||||||
byte, and the position leg's zero amount does not even differ in direction.
|
byte, and the position leg's zero amount does not even differ in direction.
|
||||||
@@ -589,13 +628,14 @@ does not.
|
|||||||
Checks that fail mean the journal disagrees with itself: row arithmetic, cash
|
Checks that fail mean the journal disagrees with itself: row arithmetic, cash
|
||||||
never negative, holdings never negative. A negative holding means a position was
|
never negative, holdings never negative. A negative holding means a position was
|
||||||
closed that was never opened in the imported data, so the export is partial or a
|
closed that was never opened in the imported data, so the export is partial or a
|
||||||
sign is wrong. Checks that only note: fee and tax recorded but not applied, and
|
sign is wrong. Checks that only note: fee and tax recorded but not applied,
|
||||||
deposits or withdrawals with no counterpart in another account.
|
deposits or withdrawals with no counterpart in another account, and holdings
|
||||||
|
left out of the wealth figure for want of a quote.
|
||||||
|
|
||||||
Out of scope, deliberately: market prices, market value, net worth over time,
|
Out of scope, deliberately: intraday prices, net worth over time, FIFO lot
|
||||||
FIFO lot accounting, realised gains, Vorabpauschale, and currency conversion. A
|
accounting, realised gains, Vorabpauschale, and currency conversion. A position's
|
||||||
position's "invested" figure is cash in less cash out, not a cost basis: a depot
|
"invested" figure is cash in less cash out, not a cost basis: a depot transfer
|
||||||
transfer moves a position with no cash at all, and a sale returns cash without
|
moves a position with no cash at all, and a sale returns cash without
|
||||||
identifying which lot it closed.
|
identifying which lot it closed.
|
||||||
|
|
||||||
Canonical files and recovery
|
Canonical files and recovery
|
||||||
@@ -696,9 +736,9 @@ Boundaries and verification
|
|||||||
---------------------------
|
---------------------------
|
||||||
There are no splits, budgets, tax/invoice/receipt processing, login/multi-user
|
There are no splits, budgets, tax/invoice/receipt processing, login/multi-user
|
||||||
support, arbitrary SQL or natural-language query execution. Investment support
|
support, arbitrary SQL or natural-language query execution. Investment support
|
||||||
covers positions and cash, not valuation: no market prices, market value,
|
covers positions, cash and a daily closing price per instrument: no intraday
|
||||||
net worth over time, FIFO lots, realised gains, Vorabpauschale or currency
|
prices, net worth over time, FIFO lots, realised gains, Vorabpauschale or
|
||||||
conversion.
|
currency conversion.
|
||||||
Natural-language query DSL and Sankey exploration remain explicitly later work.
|
Natural-language query DSL and Sankey exploration remain explicitly later work.
|
||||||
There is no browser-to-bank credential handling or payment initiation.
|
There is no browser-to-bank credential handling or payment initiation.
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
A self-hosted personal finance dashboard with a **Go backend**, **React frontend**, and **DuckDB analytics**. Human-readable `.finance` journals are the source of truth; DuckDB is a disposable index.
|
A self-hosted personal finance dashboard with a **Go backend**, **React frontend**, and **DuckDB analytics**. Human-readable `.finance` journals are the source of truth; DuckDB is a disposable index.
|
||||||
|
|
||||||
Imported bank facts are separate from editable merchant, category, and tag classifications. N26, ING, Kontist, Scalable Capital, and Trade Republic CSV imports and bank synchronization work without AI. An investment account tracks positions by ISIN alongside its cash, and reconciles both against your broker's own figures. Optional OpenRouter enrichment sends the transaction date, signed amount, currency, merchant/counterparty text, and a complete registry of editable classification choices through restrictive private routing.
|
Imported bank facts are separate from editable merchant, category, and tag classifications. N26, ING, Kontist, Scalable Capital, and Trade Republic CSV imports and bank synchronization work without AI. An investment account tracks positions by ISIN alongside its cash, values them from a daily price feed that needs no key, and reconciles both against your broker's own figures. Optional OpenRouter enrichment sends the transaction date, signed amount, currency, merchant/counterparty text, and a complete registry of editable classification choices through restrictive private routing.
|
||||||
|
|
||||||
> **There is no application login.** Keep Finance Duck behind your VPN. The default service and Docker Compose port bindings are loopback-only. Setting a hostname does not provide authentication or firewall protection.
|
> **There is no application login.** Keep Finance Duck behind your VPN. The default service and Docker Compose port bindings are loopback-only. Setting a hostname does not provide authentication or firewall protection.
|
||||||
|
|
||||||
@@ -206,9 +206,21 @@ Only `Executed` rows import from Scalable: a cancelled retry is all zeros, so it
|
|||||||
|
|
||||||
Securities are registered by **ISIN** in **Instruments**. The ISIN is the identity; the name is editable display text, because one ISIN appears under several broker names over the years. Crypto is held under the ISIN-shaped identifier the broker issues for it. Set the account's **settlement IBAN** for an export that names no counterparty of its own, so deposits from your bank pair with the funding account instead of staying unpaired. They never become income either way — a broker record is excluded from spending and income analytics, from bulk reclassification, and from the AI entirely.
|
Securities are registered by **ISIN** in **Instruments**. The ISIN is the identity; the name is editable display text, because one ISIN appears under several broker names over the years. Crypto is held under the ISIN-shaped identifier the broker issues for it. Set the account's **settlement IBAN** for an export that names no counterparty of its own, so deposits from your bank pair with the funding account instead of staying unpaired. They never become income either way — a broker record is excluded from spending and income analytics, from bulk reclassification, and from the AI entirely.
|
||||||
|
|
||||||
**Verify it yourself.** **Wealth** shows each account's cash balance, its positions as exact share counts, and named checks — row arithmetic, cash never negative, holdings never negative. Compare the cash balance and the positions against your broker's own screen. The figures come from the journal, not from the DuckDB index, so they do not depend on the cache that the same journal derives. A negative holding means the imported history is partial: a position was closed that was never opened.
|
## Value what you hold
|
||||||
|
|
||||||
Deliberately **not** included: market prices, market value, net worth over time, FIFO lot accounting, realised gains, `Vorabpauschale`, and currency conversion. A position's *invested* figure is cash in less cash out, not a cost basis.
|
Positions are share counts until they have a price. Give an instrument a **market symbol** in **Instruments** — `EUNL.DE`, `VWCE.DE` — and a daily job fetches its last close, so **Wealth** and the dashboard report cash **plus** market value.
|
||||||
|
|
||||||
|
One ISIN lists on several exchanges in different currencies, and the wrong listing misstates your wealth, so the symbol is chosen once by hand and confirmed by the app: a quote whose currency differs from the instrument's is **refused, not stored**. The price provider is a public, unauthenticated endpoint, and no key is needed.
|
||||||
|
|
||||||
|
- An instrument with **no symbol** is counted as unpriced, named in a check, and left out of the total. Valuing it at cost would report a number the journal cannot support.
|
||||||
|
- A symbol that fails to price **keeps its last quote** rather than losing it; every figure carries the day it is from, so the failure mode is stale, never wrong.
|
||||||
|
- Changing a symbol **discards the old quote**: a price from the previous listing values the holding on the wrong market.
|
||||||
|
- **Refresh prices** on the Wealth page runs the job immediately and reports what it did. Quotes are journal entries like everything else, so a backup restores them.
|
||||||
|
- A quote is rounded to seven significant digits, which is what a 32-bit float carries: the provider returns `165.26` as `165.25999450683594`, and keeping the eighth digit would print that noise as a price.
|
||||||
|
|
||||||
|
**Verify it yourself.** **Wealth** shows each account's cash, its positions as exact share counts, each holding's quote, value and result, and named checks — row arithmetic, cash never negative, holdings never negative, holdings priced. Compare the cash balance and the positions against your broker's own screen. The figures come from the journal, not from the DuckDB index, so they do not depend on the cache that the same journal derives. A negative holding means the imported history is partial: a position was closed that was never opened.
|
||||||
|
|
||||||
|
Deliberately **not** included: intraday prices, net worth over time, FIFO lot accounting, realised gains, `Vorabpauschale`, and currency conversion. A position's *invested* figure is cash in less cash out, not a cost basis, and *result* is value plus everything returned less everything put in — the outcome to date, not a taxable gain.
|
||||||
|
|
||||||
## Deployment options
|
## Deployment options
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import (
|
|||||||
"finance-duck/internal/classification"
|
"finance-duck/internal/classification"
|
||||||
"finance-duck/internal/domain"
|
"finance-duck/internal/domain"
|
||||||
"finance-duck/internal/journal"
|
"finance-duck/internal/journal"
|
||||||
|
"finance-duck/internal/quotes"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Settings holds preferences only, never credentials. ClassifyOnImport controls
|
// Settings holds preferences only, never credentials. ClassifyOnImport controls
|
||||||
@@ -77,6 +78,9 @@ type App struct {
|
|||||||
authStates map[string]authorization
|
authStates map[string]authorization
|
||||||
callbackURL string
|
callbackURL string
|
||||||
bankingSettings bankingSettings
|
bankingSettings bankingSettings
|
||||||
|
// quotes needs no configuration: it reads a public endpoint, so its zero
|
||||||
|
// value is the working client and tests replace it with a stub.
|
||||||
|
quotes quotes.Client
|
||||||
syncRequested chan struct{}
|
syncRequested chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -77,6 +77,12 @@ func SaveInstrument(d *domain.Dataset, v domain.Instrument) error {
|
|||||||
v.Name = strings.TrimSpace(v.Name)
|
v.Name = strings.TrimSpace(v.Name)
|
||||||
v.ISIN = strings.ToUpper(strings.Join(strings.Fields(v.ISIN), ""))
|
v.ISIN = strings.ToUpper(strings.Join(strings.Fields(v.ISIN), ""))
|
||||||
v.Currency = strings.ToUpper(strings.TrimSpace(v.Currency))
|
v.Currency = strings.ToUpper(strings.TrimSpace(v.Currency))
|
||||||
|
v.Symbol = strings.TrimSpace(v.Symbol)
|
||||||
|
// A quote belongs to the price job: this endpoint can neither set one nor
|
||||||
|
// erase one. Changing the symbol does discard it, because a price from the
|
||||||
|
// previous listing values the holding on the wrong market, and sometimes in
|
||||||
|
// the wrong currency.
|
||||||
|
v.Quote, v.QuotedAt = "", ""
|
||||||
if v.ID == "" {
|
if v.ID == "" {
|
||||||
if !domain.ValidISIN(v.ISIN) {
|
if !domain.ValidISIN(v.ISIN) {
|
||||||
return errors.New("an instrument needs a valid ISIN")
|
return errors.New("an instrument needs a valid ISIN")
|
||||||
@@ -88,6 +94,9 @@ func SaveInstrument(d *domain.Dataset, v domain.Instrument) error {
|
|||||||
if x.ISIN != v.ISIN {
|
if x.ISIN != v.ISIN {
|
||||||
return errors.New("an instrument's ISIN is its identity; register the other security separately")
|
return errors.New("an instrument's ISIN is its identity; register the other security separately")
|
||||||
}
|
}
|
||||||
|
if x.Symbol == v.Symbol {
|
||||||
|
v.Quote, v.QuotedAt = x.Quote, x.QuotedAt
|
||||||
|
}
|
||||||
d.Instruments[i] = v
|
d.Instruments[i] = v
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"finance-duck/internal/domain"
|
||||||
|
"finance-duck/internal/quotes"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QuoteFailure names one instrument the price job could not value, with the
|
||||||
|
// provider's already sanitized reason. It carries the ISIN as well as the ID
|
||||||
|
// because the person reading a failed refresh recognises the security by its
|
||||||
|
// ISIN, not by a registry identifier.
|
||||||
|
type QuoteFailure struct {
|
||||||
|
InstrumentID string `json:"instrument_id"`
|
||||||
|
ISIN string `json:"isin"`
|
||||||
|
Symbol string `json:"symbol"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QuoteResult is the outcome of one refresh. Every instrument is accounted for
|
||||||
|
// exactly once, so Updated, Unchanged, Skipped and the failures add up to the
|
||||||
|
// number of instruments in the journal and a partial run is visibly partial.
|
||||||
|
type QuoteResult struct {
|
||||||
|
Updated int `json:"updated"`
|
||||||
|
Unchanged int `json:"unchanged"`
|
||||||
|
Skipped int `json:"skipped"`
|
||||||
|
Failures []QuoteFailure `json:"failures"`
|
||||||
|
State State `json:"state"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// quoteInterval is how often prices refresh on their own. The provider
|
||||||
|
// publishes one close per day, so asking more often only spends requests.
|
||||||
|
const quoteInterval = 24 * time.Hour
|
||||||
|
|
||||||
|
// quotePace spaces provider calls. The chart endpoint is public and
|
||||||
|
// unauthenticated, and a household portfolio of a few dozen symbols still
|
||||||
|
// finishes in seconds at this rate while staying far below the burst at which
|
||||||
|
// the provider starts refusing.
|
||||||
|
const quotePace = 250 * time.Millisecond
|
||||||
|
|
||||||
|
// quoteStartup delays the first automatic refresh past start, so a restart
|
||||||
|
// never fetches while the journal is still being read and a rebuild is running.
|
||||||
|
const quoteStartup = 30 * time.Second
|
||||||
|
|
||||||
|
// RefreshQuotes fetches the latest close for every instrument that names a
|
||||||
|
// market symbol and writes the accepted ones to the journal in a single
|
||||||
|
// commit. One instrument's failure is recorded and the run continues: a
|
||||||
|
// delisted or mistyped symbol must not stop the rest of the portfolio from
|
||||||
|
// being valued.
|
||||||
|
func (a *App) RefreshQuotes(ctx context.Context) (QuoteResult, error) {
|
||||||
|
s, err := a.Snapshot(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return QuoteResult{}, err
|
||||||
|
}
|
||||||
|
result := QuoteResult{Failures: []QuoteFailure{}}
|
||||||
|
accepted := make(map[string]quotes.Quote)
|
||||||
|
fetched := 0
|
||||||
|
for _, instrument := range s.Data.Instruments {
|
||||||
|
if instrument.Symbol == "" {
|
||||||
|
result.Skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err = paceQuote(ctx, fetched); err != nil {
|
||||||
|
return QuoteResult{}, err
|
||||||
|
}
|
||||||
|
fetched++
|
||||||
|
fail := func(reason string) {
|
||||||
|
result.Failures = append(result.Failures, QuoteFailure{InstrumentID: instrument.ID, ISIN: instrument.ISIN, Symbol: instrument.Symbol, Error: reason})
|
||||||
|
}
|
||||||
|
quote, e := a.quotes.Latest(ctx, instrument.Symbol)
|
||||||
|
if e != nil {
|
||||||
|
// A shutdown cancels the fetch too, and recording that as this
|
||||||
|
// instrument's fault would fill the report with failures that say
|
||||||
|
// nothing about the symbols.
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return QuoteResult{}, ctx.Err()
|
||||||
|
}
|
||||||
|
fail(e.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// One ISIN is listed on several exchanges in different currencies, and
|
||||||
|
// a symbol can be resolved to the wrong listing. Storing a price in a
|
||||||
|
// currency the holding is not denominated in would misstate wealth
|
||||||
|
// silently, so a disagreement is a failure and never a write.
|
||||||
|
if !strings.EqualFold(quote.Currency, instrument.Currency) {
|
||||||
|
fail(fmt.Sprintf("quoted in %s but the instrument is held in %s", quote.Currency, instrument.Currency))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
units, e := quote.Price.Units()
|
||||||
|
if e != nil {
|
||||||
|
fail(e.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if units <= 0 {
|
||||||
|
fail("quoted price is not positive")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// An empty stored quote fails to parse, which is exactly the "not the
|
||||||
|
// same value" answer wanted here.
|
||||||
|
if current, e := instrument.Quote.Units(); e == nil && current == units && instrument.QuotedAt == quote.Day {
|
||||||
|
result.Unchanged++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
accepted[instrument.ID] = quote
|
||||||
|
}
|
||||||
|
if len(accepted) == 0 {
|
||||||
|
result.State = s
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
// The fetches took time, so the journal may have moved on underneath this
|
||||||
|
// run; re-read it and match by instrument ID rather than by position.
|
||||||
|
if s, err = a.Snapshot(ctx); err != nil {
|
||||||
|
return QuoteResult{}, err
|
||||||
|
}
|
||||||
|
s, err = a.Mutate(ctx, s.Revision, func(d *domain.Dataset) error {
|
||||||
|
for i := range d.Instruments {
|
||||||
|
quote, ok := accepted[d.Instruments[i].ID]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
d.Instruments[i].Quote = quote.Price
|
||||||
|
d.Instruments[i].QuotedAt = quote.Day
|
||||||
|
result.Updated++
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return QuoteResult{}, err
|
||||||
|
}
|
||||||
|
result.State = s
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// paceQuote waits out the spacing between provider calls and is where a run
|
||||||
|
// notices that it has been canceled: nothing has been written yet at this
|
||||||
|
// point, so abandoning the run here costs only the fetches already made.
|
||||||
|
func paceQuote(ctx context.Context, fetched int) error {
|
||||||
|
if fetched == 0 {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-time.After(quotePace):
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"finance-duck/internal/domain"
|
||||||
|
"finance-duck/internal/quotes"
|
||||||
|
)
|
||||||
|
|
||||||
|
// chartResponse is the provider's payload for one symbol. The trailing null
|
||||||
|
// close is what the endpoint really returns for a day that has not settled
|
||||||
|
// yet, so the price below belongs to the first timestamp, 2025-09-09.
|
||||||
|
func chartResponse(currency string, price float64) string {
|
||||||
|
return fmt.Sprintf(`{"chart":{"result":[{"meta":{"currency":%q},"timestamp":[1757376000,1757462400],"indicators":{"quote":[{"close":[%g,null]}]}}],"error":null}}`, currency, price)
|
||||||
|
}
|
||||||
|
|
||||||
|
func quoteStub(t *testing.T) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch path.Base(r.URL.Path) {
|
||||||
|
case "VWCE.DE":
|
||||||
|
fmt.Fprint(w, chartResponse("EUR", 128.42))
|
||||||
|
case "VUSA.AS":
|
||||||
|
// The same fund also lists in dollars; resolving a symbol to that
|
||||||
|
// listing must not value a euro holding.
|
||||||
|
fmt.Fprint(w, chartResponse("USD", 95.5))
|
||||||
|
case "BROKEN.DE":
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
case "SAP.DE":
|
||||||
|
fmt.Fprint(w, chartResponse("EUR", 210.5))
|
||||||
|
default:
|
||||||
|
t.Errorf("unexpected request for %q", r.URL.Path)
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedInstruments(t *testing.T, a *App, s State) State {
|
||||||
|
t.Helper()
|
||||||
|
s, err := a.Mutate(context.Background(), s.Revision, func(d *domain.Dataset) error {
|
||||||
|
for _, v := range []struct{ isin, name, symbol string }{
|
||||||
|
{"IE00BK5BQT80", "FTSE All-World", "VWCE.DE"},
|
||||||
|
{"IE00B3XXRP09", "S&P 500", "VUSA.AS"},
|
||||||
|
{"US0378331005", "Apple", ""},
|
||||||
|
{"LU0908500753", "Stoxx 600", "BROKEN.DE"},
|
||||||
|
{"DE0007164600", "SAP", "SAP.DE"},
|
||||||
|
} {
|
||||||
|
instrument := domain.Instrument{ID: domain.InstrumentID(v.isin), ISIN: v.isin, Name: v.name, Currency: "EUR", Symbol: v.symbol}
|
||||||
|
if v.symbol == "BROKEN.DE" {
|
||||||
|
instrument.Quote, instrument.QuotedAt = "42.5", "2025-09-01"
|
||||||
|
}
|
||||||
|
d.Instruments = append(d.Instruments, instrument)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// A refresh values what it can and reports the rest: a wrong-currency listing
|
||||||
|
// is the dangerous case, because writing it would misstate wealth without any
|
||||||
|
// visible error.
|
||||||
|
func TestRefreshQuotesWritesOnlyMatchingCurrenciesAndOutlivesOneFailure(t *testing.T) {
|
||||||
|
a, s := testApp(t)
|
||||||
|
stub := quoteStub(t)
|
||||||
|
defer stub.Close()
|
||||||
|
a.quotes = quotes.Client{BaseURL: stub.URL}
|
||||||
|
s = seedInstruments(t, a, s)
|
||||||
|
result, err := a.RefreshQuotes(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Updated != 2 || result.Unchanged != 0 || result.Skipped != 1 || len(result.Failures) != 2 {
|
||||||
|
t.Fatalf("unexpected tally: updated %d unchanged %d skipped %d failures %+v", result.Updated, result.Unchanged, result.Skipped, result.Failures)
|
||||||
|
}
|
||||||
|
fresh, err := a.Snapshot(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
held := map[string]domain.Instrument{}
|
||||||
|
for _, v := range fresh.Data.Instruments {
|
||||||
|
held[v.ISIN] = v
|
||||||
|
}
|
||||||
|
if got := held["IE00BK5BQT80"]; got.Quote != "128.42" || got.QuotedAt != "2025-09-09" {
|
||||||
|
t.Fatalf("accepted quote not journaled: %+v", got)
|
||||||
|
}
|
||||||
|
if got := held["IE00B3XXRP09"]; got.Quote != "" || got.QuotedAt != "" {
|
||||||
|
t.Fatalf("a dollar quote was written onto a euro holding: %+v", got)
|
||||||
|
}
|
||||||
|
if got := held["LU0908500753"]; got.Quote != "42.5" || got.QuotedAt != "2025-09-01" {
|
||||||
|
t.Fatalf("a failed fetch overwrote a good quote: %+v", got)
|
||||||
|
}
|
||||||
|
if got := held["DE0007164600"]; got.Quote != "210.5" || got.QuotedAt != "2025-09-09" {
|
||||||
|
t.Fatalf("an earlier failure stopped a later instrument: %+v", got)
|
||||||
|
}
|
||||||
|
failures := map[string]QuoteFailure{}
|
||||||
|
for _, f := range result.Failures {
|
||||||
|
failures[f.ISIN] = f
|
||||||
|
}
|
||||||
|
mismatch, ok := failures["IE00B3XXRP09"]
|
||||||
|
if !ok || mismatch.Symbol != "VUSA.AS" || !strings.Contains(mismatch.Error, "USD") || !strings.Contains(mismatch.Error, "EUR") {
|
||||||
|
t.Fatalf("currency mismatch not reported usefully: %+v", result.Failures)
|
||||||
|
}
|
||||||
|
if _, ok = failures["LU0908500753"]; !ok {
|
||||||
|
t.Fatalf("a provider failure went unreported: %+v", result.Failures)
|
||||||
|
}
|
||||||
|
if _, ok = failures["US0378331005"]; ok {
|
||||||
|
t.Fatalf("an instrument without a symbol must be skipped, not failed: %+v", result.Failures)
|
||||||
|
}
|
||||||
|
// A second run finds the same closes and must leave the journal alone: a
|
||||||
|
// commit per refresh would grow the journal by a revision a day for nothing.
|
||||||
|
again, err := a.RefreshQuotes(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if again.Updated != 0 || again.Unchanged != 2 {
|
||||||
|
t.Fatalf("repeated refresh rewrote unchanged quotes: updated %d unchanged %d", again.Updated, again.Unchanged)
|
||||||
|
}
|
||||||
|
if again.State.Revision != fresh.Revision {
|
||||||
|
t.Fatalf("repeated refresh committed a new revision %q after %q", again.State.Revision, fresh.Revision)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancellation must be observed between instruments so a shutdown mid-refresh
|
||||||
|
// leaves the journal exactly as it was.
|
||||||
|
func TestRefreshQuotesStopsOnCanceledContextWithoutWriting(t *testing.T) {
|
||||||
|
a, s := testApp(t)
|
||||||
|
stub := quoteStub(t)
|
||||||
|
defer stub.Close()
|
||||||
|
a.quotes = quotes.Client{BaseURL: stub.URL}
|
||||||
|
s = seedInstruments(t, a, s)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if _, err := a.RefreshQuotes(ctx); err == nil {
|
||||||
|
t.Fatal("a canceled refresh must report the cancellation")
|
||||||
|
}
|
||||||
|
fresh, err := a.Snapshot(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fresh.Revision != s.Revision {
|
||||||
|
t.Fatalf("a canceled refresh committed %q over %q", fresh.Revision, s.Revision)
|
||||||
|
}
|
||||||
|
}
|
||||||
+151
-11
@@ -15,13 +15,21 @@ import (
|
|||||||
// same journal derives.
|
// same journal derives.
|
||||||
type Wealth struct {
|
type Wealth struct {
|
||||||
Accounts []WealthAccount `json:"accounts"`
|
Accounts []WealthAccount `json:"accounts"`
|
||||||
// Totals is cash summed per currency across every account.
|
// Totals is cash, position value and their sum per currency, across every
|
||||||
|
// account.
|
||||||
Totals []WealthTotal `json:"totals"`
|
Totals []WealthTotal `json:"totals"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type WealthTotal struct {
|
type WealthTotal struct {
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency"`
|
||||||
Cash domain.Money `json:"cash"`
|
Cash domain.Money `json:"cash"`
|
||||||
|
// Positions is the market value of every priced holding, and Wealth the
|
||||||
|
// two together. Holdings with no quote are excluded from both and counted
|
||||||
|
// in Unpriced, because valuing them at cost would report a number the
|
||||||
|
// journal cannot support.
|
||||||
|
Positions domain.Money `json:"positions"`
|
||||||
|
Wealth domain.Money `json:"wealth"`
|
||||||
|
Unpriced int `json:"unpriced"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// WealthAccount is one account's position as the journal records it.
|
// WealthAccount is one account's position as the journal records it.
|
||||||
@@ -39,10 +47,46 @@ type WealthAccount struct {
|
|||||||
// balance only when the journal holds that account's complete history,
|
// balance only when the journal holds that account's complete history,
|
||||||
// which a broker export does and a date-windowed bank statement does not.
|
// which a broker export does and a date-windowed bank statement does not.
|
||||||
Cash domain.Money `json:"cash"`
|
Cash domain.Money `json:"cash"`
|
||||||
|
// Positions is the market value of every priced holding, and Wealth the two
|
||||||
|
// together: the number this page exists to show. Unpriced counts the
|
||||||
|
// holdings left out because no quote is known for them.
|
||||||
|
Positions domain.Money `json:"positions"`
|
||||||
|
Wealth domain.Money `json:"wealth"`
|
||||||
|
Unpriced int `json:"unpriced"`
|
||||||
|
// Flows is that balance grouped by what moved it, so a total that
|
||||||
|
// disagrees with a broker's own figure localises to one class of row
|
||||||
|
// instead of to the whole history.
|
||||||
|
Flows []WealthFlow `json:"flows"`
|
||||||
Holdings []WealthHolding `json:"holdings"`
|
Holdings []WealthHolding `json:"holdings"`
|
||||||
Checks []WealthCheck `json:"checks"`
|
Checks []WealthCheck `json:"checks"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WealthFlow is the cash one kind of record moved, and how many of them there
|
||||||
|
// were. The sum of every flow is the account's balance.
|
||||||
|
type WealthFlow struct {
|
||||||
|
Event string `json:"event"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Cash domain.Money `json:"cash"`
|
||||||
|
Records int `json:"records"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// flowLabels names each kind of movement in the order a statement reads, so
|
||||||
|
// the breakdown is comparable line by line against a broker's own screen.
|
||||||
|
var flowLabels = []struct{ event, label string }{
|
||||||
|
{domain.EventDeposit, "Deposits"},
|
||||||
|
{domain.EventWithdrawal, "Withdrawals"},
|
||||||
|
{domain.EventFee, "Broker fees"},
|
||||||
|
{domain.EventInterest, "Interest"},
|
||||||
|
{domain.EventTaxSettlement, "Tax settlements"},
|
||||||
|
{domain.EventDistribution, "Distributions"},
|
||||||
|
{domain.EventBuy, "Purchases"},
|
||||||
|
{domain.EventSell, "Sales"},
|
||||||
|
{domain.EventReinvest, "Reinvestments"},
|
||||||
|
{domain.EventCorporateAction, "Corporate actions"},
|
||||||
|
{domain.EventPositionTransfer, "Depot transfers"},
|
||||||
|
{"bank", "Rows from other sources"},
|
||||||
|
}
|
||||||
|
|
||||||
// WealthHolding is one instrument's position in one account.
|
// WealthHolding is one instrument's position in one account.
|
||||||
type WealthHolding struct {
|
type WealthHolding struct {
|
||||||
InstrumentID string `json:"instrument_id"`
|
InstrumentID string `json:"instrument_id"`
|
||||||
@@ -56,6 +100,16 @@ type WealthHolding struct {
|
|||||||
// Received is cash this instrument paid out without moving the position:
|
// Received is cash this instrument paid out without moving the position:
|
||||||
// distributions, and the cash side of a corporate action.
|
// distributions, and the cash side of a corporate action.
|
||||||
Received domain.Money `json:"received"`
|
Received domain.Money `json:"received"`
|
||||||
|
// Quote is the last known unit price and QuotedAt the day it is from.
|
||||||
|
// Value is the holding at that price. Priced is false when no quote is
|
||||||
|
// known, and then Value is absent rather than guessed from cost.
|
||||||
|
Quote domain.Quantity `json:"quote,omitempty"`
|
||||||
|
QuotedAt string `json:"quoted_at,omitempty"`
|
||||||
|
Value domain.Money `json:"value,omitempty"`
|
||||||
|
Priced bool `json:"priced"`
|
||||||
|
// Result is the value now plus every euro this position returned, less
|
||||||
|
// every euro put into it: the total outcome to date, realised and not.
|
||||||
|
Result domain.Money `json:"result,omitempty"`
|
||||||
Records int `json:"records"`
|
Records int `json:"records"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,6 +152,10 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
return strings.Compare(x.Facts.ID, y.Facts.ID)
|
return strings.Compare(x.Facts.ID, y.Facts.ID)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
type flowState struct {
|
||||||
|
cash int64
|
||||||
|
records int
|
||||||
|
}
|
||||||
type holdingState struct {
|
type holdingState struct {
|
||||||
units, invested, received int64
|
units, invested, received int64
|
||||||
records int
|
records int
|
||||||
@@ -107,10 +165,12 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
type accountState struct {
|
type accountState struct {
|
||||||
cash, lowestCash int64
|
cash, lowestCash int64
|
||||||
lowestCashDate string
|
lowestCashDate string
|
||||||
|
day string
|
||||||
records int
|
records int
|
||||||
first, last string
|
first, last string
|
||||||
holdings map[string]*holdingState
|
holdings map[string]*holdingState
|
||||||
order []string
|
order []string
|
||||||
|
flows map[string]*flowState
|
||||||
broken []string
|
broken []string
|
||||||
unappliedFee, unappliedTax int64
|
unappliedFee, unappliedTax int64
|
||||||
unappliedRows int
|
unappliedRows int
|
||||||
@@ -119,14 +179,34 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
states := map[string]*accountState{}
|
states := map[string]*accountState{}
|
||||||
state := func(id string) *accountState {
|
state := func(id string) *accountState {
|
||||||
if states[id] == nil {
|
if states[id] == nil {
|
||||||
states[id] = &accountState{holdings: map[string]*holdingState{}}
|
states[id] = &accountState{holdings: map[string]*holdingState{}, flows: map[string]*flowState{}}
|
||||||
}
|
}
|
||||||
return states[id]
|
return states[id]
|
||||||
}
|
}
|
||||||
|
// A day's rows are applied together before any low-water mark is taken.
|
||||||
|
// Order within a day is not knowable: a broker export states a booking date
|
||||||
|
// and a clock time, the time is local and crosses midnight, so only the
|
||||||
|
// date is imported. A purchase funded by a sale nine seconds earlier then
|
||||||
|
// arrives in an arbitrary order, and checking row by row reports a dip
|
||||||
|
// that never happened.
|
||||||
|
closeDay := func(st *accountState) {
|
||||||
|
if st.cash < st.lowestCash {
|
||||||
|
st.lowestCash, st.lowestCashDate = st.cash, st.day
|
||||||
|
}
|
||||||
|
for _, held := range st.holdings {
|
||||||
|
if held.units < held.lowest {
|
||||||
|
held.lowest, held.lowestDate = held.units, st.day
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, t := range ordered {
|
for _, t := range ordered {
|
||||||
f := t.Facts
|
f := t.Facts
|
||||||
account := accounts[f.AccountID]
|
account := accounts[f.AccountID]
|
||||||
st := state(f.AccountID)
|
st := state(f.AccountID)
|
||||||
|
if st.day != "" && st.day != f.BookingDate {
|
||||||
|
closeDay(st)
|
||||||
|
}
|
||||||
|
st.day = f.BookingDate
|
||||||
st.records++
|
st.records++
|
||||||
if st.first == "" {
|
if st.first == "" {
|
||||||
st.first = f.BookingDate
|
st.first = f.BookingDate
|
||||||
@@ -138,10 +218,16 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
st.cash += minor
|
st.cash += minor
|
||||||
if st.cash < st.lowestCash {
|
|
||||||
st.lowestCash, st.lowestCashDate = st.cash, f.BookingDate
|
|
||||||
}
|
|
||||||
inv := f.Investment
|
inv := f.Investment
|
||||||
|
flow := "bank"
|
||||||
|
if inv != nil {
|
||||||
|
flow = inv.Event
|
||||||
|
}
|
||||||
|
if st.flows[flow] == nil {
|
||||||
|
st.flows[flow] = &flowState{}
|
||||||
|
}
|
||||||
|
st.flows[flow].cash += minor
|
||||||
|
st.flows[flow].records++
|
||||||
if inv == nil {
|
if inv == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -189,13 +275,17 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
held.units += units
|
held.units += units
|
||||||
if held.units < held.lowest {
|
}
|
||||||
held.lowest, held.lowestDate = held.units, f.BookingDate
|
for _, st := range states {
|
||||||
|
if st.day != "" {
|
||||||
|
closeDay(st)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
report := Wealth{Accounts: []WealthAccount{}, Totals: []WealthTotal{}}
|
report := Wealth{Accounts: []WealthAccount{}, Totals: []WealthTotal{}}
|
||||||
totals := map[string]int64{}
|
totals := map[string]int64{}
|
||||||
|
positionTotals := map[string]int64{}
|
||||||
|
unpricedTotals := map[string]int{}
|
||||||
currencies := []string{}
|
currencies := []string{}
|
||||||
for _, account := range data.Accounts {
|
for _, account := range data.Accounts {
|
||||||
st := state(account.ID)
|
st := state(account.ID)
|
||||||
@@ -207,22 +297,62 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
AccountID: account.ID, DisplayName: account.DisplayName, Institution: account.Institution,
|
AccountID: account.ID, DisplayName: account.DisplayName, Institution: account.Institution,
|
||||||
Currency: account.Currency, Kind: kind, Active: account.Active,
|
Currency: account.Currency, Kind: kind, Active: account.Active,
|
||||||
Records: st.records, FirstBooking: st.first, LastBooking: st.last,
|
Records: st.records, FirstBooking: st.first, LastBooking: st.last,
|
||||||
Cash: domain.FormatMoney(st.cash), Holdings: []WealthHolding{}, Checks: []WealthCheck{},
|
Cash: domain.FormatMoney(st.cash), Flows: []WealthFlow{},
|
||||||
|
Holdings: []WealthHolding{}, Checks: []WealthCheck{},
|
||||||
|
}
|
||||||
|
for _, flow := range flowLabels {
|
||||||
|
if moved := st.flows[flow.event]; moved != nil {
|
||||||
|
entry.Flows = append(entry.Flows, WealthFlow{
|
||||||
|
Event: flow.event, Label: flow.label,
|
||||||
|
Cash: domain.FormatMoney(moved.cash), Records: moved.records,
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if _, seen := totals[account.Currency]; !seen {
|
if _, seen := totals[account.Currency]; !seen {
|
||||||
currencies = append(currencies, account.Currency)
|
currencies = append(currencies, account.Currency)
|
||||||
}
|
}
|
||||||
totals[account.Currency] += st.cash
|
totals[account.Currency] += st.cash
|
||||||
|
positions, unpriced, stale := int64(0), 0, []string{}
|
||||||
for _, id := range st.order {
|
for _, id := range st.order {
|
||||||
held := st.holdings[id]
|
held := st.holdings[id]
|
||||||
instrument := instruments[id]
|
instrument := instruments[id]
|
||||||
entry.Holdings = append(entry.Holdings, WealthHolding{
|
holding := WealthHolding{
|
||||||
InstrumentID: id, ISIN: instrument.ISIN, Name: instrument.Name,
|
InstrumentID: id, ISIN: instrument.ISIN, Name: instrument.Name,
|
||||||
Quantity: domain.FormatQuantity(held.units), Invested: domain.FormatMoney(held.invested),
|
Quantity: domain.FormatQuantity(held.units), Invested: domain.FormatMoney(held.invested),
|
||||||
Received: domain.FormatMoney(held.received), Records: held.records,
|
Received: domain.FormatMoney(held.received), Records: held.records,
|
||||||
})
|
}
|
||||||
|
// A closed position needs no quote: nothing multiplied by any price
|
||||||
|
// is nothing, and its result is already settled in cash.
|
||||||
|
quote, err := instrument.Quote.Units()
|
||||||
|
switch {
|
||||||
|
case held.units == 0:
|
||||||
|
holding.Priced, holding.Value = true, domain.FormatMoney(0)
|
||||||
|
case instrument.Quote == "" || err != nil:
|
||||||
|
unpriced++
|
||||||
|
stale = append(stale, instrument.ISIN)
|
||||||
|
default:
|
||||||
|
value, ok := domain.RoundedProduct(held.units, quote)
|
||||||
|
if !ok {
|
||||||
|
unpriced++
|
||||||
|
stale = append(stale, instrument.ISIN)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
holding.Priced = true
|
||||||
|
holding.Quote, holding.QuotedAt = instrument.Quote, instrument.QuotedAt
|
||||||
|
holding.Value = domain.FormatMoney(value)
|
||||||
|
positions += value
|
||||||
|
}
|
||||||
|
if holding.Priced {
|
||||||
|
settled, _ := holding.Value.Minor()
|
||||||
|
holding.Result = domain.FormatMoney(settled - held.invested + held.received)
|
||||||
|
}
|
||||||
|
entry.Holdings = append(entry.Holdings, holding)
|
||||||
}
|
}
|
||||||
slices.SortFunc(entry.Holdings, func(x, y WealthHolding) int { return strings.Compare(x.Name, y.Name) })
|
slices.SortFunc(entry.Holdings, func(x, y WealthHolding) int { return strings.Compare(x.Name, y.Name) })
|
||||||
|
entry.Positions, entry.Unpriced = domain.FormatMoney(positions), unpriced
|
||||||
|
entry.Wealth = domain.FormatMoney(st.cash + positions)
|
||||||
|
positionTotals[account.Currency] += positions
|
||||||
|
unpricedTotals[account.Currency] += unpriced
|
||||||
|
|
||||||
check := func(name, detail string, failed bool) {
|
check := func(name, detail string, failed bool) {
|
||||||
entry.Checks = append(entry.Checks, WealthCheck{Name: name, Detail: detail, Failed: failed})
|
entry.Checks = append(entry.Checks, WealthCheck{Name: name, Detail: detail, Failed: failed})
|
||||||
@@ -254,10 +384,20 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
if st.unmatchedRows > 0 {
|
if st.unmatchedRows > 0 {
|
||||||
check("Deposits and withdrawals unmatched", fmt.Sprintf("%d transfer(s) totalling %s have no counterpart in another account. They stay out of spending either way; set this account's IBAN and settlement IBAN to pair them", st.unmatchedRows, domain.FormatMoney(st.unmatchedCash)), false)
|
check("Deposits and withdrawals unmatched", fmt.Sprintf("%d transfer(s) totalling %s have no counterpart in another account. They stay out of spending either way; set this account's IBAN and settlement IBAN to pair them", st.unmatchedRows, domain.FormatMoney(st.unmatchedCash)), false)
|
||||||
}
|
}
|
||||||
|
if unpriced > 0 {
|
||||||
|
check("Holdings priced", fmt.Sprintf("%d holding(s) have no quote and are left out of the wealth above: %s. Set each one's market symbol in Instruments so the daily price job can quote it; valuing them at cost would report a number the journal cannot support", unpriced, strings.Join(stale, ", ")), false)
|
||||||
|
} else if len(st.order) > 0 {
|
||||||
|
check("Holdings priced", "every open position has a quote, so the wealth above is complete", false)
|
||||||
|
}
|
||||||
report.Accounts = append(report.Accounts, entry)
|
report.Accounts = append(report.Accounts, entry)
|
||||||
}
|
}
|
||||||
for _, currency := range currencies {
|
for _, currency := range currencies {
|
||||||
report.Totals = append(report.Totals, WealthTotal{Currency: currency, Cash: domain.FormatMoney(totals[currency])})
|
report.Totals = append(report.Totals, WealthTotal{
|
||||||
|
Currency: currency, Cash: domain.FormatMoney(totals[currency]),
|
||||||
|
Positions: domain.FormatMoney(positionTotals[currency]),
|
||||||
|
Wealth: domain.FormatMoney(totals[currency] + positionTotals[currency]),
|
||||||
|
Unpriced: unpricedTotals[currency],
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return report
|
return report
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -231,3 +231,153 @@ func TestManualTransferLinkRewritesBothPairsAtOnce(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Order within a day is not knowable. A broker states a booking date and a
|
||||||
|
// local clock time, and only the date is imported, because the time crosses
|
||||||
|
// midnight for part of the year and would move rows to the wrong day. A
|
||||||
|
// purchase funded by a sale nine seconds earlier then arrives in an arbitrary
|
||||||
|
// order, so a balance that never went negative gets reported as if it had.
|
||||||
|
// The balance is therefore only judged where it is observable: at each day's
|
||||||
|
// close.
|
||||||
|
func TestSameDayTradesDoNotReportAnIntradayDip(t *testing.T) {
|
||||||
|
build := func(funded bool) domain.Dataset {
|
||||||
|
data := domain.NewDataset()
|
||||||
|
data.Accounts = []domain.Account{{ID: "broker", DisplayName: "Scalable", Currency: "EUR", Kind: domain.AccountInvestment, Active: true}}
|
||||||
|
data.Instruments = []domain.Instrument{{ID: "ins_world", ISIN: "IE000BI8OT95", Name: "Amundi Core MSCI World (Acc)", Currency: "EUR"}}
|
||||||
|
row := func(id, date, amount string, inv domain.Investment) domain.Transaction {
|
||||||
|
f := domain.Facts{
|
||||||
|
ID: id, Source: "scalable_csv", AccountID: "broker", BookingDate: date,
|
||||||
|
Amount: domain.Money(amount), Currency: "EUR", RawDescription: "Amundi Core MSCI World (Acc)",
|
||||||
|
Fingerprint: id, Investment: &inv,
|
||||||
|
}
|
||||||
|
return domain.Transaction{Facts: f, Enrichment: domain.Fallback(f)}
|
||||||
|
}
|
||||||
|
if funded {
|
||||||
|
data.Transactions = append(data.Transactions, row("tx_0", "2025-12-18", "1000.00", domain.Investment{Event: domain.EventDeposit}))
|
||||||
|
}
|
||||||
|
// tx_a sorts before tx_b, so the purchase is applied first even though
|
||||||
|
// the sale that funded it happened nine seconds earlier.
|
||||||
|
data.Transactions = append(data.Transactions,
|
||||||
|
row("tx_a", "2025-12-19", "-30911.145", domain.Investment{Event: domain.EventBuy, InstrumentID: "ins_world", Quantity: "223", Price: "138.615", Gross: "-30911.145"}),
|
||||||
|
row("tx_b", "2025-12-19", "30619.545", domain.Investment{Event: domain.EventSell, InstrumentID: "ins_world", Quantity: "-223", Price: "138.565", Gross: "30899.995", Tax: "280.45"}),
|
||||||
|
)
|
||||||
|
if err := domain.Validate(data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
funded := WealthOf(build(true)).Accounts[0]
|
||||||
|
for _, check := range funded.Checks {
|
||||||
|
if check.Failed {
|
||||||
|
t.Errorf("a day that closed at %s reported %q: %s", funded.Cash, check.Name, check.Detail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if funded.Cash != "708.40" {
|
||||||
|
t.Errorf("balance %s, want 708.40", funded.Cash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The breakdown accounts for the balance exactly, so a total that
|
||||||
|
// disagrees with a broker's screen points at one class of row.
|
||||||
|
total := int64(0)
|
||||||
|
for _, flow := range funded.Flows {
|
||||||
|
minor, err := flow.Cash.Minor()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
total += minor
|
||||||
|
}
|
||||||
|
if domain.FormatMoney(total) != funded.Cash {
|
||||||
|
t.Errorf("flows sum to %s, balance is %s", domain.FormatMoney(total), funded.Cash)
|
||||||
|
}
|
||||||
|
if len(funded.Flows) != 3 {
|
||||||
|
t.Errorf("expected a line per kind of movement, got %+v", funded.Flows)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A day that really does close negative is still reported.
|
||||||
|
unfunded := WealthOf(build(false)).Accounts[0]
|
||||||
|
found := false
|
||||||
|
for _, check := range unfunded.Checks {
|
||||||
|
if check.Failed && check.Name == "Cash never negative" {
|
||||||
|
found = true
|
||||||
|
if !strings.Contains(check.Detail, "2025-12-19") {
|
||||||
|
t.Errorf("negative close not located: %s", check.Detail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Errorf("a day closing at %s passed: %+v", unfunded.Cash, unfunded.Checks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A page that reports only cash is not reporting wealth. An open position is
|
||||||
|
// valued at its own quote; a closed one needs none; an open one without a quote
|
||||||
|
// is named and left out, because valuing it at cost would report a number the
|
||||||
|
// journal cannot support.
|
||||||
|
func TestWealthValuesHoldingsAtTheirQuote(t *testing.T) {
|
||||||
|
data := domain.NewDataset()
|
||||||
|
data.Accounts = []domain.Account{{ID: "broker", DisplayName: "Scalable", Currency: "EUR", Kind: domain.AccountInvestment, Active: true}}
|
||||||
|
data.Instruments = []domain.Instrument{
|
||||||
|
{ID: "ins_a", ISIN: "IE00B4L5Y983", Name: "Core World", Currency: "EUR", Symbol: "EUNL.DE", Quote: "110.00", QuotedAt: "2026-09-11"},
|
||||||
|
{ID: "ins_b", ISIN: "IE00B1XNHC34", Name: "Clean Energy", Currency: "EUR"},
|
||||||
|
{ID: "ins_c", ISIN: "US67066G1040", Name: "NVIDIA", Currency: "EUR", Symbol: "NVD.DE", Quote: "150.00", QuotedAt: "2026-09-11"},
|
||||||
|
}
|
||||||
|
row := func(id, date, amount string, inv domain.Investment) domain.Transaction {
|
||||||
|
f := domain.Facts{
|
||||||
|
ID: id, Source: "scalable_csv", AccountID: "broker", BookingDate: date,
|
||||||
|
Amount: domain.Money(amount), Currency: "EUR", RawDescription: "row", Fingerprint: id, Investment: &inv,
|
||||||
|
}
|
||||||
|
return domain.Transaction{Facts: f, Enrichment: domain.Fallback(f)}
|
||||||
|
}
|
||||||
|
data.Transactions = []domain.Transaction{
|
||||||
|
row("tx_1", "2026-01-02", "50000.00", domain.Investment{Event: domain.EventDeposit}),
|
||||||
|
row("tx_2", "2026-01-03", "-10000.00", domain.Investment{Event: domain.EventBuy, InstrumentID: "ins_a", Quantity: "100", Price: "100.00", Gross: "-10000.00"}),
|
||||||
|
row("tx_3", "2026-01-04", "-500.00", domain.Investment{Event: domain.EventBuy, InstrumentID: "ins_b", Quantity: "10", Price: "50.00", Gross: "-500.00"}),
|
||||||
|
row("tx_4", "2026-01-05", "-100.00", domain.Investment{Event: domain.EventBuy, InstrumentID: "ins_c", Quantity: "5", Price: "20.00", Gross: "-100.00"}),
|
||||||
|
row("tx_5", "2026-01-06", "125.00", domain.Investment{Event: domain.EventSell, InstrumentID: "ins_c", Quantity: "-5", Price: "25.00", Gross: "125.00"}),
|
||||||
|
}
|
||||||
|
if err := domain.Validate(data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report := WealthOf(data)
|
||||||
|
account := report.Accounts[0]
|
||||||
|
if account.Cash != "39525.00" || account.Positions != "11000.00" || account.Wealth != "50525.00" {
|
||||||
|
t.Fatalf("cash %s, positions %s, wealth %s; want 39525.00, 11000.00, 50525.00", account.Cash, account.Positions, account.Wealth)
|
||||||
|
}
|
||||||
|
if account.Unpriced != 1 {
|
||||||
|
t.Errorf("unpriced holdings %d, want 1", account.Unpriced)
|
||||||
|
}
|
||||||
|
byISIN := map[string]WealthHolding{}
|
||||||
|
for _, h := range account.Holdings {
|
||||||
|
byISIN[h.ISIN] = h
|
||||||
|
}
|
||||||
|
// An open position carries its quote and the day it is from.
|
||||||
|
if open := byISIN["IE00B4L5Y983"]; !open.Priced || open.Value != "11000.00" || open.Result != "1000.00" || open.QuotedAt != "2026-09-11" {
|
||||||
|
t.Errorf("open position valued as %+v", open)
|
||||||
|
}
|
||||||
|
// A position with no quote contributes nothing and says so.
|
||||||
|
if none := byISIN["IE00B1XNHC34"]; none.Priced || none.Value != "" || none.Result != "" {
|
||||||
|
t.Errorf("unquoted position was valued anyway: %+v", none)
|
||||||
|
}
|
||||||
|
// A closed position is worth nothing at any price, and its result is the
|
||||||
|
// cash it settled.
|
||||||
|
if closed := byISIN["US67066G1040"]; !closed.Priced || closed.Value != "0.00" || closed.Result != "25.00" {
|
||||||
|
t.Errorf("closed position valued as %+v", closed)
|
||||||
|
}
|
||||||
|
if total := report.Totals[0]; total.Wealth != "50525.00" || total.Positions != "11000.00" || total.Unpriced != 1 {
|
||||||
|
t.Errorf("totals %+v", total)
|
||||||
|
}
|
||||||
|
// The gap is named rather than hidden in the number.
|
||||||
|
named := false
|
||||||
|
for _, check := range account.Checks {
|
||||||
|
if check.Name == "Holdings priced" {
|
||||||
|
named = true
|
||||||
|
if check.Failed || !strings.Contains(check.Detail, "IE00B1XNHC34") {
|
||||||
|
t.Errorf("unpriced holding not named: %+v", check)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !named {
|
||||||
|
t.Error("no note about the holdings left out of the wealth figure")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -375,8 +375,25 @@ func Validate(d Dataset) error {
|
|||||||
if other, ok := isins[v.ISIN]; ok {
|
if other, ok := isins[v.ISIN]; ok {
|
||||||
return fmt.Errorf("instrument %q: ISIN %s already held by %q", v.ID, v.ISIN, other)
|
return fmt.Errorf("instrument %q: ISIN %s already held by %q", v.ID, v.ISIN, other)
|
||||||
}
|
}
|
||||||
if !nonblank(v.Name) || !currencyPattern.MatchString(v.Currency) {
|
if !nonblank(v.Name) || !currencyPattern.MatchString(v.Currency) || !validText(v.Symbol) {
|
||||||
return fmt.Errorf("instrument %q: valid UTF-8 name and three-letter uppercase currency required", v.ID)
|
return fmt.Errorf("instrument %q: valid UTF-8 name and symbol and three-letter uppercase currency required", v.ID)
|
||||||
|
}
|
||||||
|
// A quote without its day cannot be judged stale, and a day without a
|
||||||
|
// quote values nothing, so neither stands alone.
|
||||||
|
if (v.Quote == "") != (v.QuotedAt == "") {
|
||||||
|
return fmt.Errorf("instrument %q: a quote and the day it is from are recorded together", v.ID)
|
||||||
|
}
|
||||||
|
if v.Quote != "" {
|
||||||
|
units, err := v.Quote.Units()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("instrument %q: %w", v.ID, err)
|
||||||
|
}
|
||||||
|
if units < 0 {
|
||||||
|
return fmt.Errorf("instrument %q: a quote cannot be negative", v.ID)
|
||||||
|
}
|
||||||
|
if !validDate(v.QuotedAt) {
|
||||||
|
return fmt.Errorf("instrument %q: invalid quote date %q", v.ID, v.QuotedAt)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
isins[v.ISIN] = v.ID
|
isins[v.ISIN] = v.ID
|
||||||
instruments[v.ID] = v
|
instruments[v.ID] = v
|
||||||
|
|||||||
@@ -104,6 +104,16 @@ type Instrument struct {
|
|||||||
ISIN string `json:"isin"`
|
ISIN string `json:"isin"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency"`
|
||||||
|
// Symbol is the market listing this security is quoted under. One ISIN maps
|
||||||
|
// to several listings in different currencies, and taking the wrong one
|
||||||
|
// silently misstates wealth, so it is chosen once by hand and never
|
||||||
|
// guessed. Without it the holding stays unpriced.
|
||||||
|
Symbol string `json:"symbol,omitempty"`
|
||||||
|
// Quote is the last known unit price and QuotedAt the day it is from, both
|
||||||
|
// filled by the daily price job and hand-editable. A quote is a rate, not
|
||||||
|
// money: a crypto unit price needs more than money's four places.
|
||||||
|
Quote Quantity `json:"quote,omitempty"`
|
||||||
|
QuotedAt string `json:"quoted_at,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Facts struct {
|
type Facts struct {
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
// Package quotes retrieves daily closing prices for listed instruments so a
|
||||||
|
// holding can be valued without anyone typing a price by hand. Prices enter the
|
||||||
|
// journal as exact decimals: a float would make two runs of the same valuation
|
||||||
|
// disagree in the last cents.
|
||||||
|
package quotes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"finance-duck/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Client fetches the latest close for a market symbol. It holds no mutable
|
||||||
|
// state, so a zero Client is usable and a copy is as good as the original.
|
||||||
|
type Client struct {
|
||||||
|
HTTPClient *http.Client
|
||||||
|
BaseURL string // defaults to https://query1.finance.yahoo.com
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quote is one instrument's latest close. Symbol is the caller's own symbol
|
||||||
|
// rather than the one echoed by the provider, so nothing derived from response
|
||||||
|
// text can end up keyed against an instrument.
|
||||||
|
type Quote struct {
|
||||||
|
Symbol string
|
||||||
|
Price domain.Quantity
|
||||||
|
Currency string
|
||||||
|
Day string // YYYY-MM-DD
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error reports a price lookup that failed for a reason Finance Duck
|
||||||
|
// determined itself: the provider could not be reached, or its response could
|
||||||
|
// not be used. Reason is written here and never taken from provider response
|
||||||
|
// text, so callers may show the whole message to the user. Returning it for
|
||||||
|
// every provider failure lets a caller tell provider trouble apart from a
|
||||||
|
// programming error such as an unusable base URL.
|
||||||
|
type Error struct {
|
||||||
|
Symbol string
|
||||||
|
Reason string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Error) Error() string {
|
||||||
|
if e.Symbol == "" {
|
||||||
|
return "price lookup failed: " + e.Reason
|
||||||
|
}
|
||||||
|
return "price lookup for " + e.Symbol + " failed: " + e.Reason
|
||||||
|
}
|
||||||
|
|
||||||
|
// symbolPattern admits the listing symbols the chart endpoint uses, including
|
||||||
|
// exchange suffixes ("VWCE.DE"), share classes ("BRK-B"), indices ("^GSPC")
|
||||||
|
// and currency pairs ("EURUSD=X"). Anything else is rejected before a request
|
||||||
|
// is built, so no caller-supplied text can reshape the request path.
|
||||||
|
var symbolPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.=^-]{0,31}$`)
|
||||||
|
|
||||||
|
var currencyPattern = regexp.MustCompile(`^[A-Z]{3}$`)
|
||||||
|
|
||||||
|
// defaultTimeout caps a lookup including the response read. A scheduled
|
||||||
|
// refresh walks many instruments, so one unresponsive symbol must not hold the
|
||||||
|
// whole run.
|
||||||
|
const defaultTimeout = 15 * time.Second
|
||||||
|
|
||||||
|
// A version-pinned desktop agent, not a bare "Mozilla/5.0": a real-looking
|
||||||
|
// string is what the endpoint serves, and it carries no identifying data.
|
||||||
|
const userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||||
|
|
||||||
|
// maxResponse bounds the chart response. Five daily candles are a few kilobytes
|
||||||
|
// even with the metadata Yahoo attaches; a megabyte is a decoding accident.
|
||||||
|
const maxResponse = 1 << 20
|
||||||
|
|
||||||
|
// Latest returns the most recent usable close for symbol. A day whose close is
|
||||||
|
// still null (today before the exchange settles, or a holiday) is skipped, so
|
||||||
|
// the five-day window is what makes a Monday morning refresh return Friday's
|
||||||
|
// price instead of nothing.
|
||||||
|
func (c Client) Latest(ctx context.Context, symbol string) (Quote, error) {
|
||||||
|
if !symbolPattern.MatchString(symbol) || strings.Contains(symbol, "..") {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the symbol is not a valid market listing"}
|
||||||
|
}
|
||||||
|
base := strings.TrimRight(c.BaseURL, "/")
|
||||||
|
if base == "" {
|
||||||
|
base = "https://query1.finance.yahoo.com"
|
||||||
|
}
|
||||||
|
endpoint, err := url.Parse(base)
|
||||||
|
if err != nil || endpoint.Host == "" || endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the configured price provider address is invalid"}
|
||||||
|
}
|
||||||
|
// Plain HTTP is allowed only for a loopback stub; a real lookup must not
|
||||||
|
// take prices from an unauthenticated connection.
|
||||||
|
if endpoint.Scheme != "https" && !(endpoint.Scheme == "http" && (endpoint.Hostname() == "localhost" || endpoint.Hostname() == "127.0.0.1" || endpoint.Hostname() == "::1")) {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider address must use HTTPS"}
|
||||||
|
}
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/v8/finance/chart/"+url.PathEscape(symbol)+"?range=5d&interval=1d", nil)
|
||||||
|
if err != nil {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price request could not be created"}
|
||||||
|
}
|
||||||
|
request.Header.Set("Accept", "application/json")
|
||||||
|
// The endpoint answers 429 to every request whose User-Agent names a
|
||||||
|
// programming language, whatever the rate: an empty or Go-default agent is
|
||||||
|
// refused on the first call of the day, a browser agent is served. This is
|
||||||
|
// the price of an unkeyed provider and the only reason a real symbol
|
||||||
|
// resolves at all.
|
||||||
|
request.Header.Set("User-Agent", userAgent)
|
||||||
|
client := http.Client{Timeout: defaultTimeout}
|
||||||
|
if c.HTTPClient != nil {
|
||||||
|
client = *c.HTTPClient
|
||||||
|
if client.Timeout <= 0 {
|
||||||
|
client.Timeout = defaultTimeout
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A redirect to a consent or login page would answer with HTML that only
|
||||||
|
// fails later and less clearly than the redirect status itself.
|
||||||
|
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
// Cancellation and deadlines keep their identity: a caller shutting the
|
||||||
|
// scheduler down must not read that as the provider being broken.
|
||||||
|
if cause := ctx.Err(); cause != nil {
|
||||||
|
return Quote{}, cause
|
||||||
|
}
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider could not be reached"}
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: fmt.Sprintf("the price provider returned HTTP %d", response.StatusCode)}
|
||||||
|
}
|
||||||
|
var envelope struct {
|
||||||
|
Chart struct {
|
||||||
|
Result []struct {
|
||||||
|
Meta struct {
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
} `json:"meta"`
|
||||||
|
Timestamp []int64 `json:"timestamp"`
|
||||||
|
Indicators struct {
|
||||||
|
Quote []struct {
|
||||||
|
// json.Number keeps the provider's own decimal text: the
|
||||||
|
// price must never pass through a float. A null close
|
||||||
|
// decodes as the empty string and means "no trading".
|
||||||
|
Close []json.Number `json:"close"`
|
||||||
|
} `json:"quote"`
|
||||||
|
} `json:"indicators"`
|
||||||
|
} `json:"result"`
|
||||||
|
Error json.RawMessage `json:"error"`
|
||||||
|
} `json:"chart"`
|
||||||
|
}
|
||||||
|
// Unknown keys are tolerated because Yahoo adds metadata freely, but the
|
||||||
|
// fields read below are decoded strictly. The limit bounds the decode
|
||||||
|
// itself, so an oversized response fails as a truncated document.
|
||||||
|
decoder := json.NewDecoder(io.LimitReader(response.Body, maxResponse))
|
||||||
|
if err := decoder.Decode(&envelope); err != nil {
|
||||||
|
if cause := ctx.Err(); cause != nil {
|
||||||
|
return Quote{}, cause
|
||||||
|
}
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider sent a response that could not be read"}
|
||||||
|
}
|
||||||
|
if len(envelope.Chart.Error) > 0 && string(envelope.Chart.Error) != "null" {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider reported an error for this symbol"}
|
||||||
|
}
|
||||||
|
if len(envelope.Chart.Result) == 0 {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider knows no data for this symbol"}
|
||||||
|
}
|
||||||
|
result := envelope.Chart.Result[0]
|
||||||
|
if !currencyPattern.MatchString(result.Meta.Currency) {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider did not report a currency"}
|
||||||
|
}
|
||||||
|
if len(result.Indicators.Quote) == 0 {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider returned no closing prices"}
|
||||||
|
}
|
||||||
|
closes := result.Indicators.Quote[0].Close
|
||||||
|
// Walk backwards for the newest close that actually traded, and keep the
|
||||||
|
// timestamp of that same candle: the day shown must be the day priced.
|
||||||
|
for i := len(closes) - 1; i >= 0; i-- {
|
||||||
|
if closes[i] == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if i >= len(result.Timestamp) || result.Timestamp[i] <= 0 {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider returned a closing price without a date"}
|
||||||
|
}
|
||||||
|
price, err := decimalQuantity(string(closes[i]))
|
||||||
|
if err != nil {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider returned an unusable closing price"}
|
||||||
|
}
|
||||||
|
if units, err := price.Units(); err != nil || units <= 0 {
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider returned a closing price that is not positive"}
|
||||||
|
}
|
||||||
|
return Quote{
|
||||||
|
Symbol: symbol,
|
||||||
|
Price: price,
|
||||||
|
Currency: result.Meta.Currency,
|
||||||
|
Day: time.Unix(result.Timestamp[i], 0).UTC().Format("2006-01-02"),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return Quote{}, Error{Symbol: symbol, Reason: "the price provider returned no closing price for the last five days"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// quantityScale is the journal's eight fractional places, and maxUnitDigits
|
||||||
|
// bounds the scaled result: a price needing more than eight digits before the
|
||||||
|
// point is not a security price, and the bound keeps the value inside the
|
||||||
|
// signed 64-bit units the journal stores.
|
||||||
|
const quantityScale = 8
|
||||||
|
const maxUnitDigits = 8 + quantityScale
|
||||||
|
|
||||||
|
// significantDigits is where a provider price stops being price and starts
|
||||||
|
// being float noise. Yahoo's closes are 32-bit floats widened to 64: a real
|
||||||
|
// response carries 165.26 as "165.25999450683594" and 9.408 as
|
||||||
|
// "9.4079999923706". A 32-bit float holds 24 bits of mantissa, which is 7.22
|
||||||
|
// decimal digits, so the eighth digit onwards is an artefact of the encoding
|
||||||
|
// and never a figure that traded - rounding at eight would keep the visible
|
||||||
|
// nonsense "165.25999". Seven recovers the decimal the exchange published for
|
||||||
|
// every price quoted to cents, which is every equity and fund price, and is
|
||||||
|
// still four orders of magnitude finer than a price needs to value a holding.
|
||||||
|
const significantDigits = 7
|
||||||
|
|
||||||
|
// decimalQuantity converts a provider's decimal literal to the journal's
|
||||||
|
// eight-place scale, working on the digit text so the value never passes
|
||||||
|
// through binary floating point. It rounds to significantDigits and then to
|
||||||
|
// eight fractional places, half rounding away from zero both times. Exponent
|
||||||
|
// notation is rejected rather than guessed at: the endpoint does not use it,
|
||||||
|
// and a price misread by a factor of ten is worse than a failed refresh.
|
||||||
|
func decimalQuantity(text string) (domain.Quantity, error) {
|
||||||
|
invalid := fmt.Errorf("invalid decimal price")
|
||||||
|
negative := strings.HasPrefix(text, "-")
|
||||||
|
literal := strings.TrimPrefix(text, "-")
|
||||||
|
whole, fraction, point := strings.Cut(literal, ".")
|
||||||
|
// A trailing or repeated point, or digits absent on either side, is not a
|
||||||
|
// number this endpoint produces; so is exponent notation, caught by the
|
||||||
|
// digit scan below.
|
||||||
|
if whole == "" || (point && fraction == "") || strings.Contains(fraction, ".") {
|
||||||
|
return "", invalid
|
||||||
|
}
|
||||||
|
digits := whole + fraction
|
||||||
|
for i := range len(digits) {
|
||||||
|
if digits[i] < '0' || digits[i] > '9' {
|
||||||
|
return "", invalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// value holds the significant digits and exponent counts how many of them
|
||||||
|
// stand before the decimal point, so the point can move under rounding
|
||||||
|
// without the digits being re-parsed.
|
||||||
|
value := []byte(strings.TrimLeft(digits, "0"))
|
||||||
|
exponent := len(whole) - (len(digits) - len(value))
|
||||||
|
if len(value) == 0 {
|
||||||
|
return domain.FormatQuantity(0), nil
|
||||||
|
}
|
||||||
|
if len(value) > significantDigits {
|
||||||
|
roundUp := value[significantDigits] >= '5'
|
||||||
|
value = value[:significantDigits]
|
||||||
|
if roundUp {
|
||||||
|
// A carry off the front ("99999999" to "100000000") moves the point.
|
||||||
|
if value = increment(value); len(value) > significantDigits {
|
||||||
|
exponent++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Scale to hundred-millionths: appending zeros multiplies, and dropping
|
||||||
|
// digits divides with the same half-away-from-zero rounding.
|
||||||
|
if shift := exponent - len(value) + quantityScale; shift >= 0 {
|
||||||
|
value = append(value, strings.Repeat("0", shift)...)
|
||||||
|
} else if keep := len(value) + shift; keep < 0 {
|
||||||
|
value = []byte("0")
|
||||||
|
} else {
|
||||||
|
roundUp := value[keep] >= '5'
|
||||||
|
value = value[:keep]
|
||||||
|
if len(value) == 0 {
|
||||||
|
value = []byte("0")
|
||||||
|
}
|
||||||
|
if roundUp {
|
||||||
|
value = increment(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(value) > maxUnitDigits {
|
||||||
|
return "", invalid
|
||||||
|
}
|
||||||
|
units, err := strconv.ParseInt(string(value), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return "", invalid
|
||||||
|
}
|
||||||
|
if negative {
|
||||||
|
units = -units
|
||||||
|
}
|
||||||
|
return domain.FormatQuantity(units), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// increment adds one to a decimal digit string, growing it when the carry runs
|
||||||
|
// off the front ("999" becomes "1000"). Rounding up the last kept place of
|
||||||
|
// 0.99999999|9 has to carry into the whole part, not wrap it.
|
||||||
|
func increment(digits []byte) []byte {
|
||||||
|
for i := len(digits) - 1; i >= 0; i-- {
|
||||||
|
if digits[i] != '9' {
|
||||||
|
digits[i]++
|
||||||
|
return digits
|
||||||
|
}
|
||||||
|
digits[i] = '0'
|
||||||
|
}
|
||||||
|
return append([]byte{'1'}, digits...)
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
package quotes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// secret stands in for anything a provider might put in a response body: no
|
||||||
|
// part of it may reach a message shown to the user.
|
||||||
|
const secret = "SUPER-SECRET-PROVIDER-TEXT"
|
||||||
|
|
||||||
|
func stub(t *testing.T, handler http.HandlerFunc) Client {
|
||||||
|
t.Helper()
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
return Client{BaseURL: server.URL, HTTPClient: server.Client()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func body(payload string) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(payload))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const chartVWCE = `{"chart":{"result":[{"meta":{"currency":"EUR","symbol":"VWCE.DE","exchangeName":"GER"},
|
||||||
|
"timestamp":[1757376000,1757462400],
|
||||||
|
"indicators":{"quote":[{"close":[127.11,128.42],"volume":[1,2]}]}}],"error":null}}`
|
||||||
|
|
||||||
|
func TestLatestReadsLastClose(t *testing.T) {
|
||||||
|
var path, query string
|
||||||
|
client := stub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
path, query = r.URL.Path, r.URL.RawQuery
|
||||||
|
body(chartVWCE)(w, r)
|
||||||
|
})
|
||||||
|
quote, err := client.Latest(context.Background(), "VWCE.DE")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if quote.Symbol != "VWCE.DE" || quote.Price != "128.42" || quote.Currency != "EUR" || quote.Day != "2025-09-10" {
|
||||||
|
t.Fatalf("quote: %+v", quote)
|
||||||
|
}
|
||||||
|
if path != "/v8/finance/chart/VWCE.DE" || query != "range=5d&interval=1d" {
|
||||||
|
t.Fatalf("request: %q %q", path, query)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatestSkipsTrailingNullCloses(t *testing.T) {
|
||||||
|
client := stub(t, body(`{"chart":{"result":[{"meta":{"currency":"EUR"},
|
||||||
|
"timestamp":[1757376000,1757462400,1757548800],
|
||||||
|
"indicators":{"quote":[{"close":[127.11,128.42,null]}]}}],"error":null}}`))
|
||||||
|
quote, err := client.Latest(context.Background(), "VWCE.DE")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// The day must come from the candle that priced, not from the newest one.
|
||||||
|
if quote.Price != "128.42" || quote.Day != "2025-09-10" {
|
||||||
|
t.Fatalf("quote: %+v", quote)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatestReportsForeignCurrency(t *testing.T) {
|
||||||
|
client := stub(t, body(`{"chart":{"result":[{"meta":{"currency":"USD"},
|
||||||
|
"timestamp":[1757376000],"indicators":{"quote":[{"close":[9.4079999923706]}]}}],"error":null}}`))
|
||||||
|
quote, err := client.Latest(context.Background(), "VUSA")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// A foreign currency is the caller's decision to reject, not a fetch failure.
|
||||||
|
if quote.Currency != "USD" || quote.Price != "9.408" {
|
||||||
|
t.Fatalf("quote: %+v", quote)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatestRejectsUnusableResponses(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
handler http.HandlerFunc
|
||||||
|
}{
|
||||||
|
{"every close null", body(`{"chart":{"result":[{"meta":{"currency":"EUR"},
|
||||||
|
"timestamp":[1757376000,1757462400],"indicators":{"quote":[{"close":[null,null]}]}}],"error":null}}`)},
|
||||||
|
{"server failure", func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
_, _ = w.Write([]byte(`{"chart":{"result":null,"error":{"description":"` + secret + `"}}}`))
|
||||||
|
}},
|
||||||
|
{"chart error", body(`{"chart":{"result":null,"error":{"code":"Not Found","description":"` + secret + `"}}}`)},
|
||||||
|
{"empty result", body(`{"chart":{"result":[],"error":null}}`)},
|
||||||
|
{"no currency", body(`{"chart":{"result":[{"meta":{"currency":"eur"},
|
||||||
|
"timestamp":[1757376000],"indicators":{"quote":[{"close":[128.42]}]}}],"error":null}}`)},
|
||||||
|
{"close not positive", body(`{"chart":{"result":[{"meta":{"currency":"EUR"},
|
||||||
|
"timestamp":[1757376000],"indicators":{"quote":[{"close":[0]}]}}],"error":null}}`)},
|
||||||
|
{"close without timestamp", body(`{"chart":{"result":[{"meta":{"currency":"EUR"},
|
||||||
|
"timestamp":[],"indicators":{"quote":[{"close":[128.42]}]}}],"error":null}}`)},
|
||||||
|
{"not json", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("<html>" + secret + "</html>")) }},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
quote, err := stub(t, c.handler).Latest(context.Background(), "VWCE.DE")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected failure, got %+v", quote)
|
||||||
|
}
|
||||||
|
var provider Error
|
||||||
|
if !errors.As(err, &provider) || provider.Symbol != "VWCE.DE" || provider.Reason == "" {
|
||||||
|
t.Fatalf("want typed provider error, got %#v", err)
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), secret) {
|
||||||
|
t.Fatalf("response text leaked into %q", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "VWCE.DE") {
|
||||||
|
t.Fatalf("error must name the symbol: %q", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatestRejectsUnusableSymbolAndAddress(t *testing.T) {
|
||||||
|
client := stub(t, func(http.ResponseWriter, *http.Request) {
|
||||||
|
t.Fatal("no request may be made for a rejected symbol or address")
|
||||||
|
})
|
||||||
|
if _, err := client.Latest(context.Background(), "../secrets"); err == nil {
|
||||||
|
t.Fatal("expected a path-shaping symbol to be rejected")
|
||||||
|
}
|
||||||
|
plain := Client{BaseURL: "http://prices.example.com"}
|
||||||
|
if _, err := plain.Latest(context.Background(), "VWCE.DE"); err == nil {
|
||||||
|
t.Fatal("expected non-loopback plain HTTP to be rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatestKeepsCancellationIdentity(t *testing.T) {
|
||||||
|
client := stub(t, body(chartVWCE))
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if _, err := client.Latest(ctx, "VWCE.DE"); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("want context.Canceled, got %#v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecimalQuantityRoundsHalfAwayFromZero(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
text string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
// Real closes, copied from a live response: every one is a 32-bit float
|
||||||
|
// widened to 64, and the decimal the exchange published has to come
|
||||||
|
// back out of it.
|
||||||
|
{"165.25999450683594", "165.26"},
|
||||||
|
{"125.44999694824219", "125.45"},
|
||||||
|
{"127.1449966430664", "127.145"},
|
||||||
|
{"167.77999877929688", "167.78"},
|
||||||
|
{"0.41578700000001", "0.415787"},
|
||||||
|
{"9.4079999923706", "9.408"},
|
||||||
|
{"-9.4079999923706", "-9.408"},
|
||||||
|
{"128.42", "128.42"},
|
||||||
|
{"0.000000005", "0.00000001"},
|
||||||
|
{"0.000000004", "0"},
|
||||||
|
{"0.999999995", "1"},
|
||||||
|
{"42", "42"},
|
||||||
|
{"0007.5", "7.5"},
|
||||||
|
// Past the seventh digit the provider is describing its own encoding,
|
||||||
|
// so the eighth place moves rather than being preserved.
|
||||||
|
{"12345.678912345", "12345.68"},
|
||||||
|
{"12345678.94999999", "12345680"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
got, err := decimalQuantity(c.text)
|
||||||
|
if err != nil || string(got) != c.want {
|
||||||
|
t.Fatalf("decimalQuantity(%q) = %q, %v; want %q", c.text, got, err, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, text := range []string{"", "-", ".5", "5.", "1.2.3", "1e5", "12e-3", "abc", "1 2", "999999999", "99999999.999999995"} {
|
||||||
|
if got, err := decimalQuantity(text); err == nil {
|
||||||
|
t.Fatalf("decimalQuantity(%q) = %q, want an error", text, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The provider answers 429 to every request whose agent names a programming
|
||||||
|
// language, so a missing or Go-default User-Agent breaks every quote on the
|
||||||
|
// first call rather than under load. The header is load-bearing, not decor.
|
||||||
|
func TestLatestIdentifiesAsABrowser(t *testing.T) {
|
||||||
|
agent := "unset"
|
||||||
|
client := stub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
agent = r.Header.Get("User-Agent")
|
||||||
|
body(chartVWCE)(w, r)
|
||||||
|
})
|
||||||
|
if _, err := client.Latest(context.Background(), "VWCE.DE"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(agent, "Mozilla/") || strings.Contains(agent, "Go-http-client") {
|
||||||
|
t.Fatalf("User-Agent %q is refused by the provider", agent)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ func New(a *app.App, assets fs.FS, publicURL string) (http.Handler, error) {
|
|||||||
s.mux.HandleFunc("POST /api/import/cancel", s.importCancel)
|
s.mux.HandleFunc("POST /api/import/cancel", s.importCancel)
|
||||||
s.mux.HandleFunc("POST /api/backfill", s.backfill)
|
s.mux.HandleFunc("POST /api/backfill", s.backfill)
|
||||||
s.mux.HandleFunc("POST /api/rebuild", func(w http.ResponseWriter, r *http.Request) { v, e := a.Rebuild(r.Context()); respond(w, v, e) })
|
s.mux.HandleFunc("POST /api/rebuild", func(w http.ResponseWriter, r *http.Request) { v, e := a.Rebuild(r.Context()); respond(w, v, e) })
|
||||||
|
s.mux.HandleFunc("POST /api/quotes/refresh", func(w http.ResponseWriter, r *http.Request) { v, e := a.RefreshQuotes(r.Context()); respond(w, v, e) })
|
||||||
s.mux.HandleFunc("POST /api/sync", func(w http.ResponseWriter, r *http.Request) { v, e := a.Sync(s.manualBankContext(r)); respond(w, v, e) })
|
s.mux.HandleFunc("POST /api/sync", func(w http.ResponseWriter, r *http.Request) { v, e := a.Sync(s.manualBankContext(r)); respond(w, v, e) })
|
||||||
s.mux.HandleFunc("POST /api/settings", s.settings)
|
s.mux.HandleFunc("POST /api/settings", s.settings)
|
||||||
s.mux.HandleFunc("POST /api/settings/openrouter", s.openRouterKey)
|
s.mux.HandleFunc("POST /api/settings/openrouter", s.openRouterKey)
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import type {
|
|||||||
Group,
|
Group,
|
||||||
MonthlyPoint,
|
MonthlyPoint,
|
||||||
Total,
|
Total,
|
||||||
|
Wealth,
|
||||||
} from "./api";
|
} from "./api";
|
||||||
import { compactMoney, money, request } from "./api";
|
import { compactMoney, money, request } from "./api";
|
||||||
import { Empty, ErrorMessage, Filters } from "./ui";
|
import { Empty, ErrorMessage, Filters } from "./ui";
|
||||||
@@ -394,6 +395,7 @@ export function Overview({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<WealthStrip revision={revision} currency={currency} />
|
||||||
{total ? (
|
{total ? (
|
||||||
<StatStrip
|
<StatStrip
|
||||||
total={total}
|
total={total}
|
||||||
@@ -547,6 +549,91 @@ function Trend({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WealthStrip is what you own, not what you spent: the dashboard's flow figures
|
||||||
|
// come from the analytics index, while this comes from the journal, so it is
|
||||||
|
// fetched separately rather than joined into a filtered query. The filters do
|
||||||
|
// not apply - a balance has no date range.
|
||||||
|
function WealthStrip({
|
||||||
|
revision,
|
||||||
|
currency,
|
||||||
|
}: {
|
||||||
|
revision: string;
|
||||||
|
currency: string;
|
||||||
|
}) {
|
||||||
|
const [wealth, setWealth] = useState<Wealth | null>(null);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
useEffect(() => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
request<Wealth>("/api/wealth", undefined, controller.signal)
|
||||||
|
.then((value) => {
|
||||||
|
for (const account of value.accounts ?? []) account.checks ??= [];
|
||||||
|
setWealth({
|
||||||
|
...value,
|
||||||
|
accounts: value.accounts ?? [],
|
||||||
|
totals: value.totals ?? [],
|
||||||
|
});
|
||||||
|
setError("");
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
if (e.name !== "AbortError") setError(String(e.message || e));
|
||||||
|
});
|
||||||
|
return () => controller.abort();
|
||||||
|
}, [revision]);
|
||||||
|
if (error)
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<div className="panel-heading">
|
||||||
|
<div>
|
||||||
|
<h3>
|
||||||
|
<PiggyBank size={17} />
|
||||||
|
Wealth
|
||||||
|
</h3>
|
||||||
|
<p>Could not be computed: {error}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
if (!wealth || wealth.totals.length === 0) return null;
|
||||||
|
// The selected currency when it has a balance, otherwise the first one: a
|
||||||
|
// figure in the wrong currency is worse than a figure in another tab.
|
||||||
|
const total =
|
||||||
|
wealth.totals.find((t) => t.currency === currency) ?? wealth.totals[0];
|
||||||
|
const positions = wealth.accounts.filter(
|
||||||
|
(account) => account.holdings.length > 0,
|
||||||
|
).length;
|
||||||
|
const failing = wealth.accounts.filter((account) =>
|
||||||
|
account.checks.some((check) => check.failed),
|
||||||
|
).length;
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<div className="panel-heading">
|
||||||
|
<div>
|
||||||
|
<h3>
|
||||||
|
<PiggyBank size={17} />
|
||||||
|
Wealth today
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
{money(total.cash, total.currency)} cash ·{" "}
|
||||||
|
{money(total.positions, total.currency)} in positions across{" "}
|
||||||
|
{positions} investment account
|
||||||
|
{positions === 1 ? "" : "s"}
|
||||||
|
{total.unpriced > 0 &&
|
||||||
|
` · ${total.unpriced} holding${total.unpriced === 1 ? "" : "s"} without a quote, excluded`}
|
||||||
|
{failing > 0 &&
|
||||||
|
` · ${failing} account${failing === 1 ? "" : "s"} disagree with their own records`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="figure">
|
||||||
|
<span className="eyebrow">{total.currency}</span>
|
||||||
|
<span className="large-money money">
|
||||||
|
{money(total.wealth, total.currency)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function StatStrip({
|
function StatStrip({
|
||||||
total,
|
total,
|
||||||
previous,
|
previous,
|
||||||
|
|||||||
+25
-2
@@ -79,7 +79,7 @@ export function Registry({
|
|||||||
use_defaults: false,
|
use_defaults: false,
|
||||||
}
|
}
|
||||||
: entity === "instrument"
|
: entity === "instrument"
|
||||||
? { id: "", isin: "", name: "", currency: "EUR" }
|
? { id: "", isin: "", name: "", currency: "EUR", symbol: "" }
|
||||||
: { id: "", name: "" },
|
: { id: "", name: "" },
|
||||||
);
|
);
|
||||||
const row = (item: Item, depth = 0) => (
|
const row = (item: Item, depth = 0) => (
|
||||||
@@ -114,7 +114,12 @@ export function Registry({
|
|||||||
{"hint" in item && item.hint && <small>{item.hint}</small>}
|
{"hint" in item && item.hint && <small>{item.hint}</small>}
|
||||||
{"isin" in item && (
|
{"isin" in item && (
|
||||||
<small>
|
<small>
|
||||||
{item.isin} · {item.currency}
|
{item.isin} · {item.currency} ·{" "}
|
||||||
|
{item.symbol
|
||||||
|
? item.quote
|
||||||
|
? `${item.symbol} at ${item.quote} on ${item.quoted_at}`
|
||||||
|
: `${item.symbol}, not yet quoted`
|
||||||
|
: "No market symbol, so unpriced"}
|
||||||
</small>
|
</small>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -434,6 +439,7 @@ function RegistryEditor({
|
|||||||
const instrument = "isin" in item ? item : null;
|
const instrument = "isin" in item ? item : null;
|
||||||
const [isin, setIsin] = useState(instrument?.isin || "");
|
const [isin, setIsin] = useState(instrument?.isin || "");
|
||||||
const [currency, setCurrency] = useState(instrument?.currency || "EUR");
|
const [currency, setCurrency] = useState(instrument?.currency || "EUR");
|
||||||
|
const [symbol, setSymbol] = useState(instrument?.symbol || "");
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const descendants = new Set([item.id]);
|
const descendants = new Set([item.id]);
|
||||||
@@ -489,6 +495,7 @@ function RegistryEditor({
|
|||||||
isin: isin.replaceAll(" ", "").toUpperCase(),
|
isin: isin.replaceAll(" ", "").toUpperCase(),
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
currency: currency.toUpperCase(),
|
currency: currency.toUpperCase(),
|
||||||
|
symbol: symbol.trim(),
|
||||||
}
|
}
|
||||||
: { id: item.id, name: name.trim(), hint: hint.trim() };
|
: { id: item.id, name: name.trim(), hint: hint.trim() };
|
||||||
await mutate(
|
await mutate(
|
||||||
@@ -628,6 +635,22 @@ function RegistryEditor({
|
|||||||
onChange={(e) => setCurrency(e.target.value.toUpperCase())}
|
onChange={(e) => setCurrency(e.target.value.toUpperCase())}
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
|
<Field
|
||||||
|
label="Market symbol"
|
||||||
|
hint="The listing the daily price job quotes this security under, for example EUNL.DE. One ISIN lists on several exchanges in different currencies, so the listing has to match the currency above; the wrong one misstates your wealth. Leave it empty and the holding is reported as unpriced rather than guessed at cost."
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
value={symbol}
|
||||||
|
placeholder="Unpriced"
|
||||||
|
onChange={(e) => setSymbol(e.target.value.trim())}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
{instrument?.quote && (
|
||||||
|
<p className="muted">
|
||||||
|
Last quote {instrument.quote} {instrument.currency} from{" "}
|
||||||
|
{instrument.quoted_at}.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
The broker's own description for one ISIN changes over time, so
|
The broker's own description for one ISIN changes over time, so
|
||||||
the name is display text you can correct. Renaming does not
|
the name is display text you can correct. Renaming does not
|
||||||
|
|||||||
+185
-16
@@ -6,7 +6,7 @@ import {
|
|||||||
Landmark,
|
Landmark,
|
||||||
PiggyBank,
|
PiggyBank,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import type { Wealth, WealthAccount } from "./api";
|
import type { QuoteResult, State, Wealth, WealthAccount } from "./api";
|
||||||
import { money, request } from "./api";
|
import { money, request } from "./api";
|
||||||
import { Empty, ErrorMessage } from "./ui";
|
import { Empty, ErrorMessage } from "./ui";
|
||||||
|
|
||||||
@@ -14,11 +14,19 @@ import { Empty, ErrorMessage } from "./ui";
|
|||||||
// never cached: it exists to be compared with a bank or broker's own screen.
|
// never cached: it exists to be compared with a bank or broker's own screen.
|
||||||
// Renaming a security lives in the Instruments registry, beside every other
|
// Renaming a security lives in the Instruments registry, beside every other
|
||||||
// registry entity, rather than being a second editor here.
|
// registry entity, rather than being a second editor here.
|
||||||
export default function WealthPage({ revision }: { revision: string }) {
|
export default function WealthPage({
|
||||||
|
revision,
|
||||||
|
acceptState,
|
||||||
|
}: {
|
||||||
|
revision: string;
|
||||||
|
acceptState: (state: State, message?: string) => void;
|
||||||
|
}) {
|
||||||
const [wealth, setWealth] = useState<Wealth | null>(null);
|
const [wealth, setWealth] = useState<Wealth | null>(null);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [retry, setRetry] = useState(0);
|
const [retry, setRetry] = useState(0);
|
||||||
|
const [pricing, setPricing] = useState(false);
|
||||||
|
const [priced, setPriced] = useState<QuoteResult | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -31,6 +39,7 @@ export default function WealthPage({ revision }: { revision: string }) {
|
|||||||
if (value[key] === null) Object.assign(value, { [key]: [] });
|
if (value[key] === null) Object.assign(value, { [key]: [] });
|
||||||
}
|
}
|
||||||
for (const account of value.accounts) {
|
for (const account of value.accounts) {
|
||||||
|
account.flows ??= [];
|
||||||
account.holdings ??= [];
|
account.holdings ??= [];
|
||||||
account.checks ??= [];
|
account.checks ??= [];
|
||||||
}
|
}
|
||||||
@@ -65,6 +74,35 @@ export default function WealthPage({ revision }: { revision: string }) {
|
|||||||
that decide whether the figures can be trusted.
|
that decide whether the figures can be trusted.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="row-actions">
|
||||||
|
<button
|
||||||
|
className="button secondary"
|
||||||
|
onClick={async () => {
|
||||||
|
setPricing(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
// The run commits quotes to the journal, so the new revision
|
||||||
|
// has to reach the shell: it is what every other page reads,
|
||||||
|
// and what re-runs the report below.
|
||||||
|
const result = await request<QuoteResult>(
|
||||||
|
"/api/quotes/refresh",
|
||||||
|
{ method: "POST" },
|
||||||
|
);
|
||||||
|
setPriced(result);
|
||||||
|
acceptState(
|
||||||
|
result.state,
|
||||||
|
`${result.updated} quote${result.updated === 1 ? "" : "s"} updated`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
setPricing(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={pricing || loading}
|
||||||
|
>
|
||||||
|
{pricing ? "Fetching prices…" : "Refresh prices"}
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
className="button secondary"
|
className="button secondary"
|
||||||
onClick={() => setRetry(retry + 1)}
|
onClick={() => setRetry(retry + 1)}
|
||||||
@@ -73,7 +111,42 @@ export default function WealthPage({ revision }: { revision: string }) {
|
|||||||
Recheck figures
|
Recheck figures
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
<ErrorMessage error={error} />
|
<ErrorMessage error={error} />
|
||||||
|
{priced && (
|
||||||
|
<div
|
||||||
|
className={`alert ${priced.failures.length > 0 ? "warning" : ""}`}
|
||||||
|
role="status"
|
||||||
|
>
|
||||||
|
<CandlestickChart size={19} />
|
||||||
|
<div>
|
||||||
|
<strong>
|
||||||
|
{priced.updated} quote{priced.updated === 1 ? "" : "s"} updated,{" "}
|
||||||
|
{priced.unchanged} already current, {priced.skipped} without a
|
||||||
|
market symbol.
|
||||||
|
</strong>
|
||||||
|
{priced.failures.length > 0 && (
|
||||||
|
<p>
|
||||||
|
{priced.failures.map((failure) => (
|
||||||
|
<span key={failure.instrument_id}>
|
||||||
|
{failure.symbol || failure.isin}: {failure.error}
|
||||||
|
<br />
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
A symbol that cannot be priced keeps its last quote rather than
|
||||||
|
losing it. Correct the symbol in Instruments if the listing is
|
||||||
|
wrong.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{priced.skipped > 0 && priced.failures.length === 0 && (
|
||||||
|
<p>
|
||||||
|
Set a market symbol on each unpriced instrument in Instruments
|
||||||
|
to bring it into the wealth figure.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="loading-block" role="status">
|
<div className="loading-block" role="status">
|
||||||
<span className="spinner" />
|
<span className="spinner" />
|
||||||
@@ -105,26 +178,49 @@ export default function WealthPage({ revision }: { revision: string }) {
|
|||||||
<div>
|
<div>
|
||||||
<h3>
|
<h3>
|
||||||
<PiggyBank size={17} />
|
<PiggyBank size={17} />
|
||||||
Total cash
|
Total wealth
|
||||||
</h3>
|
</h3>
|
||||||
<p>
|
<p>
|
||||||
Every recorded movement summed per currency, across all{" "}
|
Cash plus the market value of every priced holding, per
|
||||||
{wealth.accounts.length} account
|
currency, across all {wealth.accounts.length} account
|
||||||
{wealth.accounts.length === 1 ? "" : "s"}.
|
{wealth.accounts.length === 1 ? "" : "s"}.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className="figure">
|
||||||
<div className="registry">
|
|
||||||
<div className="preview-summary">
|
|
||||||
{wealth.totals.map((total) => (
|
{wealth.totals.map((total) => (
|
||||||
<span key={total.currency}>
|
<span key={total.currency}>
|
||||||
|
<span className="eyebrow">{total.currency}</span>
|
||||||
|
<span className="large-money money">
|
||||||
|
{money(total.wealth, total.currency)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="registry">
|
||||||
|
{wealth.totals.map((total) => (
|
||||||
|
<div className="preview-summary" key={total.currency}>
|
||||||
|
<span>
|
||||||
<strong className="money">
|
<strong className="money">
|
||||||
{money(total.cash, total.currency)}
|
{money(total.cash, total.currency)}
|
||||||
</strong>{" "}
|
</strong>{" "}
|
||||||
in cash
|
in cash
|
||||||
</span>
|
</span>
|
||||||
))}
|
<span>
|
||||||
|
<strong className="money">
|
||||||
|
{money(total.positions, total.currency)}
|
||||||
|
</strong>{" "}
|
||||||
|
in positions
|
||||||
|
</span>
|
||||||
|
{total.unpriced > 0 && (
|
||||||
|
<span>
|
||||||
|
<strong>{total.unpriced}</strong> holding
|
||||||
|
{total.unpriced === 1 ? "" : "s"} without a quote,
|
||||||
|
excluded
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
@@ -219,13 +315,61 @@ function AccountReport({ account }: { account: WealthAccount }) {
|
|||||||
{!account.active && " · archived"}
|
{!account.active && " · archived"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="figure">
|
||||||
<span className="eyebrow">Cash balance</span>
|
<span className="eyebrow">
|
||||||
<span className="large-money money">
|
{investing ? "Cash and positions" : "Cash balance"}
|
||||||
{money(account.cash, account.currency)}
|
|
||||||
</span>
|
</span>
|
||||||
|
<span className="large-money money">
|
||||||
|
{money(account.wealth, account.currency)}
|
||||||
|
</span>
|
||||||
|
{investing && (
|
||||||
|
<small className="muted">
|
||||||
|
{money(account.cash, account.currency)} cash ·{" "}
|
||||||
|
{money(account.positions, account.currency)} positions
|
||||||
|
{account.unpriced > 0 &&
|
||||||
|
` · ${account.unpriced} unpriced, excluded`}
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{(account.flows ?? []).length > 0 && (
|
||||||
|
<div className="table-scroll">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>What moved the cash</th>
|
||||||
|
<th className="numeric">Records</th>
|
||||||
|
<th className="numeric">Cash</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{account.flows.map((flow) => (
|
||||||
|
<tr key={flow.event}>
|
||||||
|
<td>{flow.label}</td>
|
||||||
|
<td className="numeric">{flow.records}</td>
|
||||||
|
<td className="numeric money">
|
||||||
|
{money(flow.cash, account.currency)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<strong>Balance</strong>
|
||||||
|
</td>
|
||||||
|
<td className="numeric">{account.records}</td>
|
||||||
|
<td className="numeric money">
|
||||||
|
<strong>{money(account.cash, account.currency)}</strong>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<p className="hint">
|
||||||
|
Compare each line against your broker’s own screen. A total
|
||||||
|
that disagrees points at one kind of record, not at the whole
|
||||||
|
history.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{account.holdings.length > 0 && (
|
{account.holdings.length > 0 && (
|
||||||
<div className="table-scroll">
|
<div className="table-scroll">
|
||||||
<table>
|
<table>
|
||||||
@@ -234,8 +378,10 @@ function AccountReport({ account }: { account: WealthAccount }) {
|
|||||||
<th>Instrument</th>
|
<th>Instrument</th>
|
||||||
<th>ISIN</th>
|
<th>ISIN</th>
|
||||||
<th className="numeric">Quantity</th>
|
<th className="numeric">Quantity</th>
|
||||||
|
<th className="numeric">Quote</th>
|
||||||
|
<th className="numeric">Value</th>
|
||||||
<th className="numeric">Invested</th>
|
<th className="numeric">Invested</th>
|
||||||
<th className="numeric">Received</th>
|
<th className="numeric">Result</th>
|
||||||
<th className="numeric">Records</th>
|
<th className="numeric">Records</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -263,10 +409,33 @@ function AccountReport({ account }: { account: WealthAccount }) {
|
|||||||
)}
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="numeric money">
|
<td className="numeric money">
|
||||||
{money(holding.invested, account.currency)}
|
{holding.quote ? (
|
||||||
|
<>
|
||||||
|
{holding.quote}
|
||||||
|
<small className="muted">{holding.quoted_at}</small>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="muted">no quote</span>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="numeric money">
|
<td className="numeric money">
|
||||||
{money(holding.received, account.currency)}
|
{holding.priced ? (
|
||||||
|
money(holding.value ?? "0.00", account.currency)
|
||||||
|
) : (
|
||||||
|
<span className="muted">—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="numeric money">
|
||||||
|
{money(holding.invested, account.currency)}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
className={`numeric money ${holding.result?.startsWith("-") ? "text-danger" : holding.priced ? "positive" : ""}`}
|
||||||
|
>
|
||||||
|
{holding.result ? (
|
||||||
|
money(holding.result, account.currency)
|
||||||
|
) : (
|
||||||
|
<span className="muted">—</span>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="numeric">{holding.records}</td>
|
<td className="numeric">{holding.records}</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ export interface Instrument {
|
|||||||
isin: string;
|
isin: string;
|
||||||
name: string;
|
name: string;
|
||||||
currency: string;
|
currency: string;
|
||||||
|
// symbol is the market listing this security is quoted under, chosen once by
|
||||||
|
// hand: one ISIN lists in several currencies and the wrong one misstates
|
||||||
|
// wealth. quote is the last price the daily job fetched for it.
|
||||||
|
symbol?: string;
|
||||||
|
quote?: string;
|
||||||
|
quoted_at?: string;
|
||||||
}
|
}
|
||||||
// Investment is the broker-native leg of a fact. Cash movement always stays in
|
// Investment is the broker-native leg of a fact. Cash movement always stays in
|
||||||
// Facts.amount, so a position-only event carries a zero amount. Quantity is an
|
// Facts.amount, so a position-only event carries a zero amount. Quantity is an
|
||||||
@@ -298,6 +304,15 @@ export interface WealthHolding {
|
|||||||
quantity: string;
|
quantity: string;
|
||||||
invested: string;
|
invested: string;
|
||||||
received: string;
|
received: string;
|
||||||
|
// value is the holding at its own quote. priced is false when no quote is
|
||||||
|
// known, and then value and result are absent rather than guessed from cost.
|
||||||
|
quote?: string;
|
||||||
|
quoted_at?: string;
|
||||||
|
value?: string;
|
||||||
|
priced: boolean;
|
||||||
|
// result is the value now plus everything the position returned, less
|
||||||
|
// everything put into it: the outcome to date, realised and not.
|
||||||
|
result?: string;
|
||||||
records: number;
|
records: number;
|
||||||
}
|
}
|
||||||
// WealthCheck is one named verification with its evidence. failed marks a
|
// WealthCheck is one named verification with its evidence. failed marks a
|
||||||
@@ -307,6 +322,15 @@ export interface WealthCheck {
|
|||||||
detail: string;
|
detail: string;
|
||||||
failed: boolean;
|
failed: boolean;
|
||||||
}
|
}
|
||||||
|
// WealthFlow is the cash one kind of record moved. Every flow sums to the
|
||||||
|
// account's balance, so a total that disagrees with a broker's own figure
|
||||||
|
// localises to one class of row.
|
||||||
|
export interface WealthFlow {
|
||||||
|
event: string;
|
||||||
|
label: string;
|
||||||
|
cash: string;
|
||||||
|
records: number;
|
||||||
|
}
|
||||||
export interface WealthAccount {
|
export interface WealthAccount {
|
||||||
account_id: string;
|
account_id: string;
|
||||||
display_name: string;
|
display_name: string;
|
||||||
@@ -320,12 +344,37 @@ export interface WealthAccount {
|
|||||||
// cash is every recorded movement summed. It equals the real balance only
|
// cash is every recorded movement summed. It equals the real balance only
|
||||||
// when the journal holds that account's complete history.
|
// when the journal holds that account's complete history.
|
||||||
cash: string;
|
cash: string;
|
||||||
|
// positions is the market value of every priced holding, and wealth the two
|
||||||
|
// together. unpriced counts the holdings left out for want of a quote.
|
||||||
|
positions: string;
|
||||||
|
wealth: string;
|
||||||
|
unpriced: number;
|
||||||
|
flows: WealthFlow[];
|
||||||
holdings: WealthHolding[];
|
holdings: WealthHolding[];
|
||||||
checks: WealthCheck[];
|
checks: WealthCheck[];
|
||||||
}
|
}
|
||||||
|
// QuoteResult is what one run of the price job did. A failure names the
|
||||||
|
// instrument it could not price and leaves that instrument's last quote alone,
|
||||||
|
// so one unreachable listing never blanks a whole portfolio.
|
||||||
|
export interface QuoteFailure {
|
||||||
|
instrument_id: string;
|
||||||
|
isin: string;
|
||||||
|
symbol: string;
|
||||||
|
error: string;
|
||||||
|
}
|
||||||
|
export interface QuoteResult {
|
||||||
|
updated: number;
|
||||||
|
unchanged: number;
|
||||||
|
skipped: number;
|
||||||
|
failures: QuoteFailure[];
|
||||||
|
state: State;
|
||||||
|
}
|
||||||
export interface WealthTotal {
|
export interface WealthTotal {
|
||||||
currency: string;
|
currency: string;
|
||||||
cash: string;
|
cash: string;
|
||||||
|
positions: string;
|
||||||
|
wealth: string;
|
||||||
|
unpriced: number;
|
||||||
}
|
}
|
||||||
// Wealth is a reconciliation report computed from the journal rather than the
|
// Wealth is a reconciliation report computed from the journal rather than the
|
||||||
// analytics index, so it can be checked against a bank or broker's own screen.
|
// analytics index, so it can be checked against a bank or broker's own screen.
|
||||||
|
|||||||
+3
-1
@@ -401,7 +401,9 @@ function App() {
|
|||||||
acceptState={acceptState}
|
acceptState={acceptState}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{page === "wealth" && <Wealth revision={state.revision} />}
|
{page === "wealth" && (
|
||||||
|
<Wealth revision={state.revision} acceptState={acceptState} />
|
||||||
|
)}
|
||||||
{page === "classification" && (
|
{page === "classification" && (
|
||||||
<Classification state={state} acceptState={acceptState} />
|
<Classification state={state} acceptState={acceptState} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1060,6 +1060,17 @@ tbody tr:hover {
|
|||||||
color: #8b98a5;
|
color: #8b98a5;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
}
|
}
|
||||||
|
/* A headline figure with the split that produced it underneath: the smaller
|
||||||
|
line has to leave the money's line rather than flow beside it. */
|
||||||
|
.figure {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
.figure small {
|
||||||
|
display: block;
|
||||||
|
margin-top: 5px;
|
||||||
|
color: #8b95a2;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
.large-money {
|
.large-money {
|
||||||
font-size: 22px;
|
font-size: 22px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
|||||||
Reference in New Issue
Block a user