The governed definitions this build depends on. Read them first if a term is unfamiliar.
- PrimaryDay-count conventionA day-count convention defines how dates are converted into the time fraction used by an interest calculation.
- PrimaryInterest accrualInterest accrual measures interest earned or incurred over an interval under an agreed balance and rate convention.
- ImportantAccounting accrualAn accounting accrual recognizes period-related income or expense independently of when the corresponding cash is received or paid.
- ImportantCurrency minor unitA currency minor unit is a declared subdivision used to express monetary amounts at the currency's specified scale.
- ImportantLedger posted balanceA ledger posted balance is the balance obtained from entries accepted into the relevant account ledger at a specified boundary.
A deposit holds 3,650 cents ($36.50) at 5% nominal annual interest for two days. Each day earns exactly half a cent. Round each day half-even and both halves become zero: one earned cent disappears. Round each half up instead and two cents are paid for one cent of interest.
Repeated across accounts and periods, that small choice makes rounded postings disagree with exact earned interest. This tutorial builds a daily simple-interest accrual in Python and TypeScript. It counts every calendar day, applies the rate that was known and effective for that day, keeps exact fractions and rounds once at the chosen settlement boundary.
What you'll learn
- Retain quiet days and reject a missing date instead of inventing a zero.
- Apply Actual/365 Fixed using integer rates and exact fractions.
- Select immutable, causally available rate versions.
- Preserve signed carry when a whole-cent proposal rounds up or down.
- Separate expense/payable accrual from a later customer deposit credit.
Before you start: Double-Entry Posting Engine explains bank-book account signs. Event-Sourced Balance Fold explains posted history and as-of evidence. Basic fractions and JSON are enough for the calculations.
About the data: Cedar Teaching Bank, entity CB-A, ledger CB-GENERAL and account deposits_product_usd are fictional. This separate product-calendar example uses synthetic balances, rate versions, receipts and terms.
Choose the contract before calculating
The selected balance is the posted normal deposit balance at the end of each UTC civil day. The half-open period [2026-10-01, 2026-11-05) includes 1 October through 4 November: 35 complete days, with no holiday or business-day exclusion.
The annual input is a nominal rate in integer parts per million (ppm): 50,000 ppm = 50,000 / 1,000,000 = 5%. Actual/365 Fixed counts the actual days but divides by 365 even during a leap year. Another contract may use a different denominator or balance basis.
| Input | Selected rule | Invalid or unsupported example |
|---|---|---|
| Daily balance | Canonical integer-cent string, at most 30 magnitude digits | Numeric JSON, exponent or leading zero rejects |
| Calendar | One ordered row per required day; 1–366 days | Missing, duplicate or reordered date rejects |
| Rate | Integer string from 0 to 1,000,000 ppm; at most 512 versions | Stale daily reference rejects |
| Opening carry | Reduced fraction within −1/2 to +1/2 cent | Noncanonical or out-of-bound fraction rejects |
| Currency / day count | USD / ACT_365_FIXED | Other policies route explicitly unsupported |
Negative eligible principal is also unsupported here. A negative rounding carry is valid and has a different meaning. These are Cedar's teaching choices; a syntactically valid account or receipt identifier does not authenticate ownership or source completeness.
Count every quiet day
The product account begins with 100,000 cents ($1,000.00). Withdrawals of 2,400 cents on 22 October, 12,000 cents on 24 October and 10,000 cents on 26 October give this end-of-day (EOD) calendar:
| Dates | Days | EOD balance, cents | Balance × 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 |
| Full period | 35 | — | 3,222,400 |
Those first 21 quiet days all earn interest. Four transaction-date snapshots cannot substitute for the complete 35-day path. The weighted sum has units of balance-cent-days; it is not another deposit balance.
Missing days are errors, never zero balances or interpolated guesses. In production, a posted-history reader such as Event-Sourced Balance Fold can supply dated projections. Here the rows are authored directly; they do not establish an actual integration with that reader.
Accumulate exact daily fractions
Let B[d] be a day's eligible balance in integer cents and p[d] its annual nominal rate in ppm:
daily interest = B[d] × p[d] / 365000000
period earned = sum of every exact daily fraction
The denominator is 365 × 1,000,000. The result is a fraction of a cent, not dollars. At a constant 50,000 ppm the complete calendar gives:
earned = 3222400 / 7300
= 32224/73 cents
= 441 + 31/73 cents
With zero incoming carry, one half-even rounding produces 441 cents ($4.41). The remaining 31/73 of a cent, about 0.42 cent, carries forward. Full October alone is a different period: its 31 balances sum to 2,920,000 balance-cent-days and earn exactly 400 cents ($4.00).
The opening two-day example has B = 3,650 and p = 50,000. Each day earns 3,650 / 7,300 = 1/2 cent; the period earns exactly 1 cent. Keep both halves until settlement. Interest earned by this engine is never automatically added to the next day's base: this is simple interest.
Apply each rate when it was known and effective
Each daily row names an immutable rate version containing rate_version_id, rate_ppm, effective_from and available_at. This profile requires a version to have been announced no later than its own effective-day start. A later announcement routes RETROACTIVE_RATE_POLICY_UNSUPPORTED, rather than silently changing earlier terms.
For each day, use the latest effective version available by the day's start. A stale row reference cannot bypass a newer applicable version. Equal effective dates under different IDs are ambiguous; an exact duplicate ID/payload rejects, and changed facts under one ID conflict. Rate-array delivery order is irrelevant; the daily calendar's order remains semantic.
Balance receipts have a separate clock: day close ≤ balance receipt ≤ knowledge cutoff K. K must reach the period's exclusive-end midnight. A correction learned later can support an explicitly later as-of recomputation; it cannot enter an earlier evidence snapshot invisibly. The host must establish ownership, authentic receipts and schedule completeness.
Compare a changing rate
The separate 20–28 October focus has nine balances, totaling 793,200 balance-cent-days:
100000, 100000, 97600, 97600, 85600, 85600, 75600, 75600, 75600
At a constant 5%, earned interest is 7,932/73 cents: a 109-cent proposal and −25/73-cent carry. If the final five days use 6%, keep the first four days at 5%:
first 4 days: balance sum 395200 at 50000 ppm
last 5 days: balance sum 398000 at 60000 ppm
earned = (395200 × 50000 + 398000 × 60000) / 365000000
= 8728/73 cents
rounded = 120 cents; carry = −32/73 cent
Applying the final 6% to the whole window would produce 130 cents instead of 120, repricing four earlier days. Average-Daily-Balance Interest uses the same 24 October rate change over the full 35 days: its properly separated rate segments produce 467 cents. The two examples use different periods.
Preserve signed carry across periods
settlement exact = earned exact + opening carry
rounded proposal = half_even(settlement exact)
closing carry = settlement exact − rounded proposal
Half-even chooses the nearest integer and the even integer at an exact tie: 1/2 rounds to 0, while 3/2 rounds to 2. After 3/2 rounds up, closing carry is −1/2 cent. That residual records the half-cent already over-rounded; it is not negative principal.
If the next period earns 1/2 cent, the prior −1/2 cancels it: settlement 0, zero proposal, zero carry. Across both periods, exact earned interest and rounded proposals reconcile. Zero carry is canonically 0/1; every fraction is reduced.
Accrue once, then credit separately
For the complete 35-day calculation, the uncommitted accrual proposal is:
Dr interest_expense_usd 441
Cr interest_payable_usd 441
A later actual customer credit is a separate entry:
Dr interest_payable_usd 441
Cr deposits_product_usd 441
The first recognizes the selected expense/payable; the second moves the payable into the deposit. Debiting expense again at crediting would double the cost. This pure calculator durably posts neither entry.
A zero proposal has no zero-valued legs. If the rounded amount exceeds the posting engine's 30-digit positive-leg limit, exact calculation still succeeds, but proposal status is amount-limit and legs is empty. Calculation success and posting eligibility are separate outcomes.
The host must validate the chart, assign stable journal/business identity and supply effective, booking and recording context before posting. A new calculation ID or later K does not authorize a second expense for an already accrued period: reconcile or correct the existing posting.
The validation and settlement order is:
Run the complete reference
Use the public reproduction ZIP linked in the References → Notes and reproducibility section. It contains the unchanged Python/TypeScript modules, all 93 fixtures, strict compiler configuration, original reference runners and a locked toolchain. Extract it into a clean folder; Python 3.11+ needs only the standard library. TypeScript uses Node 22+ and the included development dependencies:
# 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_daily_simple.py
python -B tests/run_parity.py
node examples/run_example.mjs
The Python example also runs before npm installation. The JavaScript example imports the TypeScript module compiled by the parity runner. From the extracted topic/ folder, this complete Python example returns the canonical result:
import json
from implementations.python.daily_simple import accrue_daily_simple
with open("datasets/interest-cases.json", encoding="utf-8") as handle:
case = json.load(handle)["cases"][0]
result = accrue_daily_simple(case["request"])
assert result["status"] == "ok"
assert result["accrual"]["earned_exact"] == {
"numerator": "32224", "denominator": "73"
}
assert result["posting_proposal"]["amount_minor"] == "441"
print(json.dumps(result, indent=2))
Python uses Fraction from validated integers; TypeScript uses gcd-reduced BigInt fractions and signed exact half-even. Both functions return status, code, accrual, trace and posting_proposal. Money and fraction components remain canonical strings. Every accepted day appears in the trace with its applied version and exact daily/cumulative fraction. Rejected evidence returns null accrual/proposal and an empty trace, never a partial-looking amount. Python 3.11 Fraction documentation.
Explore the guided comparison
The playground runs the same TypeScript reference. It opens on the complete 35-day preview. Begin replay, then Step, to see each exact daily fraction enter the accumulator. The nine-day audit focus changes only the visible rows; it does not discard the other 26 days from computation. Compare the two half-cent days, changing rate, signed carry, leap day and missing evidence.
Six Python test methods and a 93-case full-output Python/TypeScript comparison check the daily trace, exact period values, carry, proposal, nulls and rejection codes. They include genuine years 0001–0099, a 366-day calendar, large integers and a correct calculation with a blocked posting proposal. Validation evidence.
In production
- Match the applicable agreement. For covered US consumer accounts, Regulation DD recognizes daily and average daily balance methods. It separately addresses compounding and crediting. It does not choose Cedar's UTC clock or half-even rule. 12 CFR 1030.7.
- Preserve disclosed terms. Account disclosures include rate/APY, compounding and crediting frequency, and the balance-computation method. Bind the calculation to the applicable product version. 12 CFR 1030.4.
- Keep nominal rate distinct from yield. The 5% input here is nominal. APY has a separate annualized-yield calculation and disclosure context; this calculator does not compute it. Regulation DD Appendix A.
- Reconcile the posting boundary. Persist approved carry per account/period, reconcile accepted accruals to the payable ledger, and use a stable scoped identity for actual posting. Recomputing this pure result does not prove a database write occurred.
Common mistakes
- Rounding each half-cent day independently: 0 cents with half-even or 2 cents with half-up instead of 1 cent.
- Keeping only transaction dates or treating a missing balance as zero.
- Applying the final rate to earlier days: 130 cents instead of 120 in the nine-day comparison.
- Reading negative carry as negative principal, or dropping carry after a rounded-up period.
- Expensing the same interest again when crediting the deposit.
Key takeaways
- A complete daily path includes quiet days and rejects missing evidence.
- Exact daily fractions accumulate before one half-even settlement rounding.
- Every day uses its applicable, already announced rate version.
- Opening carry + earned = rounded proposal + closing carry, including signed residuals.
- Expense/payable accrual and customer credit are separate entries and separate host actions.
Continue learning
- Next: Compound Interest Accrual changes the interest-bearing base at explicit capitalization boundaries.
- Compare: Average-Daily-Balance Interest reaches equivalent totals with the same rate segments.
- Post safely: Idempotent Journal Posting protects accepted operation identity at a separate posting boundary.
References5 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. Primary evidence is scoped below; the calendar and Cedar terms are synthetic.
R01 — Regulation DD: Payment of interest
- Organization: Consumer Financial Protection Bureau.
- Source/version: 12 CFR 1030.7, current regulation and official interpretations, accessed 2026-10-27.
- URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/7/
- Supports: Daily and average daily balance methods, full daily principal, leap-year denominator options, separate compounding/crediting policies.
- Limitations: Covered US consumer accounts. Does not establish Cedar's UTC clocks, half-even rounding, eligibility or regulatory compliance; the reference routes negative principal unsupported.
R02 — Regulation DD: Account disclosures
- Organization: Consumer Financial Protection Bureau.
- Source/version: 12 CFR 1030.4(b), current regulation, accessed 2026-10-27.
- URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/4/
- Supports: Disclosure of interest rate/APY, compounding and crediting frequency, and balance-computation method.
- Limitations: Disclosure obligations are jurisdiction/product dependent; this teaching calculator does not establish a real agreement or disclosure.
R03 — Regulation DD: Definitions
- Organization: Consumer Financial Protection Bureau.
- Source/version: 12 CFR 1030.2(c)–(f), current regulation, accessed 2026-10-27.
- URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/2/
- Supports: Nominal interest rate, APY, daily balance and average daily balance terminology.
- Limitations: US definitions; no universal day-count or posting-policy mandate.
R04 — Annual percentage yield calculation
- Organization: Consumer Financial Protection Bureau.
- Source/version: Regulation DD Appendix A and official interpretation, current, accessed 2026-10-27.
- URL: https://www.consumerfinance.gov/rules-policy/regulations/1030/a/ and https://www.consumerfinance.gov/rules-policy/regulations/1030/interp-a/
- Supports: APY annualization, interest/compounding context, separate APY-earned rounding rules.
- Limitations: A nominal-rate daily accrual is not this disclosure calculation. Appendix A does not prescribe this exact rational carry or half-even policy.
R05 — Exact rational arithmetic
- Organization: Python Software Foundation.
- Source/version: Python 3.11
fractionsdocumentation; accessed 2026-10-27; local runtime 3.11.3. - URL: https://docs.python.org/3.11/library/fractions.html
- Supports: Integer-ratio construction, reduced rational arithmetic and ties-to-even rounding for Fraction.
- Limitations: Strict wire grammar, finite resource bounds and financial rounding policy are additional authored decisions. Constructing from a float retains its binary value.
Notes and reproducibility
UTC EOD, ACT/365 Fixed, nominal rate bounds, immutable causal rate selection, signed carry and the posting limit are this teaching profile's choices. The formal synthetic/historical-example decision remains in the canonical README and source/claim ledgers; it is not an external source.
- Complete public reproduction ZIP, inventory and SHA256, fresh-folder run receipt.
- Usage and setup, strict data contract, independent arithmetic, validation.
- Python primary
daily_simple.py; TypeScript primarydaily-simple.ts. The kit supplies the fixtures, strict tsconfig and reference runners absent from a single Code tab. No website checkout or global compiler is required afternpm ci.
The complete 35-day calendar, signed residuals and account proposals are independently authored arithmetic, not a real bank tariff, performance benchmark or accepted journal. Source receipts and account ownership are trusted host obligations.
Full dependency-light reference implementations in both supported languages.
/** Exact daily simple interest. All JSON money/fractions remain strings. */
type Obj = Record<string, any>;
export type Rational = {n: bigint; d: bigint};
const REQUEST = ['schema_version','calculation_id','ledger_id','entity_id','account_id','currency','period_start','period_end','knowledge_cutoff','day_count','opening_carry','rate_versions','days'];
const DAY = ['date','balance_minor','balance_available_at','balance_receipt_ref','rate_version_id'];
const VERSION = ['rate_version_id','rate_ppm','effective_from','available_at'];
const IDENT = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
const DATE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
const STAMP = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/;
const SIGNED = /^(0|-?[1-9][0-9]{0,29})$/;
const UNSIGNED = /^(0|[1-9][0-9]{0,29})$/;
const POSITIVE = /^[1-9][0-9]{0,29}$/;
const MAX_LEG = 10n ** 30n - 1n;
const DENOMINATOR = 365000000n;
export class InterestError extends Error {}
function need(condition: any, code: string): asserts condition {
if (!condition) throw new InterestError(code);
}
const object = (v: any): v is Obj => v !== null && typeof v === 'object' &&
!Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
const exact = (v: any, fields: string[]): v is Obj => object(v) &&
Object.keys(v).length === fields.length && fields.every(k => Object.hasOwn(v, k));
const full = (pattern: RegExp, value: string) => pattern.exec(value)?.[0] === value;
const identifier = (v: any) => typeof v === 'string' && full(IDENT, v);
function civil(v: any): number | null {
if (typeof v !== 'string' || !full(DATE, v) || v.slice(0, 4) === '0000') return null;
// ISO construction preserves years0001–0099; Date.UTC numeric years would not.
const d = new Date(v + 'T00:00:00.000Z');
return Number.isFinite(d.getTime()) && d.toISOString().slice(0, 10) === v ? d.getTime() : null;
}
function timestamp(v: any): boolean {
if (typeof v !== 'string' || !full(STAMP, v) || v.slice(0, 4) === '0000') return false;
const d = new Date(v);
return Number.isFinite(d.getTime()) && d.toISOString() === v;
}
function abs(n: bigint) { return n < 0n ? -n : n; }
function gcd(a: bigint, b: bigint): bigint {
while (b !== 0n) [a, b] = [b, a % b];
return a;
}
export function rational(n: bigint, d = 1n): Rational {
if (d <= 0n) throw new Error('Positive rational denominator required');
const g = gcd(abs(n), d); return {n: n / g, d: d / g};
}
export const add = (a: Rational, b: Rational) => rational(a.n * b.d + b.n * a.d, a.d * b.d);
export const mulInt = (a: Rational, n: bigint) => rational(a.n * n, a.d);
export const fractionJson = (a: Rational) => ({numerator: a.n.toString(), denominator: a.d.toString()});
export function roundHalfEven(a: Rational): bigint {
const sign = a.n < 0n ? -1n : 1n, n = abs(a.n), remainder = n % a.d;
let whole = n / a.d;
if (2n * remainder > a.d || (2n * remainder === a.d && whole % 2n === 1n)) whole++;
return sign * whole;
}
function parseCarry(value: any): Rational {
need(exact(value, ['numerator','denominator']), 'INVALID_CARRY');
need(typeof value.numerator === 'string' && full(SIGNED, value.numerator), 'INVALID_CARRY');
need(typeof value.denominator === 'string' && full(POSITIVE, value.denominator), 'INVALID_CARRY');
const n = BigInt(value.numerator), d = BigInt(value.denominator);
need(gcd(abs(n), d) === 1n && abs(2n * n) <= d, 'INVALID_CARRY');
return rational(n, d);
}
export function validateCalendar(request: any): {rows: Obj[]; carry: Rational; dayCount: number} {
need(exact(request, REQUEST), 'INVALID_SCHEMA');
need(request.schema_version === 'd30-daily-simple-interest-v1', 'UNSUPPORTED_SCHEMA');
need(['calculation_id','ledger_id','entity_id','account_id'].every(k => identifier(request[k])), 'INVALID_IDENTIFIER');
need(request.currency === 'USD', 'UNSUPPORTED_CURRENCY');
need(request.day_count === 'ACT_365_FIXED', 'UNSUPPORTED_DAY_COUNT');
const start = civil(request.period_start), end = civil(request.period_end);
need(start !== null && end !== null, 'INVALID_DATE');
const count = (end - start) / 86400000;
need(count >= 1 && count <= 366, 'INVALID_PERIOD');
need(timestamp(request.knowledge_cutoff), 'INVALID_TIMESTAMP');
need(request.knowledge_cutoff >= request.period_end + 'T00:00:00.000Z', 'KNOWLEDGE_BEFORE_PERIOD_END');
const carry = parseCarry(request.opening_carry), versions = request.rate_versions;
need(Array.isArray(versions) && versions.length <= 512, 'INVALID_RATE_VERSIONS');
const byId = new Map<string, Obj>(), byEffective = new Set<string>();
for (const version of versions) {
need(exact(version, VERSION), 'INVALID_SCHEMA');
need(identifier(version.rate_version_id), 'INVALID_IDENTIFIER');
need(typeof version.rate_ppm === 'string' && full(UNSIGNED, version.rate_ppm), 'INVALID_RATE');
need(BigInt(version.rate_ppm) <= 1000000n, 'UNSUPPORTED_RATE');
need(civil(version.effective_from) !== null, 'INVALID_DATE');
need(timestamp(version.available_at), 'INVALID_TIMESTAMP');
need(version.available_at <= version.effective_from + 'T00:00:00.000Z', 'RETROACTIVE_RATE_POLICY_UNSUPPORTED');
if (byId.has(version.rate_version_id)) {
const saved = byId.get(version.rate_version_id)!;
need(!VERSION.every(k => saved[k] === version[k]), 'DUPLICATE_RATE_VERSION');
throw new InterestError('RATE_VERSION_CONFLICT');
}
need(!byEffective.has(version.effective_from), 'AMBIGUOUS_RATE_SCHEDULE');
byId.set(version.rate_version_id, version); byEffective.add(version.effective_from);
}
const days = request.days;
need(Array.isArray(days), 'INVALID_CALENDAR');
need(days.length === count, 'INCOMPLETE_CALENDAR');
const rows: Obj[] = [], seen = new Set<string>(); let negative = false;
for (const [index, row] of days.entries()) {
need(exact(row, DAY), 'INVALID_SCHEMA');
const current = civil(row.date); need(current !== null, 'INVALID_DATE');
need(current >= start && current < end, 'DAY_OUTSIDE_PERIOD');
need(!seen.has(row.date), 'DUPLICATE_DAY');
need(current === start + index * 86400000, 'OUT_OF_ORDER_DAY'); seen.add(row.date);
need(typeof row.balance_minor === 'string' && full(SIGNED, row.balance_minor), 'INVALID_BALANCE');
negative = negative || BigInt(row.balance_minor) < 0n;
need(timestamp(row.balance_available_at), 'INVALID_TIMESTAMP');
need(row.balance_available_at >= row.date + 'T23:59:59.999Z', 'BALANCE_BEFORE_DAY_CLOSE');
need(row.balance_available_at <= request.knowledge_cutoff, 'BALANCE_BEYOND_KNOWLEDGE');
need(identifier(row.balance_receipt_ref) && identifier(row.rate_version_id), 'INVALID_IDENTIFIER');
const applicable = versions.filter(v => v.effective_from <= row.date && v.available_at <= row.date + 'T00:00:00.000Z');
need(applicable.length > 0, 'NO_APPLICABLE_RATE');
need(byId.has(row.rate_version_id), 'UNKNOWN_RATE_VERSION');
const applied = byId.get(row.rate_version_id)!;
need(applied.effective_from <= row.date, 'RATE_NOT_EFFECTIVE');
need(applied.available_at <= row.date + 'T00:00:00.000Z', 'RATE_NOT_AVAILABLE');
const latest = applicable.reduce((a, b) => a.effective_from > b.effective_from ? a : b);
need(applied.rate_version_id === latest.rate_version_id, 'STALE_RATE_VERSION');
rows.push({...row, rate_ppm: applied.rate_ppm});
}
need(!negative, 'NEGATIVE_BALANCE_POLICY_UNSUPPORTED');
return {rows, carry, dayCount: count};
}
export function makePostingProposal(request: Obj, rounded: bigint): Obj {
const status = rounded === 0n ? 'zero' : rounded > MAX_LEG ? 'amount-limit' : 'ready';
const legs = status !== 'ready' ? [] : [
{account_id:'interest_expense_usd', side:'debit', amount_minor:rounded.toString()},
{account_id:'interest_payable_usd', side:'credit', amount_minor:rounded.toString()}
];
return {schema_version:'d30-interest-accrual-proposal-v1', calculation_id:request.calculation_id,
ledger_id:request.ledger_id, entity_id:request.entity_id, account_id:request.account_id,
currency:request.currency, period_start:request.period_start, period_end:request.period_end,
knowledge_cutoff:request.knowledge_cutoff, status, amount_minor:rounded.toString(), legs};
}
export function accrueDailySimple(request: any): Obj {
try {
const validated = validateCalendar(request); let earned = rational(0n), balanceSum = 0n;
const trace: Obj[] = [];
for (const row of validated.rows) {
const balance = BigInt(row.balance_minor);
const daily = rational(balance * BigInt(row.rate_ppm), DENOMINATOR);
earned = add(earned, daily); balanceSum += balance;
trace.push({...row, exact_daily_interest:fractionJson(daily), cumulative_earned_exact:fractionJson(earned)});
}
const settlement = add(earned, validated.carry), rounded = roundHalfEven(settlement);
const accrual: Obj = {};
for (const k of ['ledger_id','entity_id','account_id','currency','period_start','period_end','day_count','knowledge_cutoff']) accrual[k] = request[k];
Object.assign(accrual, {day_count_value:String(validated.dayCount), balance_sum_minor:balanceSum.toString(),
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)))});
return {status:'ok', code:'INTEREST_ACCRUED', accrual, trace, posting_proposal:makePostingProposal(request, rounded)};
} catch (error) {
if (error instanceof InterestError) return {status:'rejected', code:error.message, accrual:null, trace:[], posting_proposal:null};
throw error;
}
}
Choose a scenario, step through the decisions and compare the result with the worked example.
