I'm trying to compute a moving window transition matrix for credit rating data. My data looks like this but then with 4000+ rows (there are 8 different ratings in the complete dataset). So we have firms (id) and their prior and current credit rating and at what date this transition took place.
df <- data.frame(id = c(100,100,98,99,98,98,56,54), date = c(19750102, 19750205, 19750402, 19750609, 19831212, 19840202, 19840704,19861104), priorrating = c("A","BBB","AAA","AAA","AA","A","BB", "D"), currentrating = c("BBB","BB","AA","AAA","A","A","BB","D"))
I want to compute the transition probability matrices of these ratings as a moving window. I want to shift 6 months intervals by 1 month. So you would get matrices P for intervals [19750102,19750602], [19750202,19750702] and so forth.
For each element (each date) in the different intervals I want to compute the following. There are no ties (so no dates with multiple different transitions).
require(Matrix)
#Table with transitions between ratings at time t in the interval
N <- table(df$priorrating,df$currentrating)
#Getting the number of total exposed firms Y at time t in the interval
firms <- apply(N,1,sum)
Y <- sum(firms)
#Computing the off-diagional elements of matrix dA; the kjth off-diagonal element count the
#fraction of transitions from the kth category to the jth category in the number of exposed
#firms at time t.
dA <- N/Y
#Complete matrix dA by adding default row
dA[6,] <- 0
#Computing diagonal elements of dA; e, the kth diagonal element counts the fraction of the
#exposed firms Y leaving the state at time t
D <- rep(0,6)
diag(dA) <- D #setting diagonal to zeros
diag(N) <- D #setting diagonal of transition count matrix to zero
outtrans <- apply(N,1,sum) #vector with number of firms leaving each state at time t
diag(dA) <- -outtrans/Y
#Finally compute probability matrix P for element i in the interval (time t)
attributes(dA)$class <- "matrix"
P <- (diag(6) + dA) #note that there are 8 different ratings in the complete dataset.
And finally I want to compute P.hat
for the entire interval, which would be the P matrix computed above of each element in the interval multiplied by eachother.
So the output would look like a list of matrices P.hat for each interval.
Now, my code above works on the entire sample. But I'm quite unsure how to implement it as a moving window.
PS: Hopefully my question is clear, if not please let me know!