Contents Lesson 11 of 19

11 min read · professional

A portfolio panel whose sums you can check

By the end of this lesson you will have a portfolio panel that keeps your trades in its saved config, works out positions first in, first out with fees in the cost, gives shares bought today the change they had today, leaves a position with no price out of the totals and says so, and tests that do each of those sums by hand.

The third recipe is the vendor/calculations.js file of eodhd-portfolio-tracker, and it is the one where a wrong sum costs money. A tile in the wrong shade misleads you for a moment. A cost basis that is out by $48.75 sits inside every gain you read afterwards.

Keep the trades, work out the positions

A position is a sum over trades. Store only the sum and you lose which shares were sold and when, and a trade typed wrong can no longer be corrected. So the panel keeps the trades and works the positions out from them on every render.

The trades go in the panel's config and are saved with the layout, the way the watchlist panel's symbols are. They are private. The store lives in .data/, which git ignores, and that matters because this repository goes public in Ship Your Tool. Export, from lesson 3, writes the trades into the file it saves: mind who gets it.

First in, first out

Each buy is a lot: its quantity, its price, and its fees spread over its shares. A sell takes shares from the oldest lot first, and on a day with both a buy and a sell, the buy counts first. What you still hold costs the open lots' quantity times price plus fee per share.

Date Trade Open lots after it
5 January buy 10 at 100, fees 5 10 at 100.50
2 February buy 10 at 120, no fees 10 at 100.50, 10 at 120
2 March sell 15 5 at 120

Five shares left, costing 600. An average cost would have been (1005 + 1200) / 20 = 110.25 a share, or 551.25 for the five. Both methods are in use, and they differ by $48.75 on this five-share position, so the panel uses one and its header comment says which.

Today's change for shares bought today

Shares held overnight moved from the previous close. Shares bought today did not exist at yesterday's close: they moved from what you paid. With the mock quote for Apple, a previous close of 248.90 and a last price of 251.32, and ten shares held overnight plus five bought today at 250.00:

  • all fifteen counted from the previous close: 2.42 × 15 = 36.30
  • the five counted from what you paid: 2.42 × 10 + 1.32 × 5 = 30.80

The first figure gives you 1.10 a share on five shares you did not hold when that 1.10 happened. "Today" is the date in the quote's timestamp, not your clock; in mock mode it is 30 October 2026.

A position with no price is not worth zero

A position whose quote did not come back keeps its quantity and cost. It has no value. So it is left out of every total, and the totals say how many positions they left out. Valued at zero, it would show a loss of everything you paid for it, which is the heatmap's rule again: a number you do not have is not zero.

One currency

A quote carries no currency, and most London prices are in pence: Vodafone's 74.62 in the fixture is 74.62 pence. Added to dollar prices, that is a wrong number, which is worse than a missing one. So the panel takes US-listed symbols only. The app converts through currency pairs priced as quotes and divides pence by 100, and that is a lesson of its own. It also works out realised gains, dividends and splits, which this port leaves out; the header comment names each.

Its quotes come from the union

The panel's dataNeeds names the symbols you hold, so they join every other panel's quotes in one request. A stock on your watchlist and in your portfolio costs one call per refresh, and a portfolio of symbols the cockpit already prices costs nothing extra. Our Markets layout starts its quote panel on a symbol the portfolio holds for that reason, and one live load of it is 18 calls: the screen's 5, the sentiment's 10 and three quotes. On the Free plan that is most of a day's 20, which is why it is a layout of its own and the default stays cheap.

Try it now

The prompt

Mock mode on, plan mode on, and paste:

Plan, then build, a portfolio panel. In a new src/lib/portfolio.ts:
a Trade has id, symbol, side (buy or sell), date, quantity, price and
fees. parseTrades(raw) refuses, never repairs: a symbol that is not
US-listed, a quantity or price that is not positive, negative fees, a
bad date, and a sell larger than what is held on its date.
openLots(trades) is first in, first out per symbol, buys before sells
on the same day, each lot carrying its fees per share.
positions(trades, quotes) gives quantity, cost, average cost, price
(the quote's close), value, unrealised gain, the day's change and
weight. Shares from lots dated on or after the quote's own day
move from what was paid, the rest from the previous close. A position
with no price is left out of the totals and counted, never valued at
zero; weights are over priced positions. The file opens with a comment
naming EodHistoricalData/eodhd-portfolio-tracker,
vendor/calculations.js and the MIT licence, with a line each for what
is not ported: realised gains, dividends, splits, other currencies.
Write tests/portfolio.test.ts first, with sums worked by hand: buy 10
at 100 with fees 5, buy 10 at 120, sell 15 leaves 5 at a cost of 600;
and a day with 10 shares held overnight and 5 bought that day. Add a
portfolio panel type whose config holds the trades and whose dataNeeds
names the symbols held: a table, a totals row, and a small form that
adds a trade through onConfigChange and says why when parseTrades
refuses it. Add it to the Markets layout with a few example trades.
Mock mode. Run npm test, typecheck, lint and check:leak, and show me
the diff.

A good answer adds portfolio.ts, the panel and the test, and changes the layout module and the container's list of panels. The form's inputs are the panel's own state, which the contract allows: they are panel-local, and nothing leaves the panel except through onConfigChange.

Check it yourself

  1. The new tests failed first and pass now; in the first-in-first-out test the five shares left cost 600.
  2. In mock mode the Markets layout shows the portfolio with a totals row, and its weights add up to 100%.
  3. Through the form, add a buy of five Apple shares dated 30 October 2026 at 250: Apple's change today grows by 6.60, not by 12.10.
  4. Try to sell more Microsoft shares than the panel shows you hold: the form refuses and says how many you hold.
  5. Ask the agent to delete Microsoft's row from fixtures/real-time.json, and reload: that position reads "no price: left out of the totals", and the totals say one position was left out. Put the row back.
Compare with ours
// src/lib/portfolio.ts: shares bought on the quote's day move from what was paid
export function dayChange(
  price: number,
  previousClose: number,
  quantity: number,
  boughtToday: { quantity: number; cost: number },   // lots dated on the quote's day
): number {
  let change = (price - previousClose) * quantity;
  const bought = Math.min(boughtToday.quantity, quantity);
  if (bought > 0) {
    const paidPerShare = boughtToday.cost / boughtToday.quantity;   // fees included
    change += (previousClose - paidPerShare) * bought;
  }
  return change;
}

The full state at the end of this unit is on the starter's branch ref/build-a-dashboard/u2.

Checkpoint

npm test && npm run typecheck
git status          # the files you expect, and no .env file
git add -A
git commit -m "Portfolio panel: trades in config, FIFO lots with fees, today's change from what was paid"

Then answer this lesson's questions.