migrate"

options(width = 999)

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

library(migrate)

Using migrate

This package is intended to serve as a set of tools to help convert credit risk data at two time points into traditional credit state migration (aka, "transition") matrices. At a higher level, migrate is intended to help an analyst understand how risk moved in their credit portfolio over a time interval.

Background

One of the more difficult aspects of making a credit state migration matrix in R (or Python, for that matter) is the fact that the output doesn't satisfy the structure of a traditional data frame object. Rather, the output needs to be a matrix, which is a data structure that R does support. In the past, there has been difficulty converting a matrix to something more visual-friendly. More recently, however, tools like the kableExtra and gt packages allow us to present visually appealing output that extends the structure of a data frame. Using the matrix-style output of migrate's functions with a visual formatting package such as the two mentioned above will hopefully help analysts streamline the presentation of their credit portfolio's state migration matrices to an audience.

Getting Started

If you haven't done so already, first install migrate with the instructions in the README section.

First, load the package & the mock dataset (as a data frame) using library()

library(migrate)

The package has a built-in mock dataset, which can be loaded into the environment like so:

data("mock_credit")

head(mock_credit[order(mock_credit$customer_id), ])   # sort by 'customer_id'
head(mock_credit[order(mock_credit$customer_id), ]) %>% 
  knitr::kable(row.names = FALSE)

Note that an important feature of the mock_credit dataset is that there are exactly two (2) unique values in the date column variable; if the time argument passed to migrate has more than two (2) unique values, the function will throw an error.

unique(mock_credit$date)

To summarize the migration within the data, use the migrate() function

migrated_df <- migrate(
  data = mock_credit, 
  id = customer_id, 
  time = date, 
  state = risk_rating, 
)

head(migrated_df)

To create the state migration matrix, use the build_matrix() function

build_matrix(migrated_df)

Or, to do it all in one shot, use the %>%

mock_credit %>% 
  migrate(
    id = customer_id, 
    time = date, 
    state = risk_rating, 
    metric = principal_balance, 
    percent = FALSE, 
    verbose = FALSE
  ) %>% 
  build_matrix(
    state_start = risk_rating_start, 
    state_end = risk_rating_end, 
    metric = principal_balance
  )


Try the migrate package in your browser

Any scripts or data that you put into this service are public.

migrate documentation built on Oct. 16, 2021, 1:06 a.m.