
Image by Editor | Canva
Markov chain analysis is used to model systems that move between states. It helps predict future states based on the current state only (the Markov property). The process involves defining a transition matrix and running simulations. For more details on the basics of Markov chains, check out this article. Python provides great tools for performing Markov chain analysis — most commonly NumPy for numerical computation and Matplotlib for plotting. In this article, we show how to perform Markov chain analysis using Python.
Define The Transition Matrix
A transition matrix shows the probabilities of state changes. For example, say we have these transition probabilities:
- From state A, there’s a 0.5 chance of staying in A, 0.3 chance of moving to B, and 0.2 chance of moving to C.
- From state B, there’s a 0.4 chance of moving to A, 0.4 chance of staying in B, and 0.2 chance of moving to C.
- From state C, there’s a 0.3 chance of moving to A, 0.4 chance of moving to B, and 0.3 chance of staying in C.
Let’s define the transition matrix and an initial state vector in Python:
import numpy as np
# Transition matrix
P = np.array([[0.5, 0.3, 0.2],
[0.4, 0.4, 0.2],
[0.3, 0.4, 0.3]])
# Initial state vector (start in state A)
initial_state = np.array([1.0, 0.0, 0.0])
Simulate The Markov Chain
We simulate the Markov chain to analyze how the system behaves over time by repeatedly multiplying the current state distribution by the transition matrix.
# Function to simulate the Markov chain
def simulate_markov_chain(P, initial_state, steps):
state = initial_state.astype(float)
history = [state]
for _ in range(steps):
state = state @ P # same as np.dot(state, P)
history.append(state)
return np.vstack(history)
# Simulate the Markov chain for 10 steps
steps = 10
history = simulate_markov_chain(P, initial_state, steps)
# Display the history of states
print("History of states over time:")
print(history)

Each row represents the probabilities of being in states A, B, and C at a given step. The first row is the initial state, and each following row shows how the system transitions to new states after each step.
Visualize The State Transitions
Visualization helps us see how the probabilities evolve. We can plot the probability of being in each state over multiple steps using Matplotlib.
import matplotlib.pyplot as plt
# Plotting the state probabilities over time
plt.figure(figsize=(10, 6))
for i, state_probabilities in enumerate(history.T):
plt.plot(state_probabilities, label=f"State {chr(i + 65)}")
plt.xlabel("Time Step")
plt.ylabel("Probability")
plt.title("Markov Chain Simulation")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

The plot shows how the system changes between states. It starts in state A. Over time, the probabilities change and eventually stabilize — meaning the system is reaching a steady state.
Find The Steady State
An important property of many Markov chains is convergence to a steady state (also called the stationary distribution), which represents the long-term behavior of the system.
To find the steady state mathematically, solve the equation \( \pi P = \pi \), where \( \pi \) is the steady-state vector. In Python, we can compute this using the eigenvectors of the transition matrix:
# Find the steady state by solving πP = π
eigenvalues, eigenvectors = np.linalg.eig(P.T)
# Select the eigenvector corresponding to eigenvalue 1
steady_state = eigenvectors[:, np.isclose(eigenvalues, 1.0)]
# Convert to a 1-D real vector and normalize to sum to 1
steady_state = steady_state[:, 0].real
steady_state = steady_state / steady_state.sum()
print("Steady State:")
print(steady_state)
For the given transition matrix, the steady-state probabilities are:

In the long term, the system will spend approximately 41.9% of the time in state A, 35.8% in state B, and 22.2% in state C.
Conclusion
By following these steps, you’ve completed a Markov chain analysis in Python. You created the transition matrix and simulated the system’s behavior. You visualized how state probabilities change over time. Lastly, you found the system’s steady state.
Markov chains are great for modeling dynamic systems, and Python makes them straightforward to analyze. You can expand this analysis to more complex systems with additional states or time-varying transition matrices.
