The governed definitions this build depends on. Read them first if a term is unfamiliar.
- PrimaryAverage daily balanceAverage daily balance is the arithmetic average of eligible daily balances over a specified period.
- PrimaryInterest accrualInterest accrual measures interest earned or incurred over an interval under an agreed balance and rate convention.
- ImportantCurrency minor unitA currency minor unit is a declared subdivision used to express monetary amounts at the currency's specified scale.
- ImportantDay-count conventionA day-count convention defines how dates are converted into the time fraction used by an interest calculation.
- ImportantEvent TimeEvent time is the timestamp assigned to when a market or business event occurred at its source.
Two synthetic deposit accounts close at the same 75,600 cents ($756.00). The first held 100,000 cents for most of October and earns 441 cents; the second stayed at 75,600 throughout the period and earns 362 cents. The ending balance hides 79 cents of difference.
A rate change adds another trap: paying the first path at the final 6% rate for every date gives 530 cents, while preserving the earlier 5% days gives 467. This tutorial explains both differences with a complete calendar, exact fractions and explicit rate segments.
What you'll learn
- Count quiet days in both the balance sum and actual-day denominator.
- Preserve exact averages instead of rounding them early.
- Pair each balance with the rate version applicable on that date.
- Check segment-average interest against exact daily-simple accumulation.
- Distinguish signed carry, missing evidence and an uncommitted accrual proposal.
Before you start: Daily Simple Interest Accrual and Event-Sourced Balance Fold.
About the data: Cedar Teaching Bank, the 35-day balance paths, rates and receipts are synthetic teaching inputs. All worked amounts are independently derived.
Start with every day
A period average needs a complete calendar. Days without transactions still contribute their end-of-day balance and increase the denominator. Averaging only the dates on which money moved gives those dates the wrong weight.
Event-Sourced Balance Fold reconstructs posted balance from complete committed evidence. Bitemporal Ledger Versioning separates economic dates from what evidence was available at a knowledge cutoff. This calculation consumes trusted daily receipts from that kind of adapter; the receipt strings do not authenticate themselves.
The US definition in CFPB Regulation DD §1030.2(d) uses the full daily principal sum and the period's day count. Cedar selects a UTC end-of-day, simple-interest, Actual/365 Fixed profile. Its boundaries are explicit; this tutorial does not claim to implement every US rule or another jurisdiction's product terms.
The synthetic account is deposits_product_usd; no actual customer history or database recording chronology is inferred. The period is 1 October through 4 November 2026, with 5 November excluded. All 35 dates appear, including the quiet days.
For a small hand check, balances of 10,000, 10,000, 20,000 and 20,000 cents sum to 60,000 cent-days. Dividing by all four days gives a 15,000-cent average. Quiet dates count just as much as transaction dates. The full 35-day example groups repeated values without dropping any dates:
| Dates | Days | EOD balance, cents | Sum contribution, cent-days |
|---|---|---|---|
| 1–21 October | 21 | 100,000 | 2,100,000 |
| 22–23 October | 2 | 97,600 | 195,200 |
| 24–25 October | 2 | 85,600 | 171,200 |
| 26 October–4 November | 10 | 75,600 | 756,000 |
The total is 3,222,400 cent-days. Divide by all 35 days: 3222400/35 = 644480/7 cents. Keep that fraction; rounding the average first changes the calculation.
At 50,000 parts per million, or 5% annual nominal, Actual/365 Fixed interest is 32224/73 cents. One final half-even rounding produces 441 cents ($4.41), with 31/73 of a cent carried forward. The full October subset has 31 days and exact interest 400. These synthetic expectations were independently specified before reference execution.
A flat 75,600 on every one of the same 35 dates also closes at 75,600. Its average is 75,600 and its interest rounds to 362. Ending balance alone cannot explain what was available to earn interest throughout the period.
Keep changing rates with their days
With a single rate r, the exact average multiplied by actual days is the original balance sum. With changing rates, split the period into contiguous rate-version segments. A version boundary remains visible even when the new version has the same ppm; version identity carries evidence beyond the numeric rate.
Let S_s be the segment's sum of daily balances, n_s its number of days, A_s=S_s/n_s its exact average, and r_s its annual nominal rate in ppm. Units are cents and actual civil days:
interest_s = A_s × n_s × r_s / 365000000
earned_exact = sum(interest_s)
Suppose Cedar pays 5% through 23 October and 6% from 24 October. The first 23 dates sum to 2,295,200; the last 12 sum to 927,200.
The two exact segment amounts are 22952/73 and 55632/365. Together they earn 170392/365, which rounds to 467 and leaves carry -63/365. Applying the final 6% rate to the whole-period average would instead round to 530. That shortcut pays the later rate on earlier days.
The full-period average still describes the path, but it does not retain the balance/rate pairing. Do not take an unweighted mean of the two segment averages either: the first represents 23 days and the second 12. Their combined average is (23 × A1 + 12 × A2) / 35, not (A1 + A2) / 2. Even equal overall averages can earn different amounts under the same changing-rate schedule: two days with balances [10000,20000] at 5% then 6% round to 5, while [20000,10000] at those same rates round to 4. Rate-version boundaries remain in the explanation even when adjacent versions have equal ppm.
Validate the calendar and rate history before calculating
The input has exact scope, currency, period, knowledge cutoff, day-count convention, incoming carry, rate versions and daily rows. A daily row includes date, signed canonical balance_minor, a balance receipt and its availability time, and applied rate-version ID. No numeric coercion, leading zeros, null values or unknown keys are accepted.
Every date in [period_start,period_end) must appear once, in order. The selected profile permits 1–366 days. A balance receipt must cover that day's UTC close and be available by the declared knowledge cutoff, which covers the whole period. A missing date rejects the complete result; it is never assumed zero or silently interpolated.
Each rate version has immutable identity, ppm, effective date and announcement time. It must be announced by the start of its effective day. Each row uses the latest applicable version already available by that day's start. A stale reference cannot bypass a known rate change. Duplicate versions, changed facts under one ID and ambiguous equal effective dates reject. Retroactive rate changes require a different policy.
Negative eligible interest principal routes to unsupported policy in this variant. The US interpretation in §1030.7 has a negative-balance zero treatment; Cedar does not claim that treatment is implemented. A signed fractional carry is a separate matter and remains valid. Minimum-Balance Fee instead accepts signed balances under its separate low-day policy.
Preserve fractions until settlement
Daily Simple Interest Accrual supplies the underlying exact daily calculation. Average-balance segments agree with it because multiplying sum/count by that same count cancels exactly. No intermediate average or daily amount needs whole-cent rounding.
The TypeScript reference keeps an integer numerator and positive denominator:
const average = rational(sum, BigInt(count));
const product = mulInt(average, BigInt(count) * BigInt(rows[0].rate_ppm));
const interest = rational(product.n, product.d * 365000000n);
Using sum / BigInt(count) alone would truncate the average. The rational pair retains the remainder and is reduced by gcd. Python uses Fraction constructed only from validated integers; Python's documented rational arithmetic supports this exact representation and half-even rounding.
For a complete executable example, download the public reproduction kit. It supplies algorithm.py and its interest_calendar.py helper, algorithm.ts and interest_calendar.ts, all 101 complete fixtures, actual reference suites/runners and an exact compiler lock. Extract it, run npm ci --ignore-scripts --no-audit --no-fund at its root, then enter topic/. Its REPRODUCE.md and examples/USAGE.md include both demos and the full python tests/run_parity.py command.
From that complete topic/, this Python demo keeps the request's rates, receipts and carry intact:
import json
import sys
from pathlib import Path
sys.path.insert(0, "implementations/python")
from algorithm import calculate_average_daily_balance_interest
cases = json.loads(Path("datasets/cases.json").read_text(encoding="utf-8"))["cases"]
request = next(c["request"] for c in cases if c["id"] == "A03-full35-changing-rate")
result = calculate_average_daily_balance_interest(request)
a = result["accrual"]
print(a["rounded_amount_minor"], a["closing_carry"])
Expected output is 467 {'numerator': '-63', 'denominator': '365'}. The TypeScript excerpt above is the same segment operation used by the unchanged reference, not a separate runnable project. The complete kit supplies its required helper and setup.
After summing the segments, add the opening fractional carry, round once and retain the signed difference:
settlement_exact = earned_exact + opening_carry
rounded_amount = half_even(settlement_exact)
closing_carry = settlement_exact - rounded_amount
Two 3,650-balance days at 5% each earn half a cent. Together they earn one. Rounding each day half-even to zero would lose it. One 10,950-balance day earns 3/2, rounds to two and carries -1/2. A negative half-cent carry with zero new earnings rounds to zero while retaining that carry; it is not a negative principal balance.
ACT/365 Fixed keeps denominator 365 on leap day. The supplied 2028 leap-calendar example earns exactly three cents; a 366-denominator comparison earns 365/122 before rounding. These are declared variants, not an assertion that every product must use Cedar's convention.
An accrual proposal is a separate accounting step
The result reports the full exact average, day/segment traces, exact earned and settlement values, rounded amount and closing carry. A positive bounded amount proposes debit interest_expense_usd and credit interest_payable_usd. Zero has no zero-value legs; an amount above the journal leg limit remains inspectable with a blocked amount-limit proposal.
That proposal is not an accepted journal. A host still supplies durable business identity and booking authority, then validates it through the posting control. Later customer credit debits payable and credits deposits_product_usd; it must not expense the same interest again. A changed as-of recomputation after a prior accepted accrual needs a controlled correction.
This is simple interest on supplied posted balances. It does not capitalize its own accrual, subtract pending holds, calculate annual percentage yield or choose a real customer's legal recognition policy. CFPB Appendix A provides a bounded comparison for the distinct yield concept.
Inspect the evidence and compare paths
The reference passes 101 cases: 31 accepted and 70 rejected, with strict TypeScript compilation and complete Python/TypeScript output parity. It independently compares every common accrual/proposal/day-trace fact against daily accumulation on the same inputs. Cases cover changing rates, same close/different path, same average/different rate association, missing and malformed dates, years 0001/0099/0100, leap day, carry ties, huge exact values and blocked proposals. The package keeps raw full-output parity and local validation beside its complete runnable source.
Open the guided full-calendar lab. Its initial screen includes the full-period result and all 35 primary dates. Step the labeled prefix illustration to watch sum, count, average and segments grow; compare the flat path and changing rate. The missing-day scenario returns no complete amount. The lab bundles the actual TypeScript kernel and records its source hash. Prefix demonstrations use a shorter complete period at the same final knowledge cutoff; they do not pretend to reconstruct knowledge on each historical date.
Why synthetic data? Complete applicable rate histories and point-in-time daily evidence are needed to reproduce an accrual. These calendars make every assumption visible without inventing a real customer's terms or balance history.
In production
- Bind the actual balance method. For covered US consumer deposits, Regulation DD §1030.7(a)(1) addresses daily or average-daily-balance methods on full daily principal. This profile deliberately routes negative principal as unsupported, so it is not a complete implementation of the regulation's negative-balance treatment.
- Retain every effective rate version. Trusted adapters must select complete applicable terms and authentic daily evidence. A receipt ID cannot establish completeness. A changed knowledge-cutoff calculation after an accepted accrual needs controlled correction, not silent replacement.
- Keep product variants separate. This is simple deposit interest on posted balances. Pending holds, collected-balance eligibility, compounding, credit-card finance charges and APY need their own declared rules; a shared average formula does not make the whole product policy transferable.
- Reconcile before booking. Under the same valid balances, rates, carry and day count, segment-average and daily-simple accrual agree exactly. An uncommitted expense/payable proposal still needs authorized scope, booking period and durable business identity. Later crediting clears payable rather than expensing the same interest twice.
Common mistakes
- Averaging only transaction dates or replacing an absent date with zero.
- Rounding or truncating
sum / countbefore applying the period rate. - Taking an unweighted mean of segment averages with unequal day counts.
- Applying the final 6% to earlier 5% days: 530 cents instead of 467.
- Confusing a negative fractional carry, unsupported negative principal, APY or an accepted journal with the same calculation state.
Key takeaways
- Every calendar date contributes its balance and one day to the denominator.
- Keep the average exact; multiplying by its own count recovers the original sum.
- Segment by rate-version identity and preserve balance/rate pairing.
- Sum exact earned amounts, add carry, then round half-even once.
- Keep calculation, product applicability and durable posting controls distinct.
Continue learning
Next, Tiered Fee Calculation prices usage rather than balance-days. Compare Minimum-Balance Fee for a low-day threshold, and Compound Interest Accrual when credited interest can earn interest. Revisit Daily Simple Interest Accrual to inspect the exact daily-equivalence check.
Rendered from the canonical Mermaid sources linked by this article.
Preserve every day and its rate
Validate the complete as-of calendar before displaying a complete calculation.
The whole-period average describes the balance path. Rate segments determine interest when rates change. An exact calculation and a posting proposal are distinct from an accepted durable journal.
References6 primary sources and evidence notesExpand the source trail, evidence role, and limitations behind the engineering choices.
Expand the source trail, evidence role, and limitations behind the engineering choices.
- Accessed: 27 October 2026.
- Supports: the source-specific definitions, comparison and arithmetic representation below.
- Limitations: no real tariff, authenticated history, universal product treatment or full compliance endorsement.
R01 — Regulation DD §1030.2(d): average daily balance
- Organization and source-version: Consumer Financial Protection Bureau; current 12 CFR 1030.2(d), United States.
- URL: Regulation DD §1030.2(d): average daily balance.
- Accessed: 27 October 2026.
- Supports: Full daily principal sum divided by every day in the period; nominal interest and yield terminology.
- Limitations: Covered consumer deposits; does not select Cedar UTC, causal source, carry, rate-segmentation or accounting policy.
R02 — Regulation DD §1030.7: payment of interest
- Organization and source-version: Consumer Financial Protection Bureau; current regulation and official interpretation, United States.
- URL: Regulation DD §1030.7: payment of interest.
- Accessed: 27 October 2026.
- Supports: Daily/average methods, daily-rate and leap context, minimum-to-earn-interest and compounding/crediting distinctions. Interpretation 7(a)(2)-5 treats negative account balances as zero.
- Limitations: Cedar deliberately routes negative eligible principal unsupported and does not claim full regulatory implementation. Its nominal ACT/365 Fixed profile is selected, not universal.
R03 — Regulation DD Appendix A: annual percentage yield
- Organization and source-version: Consumer Financial Protection Bureau; current appendix, United States.
- URL: Regulation DD Appendix A: annual percentage yield.
- Accessed: 27 October 2026.
- Supports: APY is a distinct yield concept whose rules include interest and compounding effects.
- Limitations: This tutorial calculates an exact simple accrual, not APY or disclosure conformance.
R04 — Official interpretation of Appendix A
- Organization and source-version: Consumer Financial Protection Bureau; current official interpretation, United States.
- URL: Official interpretation of Appendix A.
- Accessed: 27 October 2026.
- Supports: Part II.A.1 complete-period average context and separate precision/rounding rules in yield calculations.
- Limitations: Exact rational retention, settlement half-even and signed carry are Cedar choices; do not present them as a quoted regulatory rounding mandate.
R05 — Exact rational arithmetic
- Organization and source-version: Python Software Foundation; official Python 3.11 documentation, technical.
- URL: Exact rational arithmetic.
- Accessed: 27 October 2026.
- Supports: Integer-pair exact rational construction, gcd reduction and exact Fraction rounding.
- Limitations: Strict financial input validation precedes library use. No permissive float/text construction or source/persistence authority is inferred.
R06 — ECMAScript BigInt type
- Organization and source-version: Ecma TC39; official living language specification, technical.
- URL: ECMAScript BigInt type.
- Accessed: 27 October 2026.
- Supports: Exact integer foundation for sums, rate products, gcd and display without Number money conversion.
- Limitations: Integer division alone truncates; authored rational and half-even logic are still required. No durable acceptance guarantee.
Notes
Local authored evidence: complete reproduction kit, inventory, fresh extraction/install/full-parity receipt, learner setup, all 101 cases, independent calendar arithmetic, validation. The original R01–R06 identities retain their source roles. The main module computes segment-average interest independently using locally pinned interest_calendar helpers; all financial module/fixture/PINNED-KERNEL bytes are retained.
All Cedar accounts, daily balances, receipts and rates are synthetic. Calendar arithmetic and segment/daily equivalence are author-derived under the declared convention; validation outcomes are local observations. Historical-example decision remains not useful without complete applicable real terms, rights, source chronology and account evidence. Credit-card finance-charge calculations, business-account legal rules, provider observations and source authentication are outside this deposit profile; no unverified Regulation Z/AFP/SEC/FASB authority is added to fill a reference count. Current web-page versions are not cryptographically archived. No credential, customer dataset, provider license, real charge or fresh SQL execution is included.
Full dependency-light reference implementations in both supported languages.
/** Exact segment-average deposit interest under the synthetic Cedar profile.
* The pinned local kernel validates calendars/rates and proposes posting legs.
* This module independently accumulates the segment-average interest method.
*/
import { InterestError, add, fractionJson, makePostingProposal, mulInt, rational, roundHalfEven, validateCalendar } from './interest_calendar.js';
const SCHEMA = 'd30-average-daily-balance-interest-v1';
const BASE_SCHEMA = 'd30-daily-simple-interest-v1';
const DENOMINATOR = 365000000n;
const DAY_MS = 86400000;
type RecordValue = Record<string, unknown>;
function calendarRequest(request: unknown): unknown {
if (request === null || typeof request !== 'object' || Array.isArray(request) || ![Object.prototype, null].includes(Object.getPrototypeOf(request))) return request;
const adapted = { ...request } as RecordValue;
if (Object.hasOwn(adapted, 'schema_version')) {
adapted.schema_version = adapted.schema_version === SCHEMA ? BASE_SCHEMA : 'unsupported-a03-input';
}
return adapted;
}
export function calculateAverageDailyBalanceInterest(request: unknown) {
try {
const validated = validateCalendar(calendarRequest(request));
const source = request as RecordValue;
const groups: typeof validated.rows[] = [];
for (const row of validated.rows) {
if (groups.length === 0 || groups.at(-1)![0].rate_version_id !== row.rate_version_id) groups.push([]);
groups.at(-1)!.push(row);
}
const segments = [];
let earned = rational(0n, 1n), totalBalance = 0n;
for (let index = 0; index < groups.length; index++) {
const rows = groups[index], count = rows.length;
const sum = rows.reduce((total, row) => total + BigInt(row.balance_minor), 0n);
const average = rational(sum, BigInt(count));
// Division keeps a rational pair; no monetary value becomes a Number.
const product = mulInt(average, BigInt(count) * BigInt(rows[0].rate_ppm));
const interest = rational(product.n, product.d * DENOMINATOR);
segments.push({
segment_index: index,
period_start: rows[0].date,
period_end: new Date(new Date(rows.at(-1)!.date + 'T00:00:00.000Z').getTime() + DAY_MS).toISOString().slice(0, 10),
day_count_value: String(count),
rate_version_id: rows[0].rate_version_id,
rate_ppm: rows[0].rate_ppm,
balance_sum_minor: sum.toString(),
average_balance_exact: fractionJson(average),
earned_exact: fractionJson(interest),
});
earned = add(earned, interest);
totalBalance += sum;
}
const trace = [];
let cumulative = rational(0n, 1n);
for (let index = 0; index < groups.length; index++) {
for (const row of groups[index]) {
const daily = rational(BigInt(row.balance_minor) * BigInt(row.rate_ppm), DENOMINATOR);
cumulative = add(cumulative, daily);
trace.push({
date: row.date,
balance_minor: row.balance_minor,
balance_receipt_ref: row.balance_receipt_ref,
balance_available_at: row.balance_available_at,
rate_version_id: row.rate_version_id,
rate_ppm: row.rate_ppm,
exact_daily_interest: fractionJson(daily),
cumulative_earned_exact: fractionJson(cumulative),
segment_index: index,
});
}
}
if (cumulative.n !== earned.n || cumulative.d !== earned.d) throw Error('Segment/day algebra mismatch');
const settlement = add(earned, validated.carry), rounded = roundHalfEven(settlement);
const accrual = {
ledger_id: source.ledger_id,
entity_id: source.entity_id,
account_id: source.account_id,
currency: source.currency,
period_start: source.period_start,
period_end: source.period_end,
day_count: source.day_count,
day_count_value: String(validated.dayCount),
balance_sum_minor: totalBalance.toString(),
average_balance_exact: fractionJson(rational(totalBalance, BigInt(validated.dayCount))),
opening_carry: fractionJson(validated.carry),
earned_exact: fractionJson(earned),
settlement_exact: fractionJson(settlement),
rounded_amount_minor: rounded.toString(),
closing_carry: fractionJson(add(settlement, rational(-rounded, 1n))),
knowledge_cutoff: source.knowledge_cutoff,
};
return { status: 'ok', code: 'AVERAGE_BALANCE_INTEREST_CALCULATED', accrual, trace, segments, posting_proposal: makePostingProposal(source, rounded) };
} catch (error) {
if (!(error instanceof InterestError)) throw error;
return { status: 'rejected', code: error.message, accrual: null, trace: [], segments: [], posting_proposal: null };
}
}
Choose a scenario, step through the decisions and compare the result with the worked example.
