Skip to content
TotalFinance

Track portfolio P&L

Separate investment profit from deposits with an event-sourced ledger and reconciled P&L.

Run it

Live, in your browser. Nothing leaves this page.

Local
100

shares

150

USD / share

165

USD / share

5,000

USD · February 15

Change any input; everything updates.

Ending account value
$106,500
USD
Investment P&L
$1,500.00
USD · profit, not deposits
External cash flow
$5,000.00
USD · deposits are not profit
Reconciliation residual
$0.00
USD · should be 0
From opening to closing account valueInvestment P&L and external cash flows are separate steps: a deposit raises account value without being profit. Zero components are omitted. The axis starts at $96,000.00, not zero, so the changes stay visible.
$100,000Opening value+$1,500.00Unrealized P&L+$5,000.00Deposits & withdrawals$106,500Closing value
Show data (4 rows)
StepUSDRunning total
Opening value$100,000$100,000
Unrealized P&L$1,500.00$101,500
Deposits & withdrawals$5,000.00$106,500
Closing value$106,500$106,500
Account value across sample weekly marks
Show data (5 rows)
Days since February 1, 2026Account value (includes deposits)
0$100,000
7$100,375
14$100,750
21$106,125
28$106,500

Assumptions & conventions

What the calculation assumed, echoed by the library rather than hidden.

pnl.conventionsVersion
0.0.1
pnl.lotRelief
fifo
pnl.identity
ending NAV − beginning NAV − external flows = realized P&L + unrealized P&L + income − transaction costs − financing + foreign-exchange P&L + residual. Beginning and ending NAV are portfolioSnapshot at the two marks (each mark folds every event strictly before 00:00 UTC of its date); external flows are cash.deposit minus cash.withdrawal over the window; realized, income, costs, and financing are the differences of the fold accumulators; unrealized P&L is the difference of open-lot mark-to-market; the residual is what the components leave unexplained and is float rounding by construction.
pnl.conversionConvention
Every local-currency component over the window converts to base at the CLOSING mark’s quote. Foreign-exchange P&L = Σ over non-base currencies of opening local value × (closing quote − opening quote) [translation] + Σ over cash.conversion events of (amount received × closing quote of the received currency − amount given × closing quote of the given currency). Note that portfolioPerformanceInputs converts external flows at the FLOW-DATE mark for FC4; this report converts them at the closing mark so the identity holds exactly.
pnl.residualTolerance
0.0001065
timeline.conventionsVersion
0.0.1
timeline.lotRelief
fifo
timeline.markInstant
A mark dated D values the fold of every event with effectiveTimestampMs strictly before 00:00 UTC of D — the mark lands BEFORE any external flow dated D, exactly FC4’s flow convention; external flows since the prior mark convert at THIS mark’s quotes (the P&L identity convention), while the FC4 series converts each flow at its own flow-date mark.
timeline.indexConvention
indexValue is @insiderfinance/totalfinance/performance portfolioReturnIndex over the FC4 series (base value 1, geometric linking, flows at-flow-timestamp); drawdown is underwater() over that index — a flow-adjusted decline, so a withdrawal is never mistaken for a loss. One missing mark withholds the whole index with a reason rather than restarting it.
timeline.exposureConvention
Exposure is position NOTIONAL value in base currency at the mark (quantity × mark × multiplier — a variation-margin position’s full notional, not its unsettled P&L): long = Σ positive values, short = Σ |negative values|, gross = long + short, net = long − short; cash is not exposure. exposureByGroup partitions the same positions by the caller’s classification (tags overlap and do not partition).
sample
Linear hypothetical price path. No trading, fees, dividends, or FX during the measurement window.

Diagnostics & warnings

  • Warning: portfolioPerformanceInputs: 1 external flow(s) fall outside the [2026-02-01, 2026-03-01] mark window and are excluded from the series — widen the marks to include them.
pnl.eventCount
1
pnl.residualWithinTolerance
true
timeline.markCount
5
timeline.gaps
none

Use it in your project

portfolioPnl returns a report separating investment return from external cash flows. This example prints selected fields in USD. A timeline is optional: only the opening and closing marks are needed for this report.

Sample inputs

Sample inputs: a USD ledger with an opening deposit, a share purchase and an optional later deposit. The two market snapshots below are hypothetical marks, not a data connection. Copy setup + call includes the complete setup.

Preview
{
  "quantity": 100,
  "openingPrice": 150,
  "closingPrice": 165,
  "deposit": 5000
}
Complete setup · included when you copy
First call
const pnl = portfolioPnl({ ledger, from, to });
const result = {
  endingAccountValue: pnl.to.netAssetValue,
  investmentReturn: pnl.investmentReturn,
  externalFlows: pnl.externalFlows,
  residual: pnl.residual,
};
console.log(result);
Output of this example
{
  "endingAccountValue": 106500,
  "investmentReturn": 1500,
  "externalFlows": 5000,
  "residual": 0
}
Reproduce this entire calculator
Full result object

Both examples use the inputs of the last successful calculation. Displayed metrics are rounded; copied programs keep exact values. Every copy on this page is type-checked and executed against the packed package in CI.

Ask your AI agent

With the TotalFinance MCP server connected, your agent runs this calculation with the totalfinance_portfolio_explain_pnl tool (start the server with --profile portfolio). The prompt below uses your current inputs.

Prompt

Use the TotalFinance MCP tool totalfinance_portfolio_explain_pnl: I bought 100 shares at 150 USD, deposited 5,000 USD later, and the shares are now marked at 165 USD. Separate the deposit from the investment return and show how the components reconcile.

Connect Claude, Cursor, VS Code, Codex or ChatGPT

What this calculates

createPortfolioLedger turns dated events (deposits, fills, dividends, fees) into an immutable ledger. portfolioPnl values that ledger at two marks and explains the change: realized and unrealized P&L, income, costs, financing, foreign-exchange effects, external cash flows and a reconciliation residual that should be zero.

Why the waterfall matters

A deposit raises account value, but it is not profit. The waterfall keeps the two apart: investment P&L and external flows are separate steps from the opening to the closing value. Change the deposit in the panel and only the deposits step moves; investment P&L stays put.

Your own portfolio

Replace the sample events with your own fills and cash movements, and the sample marks with your own timestamped prices. TotalFinance never fetches prices: every valuation uses the market snapshot you pass in, and the report carries the assumptions it used.

Edit this page on GitHub ↗Every code block on this site is executed in CI against the library.