A portfolio starts at $1,000 and finishes at $1,575. A dashboard displays a 57.5% return. Then someone notices that the investor added $900 and withdrew $400 along the way.
The ending balance is right. The return is answering the wrong question.
Time-weighted return separates investment performance from money moving into and out of an account. This guide explains the formula, works through a complete example in Python, and shows how to use SiftingIO historical prices to build the portfolio valuations behind the calculation.
The worked return figures are illustrative. The API example retrieves prices when you run it.
What is time-weighted return?#
Time-weighted return, usually shortened to TWR, measures compounded portfolio performance after removing the direct effect of external deposits and withdrawals.
Calculate a return for each interval between cash flows, then multiply the interval growth factors. An exact calculation values the portfolio immediately before each external flow. That valuation closes one interval; the balance after the flow opens the next.
This is the geometric linking approach described in the GIPS Standards Handbook.
TWR is useful when a portfolio tracker needs to show how investments performed without treating a new deposit as a gain. A separate balance chart can still show how much money the account actually holds.
A worked example with a deposit and a withdrawal#
Start with $1,000. The portfolio gains 10%, taking its value to $1,100. The investor then adds $900, so the next interval starts at $2,000.
The portfolio subsequently falls to $1,900. After a $400 withdrawal, the remaining balance is $1,500. It then grows to $1,575.
| Interval | Starting value, after any prior flow | Ending value, before the next flow | External flow at the end | Interval return |
|---|---|---|---|---|
| 1 | $1,000 | $1,100 | +$900 deposit | +10.00% |
| 2 | $2,000 | $1,900 | −$400 withdrawal | −5.00% |
| 3 | $1,500 | $1,575 | $0 | +5.00% |
The interval boundaries do the important work. The $900 deposit enters the next starting balance, so it does not count as profit in interval 1. The $400 withdrawal leaves the portfolio after interval 2 has been valued, so it does not count as a market loss.
For each interval:
Growth factor = ending value before the flow ÷ starting value after the previous flow
Then:
TWR = (1.10 × 0.95 × 1.05) − 1 = 0.09725
The time-weighted return is 9.725%.
There are three useful results here, each with a different meaning:
| Result | Calculation | What it tells you |
|---|---|---|
| Ending account value | $1,575 | The value remaining in the account |
| Investment gain in dollars | $1,575 + $400 − $900 − $1,000 = $75 | The gain after allowing for money added and removed |
| Time-weighted return | 1.10 × 0.95 × 1.05 − 1 = 9.725% | Compounded performance across the three intervals |
The 57.5% change in the displayed account balance is not an investment return. Nor should the $75 gain simply be divided by net contributions and presented as TWR: different amounts were invested at different times.
Calculate time-weighted return in Python#
The following example runs with Python's standard library. Save it as twr_example.py and run python twr_example.py.
Use decimal strings for the inputs so that amounts enter the calculation exactly as written. Each row contains the portfolio value before a flow and the signed flow that follows it. Positive flows add money; negative flows remove it.
from decimal import Decimal
def time_weighted_return(start_value, rows):
start = Decimal(start_value)
growth = Decimal("1")
interval_returns = []
for value_before_flow, external_flow in rows:
end = Decimal(value_before_flow)
flow = Decimal(external_flow)
if not all(x.is_finite() for x in (start, end, flow)):
raise ValueError("Values must be finite")
if start <= 0 or end < 0 or end + flow < 0:
raise ValueError("Check portfolio values and cash flows")
factor = end / start
growth *= factor
interval_returns.append(factor - 1)
start = end + flow
if not interval_returns:
raise ValueError("Provide at least one valuation interval")
return growth - 1, interval_returns
observations = [
("1100", "900"), # Value, then deposit
("1900", "-400"), # Value, then withdrawal
("1575", "0"), # Final value
]
twr, intervals = time_weighted_return("1000", observations)
for number, result in enumerate(intervals, start=1):
print(f"Interval {number}: {result:.2%}")
print(f"Time-weighted return: {twr:.3%}")
assert twr == Decimal("0.09725")
The output is:
Interval 1: 10.00%
Interval 2: -5.00%
Interval 3: 5.00%
Time-weighted return: 9.725%
This function is for a portfolio with a positive starting value in each interval. If an account is fully emptied, close that performance series and start a new one when it is funded again. A return with a zero opening value has no denominator.
The cash flow following the final valuation does not alter the return already earned. It only establishes a starting balance if another interval follows.
Decide what counts as an external cash flow#
The boundary of the portfolio determines the answer. For a whole investment account, moving cash from the investor's bank into the account is external. Buying an asset with cash already in the account is internal.
| Event | Treatment for the whole account |
|---|---|
| Cash deposited from outside | Positive external flow |
| Cash withdrawn to a bank | Negative external flow |
| Buy or sell using account cash | Update holdings and cash; no external flow |
| Dividend or interest retained in the account | Investment income included in account value |
| Trading fee paid from the account | Reduce account value; include in the reported net result |
| Asset transferred in from another account | External contribution valued at the transfer time |
For example, buying $300 of Bitcoin with existing cash reduces cash and increases the Bitcoin position. Recording another $300 contribution would count the same capital twice.
Keep fees consistent with the label shown to the reader. The examples here assume account values already reflect fees charged to the account. A report intended to show returns before fees needs a separately defined calculation.
Use SiftingIO prices to value the holdings#
The return function needs portfolio values. Your account ledger supplies quantities, cash balances and transfers. A market data API supplies prices for the valuation timestamps.
For a simple portfolio of spot assets quoted in US dollars:
Portfolio value = cash + sum(quantity × price)
SiftingIO's crypto historical bars endpoint provides OHLCV data for symbols such as BTCUSD and ETHUSD. The c field is the bar's close. The t field marks its opening time in UTC milliseconds.
Here is a request for a completed daily Bitcoin bar:
curl --compressed \
-H "X-API-Key: $SIFTINGIO_API_KEY" \
-H "Accept-Encoding: gzip" \
"https://api.sifting.io/v1/hist/crypto/BTCUSD/bars?start=2026-09-07&end=2026-09-07&interval=1d&limit=10"
Both date bounds refer to the bar's opening time. This selects the daily bucket beginning at midnight on 7 September, whose closing valuation belongs to the midnight boundary entering 8 September. Use a completed bucket when building a completed daily return.
The next Python example values a hypothetical holding of 0.02 BTC, 0.5 ETH and $250 cash at that same boundary. Replace those quantities and cash with the ledger balances for your own valuation time.
Install requests, set SIFTINGIO_API_KEY in your environment, and save the code as portfolio_value.py.
python -m pip install requests
python portfolio_value.py
import os
from datetime import datetime, timedelta, timezone
from decimal import Decimal
import requests
def daily_close(session, symbol, day):
opening = datetime.strptime(day, "%Y-%m-%d").replace(
tzinfo=timezone.utc
)
if opening + timedelta(days=1) > datetime.now(timezone.utc):
raise ValueError("Choose a completed daily bucket")
response = session.get(
f"https://api.sifting.io/v1/hist/crypto/{symbol}/bars",
params={
"start": day,
"end": day,
"interval": "1d",
"limit": 10,
},
timeout=30,
)
response.raise_for_status()
payload = response.json(parse_float=Decimal)
expected_time = int(opening.timestamp() * 1000)
matches = [
bar for bar in payload["data"]
if bar["t"] == expected_time
]
if len(matches) != 1:
raise ValueError(f"Expected one daily bar for {symbol} on {day}")
price = Decimal(str(matches[0]["c"]))
if not price.is_finite() or price <= 0:
raise ValueError(f"Invalid closing price for {symbol}")
return price
holdings = {"BTCUSD": Decimal("0.02"), "ETHUSD": Decimal("0.5")}
cash = Decimal("250")
bar_day = "2026-09-07"
with requests.Session() as session:
session.headers.update({
"X-API-Key": os.environ["SIFTINGIO_API_KEY"],
"Accept-Encoding": "gzip",
})
prices = {
symbol: daily_close(session, symbol, bar_day)
for symbol in holdings
}
value = cash + sum(
(quantity * prices[symbol] for symbol, quantity in holdings.items()),
Decimal("0"),
)
print(f"Portfolio value at 2026-09-08 00:00 UTC: USD {value:.2f}")
Run the valuation at each required boundary, using the holdings that existed at that time, then pass the resulting values and external flows into the TWR function. Keep full precision during calculation and round the displayed result at the end.
For assets priced in different currencies, convert each position and cash balance into the same reporting currency. The separate guide to multi-currency portfolio valuation covers that step.
Match the valuation time to the cash flow#
A daily close is a convenient boundary for a daily performance series. A transfer at 14:37 is a different boundary.
If cash flows occur at your daily boundary, record the valuation before the flow and use the balance after the flow to open the next day. The table and Python function follow that convention directly.
If money arrives during the day, calculate a valuation at that event for exact TWR. A daily close by itself cannot tell you the portfolio's value at 14:37. Use the appropriate historical resolution or capture a timestamped valuation from your live price stream. A completed one-minute candle is still a minute-level observation, not a tick at the precise transfer time.
SiftingIO's WebSocket documentation is the starting point for a live valuation service. Store the observation times with the prices you use, and apply the same valuation rule throughout the series. Your app can then show a current portfolio value while preserving the completed intervals used for its performance chart.
For a daily estimate that assigns intraday flows to the end of the day, label and document that convention. It should not silently replace event-time valuation.
Time-weighted return vs money-weighted return#
TWR asks how the portfolio performed across the intervals. Money-weighted return asks what return the investor experienced given the amounts invested and their timing.
| Metric | Useful for | How deposits and withdrawals enter the calculation |
|---|---|---|
| Time-weighted return | Comparing investment performance across accounts with different funding patterns | Remove their direct effect at each valuation boundary, then link returns |
| Money-weighted return | Measuring the investor's experience of when capital was committed | Use the amounts and dates of flows, plus ending value |
| Gain in dollars | Showing how much was earned or lost | Reconcile opening value, ending value and external flows |
An internal rate of return calculation is a common way to express money-weighted performance. CFA Institute's GIPS guidance explains why cash flow timing makes it different from time-weighted performance.
A product can show both TWR and money-weighted return when those questions matter. Give the metrics distinct labels instead of presenting either one as the single meaning of "return."
What to show on the portfolio dashboard#
Separate account value from performance. A useful display puts the current balance, net external contributions, investment gain and TWR next to one another, with the reporting period visible.
You can turn the linked returns into a chart that starts at 100. After each interval, multiply the previous chart value by that interval's growth factor. In the worked example, the line moves from 100 to 110, then 104.5, then 109.725. Deposits and withdrawals do not create jumps in that performance line.
Keep the account balance chart too. It answers a useful question, just a different one. Someone checking how much money remains in the account wants to see the withdrawal; someone comparing investment performance wants its direct effect removed.
The 9.725% in this example is a cumulative return over the observed intervals, not an annual rate. If you later annualise a multi-year series, use its actual elapsed time. Our CAGR guide explains the compounding step.
Build the first version#
Start with one reporting currency, a small set of holdings and a clearly defined valuation boundary. Reconcile the ledger first, retrieve prices for those boundaries, and calculate each interval before linking the series.
Create a free SiftingIO account to get an API key and run the historical price example. Once the valuation is working, connect live prices for the current balance and choose the plan that fits your markets, request volume and product use.
A deposit should change the balance. The return should change when the investments do.


