Building a Multi-Country Real Estate Underwriting Engine in Pure JS (Canadian Semi-Annual Mortgages, OSFI B-20, US 30yr & French LMNP)
Almost every real estate calculator on the web makes the same shortcut: it takes a US 30-year monthly-compounded mortgage formula (r / 12), slaps on a flat 2% closing cost, and calls it a day. The moment you underwrite
Almost every real estate calculator on the web makes the same shortcut: it takes a US 30-year monthly-compounded mortgage formula (r / 12), slaps on a flat 2% closing cost, and calls it a day.
The moment you underwrite a duplex in Montreal, a triplex in Toronto, a single-family rental in Chicago, and a furnished apartment in Lyon inside the same codebase, that shortcut produces numbers that are off by hundreds of dollars per month and thousands of dollars at closing.
When I built PlexPulse (a free client-side Chrome and Firefox extension + interactive underwriting calculator for Canada, the US, and France), I had to model every regional rule in a single zero-dependency JavaScript module (finance.js) that runs in < 1 ms right inside listing pages.
Here is the math, the edge cases, and the pure JS implementation behind a genuinely accurate multi-country underwriting engine.
1. Canadian Semi-Annual Compounding vs. US/FR Monthly Compounding
In the United States and France, fixed-rate mortgages compound monthly:
r_monthly = r_nominal / 12
In Canada, under the federal Interest Act, fixed-rate residential mortgages must be compounded semi-annually, not in advance. Converting a nominal Canadian rate r to an effective monthly rate requires:
r_monthly_ca = (1 + r / 2)^(2/12) - 1 = (1 + r / 2)^(1/6) - 1
At 5.00% nominal on a $600,000 / 25-year loan:
- Naive monthly compounding (
0.05 / 12 = 0.41667%): $3,507.54/mo - Exact Canadian semi-annual compounding (
0.41239%): $3,489.63/mo
That is an $17.91/mo ($215/year) error before you even look at taxes or insurance β and it cascades directly into DSCR, cash-on-cash return, and Year-1 principal paydown.
In pure JS, unifying both regimes is clean:
function getMonthlyRate(annualRatePct, compounding) {
const rate = Number(annualRatePct) || 0;
if (rate <= 0) return 0;
if (compounding === 'monthly') {
return rate / 100 / 12;
}
// Canadian legal semi-annual compounding: (1 + r/2)^(2/12) - 1
return Math.pow(1 + rate / 100 / 2, 1 / 6) - 1;
}
function getMonthlyMortgageFactor(annualRatePct, amortizationYears, compounding) {
const n = Math.max(1, Number(amortizationYears) || 25) * 12;
const r = getMonthlyRate(annualRatePct, compounding);
if (r === 0) return 1 / n;
return r / (1 - Math.pow(1 + r, -n));
}
Exact Year-1 Principal Paydown (and Interest for Tax Deductibility)
Instead of approximating Year-1 equity paydown, simulate the first 12 monthly periods directly. It takes 12 iterations and gives you both Total Year-1 ROI ((annualCashflow + year1PrincipalPaydown) / totalCashRequired) and the exact Year-1 deductible interest needed for French LMNP RΓ©el tax modeling:
function calcYear1PrincipalPaydown(principal, annualRatePct, amortizationYears, compounding) {
let balance = Number(principal) || 0;
if (balance <= 0) return 0;
const r = getMonthlyRate(annualRatePct, compounding);
const payment = balance * getMonthlyMortgageFactor(annualRatePct, amortizationYears, compounding);
let totalPrincipal = 0;
for (let month = 0; month < 12 && balance > 0; month += 1) {
const interest = balance * r;
const principalPaid = Math.min(balance, Math.max(0, payment - interest));
balance -= principalPaid;
totalPrincipal += principalPaid;
}
return totalPrincipal;
}
2. Mortgage Insurance Across 3 Jurisdictions (CMHC, US PMI & French Borrower Insurance)
Each market handles loan insurance completely differently β and getting whether it is capitalized into principal, paid monthly, or taxed upfront in cash makes a massive difference to cash-to-close:
| Market | Trigger | Rate Structure | How It Is Paid |
|---|---|---|---|
| Canada (CMHC/SCHL) |
< 20% down, owner-occupied, 1β4 units, price < $1.5M
|
4.0% (<10%), 3.1% (10β14.99%), 2.8% (15β19.99%), +0.2% if amort > 25y
|
Premium capitalized into mortgage; provincial tax (9% QC PST, 8% ON RST) paid in cash at closing |
| US (PMI) |
< 20% down (min 3.5% owner-occ / 15% investor) |
~0.85%/yr of base loan |
Monthly cash expense (baseLoan * 0.0085 / 12) |
| France (Assurance emprunteur) | Practically mandatory on all loans |
~0.34%/yr of base loan |
Monthly cash expense + tax-deductible under LMNP RΓ©el |
Notice two Canadian gotchas most calculators miss:
-
The eligibility cliff: Investment properties (
!isOwnerOccupied), 5+ unit multiplexes, and purchases>= $1,500,000(the updated federal insured cap) are ineligible for CMHC, forcing at least 20% down. For 1β2 unit owner-occupied homes between$500kand$1.5M, the legal minimum down payment is tiered:5%on the first$500,000+10%on the remainder. -
Quebec 9% PST & Ontario 8% RST on the CMHC premium: Even though the CMHC premium itself is rolled into the mortgage (
financedPrincipal = baseLoan + cmhc.premium), Quebec charges 9% PST (and Ontario 8% RST) on that premium due in cash at the notary. On a $750,000 owner-occupied duplex with 10% down, that's~$1,883of surprise closing cash.
function getMinDownPaymentPct(price, units, isOwnerOccupied) {
if (price <= 0) return 20;
if (!isOwnerOccupied || units >= 5 || price >= 1500000) return 20;
if (units >= 3) return 10;
if (price <= 500000) return 5;
const minAmount = 500000 * 0.05 + (price - 500000) * 0.10;
return Math.round((minAmount / price) * 10000) / 100;
}
function calcCmhcInsurance(price, downPct, isOwnerOccupied, amortYears, units, jurisdiction) {
const minDownPct = getMinDownPaymentPct(price, units, isOwnerOccupied);
const ineligible = !isOwnerOccupied || price >= 1500000 || units >= 5;
if (price <= 0 || downPct >= 20 || ineligible) {
return { ratePct: 0, premium: 0, taxOnPremium: 0, minDownPaymentPct: minDownPct };
}
let baseRatePct = 4.0;
if (downPct >= 15) baseRatePct = 2.8;
else if (downPct >= 10) baseRatePct = 3.1;
const ratePct = baseRatePct + (amortYears > 25 ? 0.2 : 0);
const premium = price * (1 - downPct / 100) * (ratePct / 100);
const taxRate =
(jurisdiction === 'montreal' || jurisdiction === 'quebec') ? 0.09 :
(jurisdiction === 'ontario' || jurisdiction === 'toronto') ? 0.08 : 0;
return { ratePct, premium, taxOnPremium: premium * taxRate, minDownPaymentPct: minDownPct };
}
3. OSFI B-20 Stress Test & Multi-Market Rate Shocks
In Canada, federally regulated lenders qualify borrowers at the OSFI B-20 qualifying rate:
r_stress_ca = max(r_contract + 2.0%, 5.25%)
In our engine, every market defines { stressOffsetPct, stressFloorPct } (CA: +2.0% / 5.25% floor, US: +2.0% / 0, FR: +1.5% / 0) and immediately outputs stressedMonthlyMortgage, stressedMonthlyCashflow, and stressedDscr:
const stressTestRatePct = Math.max(ratePct + cfg.stressOffsetPct, cfg.stressFloorPct);
const stressedMonthlyMortgage =
calcMonthlyMortgage(financedPrincipal, stressTestRatePct, amortYears, cfg.compounding) +
monthlyLoanInsurance;
const stressedDscr = stressedMonthlyMortgage > 0 ? noi / (stressedMonthlyMortgage * 12) : null;
Showing stressed DSCR right beside base cashflow immediately exposes deals that look positive at 4.5% but turn deeply negative on a 5-year Canadian renewal.
4. Progressive Transfer Taxes (Montreal 2026, Toronto 2026 MLTT, BC & French DMTO)
Closing taxes are the single biggest source of Cash-on-Cash error across jurisdictions. Every progressive tax schedule boils down to one 10-line marginal bracket reducer:
function calcProgressiveBrackets(basis, brackets) {
let tax = 0;
let prevCap = 0;
for (const [cap, rate] of brackets) {
if (basis <= prevCap) break;
tax += (Math.min(basis, cap) - prevCap) * rate;
prevCap = cap;
}
return tax;
}
Four jurisdiction-specific quirks worth getting right:
-
Montreal 2026 (Taxe de bienvenue): The tax basis is
Math.max(price, municipalAssessment)β if you buy below municipal assessment, the city still taxes you on the assessment! Brackets run across 7 tiers from0.5%(up to$62,900) to4.0%(above$3,113,000). -
Toronto 2026 (Double LTT + April 2026 Luxury MLTT): Buyers pay both Ontario's provincial LTT (
0.5% β 2.5%) and Toronto's Municipal LTT, whose graduated luxury tiers for 1β2 single-family residences step up sharply above$3M(4.4%,5.45%,6.50%,7.55%, and8.60%above$20M). -
British Columbia PTT:
1%to$200k,2%to$2M,3%to$3M, and5%above$3M. -
France (Frais de notaire / DMTO): Resale properties (
fr_ancien) now average ~8.4% following the 2025/2026 departmental DMTO ceiling increase, versus ~2.5% on new builds (fr_neuf).
5. French LMNP Tax Modeling: Micro-BIC vs. RΓ©gime RΓ©el
For French furnished rentals (Loueur en MeublΓ© Non Professionnel), pre-tax cashflow is misleading because after-tax outcomes diverge dramatically between Micro-BIC and RΓ©gime RΓ©el (assuming a typical 30% marginal income bracket + 17.2% social levies = 47.2% combined):
const lmnpMarginalTaxRate = 0.472; // 30% TMI + 17.2% prélèvements sociaux
// Long-term furnished Micro-BIC (50% flat allowance)
const lmnpMicroBicTaxAnnual = effectiveGrossIncome * 0.50 * lmnpMarginalTaxRate;
const lmnpMicroBicNetCashflowMo = (annualCashflow - lmnpMicroBicTaxAnnual) / 12;
// RΓ©gime RΓ©el: deducts opex, Year-1 interest, borrower insurance, and ~85% building depreciation over 30y
const year1Interest = Math.max(0, monthlyMortgage * 12 - year1PrincipalPaydown);
const estBuildingAmortAnnual = (price * 0.85) / 30;
const lmnpReelTaxable = Math.max(
0,
effectiveGrossIncome - operatingExpensesTotal - year1Interest - monthlyLoanInsurance * 12 - estBuildingAmortAnnual
);
const lmnpReelNetCashflowMo = (annualCashflow - lmnpReelTaxable * lmnpMarginalTaxRate) / 12;
(Note: France's 2025 Finance Act began recapturing LMNP depreciation into the capital-gains basis on resale for most non-student residences, so investors should treat RΓ©gime RΓ©el as a powerful cashflow deferral rather than permanent tax erasure.)
6. Solving maxOfferZeroCashflow: Closed Form vs. Binary Search
Investors constantly ask: "At what maximum offer price does this property break even (monthlyCashflow === 0)?"
When your down payment is expressed as a fixed percentage of offer price and you are away from insurance cliffs, annual debt service scales linearly with price P:
const insAnnualRate =
cfg.market === 'US' && downPct < 20 ? pmiRatePct / 100 :
cfg.market === 'FR' ? borrowerInsuranceRatePct / 100 : 0;
const factor = getMonthlyMortgageFactor(ratePct, amortYears, cfg.compounding);
const debtPerPurchaseDollar =
(1 - downPct / 100) * (12 * factor * (1 + cmhc.ratePct / 100) + insAnnualRate);
const maxOfferZeroCashflow = noi > 0 && debtPerPurchaseDollar > 0
? noi / debtPerPurchaseDollar
: 0;
Where closed-form breaks down β and why binary search wins for general underwriting:
What if your offer price crosses the $1.5M CMHC cliff (jumping minimum down payment from 10% to 20%), OR your down payment is a fixed dollar budget (e.g., "$120,000 cash available including Montreal's progressive transfer tax"), OR you want the exact max offer hitting Cash-on-Cash >= 8%?
Because monthlyCashflow(P) and cashOnCash(P) are strictly monotonically decreasing in offer price P (higher price β larger loan + higher progressive transfer tax β lower cashflow), a 40-step binary search wrapping analyzeDeal() solves any piecewise-discontinuous rule set to < $0.01 precision in < 0.1 ms:
function findMaxOfferBinarySearch(baseParams, targetFn, maxPrice = 10_000_000) {
let lo = 0;
let hi = Math.max(baseParams.price * 1.5, maxPrice);
// If even a $1 offer fails the target (e.g., negative NOI), no positive offer works
if (!targetFn(analyzeDeal({ ...baseParams, price: 1 }))) return 0;
for (let i = 0; i < 40; i += 1) {
const mid = (lo + hi) / 2;
const res = analyzeDeal({ ...baseParams, price: mid });
if (targetFn(res)) lo = mid;
else hi = mid;
}
return Math.floor(lo);
}
// Example: max offer for cashflow >= 0 AND OSFI B-20 stressed DSCR >= 1.10
const maxSafeOffer = findMaxOfferBinarySearch(
dealInputs,
(r) => r.monthlyCashflow >= 0 && (r.stressedDscr === null || r.stressedDscr >= 1.10)
);
Because the entire engine is a pure function with zero DOM or network dependencies, running 40 iterations during a slider drag stays well under a single 16 ms animation frame.
Try the Live Engine
Full disclosure: I built *PlexPulse** around this exact engine.*
- Free Chrome extension (instant overlay on Centris, Realtor.ca, Zillow, Redfin, Leboncoin, SeLoger β 100% local, no account): PlexPulse on the Chrome Web Store
- Free Firefox extension (100% local, no account): PlexPulse on Firefox Add-ons
- Interactive web calculator (Centris / Montreal Triplex, zero signup): PlexPulse ROI & Cashflow Calculator
If you have built real estate underwriting models for other markets (UK Stamp Duty / BTL ICR stress tests, German Grunderwerbsteuer, or Australian negative gearing), I'd love to compare edge cases in the comments.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.