Data room / The current model

Model source

Code, 3,088 words

model/equity_flow.js Open the file as written

// Equity Flow: the one model.
//
// Every number on the site comes from this file: the live calculator in
// public/equity-flow.html imports it in the browser, the Equity Tap page uses
// lumpSumBalance() for its Equity Flow column, and scripts/build_site.js runs
// it in Node to render the homeowner stories, the investor economics table,
// and the "what happens at 62" figures into the HTML. docs/MODEL_MAP.md
// describes the layout; tests/ holds the invariant, acceptance, and drift
// tests.
//
// Plain ESM. No dependencies. Works in the browser and in Node.

import { CONFIG } from './config.js';
import { CONTRACT } from './contract.js';

export { CONFIG, CONTRACT };

// ---------------------------------------------------------------------------
// Dates and ages. A date is { year, month } with month 1..12.

export function monthsBetween(from, to) {
  return (to.year - from.year) * 12 + (to.month - from.month);
}

// Whole years of age on asOf.
export function ageAt(dob, asOf) {
  return Math.floor(monthsBetween(dob, asOf) / 12);
}

// Months from asOf until the birthday month at which the borrower turns `age`.
export function monthsUntilAge(dob, asOf, age) {
  return monthsBetween(asOf, { year: dob.year + age, month: dob.month });
}

// A date of birth for someone who turns `age` exactly in the asOf month.
export function dobForAge(age, asOf) {
  return { year: asOf.year - age, month: asOf.month };
}

// ---------------------------------------------------------------------------
// Amortization.

export function amortPayment(principal, annualRate, nMonths) {
  const r = annualRate / 12;
  if (r === 0) return principal / nMonths;
  return principal * r / (1 - Math.pow(1 + r, -nMonths));
}

export function amortBalance(principal, annualRate, nMonths, monthsElapsed) {
  if (monthsElapsed <= 0) return principal;
  if (monthsElapsed >= nMonths) return 0;
  const r = annualRate / 12;
  if (r === 0) return principal * (1 - monthsElapsed / nMonths);
  const pmt = amortPayment(principal, annualRate, nMonths);
  return principal * Math.pow(1 + r, monthsElapsed) - pmt * (Math.pow(1 + r, monthsElapsed) - 1) / r;
}

// The first lien is described the way a homeowner remembers it:
// { origLoan, rate, termYears, origYear }. Seasoning is counted in whole years
// from origYear to asOf.year, matching the calculator's inputs.
export function lienMonthsElapsed(lien, asOf) {
  return Math.max(0, (asOf.year - lien.origYear) * 12);
}

export function seniorBalanceAt(lien, asOf, monthsFromNow) {
  return amortBalance(lien.origLoan, lien.rate, lien.termYears * 12, lienMonthsElapsed(lien, asOf) + monthsFromNow);
}

export function seniorPayment(lien) {
  return amortPayment(lien.origLoan, lien.rate, lien.termYears * 12);
}

// ---------------------------------------------------------------------------
// Fees and balances.

// Origination fee: max(pct x commitment, floor). The floor covers counseling,
// appraisal, title, recording, trust setup, and servicing onboarding. It is
// financed into the balance at closing; the borrower pays nothing in cash.
export function originationFee(totalCommitment, cfg = CONFIG) {
  const pctFee = cfg.origination_fee_pct * totalCommitment;
  const fee = Math.max(pctFee, cfg.origination_fee_floor);
  return { fee, pctFee, floor: cfg.origination_fee_floor, floorBinds: cfg.origination_fee_floor > pctFee };
}

// A schedule is { deposit, months } plus an optional stopAtMonth when the
// borrower stops deposits early. Deposits land at the end of months 1..D.
export function depositsMade(schedule, m) {
  const D = Math.min(schedule.months, schedule.stopAtMonth ?? schedule.months);
  return schedule.deposit * Math.max(0, Math.min(m, D));
}

// Balance owed at month m: financed fee plus every deposit made, each
// compounding monthly at the fixed coupon from the month it landed.
export function efBalanceAt(schedule, m, cfg = CONFIG) {
  const r = cfg.coupon_illustrative / 12;
  const fee = originationFee(schedule.deposit * schedule.months, cfg).fee;
  const D = Math.min(schedule.months, schedule.stopAtMonth ?? schedule.months);
  const dm = Math.max(0, Math.min(m, D));
  const drawsFV = schedule.deposit * (Math.pow(1 + r, dm) - 1) / r;
  return fee * Math.pow(1 + r, m) + drawsFV * Math.pow(1 + r, Math.max(0, m - dm));
}

// A single lump sum drawn at closing and left unpaid for `months`. Used by the
// Equity Tap comparison page, which quotes a one-time amount.
export function lumpSumBalance(amount, months, cfg = CONFIG) {
  const r = cfg.coupon_illustrative / 12;
  const fee = originationFee(amount, cfg).fee;
  return (amount + fee) * Math.pow(1 + r, months);
}

// ---------------------------------------------------------------------------
// The HECM takeout at 62 (section 1).

export function hecmCapacityAt62(homeValue, cfg = CONFIG) {
  const base = Math.min(homeValue, cfg.fha_hecm_limit);
  const principalLimit = base * cfg.hecm_plf_62;
  const closingCosts = base * cfg.hecm_closing_cost_pct;
  return { base, principalLimit, closingCosts, capacity: principalLimit - closingCosts, cappedByLimit: homeValue > cfg.fha_hecm_limit };
}

// Projection to the month the youngest borrower turns 62, at 0% HPI, on the
// committed schedule (an early stop is the borrower's option, not the lender's
// assumption).
export function hecmAt62(inputs, schedule, cfg = CONFIG) {
  const monthsTo62 = monthsUntilAge(inputs.dob, inputs.asOf, cfg.hecm_age);
  const committed = { deposit: schedule.deposit, months: schedule.months };
  const firstLienAt62 = seniorBalanceAt(inputs.lien, inputs.asOf, monthsTo62);
  const efAt62 = efBalanceAt(committed, monthsTo62, cfg);
  const hecm = hecmCapacityAt62(inputs.homeValue, cfg);
  const stack = firstLienAt62 + efAt62;
  return {
    monthsTo62,
    firstLienAt62,
    efAt62,
    stack,
    ...hecm,
    fits: stack <= hecm.capacity + 1e-6,
    slack: hecm.capacity - stack,
    cashLeftAfterPayoff: Math.max(0, hecm.capacity - stack)
  };
}

// ---------------------------------------------------------------------------
// Underwriting constraints.

export const CONSTRAINT_LABELS = Object.freeze({
  cltv_60_at_close: 'CLTV at close must be 60% or less',
  cltv_75_at_draw_end: 'Projected CLTV at draw end, flat prices, must be 75% or less',
  cushion_25_at_draw_end: 'Equity cushion at draw end, net of costs of sale, must be 25 points or more',
  hecm_fit_at_62: 'First lien plus Equity Flow balance at the 62nd birthday must fit the HECM capacity',
  schedule_ends_by_62: 'The draw schedule may not run past the 62nd birthday',
  min_total_commitment: 'Total commitment must be at least the minimum'
});

export const MESSAGES = Object.freeze({
  age_under_min: `Equity Flow is built for borrowers aged ${CONFIG.min_age_at_close} to ${CONFIG.max_age_at_close} at closing.`,
  age_hecm: 'A HECM is built for that age. At 62 and over, a federally insured reverse mortgage fits better, and the required counselor covers it.',
  cltv_over_max: `Your mortgage must be ${Math.round(CONFIG.max_start_cltv * 100)}% or less of your home’s value.`,
  min_total_commitment: `Schedules under $${CONFIG.min_total_commitment.toLocaleString()} in total are not offered. A home equity loan fits better at that size.`
});

export function eligibility(inputs, cfg = CONFIG) {
  const age = ageAt(inputs.dob, inputs.asOf);
  const senior = seniorBalanceAt(inputs.lien, inputs.asOf, 0);
  const startCltv = senior / inputs.homeValue;
  const reasons = [];
  if (age < cfg.min_age_at_close) reasons.push('age_under_min');
  if (age >= cfg.hecm_age) reasons.push('age_hecm');
  if (startCltv > cfg.max_start_cltv + 1e-12) reasons.push('cltv_over_max');
  return { ok: reasons.length === 0, age, senior, startCltv, reasons, launchCohort: age >= cfg.launch_age_min && age <= cfg.max_age_at_close };
}

// Every constraint, evaluated for one schedule. `inputs` is
// { homeValue, lien, dob, asOf }.
export function evaluate(inputs, schedule, cfg = CONFIG) {
  const V = inputs.homeValue;
  const N = schedule.months;
  const d = schedule.deposit;
  const committed = { deposit: d, months: N };
  const S0 = seniorBalanceAt(inputs.lien, inputs.asOf, 0);
  const SN = seniorBalanceAt(inputs.lien, inputs.asOf, N);
  const EFN = efBalanceAt(committed, N, cfg);
  const h = hecmAt62(inputs, committed, cfg);
  const projCltv = (SN + EFN) / V;
  const cushion = (V * (1 - cfg.costs_of_sale) - SN - EFN) / V;
  const eps = 1e-9;
  const checks = [
    { name: 'cltv_60_at_close', ok: S0 / V <= cfg.max_start_cltv + eps, value: S0 / V, limit: cfg.max_start_cltv, dependsOnDeposit: false },
    { name: 'cltv_75_at_draw_end', ok: projCltv <= cfg.max_proj_cltv_at_draw_end + eps, value: projCltv, limit: cfg.max_proj_cltv_at_draw_end, dependsOnDeposit: true },
    { name: 'cushion_25_at_draw_end', ok: cushion >= cfg.min_cushion_pts_at_draw_end - eps, value: cushion, limit: cfg.min_cushion_pts_at_draw_end, dependsOnDeposit: true },
    { name: 'hecm_fit_at_62', ok: h.fits, value: h.stack, limit: h.capacity, dependsOnDeposit: true },
    { name: 'schedule_ends_by_62', ok: N <= h.monthsTo62, value: N, limit: h.monthsTo62, dependsOnDeposit: false },
    { name: 'min_total_commitment', ok: d * N >= cfg.min_total_commitment - eps, value: d * N, limit: cfg.min_total_commitment, dependsOnDeposit: true }
  ];
  return {
    ok: checks.every(c => c.ok),
    checks,
    failed: checks.filter(c => !c.ok).map(c => c.name),
    detail: { seniorNow: S0, seniorAtDrawEnd: SN, efAtDrawEnd: EFN, projCltv, cushion, hecm: h }
  };
}

function bisectCap(okAt, hi = 50000) {
  if (okAt(hi)) return hi;
  if (!okAt(0)) return 0;
  let lo = 0;
  for (let i = 0; i < 60; i++) {
    const mid = (lo + hi) / 2;
    if (okAt(mid)) lo = mid; else hi = mid;
  }
  return lo;
}

export function roundDownTo(x, step) {
  return Math.floor(x / step + 1e-9) * step;
}

// The largest monthly deposit for a schedule of `months`, and the constraint
// that caps it. Returns deposit 0 and the reason when nothing is offerable.
export function maxDeposit(inputs, months, cfg = CONFIG, step = 25) {
  const fixed = evaluate(inputs, { deposit: 0, months }, cfg).checks
    .filter(c => !c.dependsOnDeposit && !c.ok);
  if (fixed.length) return { deposit: 0, binding: fixed[0].name, refused: true, caps: [] };
  const names = ['cltv_75_at_draw_end', 'cushion_25_at_draw_end', 'hecm_fit_at_62'];
  const caps = names.map(name => ({
    name,
    cap: bisectCap(d => evaluate(inputs, { deposit: d, months }, cfg).checks.find(c => c.name === name).ok)
  }));
  let best = caps[0];
  for (const c of caps) if (c.cap < best.cap - 1e-9) best = c;
  const deposit = roundDownTo(best.cap, step);
  if (deposit * months < cfg.min_total_commitment - 1e-9) {
    return { deposit: 0, binding: 'min_total_commitment', refused: true, caps, capBeforeMinimum: deposit, capBinding: best.name };
  }
  return { deposit, binding: best.name, refused: false, caps };
}

// The longest schedule a given deposit supports, or 0 when none passes.
export function maxMonths(inputs, deposit, cfg = CONFIG) {
  const m62 = monthsUntilAge(inputs.dob, inputs.asOf, cfg.hecm_age);
  const top = Math.min(cfg.max_schedule_months, m62);
  for (let N = top; N >= cfg.min_schedule_months; N--) {
    if (evaluate(inputs, { deposit, months: N }, cfg).ok) return N;
  }
  return 0;
}

// The largest deposit over every admissible schedule length (shorter schedules
// allow larger deposits, so this is the ceiling the calculator's slider uses).
export function maxDepositAnySchedule(inputs, cfg = CONFIG) {
  const m62 = monthsUntilAge(inputs.dob, inputs.asOf, cfg.hecm_age);
  const top = Math.min(cfg.max_schedule_months, m62);
  let best = null;
  let nearest = null; // the refused schedule that came closest, for the reason
  for (let N = cfg.min_schedule_months; N <= top; N++) {
    const r = maxDeposit(inputs, N, cfg);
    if (!r.refused) {
      if (!best || r.deposit > best.deposit) best = { ...r, months: N };
    } else if (!nearest || (r.capBeforeMinimum || 0) * N > (nearest.capBeforeMinimum || 0) * nearest.months) {
      nearest = { ...r, months: N };
    }
  }
  if (best) return best;
  if (nearest) return nearest;
  return { deposit: 0, months: 0, binding: 'schedule_ends_by_62', refused: true, caps: [] };
}

// ---------------------------------------------------------------------------
// Projections for the homeowner.

export function projectSale(inputs, schedule, monthsAhead, hpi, cfg = CONFIG) {
  const V = inputs.homeValue * Math.pow(1 + hpi, monthsAhead / 12);
  const senior = seniorBalanceAt(inputs.lien, inputs.asOf, monthsAhead);
  const balance = efBalanceAt(schedule, monthsAhead, cfg);
  const received = depositsMade(schedule, monthsAhead);
  const fee = originationFee(schedule.deposit * schedule.months, cfg);
  const netAfterSenior = Math.max(0, V * (1 - cfg.costs_of_sale) - senior);
  const repay = Math.min(balance, netAfterSenior);
  const capped = repay < balance - 1;
  return {
    monthsAhead, hpi, homeValue: V, senior, balance, received, fee: fee.fee, feeFloorBinds: fee.floorBinds,
    accruedInterest: balance - received - fee.fee,
    netAfterSenior, repay, capped,
    cashToBorrower: Math.max(0, netAfterSenior - balance),
    trueCost: repay - received
  };
}

export function payoffTable(inputs, schedule, saleYear, cfg = CONFIG) {
  return cfg.hpi_scenarios.map(s => ({ ...s, ...projectSale(inputs, schedule, saleYear * 12, s.hpi, cfg) }));
}

// What the closing package prints: the fee line items and the balance at
// every future year if the borrower never prepays (the worst case, in writing,
// on day one). Deposits stop at the schedule end; interest keeps accruing.
export function closingPackage(inputs, schedule, years = 30, cfg = CONFIG) {
  const commitment = schedule.deposit * schedule.months;
  const fee = originationFee(commitment, cfg);
  const lineItems = [
    { label: 'Origination fee, financed into the balance', amount: fee.fee,
      note: fee.floorBinds
        ? `Fee floor of $${fee.floor.toLocaleString()} applies; ${Math.round(cfg.origination_fee_pct * 100)}% of the commitment would be $${Math.round(fee.pctFee).toLocaleString()}`
        : `${Math.round(cfg.origination_fee_pct * 100)}% of the $${Math.round(commitment).toLocaleString()} commitment` },
    { label: 'Independent counseling, appraisal, title, recording, trust setup, servicing onboarding', amount: 0, note: 'Covered by the origination fee. No cash due at closing.' }
  ];
  const schedule62 = hecmAt62(inputs, schedule, cfg);
  const rows = [];
  for (let y = 1; y <= years; y++) {
    const m = y * 12;
    rows.push({
      year: y,
      age: ageAt(inputs.dob, inputs.asOf) + y,
      deposits: depositsMade(schedule, m),
      balance: efBalanceAt(schedule, m, cfg),
      senior: seniorBalanceAt(inputs.lien, inputs.asOf, m)
    });
  }
  return { commitment, fee, lineItems, totalClosingCosts: fee.fee, rows, at62: schedule62 };
}

// ---------------------------------------------------------------------------
// Alternatives for the monthly impact comparison.

export function alternatives(totalCommitment, cfg = CONFIG) {
  return {
    heloc: { rate: cfg.heloc_rate, monthly: totalCommitment * cfg.heloc_rate / 12 },
    heLoan: { rate: cfg.he_loan_rate, termYears: cfg.he_loan_term_years, monthly: amortPayment(totalCommitment, cfg.he_loan_rate, cfg.he_loan_term_years * 12) },
    homesafeSecond: { ...cfg.homesafe_second, monthly: 0 }
  };
}

// Extra interest over a horizon if the current first-lien balance is re-priced
// from its locked rate to the market rate on a new 30-year loan, versus keeping
// the old loan. This is the cash-out refi's "rate-lock toll" on money the
// borrower already owes.
export function refiToll(lien, asOf, horizonMonths, cfg = CONFIG) {
  const S0 = seniorBalanceAt(lien, asOf, 0);
  const elapsed = lienMonthsElapsed(lien, asOf);
  const remaining = Math.max(1, lien.termYears * 12 - elapsed);
  const h = Math.min(horizonMonths, remaining);
  const oldPmt = seniorPayment(lien);
  const oldInterest = oldPmt * h - (S0 - amortBalance(S0, lien.rate, remaining, h));
  const newPmt = amortPayment(S0, cfg.market_rate_30y, 360);
  const hn = Math.min(horizonMonths, 360);
  const newInterest = newPmt * hn - (S0 - amortBalance(S0, cfg.market_rate_30y, 360, hn));
  return { balance: S0, horizonMonths, oldInterest, newInterest, toll: newInterest - oldInterest, marketRate: cfg.market_rate_30y };
}

// ---------------------------------------------------------------------------
// Investor cash flows (section 3): rolling 12-month prefund, standby facility
// on the remainder, trust yield on trust balances, interest only on drawn
// amounts, realized IRR per exit.

export function irrAnnual(flows) {
  const npv = r => flows.reduce((s, f) => s + f.amount / Math.pow(1 + r, f.month), 0);
  let lo = -0.5, hi = 0.5;
  let flo = npv(lo), fhi = npv(hi);
  if (flo * fhi > 0) return null;
  for (let i = 0; i < 200; i++) {
    const mid = (lo + hi) / 2;
    const fm = npv(mid);
    if (fm * flo <= 0) { hi = mid; fhi = fm; } else { lo = mid; flo = fm; }
  }
  // Stated as a nominal annual rate compounded monthly, the same basis as the
  // coupon, so the two columns of the investor table compare directly.
  return ((lo + hi) / 2) * 12;
}

// exit: { type: 'sale', month, hpi } or { type: 'hecm_refi_at_62' }
export function investorFlows(inputs, schedule, exit, cfg = CONFIG) {
  const d = schedule.deposit;
  const N = schedule.months;
  const P = Math.min(cfg.prefund_months, N);
  const fee = originationFee(d * N, cfg).fee;
  const T = exit.type === 'hecm_refi_at_62' ? monthsUntilAge(inputs.dob, inputs.asOf, cfg.hecm_age) : exit.month;
  const ry = cfg.trust_yield / 12;
  const rs = cfg.standby_commitment_fee / 12;
  const flows = [{ month: 0, amount: -(P * d + fee) }];
  let trust = P * d;
  let standby = (N - P) * d;
  let trustYield = 0, standbyFees = 0, funded = P * d + fee;
  for (let m = 1; m <= T; m++) {
    let amt = 0;
    if (m <= N) {
      const y = trust * ry;
      const s = standby * rs;
      amt += y - s;
      trustYield += y; standbyFees += s;
      trust -= d;
      if (m <= N - P) { amt -= d; trust += d; standby -= d; funded += d; }
    }
    if (m === T) {
      const balance = efBalanceAt({ deposit: d, months: N }, T, cfg);
      let payoff, capped = false, homeValue = null, netAfterSenior = null;
      if (exit.type === 'hecm_refi_at_62') {
        payoff = balance;
      } else {
        homeValue = inputs.homeValue * Math.pow(1 + exit.hpi, T / 12);
        netAfterSenior = Math.max(0, homeValue * (1 - cfg.costs_of_sale) - seniorBalanceAt(inputs.lien, inputs.asOf, T));
        payoff = Math.min(balance, netAfterSenior);
        capped = payoff < balance - 1;
      }
      amt += payoff + trust;
      flows.push({ month: m, amount: amt });
      const senior = seniorBalanceAt(inputs.lien, inputs.asOf, T);
      const cushion0 = inputs.homeValue * (1 - cfg.costs_of_sale) - senior - balance;
      const cushionBase = inputs.homeValue * Math.pow(1 + cfg.hpi_base, T / 12) * (1 - cfg.costs_of_sale) - senior - balance;
      return {
        exit, exitMonth: T, flows, balance, payoff, capped, trustReturned: trust, totalFunded: funded,
        trustYield, standbyFees, coupon: cfg.coupon_illustrative, irr: irrAnnual(flows),
        cushion0, cushionBase, homeValue, netAfterSenior
      };
    }
    flows.push({ month: m, amount: amt });
  }
  throw new Error('exit month must be at least 1');
}

// A lump-sum competitor on the same basis: the whole commitment advanced at
// closing at the same coupon, paid at the same exit. Its IRR is the coupon
// whenever the payoff is uncapped, so it is the yardstick for any claim that
// scheduled draws carry a pricing edge.
export function lumpSumCompetitorIrr(inputs, schedule, exit, cfg = CONFIG) {
  const C = schedule.deposit * schedule.months;
  const fee = originationFee(C, cfg).fee;
  const T = exit.type === 'hecm_refi_at_62' ? monthsUntilAge(inputs.dob, inputs.asOf, cfg.hecm_age) : exit.month;
  const balance = (C + fee) * Math.pow(1 + cfg.coupon_illustrative / 12, T);
  let payoff = balance;
  if (exit.type === 'sale') {
    const V = inputs.homeValue * Math.pow(1 + exit.hpi, T / 12);
    payoff = Math.min(balance, Math.max(0, V * (1 - cfg.costs_of_sale) - seniorBalanceAt(inputs.lien, inputs.asOf, T)));
  }
  return irrAnnual([{ month: 0, amount: -(C + fee) }, { month: T, amount: payoff }]);
}

export function investorTable(inputs, schedule, cfg = CONFIG) {
  const rows = cfg.investor_exit_years.map(y => {
    const base = investorFlows(inputs, schedule, { type: 'sale', month: y * 12, hpi: cfg.hpi_base }, cfg);
    const flat = investorFlows(inputs, schedule, { type: 'sale', month: y * 12, hpi: 0 }, cfg);
    return {
      key: `sale_${y}`, label: y * 12 === schedule.months ? `${y} (draw end)` : String(y), exitYear: y,
      balance: base.balance, cushion0: flat.cushion0, cushionBase: base.cushionBase,
      coupon: base.coupon, irrBase: base.irr, irrFlat: flat.irr, cappedFlat: flat.capped, cappedBase: base.capped,
      lumpSumIrr: lumpSumCompetitorIrr(inputs, schedule, { type: 'sale', month: y * 12, hpi: cfg.hpi_base }, cfg)
    };
  });
  const h = investorFlows(inputs, schedule, { type: 'hecm_refi_at_62' }, cfg);
  const at62 = hecmAt62(inputs, schedule, cfg);
  rows.push({
    key: 'hecm_refi_at_62', label: `HECM refinance at 62 (base case, month ${h.exitMonth})`, exitYear: h.exitMonth / 12,
    balance: h.balance, cushion0: h.cushion0, cushionBase: h.cushionBase,
    coupon: h.coupon, irrBase: h.irr, irrFlat: h.irr, cappedFlat: false, cappedBase: false,
    lumpSumIrr: lumpSumCompetitorIrr(inputs, schedule, { type: 'hecm_refi_at_62' }, cfg),
    hecm: at62
  });
  return rows;
}

// ---------------------------------------------------------------------------
// Formatting helpers shared by the page and the build.

export function fmtMoney(x) {
  const n = Math.round(x);
  return (n < 0 ? '−$' : '$') + Math.abs(n).toLocaleString('en-US');
}

export function fmtK(x) {
  const n = Math.round(x / 1000);
  return (n < 0 ? '−$' : '$') + Math.abs(n) + 'K';
}

export function fmtPct(x, digits = 2) {
  return (x * 100).toFixed(digits) + '%';
}

export function describeMonths(m) {
  const y = Math.floor(m / 12), mo = m % 12;
  if (y === 0) return mo + ' mo';
  return y + (y === 1 ? ' yr' : ' yrs') + (mo ? ' ' + mo + ' mo' : '');
}