Overview
This example uses code and analytics from Transition Matrix
Scripts
In order to compute the probability of transition, we keep track of the number of transitions from one rating to the next. This is done by constructing a map, keyed by rating. The map is initiallized to a count of zero for each transition.
The ratings are obtained by callling the $group function.
let ratings = $group(data, p=>p.rating)();
let map = {};
for(let rating in ratings){
map[rating]={
"default":0
};
for(let rating2 in ratings) map[rating][rating2] = 0;
}
Next we iterate through each item in the dataset. The data is sorted first by loan id and date. This means that each consecutive record represents a transition from the prior record, as long as the ids match. We record the number of transitions in the map constructed from above.
data = $sort(data, p=>[p.id, p.date]);
let last;
for(let item of data){
if(last !== undefined){
if(last.id === item.id){
if(item.default === 1) map[last.rating]['default'] += 1;
else map[last.rating][item.rating] += 1;
}
}
last = item;
}
The last step is to create a matrix (an array of arrays, see linear algebra api)
let matrix = [];
for(let rating in map){
let row = [];
matrix.push(row);
let sum = 0;
for(let rating2 in map) sum += map[rating][rating2];
sum += map[rating]['default'];
for(let rating2 in map){
row.push(map[rating][rating2]/sum);
}
row.push(map[rating]['default']/sum);
}
let row = [0,0,0,1];
matrix.push(row);