VBA – Markov Chain with Excel example

Markov model is a a stochastic model describing a sequence of possible events in which the probability of each event depends only on the state attained in the previous event. Wikipedia

This is a good introduction video for the Markov chains, too bad it cannot be embedded.

So, let’s consider that you have to consider the following example – you are working in a car insurance company and the rules for the insurance are the following –  each year every customer is given one of four insurance classes, based on their “behaviour” on the road from the previous year. The classes are A, B, C and D. The transition probabilities look like these:

As you see, state “D” is a final state and it can be achieved from each of the other 3 states. State “A” can not be achieved from any of the other states. State “B” can be achieved only from State “A”. All the coefficients in the transition probability matrix look like this:

And the dashboard looks like this:

Cool! So how do we calculate the whole party? And what is the “ok” under check? And how we make sure that from state “A” to state “A” we pass exactly 0.6111 cases, when the total is 1000?

There is some preparation, before we calculate everything. With named ranges like tpA2A and initialStateVector. Once we have them, we can simply copy and paste this code:

As you see, it loops 20 times, once per period, and multiplies the cases, based on the coefficients. It is important to make sure that the A2A, B2B, C2C coefficients are calculated before the calculations are carried out. I am saving them in the n2nVector.

Concerning the “rounding questions”, this Markov Model supports 3 types of rounding:

  • Number of cases is rounded to Integer;
  • No rounding. Cases are a floating point number;
  • Number of cases is rounded to Integer and is equal to the initial sum;

As far as “No rounding. Cases are a floating point number” is rather self-explanatory, I will explain the other two types of rounding. In the screenshot above, the selected option is Number of cases is rounded to Integer and is equal to the initial sum. If you have done some advanced modelling with any tool, you would understand that if you have to divide 100 by 3 and round to an Integer, then you would automatically get 33+33+33, which is 99 and which is a bit away from 100. Thus, I am using an additional function, which would actually check that 33+33+33 is not 100 and would add to make it equal. In general, this is how the result would look like just for Number of cases is rounded to Integer case:

As you see, the sum is not always equal to 1200 (the initial state vector), thus it is a good idea to implement some rounding strategy there.


Tagged with: , , , , ,