Functional Weave
Code in TypeScript

invest.time-weighted-return@1.0.0

README.md

2,155 bytes · view raw

# invest.time-weighted-return

The time-weighted return (TWR) of a portfolio: the growth of one unit invested
at the start, with the effect of money the client adds or withdraws taken
out. It measures the manager, not the timing of the client's deposits, and is
the return the CFA Institute's Global Investment Performance Standards
require for most portfolios (GIPS 2020;
https://www.gipsstandards.org/wp-content/uploads/2021/02/2020_gips_standards_asset_owners.pdf,
read 2026-09-23).

## The calculation

The portfolio is valued on the date of every external cash flow, **just
before** the flow. Between two consecutive points the sub-period return is

    r_i = value_i / (value_(i−1) + flow_(i−1)) − 1

and the sub-periods are linked geometrically: 1 + R = Π (1 + r_i). This is
the "true" TWR; it needs a valuation at every flow, which is what the points
are. (Approximations such as Modified Dietz, which avoid the valuations, are
not this capability.)

The product is formed exactly, as a fraction of big integers, and rounded
once: every figure is in basis points, **half away from zero** (+0.5 bp is 1,
−0.5 bp is −1). A naive "gain over opening value" gets deposits wrong:
£100,000 that grows 10%, receives £50,000 and then grows 5% ends at £168,000,
a TWR of 15.5%, not 18%.

## Annualised

When the first and last dates are 365 days or more apart,
`annualisedBasisPoints` is (1 + R)^(365 / days) − 1, taken in
`math.fractional-power`'s 18-place fixed point (actual days over 365, as
XIRR does, so a leap year counts as 366/365). Under 365 days it is null:
GIPS says returns for periods of less than one year must not be annualised.
A total loss annualises to −100%.

## Edge cases

- The first point's value may be zero when its flow opens the account.
- The last point's flow does not affect the return: nothing is measured after
  it. It is still checked for currency.
- Errors: fewer than two points; dates not strictly increasing; a negative
  valuation; a sub-period that starts with nothing invested (value plus flow
  zero or less); mixed currencies; fractional minor units; more than 36,500
  days from first to last.