D30-F02-A02 / Released engineering topic

Compound Interest Accrual: Capitalize Without Counting It Twice

Calculate compound deposit interest in Python and TypeScript. Separate capitalization, customer credits and signed rounding carry across a complete daily path.

The same 35-day deposit path gives settlement estimates of 441 cents simple, 442 month-end and 443 daily, without customer credits.D30 / D30-F02
Key concepts

The governed definitions this build depends on. Read them first if a term is unfamiliar.

The same 35-day deposit path gives rounded pending estimates of 441 cents ($4.41) with simple interest, 442 cents with month-end capitalization and 443 cents with daily capitalization. The balance path is unchanged; the date when earned interest starts earning more interest changes the answer.

Crediting introduces another boundary. After a modeled 401-cent October credit, November begins with 75,600 external cents plus 401 credited cents: 76,001 cents. Feed an already credited 76,001 into a calculator that adds its own 401 again and the base becomes 76,402. The same credit is counted twice.

This tutorial builds an exact compound-interest accrual in Python and TypeScript. It separates internal capitalization from customer crediting, keeps every eligible date and signed rounding fraction, and exposes the daily state behind each result. All scheduled credits and closing states are hypothetical product projections until a host establishes actual funding and accepted postings.

What you'll learn

  • Keep the interest-bearing base free of duplicated customer credits.
  • Apply daily or actual month-end capitalization in a fixed daily order.
  • Explain the 441 / 442 / 443 comparison with independent arithmetic.
  • Round scheduled credits while retaining non-interest-bearing signed carry.
  • Continue a projection across a period boundary without forcing an extra event.

Before you start: Daily Simple Interest Accrual covers exact daily fractions. Double-Entry Posting Engine explains bank-book journals; Event-Sourced Balance Fold explains complete posted evidence.

About the data: Cedar Teaching Bank, CB-GENERAL / CB-A and deposits_product_usd form a fictional product-calendar example. Every balance, rate, schedule and receipt below is synthetic.

Keep five pools with different jobs

Before naming all the state, distinguish two principal amounts: the external balance feed excludes every interest credit modeled by this engine; cumulative modeled credits are added exactly once. The model then tracks:

PoolMeaningEarns interest?
XExternal principal after that day's eligible external flows, excluding model creditsYes
QCumulative modeled whole-cent customer creditsYes, from the following day
CExact capitalized interest not yet creditedYes
AExact accrual awaiting capitalizationNot yet
RSigned rounding carryNever

The projected customer principal is P = X + Q. The daily interest base is X + Q + C. A waits for capitalization; R offsets prior rounding without earning interest. A balance feed that already contains Q cannot be used as X without reconciling that overlap. The input declares its excluded-interest basis, but JSON cannot establish whether the host's feed is honest.

Only external principal X, scheduled credits Q and capitalized interest C enter the base; A waits and R never earns.

These are product-model pools, not general-ledger accounts. Capitalization transfers A into C within the model; it does not itself prove a customer credit or a journal was posted.

Fix the daily order

We use complete UTC civil days and Actual/365 Fixed, including leap years. An integer annual nominal rate of 50,000 ppm means 5%; it does not mean 5% APY. Apply that day's eligible external flows before its interest. Intraday time-weighting is outside this profile.

For each day d:

Pd=Xd+Q,Id=(Pd+C)rd365⋅106,A←A+Id.P_d=X_d+Q,\qquad I_d=(P_d+C)\frac{r_d}{365\cdot10^6},\qquad A\leftarrow A+I_d.

Here rdr_d is the annual nominal rate in ppm and IdI_d is an exact fraction of a cent. Keep the remaining event order explicit:

  1. Capitalize if due: C ← C + A, then A ← 0. Daily capitalization runs every day; month-end runs on the actual calendar month-end, including 29 February.
  2. Credit if scheduled: T = C + R; q = halfEven(T); Q ← Q + q; C ← 0; R ← T − q. Credit dates must also be capitalization dates, so A is already zero.
  3. Record the state. A day-end credit changes the following day's base once. It causes no extra same-day accrual.

The requested period ending is not itself an event. The last day here is 4 November, so month-end capitalization leaves November's A uncapitalized. A final settlement estimate reads the pools without mutating them or scheduling a customer credit.

Compare one complete 35-day path

External principal is 100,000 cents ($1,000.00) for 1–21 October 2026, 97,600 for 22–23 October, 85,600 for 24–25 October and 75,600 for 26 October–4 November. Withdrawals of 2,400, 12,000 and 10,000 cents apply on 22, 24 and 26 October respectively.

All 35 days are retained. Their external balance sum is 3,222,400 balance-cent-days. At 50,000 ppm and with no customer credits, independent calculations give:

MethodEarned interest, centsPending half-even estimate, cents
Simple comparison32,224/73 ≈ 441.424657534441
Month-end capitalization32,240/73 ≈ 441.643835616442
Daily capitalization≈ 442.515457121443

These are estimates from product calculations, not accepted journals or observed real product returns.

One complete external balance path produces estimates of 441, 442 or 443 cents depending on capitalization.

For month-end capitalization, October's 31-day weighted sum is 2,920,000. Dividing by 7,300 gives exactly 400 cents. Those 400 move into C at 31 October end. November's four days then earn on 75,600 + 400 = 76,000, adding 3,040/73 cents. On 4 November, C = 400 and A = 3,040/73: total 32,240/73. No premature capitalization is needed.

For an independent daily-capitalization check, let a = 7,301/7,300, the daily growth factor at 5% / 365. With zero opening pools and no customer credits, each external flow compounds for its remaining eligible days:

Plain text
earned = 100000(a^35 − 1) − 2400(a^14 − 1)
         − 12000(a^12 − 1) − 10000(a^10 − 1)

The signed withdrawal exponents include the withdrawal day under this selected daily-balance policy. This closed-form cash-flow polynomial checks the iterative engine without using the engine's own answer as its oracle.

Credit once and keep signed carry

Now keep daily capitalization and schedule a customer credit on 31 October. October earns about 400.8626 cents, so the half-even proposal is 401 cents. The model adds 401 to Q, clears C and keeps the exact difference, about −0.1374 cent, in R. November begins with X = 75,600 and Q = 401, before new November interest capitalizes daily.

The full 35 days now earn about 442.515532429 cents, with 401 scheduled cents and a pending estimate of 42. That differs slightly from the uncredited 442.515457121: whole-cent credit rounding changes the following day's principal, while R never earns. Credit frequency need not leave exact earnings unchanged under this selected policy.

In the month-end example, October earns exactly 400. Crediting it or leaving it in C happens to produce the same November base of 76,000. That coincidence is not a general rule.

Negative carry is not negative principal

At 50,000 ppm, 3,650 cents earns exactly 1/2 cent in a day. A scheduled half-even credit rounds to zero, retains +1/2 in R and emits no zero-valued journal legs. With 10,950 cents, earned interest is 3/2, the credit rounds to 2 and R becomes −1/2. The following day's projected customer principal is 10,952, not 10,953.5.

R corrects previous over-rounding or under-rounding at settlement. It is outside the interest base. The model's pending entitlement is C + A + R, not just C + A. This is still a hypothetical product amount; it is not automatically the actual interest-payable account balance or a legally determined closure payment.

Validate evidence before projecting amounts

Every date in [start, end) must appear once in order, including quiet and leap days. A balance receipt must be at or after day close and no later than K; K must reach the period's exclusive-end midnight. Missing a date returns no accrual, closing state, proposals or trace.

Rates are immutable versions. The selected policy requires announcement by the version's own effective-day start, then chooses the latest applicable version known at each day's start. Stale references, conflicting identities and ambiguous equal effective dates reject. A late announcement routes unsupported retroactive-rate policy rather than silently repricing earlier days.

Opening state explicitly supplies Q, C, A and R with as_of equal to the period start. C and A are nonnegative reduced fractions; R is reduced and within ±1/2 cent. Negative external principal is unsupported even if Q or C would offset it. Identifier syntax and receipt clocks do not authenticate ownership, opening state or source completeness.

The finite reference profile supports USD, 1–366 days, at most 512 rate versions and nominal rates from 0 to 1,000,000 ppm. Detailed wire/resource limits are in the References Notes data-contract link. Exact output may exceed the next call's accepted input size; a longer continuation needs an explicit resource profile, never truncation.

Run the exact implementations

Use the complete public reproduction ZIP in References → Notes and reproducibility. It supplies both unchanged financial modules, all 77 fixtures, the 15 independent algebra cases, reference tests, a portable parity runner and pinned development-tool lock. Python 3.11+ uses only the standard library. TypeScript uses Node 22+ and the included compiler:

Plain text
# At the extracted kit root:
npm ci --ignore-scripts --no-audit --no-fund
cd topic
python -B examples/run_example.py
python -B tests/test_compound.py
python -B tests/run_portable_parity.py
node examples/run_example.mjs

The original repository parity runner assumes the repository's directory depth. The separate portable runner uses the same unchanged reference tests and full fixture corpus with the kit's pinned compiler. The Python example works before npm installation; the JavaScript example imports the strictly compiled TypeScript module after parity.

From the extracted topic/, this complete Python example reads the three modeled scenarios and prints a short approximate display while leaving all financial outputs exact:

Python
import json, sys
from fractions import Fraction
sys.path.insert(0, "implementations/python")
from compound_interest import accrue_compound

with open("datasets/compound-cases.json", encoding="utf-8") as handle:
    cases = json.load(handle)["cases"]
for case_id in ["C01-35days-daily-delayed", "C02-35days-month-end-delayed",
                "C03-35days-daily-Oct31-credit"]:
    request = next(c["request"] for c in cases if c["id"] == case_id)
    result = accrue_compound(request)
    assert result["status"] == "ok"
    accrual = result["accrual"]
    value = accrual["earned_exact"]
    earned = Fraction(int(value["numerator"]), int(value["denominator"]))
    scaled = round(earned * 10**9)  # Display only; no state is changed.
    approximate = f"{scaled // 10**9}.{scaled % 10**9:09d}"
    print(case_id, approximate, accrual["scheduled_credit_minor"],
          accrual["pending_round_half_even_minor"])

The three displays are 442.515457121 0 443, 441.643835616 0 442 and 442.515532429 401 42. Python uses Fraction; TypeScript uses reduced BigInt fractions. All monetary wire values and fraction components remain strings. Long exact fractions remain available for audit rather than being printed as the first teaching result. Python 3.11 Fraction documentation.

Three Python test methods exercise fixture expectations, detached outputs, zero legs and a contiguous 31 + 4-day projection matching one 35-day request. All 77 complete outputs agree across Python and TypeScript; 15 independent cases use pre-code closed-form or weighted arithmetic. Long-output tests preserve exact state without changing the process-wide integer-conversion setting. Validation evidence.

Explore capitalization and crediting

The playground embeds the same TypeScript reference. It opens at day 35 with the daily-capitalization estimate of 443. Compare month-end's 442, then Begin replay a scheduled-credit scenario and step to 31 October: Q receives 401, C clears and signed R remains. The focused audit changes the visible rows only; computation retains all 35 dates. Missing evidence withholds the whole result.

Keep product state separate from accepted accounting

A positive customer-credit proposal maps Dr interest payable / Cr the requested deposit account, conditional on funded payable and accepted posting. Fresh interest normally follows a separate Dr interest expense / Cr interest payable accrual first. Customer crediting must not debit expense a second time.

This calculator does not know which payable accruals already posted, so it does not invent a new expense journal from C or A. The host must reconcile actual prior accrual/funding, authorize the account and use a stable scoped posting identity. A zero proposal has no legs; an oversized amount produces a blocked amount-limit proposal with no legs while retaining the exact calculation.

Even an unfunded or blocked proposal remains in the model's scheduled Q and closing state. Those values must not be presented as an accepted customer balance. Reconcile accepted postings before using the projection in an actual ledger pipeline.

In production

  • Keep the two schedules explicit. For covered US consumer accounts, Regulation DD treats compounding and crediting as distinct choices; it does not mandate a particular frequency. 12 CFR 1030.7(b).
  • Match applicable disclosures. Compounding and crediting frequency are disclosed separately. If accrued interest is forfeited on closing before crediting, the applicable disclosure must state that consequence. This model does not determine closure entitlement. 12 CFR 1030.4(b)(2).
  • Separate yield and accounting evidence. Nominal accrual is not an APY calculation; accrued/uncredited interest has specific disclosure treatment. Model pools alone do not prove the funded payable ledger. Appendix A interpretation.

Common mistakes

  • Adding modeled Q to a balance feed that already includes the same credits.
  • Treating daily capitalization as proof of daily posted customer credits.
  • Capitalizing merely because a report ends on 4 November.
  • Letting A or signed R enter the interest base before the selected transition.
  • Equating C + A with a funded payable balance, or ignoring R in modeled pending entitlement.

Key takeaways

  • Only X + Q + C earns; the excluded-interest feed keeps Q present once.
  • Capitalization and scheduled crediting are distinct model events with ordered boundaries.
  • The same external path gives pending estimates of 441, 442 or 443 under different capitalization rules.
  • Signed carry never earns, and period-end alone triggers no extra capitalization or credit.
  • Exact, consistent product projections still require separate source, funding and posting evidence.

Continue learning

References5 primary sources and evidence notes

Expand the source trail, evidence role, and limitations behind the engineering choices.

Accessed: 27 October 2026. US regulatory comparisons are bounded; all Cedar balances, rates, schedules and product terms are synthetic.

R01 — Regulation DD: Compounding and crediting

  • Organization: Consumer Financial Protection Bureau.
  • Source/version: 12 CFR 1030.7(b) and official interpretation, current; accessed 2026-10-27.
  • URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/7/
  • Supports: Compounding/crediting are distinct policies with no prescribed particular frequency in this section; closing-account treatment is subject to law/disclosure.
  • Limitations: Covered US consumer accounts. Does not prescribe Cedar's UTC days, pool schema, half-even carry, daily order or compliance; negative external principal routes unsupported.

R02 — Regulation DD: Account disclosures

  • Organization: Consumer Financial Protection Bureau.
  • Source/version: 12 CFR 1030.4(b)(2)(i)–(ii), current; accessed 2026-10-27.
  • URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/4/
  • Supports: Disclosure of compounding and crediting frequency and, when applicable, forfeiture if an account closes before accrued interest is credited.
  • Limitations: Disclosure context does not make C+A a legal entitlement or an actual payable balance; this model's pending amount includes R and does not implement closure rules.

R03 — Annual percentage yield calculation

  • Organization: Consumer Financial Protection Bureau.
  • Source/version: Regulation DD Appendix A, current; accessed 2026-10-27.
  • URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/a/
  • Supports: Separate annual-yield calculation context; nominal rate and APY are distinct concepts.
  • Limitations: This tutorial is a nominal-rate product projection, not an APY disclosure calculator.

R04 — APY official interpretation

  • Organization: Consumer Financial Protection Bureau.
  • Source/version: Official interpretation of Appendix A, Part II.A.1–2; current; accessed 2026-10-27.
  • URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/interp-a/
  • Supports: Specific statement-yield treatment of accrued/uncredited interest and rounding of paid interest.
  • Limitations: Those disclosure definitions do not turn the authored C/A/R pools into posted GL accounts or choose this calculator's crediting rule.

R05 — Exact rational arithmetic

  • Organization: Python Software Foundation.
  • Source/version: Python 3.11 fractions documentation, accessed 2026-10-27; local runtime 3.11.3.
  • URL: https://docs.python.org/3.11/library/fractions.html
  • Supports: Exact reduced ratios from integers, rational arithmetic and ties-to-even Fraction rounding.
  • Limitations: Financial schedules, strict wire grammar, input/output resource policy and large-integer chunking are authored choices, not library-defined product terms.

Notes and reproducibility

UTC EOD, ACT/365 Fixed, rate causality, excluded-interest feed, five-pool state, half-even credit/carry and finite resource bounds are selected fictional conventions. C+A+R is modeled pending entitlement; actual payable funding and legal closure treatment require independent evidence. The justified historical-example decision remains canonical README/research, not another external authority.

compound-interest.ts
/** Exact hypothetical product schedule. Proposals are not accepted postings. */
type Obj=Record<string,any>;
type Rat={n:bigint,d:bigint};
const fields=(s:string)=>s.split(' ');
const REQUEST=fields('schema_version calculation_id ledger_id entity_id account_id currency period_start period_end knowledge_cutoff day_count balance_basis capitalization credit_dates opening_state rate_versions days');
const OPENING=fields('as_of credited_minor capitalized uncapitalized rounding_carry');
const DAY=fields('date balance_minor balance_available_at balance_receipt_ref rate_version_id');
const RATE=fields('rate_version_id rate_ppm effective_from available_at');
const exact=(x:any,f:string[])=>x!==null&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).length===f.length&&f.every(k=>Object.hasOwn(x,k));
const match=(x:any,re:RegExp,digits=Infinity)=>typeof x==='string'&&re.exec(x)?.[0]===x&&x.replace(/^-/,'').length<=digits;
const ident=(x:any)=>match(x,/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/);
const signed=(x:any,digits:number)=>match(x,/^(0|-?[1-9][0-9]*)$/,digits);
const nonneg=(x:any,digits:number)=>match(x,/^(0|[1-9][0-9]*)$/,digits);
class ContractError extends Error{}
function need(ok:any,code:string):void{if(!ok)throw new ContractError(code);}
const abs=(n:bigint)=>n<0n?-n:n;
function gcd(a:bigint,b:bigint):bigint{a=abs(a);b=abs(b);while(b){const r=a%b;a=b;b=r;}return a;}
function f(n:bigint,d=1n):Rat{if(d<0n){n=-n;d=-d;}const g=gcd(n,d);return {n:n/g,d:d/g};}
const add=(a:Rat,b:Rat)=>f(a.n*b.d+b.n*a.d,a.d*b.d);
const sub=(a:Rat,b:Rat)=>add(a,{n:-b.n,d:b.d});
const mul=(a:Rat,b:Rat)=>f(a.n*b.n,a.d*b.d);
const wire=(x:Rat)=>({numerator:String(x.n),denominator:String(x.d)});
function rational(x:any,nonnegative=false,carry=false):Rat{
 need(exact(x,fields('numerator denominator')),'INVALID_RATIONAL');
 need(signed(x.numerator,4096)&&match(x.denominator,/^[1-9][0-9]*$/,4096),'INVALID_RATIONAL');
 const n=BigInt(x.numerator),d=BigInt(x.denominator);need(gcd(n,d)===1n,'INVALID_RATIONAL');
 if(nonnegative)need(n>=0n,'INVALID_OPENING_STATE');if(carry)need(2n*abs(n)<=d,'INVALID_CARRY');return {n,d};
}
function halfEven(x:Rat):bigint{const sign=x.n<0n?-1n:1n,n=abs(x.n);let q=n/x.d;const r=n%x.d;if(r*2n>x.d||(r*2n===x.d&&q%2n===1n))q++;return sign*q;}
function monthDays(y:number,m:number):number{return [31,y%4===0&&(y%100!==0||y%400===0)?29:28,31,30,31,30,31,31,30,31,30,31][m-1]!;}
function validDate(x:any):boolean{if(!match(x,/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/))return false;const y=Number(x.slice(0,4)),m=Number(x.slice(5,7)),d=Number(x.slice(8,10));return y>=1&&m>=1&&m<=12&&d>=1&&d<=monthDays(y,m);}
function timestamp(x:any):boolean{return match(x,/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/)&&validDate(x.slice(0,10))&&Number(x.slice(11,13))<24&&Number(x.slice(14,16))<60&&Number(x.slice(17,19))<60;}
const dayEpoch=(x:string)=>Date.parse(x+'T00:00:00.000Z');
const monthEnd=(x:string)=>Number(x.slice(8,10))===monthDays(Number(x.slice(0,4)),Number(x.slice(5,7)));
const sig=(v:Obj)=>JSON.stringify(RATE.map(k=>v[k]));

export function accrueCompound(request:any):Obj{
 try{return calculate(request);}catch(e){if(e instanceof ContractError)return {status:'rejected',code:e.message,accrual:null,closing_state:null,credit_proposals:[],trace:[]};throw e;}
}
function calculate(r:any):Obj{
 need(exact(r,REQUEST),'INVALID_SCHEMA');need(r.schema_version==='d30-compound-interest-v1','UNSUPPORTED_SCHEMA');
 need(['calculation_id','ledger_id','entity_id','account_id'].every(k=>ident(r[k])),'INVALID_IDENTIFIER');need(r.currency==='USD','UNSUPPORTED_CURRENCY');
 need(validDate(r.period_start)&&validDate(r.period_end),'INVALID_DATE');const length=(dayEpoch(r.period_end)-dayEpoch(r.period_start))/86400000;need(length>=1&&length<=366,'INVALID_PERIOD');
 need(timestamp(r.knowledge_cutoff),'INVALID_TIMESTAMP');need(r.knowledge_cutoff>=r.period_end+'T00:00:00.000Z','PERIOD_NOT_COVERED');
 need(r.day_count==='ACT_365_FIXED','UNSUPPORTED_DAY_COUNT');need(r.balance_basis==='external_principal_excluding_model_interest','UNSUPPORTED_BALANCE_BASIS');
 need(['daily','calendar_month_end'].includes(r.capitalization),'UNSUPPORTED_CAPITALIZATION');
 const opening=r.opening_state;need(exact(opening,OPENING),'INVALID_OPENING_STATE');need(opening.as_of===r.period_start&&nonneg(opening.credited_minor,30),'INVALID_OPENING_STATE');
 let Q=BigInt(opening.credited_minor),C=rational(opening.capitalized,true),A=rational(opening.uncapitalized,true),R=rational(opening.rounding_carry,false,true);const openingQ=Q;
 need(Array.isArray(r.credit_dates)&&r.credit_dates.length<=length,'INVALID_CREDIT_SCHEDULE');const creditDates=new Set<string>();let previous:string|null=null;
 for(const value of r.credit_dates){need(validDate(value)&&value>=r.period_start&&value<r.period_end,'INVALID_CREDIT_SCHEDULE');need(!creditDates.has(value),'DUPLICATE_CREDIT_DATE');need(previous===null||value>previous,'INVALID_CREDIT_SCHEDULE');need(r.capitalization==='daily'||monthEnd(value),'CREDIT_NOT_CAPITALIZATION_BOUNDARY');creditDates.add(value);previous=value;}
 need(Array.isArray(r.rate_versions)&&r.rate_versions.length>=1&&r.rate_versions.length<=512,'INVALID_RATE_VERSIONS');
 const rates=new Map<string,Obj>(),effectiveDates=new Set<string>();
 for(const v of r.rate_versions){need(exact(v,RATE),'INVALID_RATE_SCHEMA');need(ident(v.rate_version_id),'INVALID_IDENTIFIER');need(nonneg(v.rate_ppm,7)&&BigInt(v.rate_ppm)<=1000000n,'INVALID_RATE');need(validDate(v.effective_from),'INVALID_DATE');need(timestamp(v.available_at),'INVALID_TIMESTAMP');
  if(rates.has(v.rate_version_id))throw new ContractError(sig(v)===sig(rates.get(v.rate_version_id)!)?'DUPLICATE_RATE_VERSION':'RATE_VERSION_CONFLICT');
  need(!effectiveDates.has(v.effective_from),'AMBIGUOUS_RATE_SCHEDULE');need(v.available_at<=v.effective_from+'T00:00:00.000Z','RETROACTIVE_RATE_POLICY_UNSUPPORTED');effectiveDates.add(v.effective_from);rates.set(v.rate_version_id,v);
 }
 need(Array.isArray(r.days)&&r.days.length===length,'INVALID_DAY_COVERAGE');const rows:{row:Obj,ppm:bigint}[]=[],seen=new Set<string>();previous=null;
 for(let i=0;i<r.days.length;i++){const row=r.days[i];need(exact(row,DAY),'INVALID_DAY_SCHEMA');need(validDate(row.date),'INVALID_DATE');need(!seen.has(row.date),'DUPLICATE_DAY');need(previous===null||row.date>previous,'OUT_OF_ORDER_DAY');need(row.date===new Date(dayEpoch(r.period_start)+i*86400000).toISOString().slice(0,10),'INVALID_DAY_COVERAGE');seen.add(row.date);previous=row.date;
  need(signed(row.balance_minor,30),'INVALID_BALANCE');need(BigInt(row.balance_minor)>=0n,'NEGATIVE_BALANCE_POLICY_UNSUPPORTED');need(ident(row.balance_receipt_ref)&&ident(row.rate_version_id),'INVALID_IDENTIFIER');need(timestamp(row.balance_available_at),'INVALID_TIMESTAMP');need(row.balance_available_at>=row.date+'T23:59:59.999Z','BALANCE_NOT_COMPLETE');need(row.balance_available_at<=r.knowledge_cutoff,'BALANCE_NOT_AVAILABLE');
  need(rates.has(row.rate_version_id),'UNKNOWN_RATE_VERSION');const chosen=rates.get(row.rate_version_id)!,dayStart=row.date+'T00:00:00.000Z';need(chosen.effective_from<=row.date&&chosen.available_at<=dayStart,'RATE_NOT_AVAILABLE_AT_DAY_START');const applicable=[...rates.values()].filter(v=>v.effective_from<=row.date&&v.available_at<=dayStart).sort((a,b)=>a.effective_from.localeCompare(b.effective_from));need(chosen.rate_version_id===applicable[applicable.length-1]!.rate_version_id,'STALE_RATE_VERSION');rows.push({row,ppm:BigInt(chosen.rate_ppm)});
 }
 let earned=f(0n);const trace:Obj[]=[],proposals:Obj[]=[];
 for(const {row,ppm} of rows){const X=BigInt(row.balance_minor),beforeQ=Q,base=add(f(X+Q),C),interest=mul(base,f(ppm,365000000n));earned=add(earned,interest);A=add(A,interest);const capped=r.capitalization==='daily'||monthEnd(row.date);if(capped){C=add(C,A);A=f(0n);}const scheduled=creditDates.has(row.date);let q=0n;
  if(scheduled){const entitlement=add(C,R);q=halfEven(entitlement);Q+=q;C=f(0n);R=sub(entitlement,f(q));const status=q===0n?'zero':q<=10n**30n-1n?'ready':'amount-limit';const legs=status!=='ready'?[]:[{account_id:'interest_payable_usd',side:'debit',amount_minor:String(q)},{account_id:r.account_id,side:'credit',amount_minor:String(q)}];proposals.push({date:row.date,exact_entitlement:wire(entitlement),amount_minor:String(q),carry_after:wire(R),status,payable_funding_required:q>0n,legs});}
  trace.push({date:row.date,external_principal_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:String(ppm),credited_before_minor:String(beforeQ),interest_base_exact:wire(base),exact_daily_interest:wire(interest),cumulative_earned_exact:wire(earned),capitalization_applied:capped,credit_scheduled:scheduled,credit_minor:String(q),projected_principal_after_minor:String(X+Q),capitalized_after:wire(C),uncapitalized_after:wire(A),rounding_carry_after:wire(R)});
 }
 const pending=add(add(C,A),R),estimate=halfEven(pending),accrual:Obj={};for(const k of fields('ledger_id entity_id account_id currency period_start period_end day_count balance_basis capitalization knowledge_cutoff'))accrual[k]=r[k];
 Object.assign(accrual,{day_count_value:length,earned_exact:wire(earned),scheduled_credit_minor:String(Q-openingQ),projected_principal_minor:String(BigInt(rows[rows.length-1]!.row.balance_minor)+Q),pending_entitlement_exact:wire(pending),pending_round_half_even_minor:String(estimate),pending_estimate_residual:wire(sub(pending,f(estimate)))});
 return {status:'ok',code:'COMPOUND_INTEREST_ACCRUED',accrual,closing_state:{as_of:r.period_end,credited_minor:String(Q),capitalized:wire(C),uncapitalized:wire(A),rounding_carry:wire(R)},credit_proposals:proposals,trace};
}
Interactive labcompound labOpen full screen
Written by

Fintech engineer building market-data and financial systems, and the author of every article, glossary record, and reference implementation on The Fintech Builder.