Deriva
Cómo se desglosa el cambio en la tasa de impago
El cálculo separa el cambio de composición del cambio de tasas dentro de cada segmento. Los grupos sin observaciones comparables quedan identificados.
export function decomposeRates(cohorts, groups, withSegment) {
const totals = cohorts.map(c => c.evaluated);
const comparable = totals.every(n => n > 0);
const change = comparable ? cohorts[1].baseRate - cohorts[0].baseRate : null;
const summary = {status:'no-segment', change, composition:null, within:null, unallocated:null, matched:[0,0], rows:[]};
if (!withSegment) return summary;
const names = new Set([...groups[0].keys(), ...groups[1].keys()]);
let composition = 0, within = 0, shared = 0;
const outsidePositives = [0,0];
for (const segment of names) {
const periods = groups.map((groupsForPeriod,i) => {
const {count=0,positives=0} = groupsForPeriod.get(segment) ?? {};
return {count, positives, rate:count ? positives/count : null, weight:totals[i] ? count/totals[i] : null};
});
const [a,b] = periods;
const row = {segment, periods, composition:null, within:null};
if (segment !== null && a.count > 0 && b.count > 0) {
row.composition = (b.weight-a.weight)*(a.rate+b.rate)/2;
row.within = (b.rate-a.rate)*(a.weight+b.weight)/2;
composition += row.composition;
within += row.within;
shared++;
summary.matched[0] += a.count;
summary.matched[1] += b.count;
} else {
outsidePositives[0] += a.positives;
outsidePositives[1] += b.positives;
}
summary.rows.push(row);
}
summary.rows.sort((a,b) => {
const count = r => r.periods[0].count + r.periods[1].count;
return count(b) - count(a) || (a.segment ?? '').localeCompare(b.segment ?? '', 'es');
});
if (!comparable) { summary.status = 'no-results'; return summary; }
summary.unallocated = outsidePositives[1]/totals[1] - outsidePositives[0]/totals[0];
if (!shared) { summary.status = 'no-overlap'; return summary; }
summary.status = summary.matched.every((n,i) => n === totals[i]) ? 'complete' : 'partial';
summary.composition = composition;
summary.within = within;
return summary;
}