03 — Personal Analytics / Simulation

Match Simulator + Opponent Strategy AI

A ball-by-ball T20 cricket engine built on Markov chains over 17 seasons of IPL ball-by-ball data. Every transition is a real historical transition. Venue, phase, and bowler-type multipliers re-weight the probabilities. The Opponent Strategy AI sits on top as a prototype classifier layer — and I'm honest about which parts of it work and which don't.

DomainT20 Cricket / IPL
ApproachMarkov Chain
State Space(r, w, b)
Interfaceipywidgets
01 / Problem

A match is a sequence, not a final score.

Most cricket prediction work asks the wrong question: what will the final score be? A coach asks a different question — what does the rest of the match look like from here? If we're 80/4 in over 12 chasing 170, what's the realistic distribution of where the innings ends? If the same situation moves from Wankhede to Chepauk, how does that distribution shift?

A point-estimate score predictor can't answer that. A bootstrap from historical matches can't either, unless an exact past match matches the current state. What's needed is something that can simulate the rest of an innings from any state, ball by ball, with a stochastic engine that's grounded in real cricket — not a regression artifact.

That's what this is.

02 / Solution

A Markov chain over real cricket states.

The simulator represents an innings as a sequence of states. Each state is three integers: cumulative runs, cumulative wickets, ball number. From the IPL ball-by-ball dataset, every observed transition between consecutive states across 17 seasons is counted, and the counts become transition probabilities. To simulate a match, you start at (0, 0, 0), sample a next state proportional to its historical frequency, jump to it, repeat. Every transition is real.

(80, 3, 71)current state (81, 3, 72)single · 0.34 (80, 3, 72)dot · 0.31 (84, 3, 72)four · 0.21 (80, 4, 72)wicket · 0.14 RUNS · WICKETS · BALL17 IPL seasons240k+ deliveries SAMPLE PROPORTIONAL TO HISTORICAL FREQUENCY
From state (80, 3, 71) — 80 runs, 3 wickets, 71 balls in — the chain has four observed next-states from historical IPL data, with the listed probabilities. The simulator samples one stochastically. Numbers are illustrative.
03 / How It Works

From ball-by-ball to simulated innings.

01

Ingest IPL ball-by-ball + match metadata

Deliveries and matches tables joined on match_id. Compute ball_number, mark is_wicket from dismissal_kind, compute cumulative runs and wickets per match.

pandascricsheet
02

Define the state and the transitions

Each delivery becomes a tuple (cumulative_runs, cumulative_wickets, ball_number). Using shift(-1) within each match, pair every state with its next state. The result is a long list of (current_state → next_state) pairs across hundreds of thousands of deliveries.

state engineeringshift / groupby
03

Build the transition probability table

For every observed current_state, collect all the next_states that followed it. Count each unique next-state; divide by the total to get a probability. The result is a dictionary mapping each state to a list of (next_state, probability) pairs — the trained Markov chain.

probability estimation
04

Layer venue, phase, and bowler-type multipliers

Hand-tuned re-weights on top of the base probabilities. Wankhede (1.1), Chepauk (0.9), Chinnaswamy (1.2) reflect pitch character. Phase factors push Powerplay (1.1) and Death (1.3) over the Middle. Spin (0.8) restricts vs Pace (1.0). Probabilities normalized to sum to 1 after re-weighting. Honest note: these are domain-informed guesses, not learned parameters. V2 replaces them with venue-conditional transition tables.

hand-tunednormalization
05

Simulate the innings

Start at (0, 0, 0). At each step: look up the current state's transitions, apply the multipliers, sample the next state via random.choices() weighted by adjusted probabilities. Walk until 120 balls used or 10 wickets lost. Output is a DataFrame of every state visited — a complete simulated innings trajectory.

Monte Carlostochastic walk
06

Wrap in an interactive dashboard

ipywidgets dropdowns for venue and bowler type, with a Simulate button that runs the chain and plots runs and wickets progression with Plotly. Visualizes the trajectory ball-by-ball.

ipywidgetsPlotlymatplotlib
07

Layer the Opponent Strategy AI (prototype)

Three RandomForest classifiers — one per phase — attempting to predict opposition tactics from match metadata (team, venue, toss). This layer is exploratory; the next section explains exactly what works in it and what doesn't.

RandomForestXGBoostscikit-learn
04 / Results

The simulator's numbers.

IPL Seasons
17
Every delivery from IPL men's competition feeding the transition table.
Deliveries
240k+
Ball-by-ball transitions counted across all matches in the dataset.
State Dimensions
3
Runs, wickets, ball number — the compact state that keeps the chain tractable.
Sample Sim Score
176 / 8
Single run with Wankhede multiplier — par T20 first innings.
Sample Run Rate
8.80
Runs per over from the same simulation. Within the realistic IPL band.
Adjustable Factors
venue · phase · bowler
Three hand-tuned dimensions re-weighting the base chain.
05 / Technical Decisions

Why these choices.

Why Markov
over RNN/regression?
A Markov chain over real states gives you three things a regression or RNN can't: empirical grounding (every transition is a real cricket transition, not a model artifact), native stochasticity (run a thousand simulations, get a distribution), and conditional simulation (start the chain at any state — "what does the rest of the innings look like from 80/4 in over 12?"). An RNN would need vastly more data, isn't interpretable to a coach, and gives you a point estimate per ball rather than a sampling distribution.
Why exclude
batter / bowler identity?
Including identity collapses the state space. With ~70 batters × ~70 bowlers × 300 runs × 10 wickets × 120 balls, almost every state would be unique and the transition table would be useless. The v1 trade-off: lose player identity to keep enough observations per state to estimate probabilities. V2 fix is adding a 3-to-5 tier player class to the state (e.g., top-order, anchor, finisher, all-rounder, tailender) — keeps cardinality manageable while letting Kohli and a tailender produce different next-state distributions.
Why hand-tune
the multipliers?
Speed. Wankhede 1.1, Chepauk 0.9, Death 1.3 are informed guesses, not fit parameters — and I'm explicit about that. They make the simulator responsive to context for v1. The proper version is venue-conditional transition tables — separately estimate transitions for "ball 16, death overs, at Wankhede" from the actual delivery-level data. That's strictly better, because it captures what kind of transitions get more probable, not just a uniform boost.
Why single
innings only?
A chase needs a different state — at minimum (runs, wickets, balls, target, balls_remaining) with required run rate, and aggression shifts non-linearly as the chase tightens. Treating the chase as the same chain misses everything important about the second innings. V2 is a separate but linked chain that conditions on the first-innings target.
Why ipywidgets
over Streamlit?
Honest answer: fastest path to a working in-notebook UI while iterating on the simulator. The conversion to Streamlit is mechanical because the simulation function is already pure. V2 ships the Streamlit version with multi-run distribution plots.
06 / Honesty Check

The Strategy AI is a prototype.

⚠ Prototype Quality — Read Before Citing

If you saw "Accuracy: 1.0" on a portfolio, you'd close the tab.

The Strategy AI layer has three RandomForest sub-models. None of them are publication-grade. They're in the notebook as scaffolding for V2 — and rather than hiding the inflated metrics or quietly cutting the section, the right move is to lay them out and explain exactly why each accuracy number is a red flag instead of a result.

Powerplay batting strategy
1.00
Data leakage. Only 3 low-cardinality categorical features (team, venue, toss) — train and test draw from the same combinations, so RandomForest memorizes the majority label per combo. Not generalization.
Middle-overs bowling strategy
0.53
The features spin_overs, team_bowling_strength, and opposition_weakness are all generated by np.random.randint. Noise predicting noise. The 0.53 is exactly what you'd expect from chance.
Death-overs bowler type
1.00
Trivial label leakage. The label is "Pace if bowler in [SM Curran, CJ Jordan] else Spin" — and bowler is also a feature. The model is just learning a lookup table from an input feature.

The reason these are in the writeup is the same reason the 1.0 accuracy is left in the notebook: knowing what overfitting looks like in a small categorical feature space is more useful than pretending the number is real. V2 rebuilds the strategy classifiers with stratified train/test, leave-one-team-out cross-validation, and features that aren't randomly generated.

07 / Limitations

What the simulator can't see.

The simulator is the strong half. These are the specific things I'd attack first in V2.

01
State excludes player identity. Kohli batting at 80/3 and a tailender batting at 80/3 transition the same way. The model can't distinguish them.
02
Sparse states. Many (runs, wickets, ball) triples appear only once in 17 seasons. From those states, the next-state is essentially deterministic — the chain loses variance there.
03
Multipliers are hand-tuned, not learned. Wankhede 1.1, Chepauk 0.9, Death 1.3 are domain-informed guesses. Reasonable, but not fit to data.
04
No distribution validation. The simulator's score distribution hasn't been KS-tested against the real IPL first-innings score distribution. That's the first V2 check.
05
Dead-end fallback is too crude. If the walk hits a state not in the transition table, the simulation just ends. Better: fall back to nearest-neighbour state or phase-conditional empirical distribution.
06
Single-innings only. No chase logic — no required run rate, no aggression shift as the target gets closer.
07
ipywidgets is Colab-only. Not a real deployed web app yet. Streamlit conversion is mechanical and on the V2 list.
Version 2 — Build Order

What ships next.

  • 01Run 1000 simulations and KS-test against the real IPL first-innings score distribution.
  • 02Add a player-tier dimension to the state — top-order / anchor / finisher / all-rounder / tailender.
  • 03Replace hand-tuned multipliers with venue-conditional and phase-conditional transition tables.
  • 04Rebuild the Strategy AI classifiers with real features and leave-one-team-out cross-validation.
  • 05Second-innings chase chain conditioned on target and required run rate.
  • 06Deploy to Streamlit with a multi-run distribution view.
  • 07Smarter dead-end handling: nearest-neighbour fallback when state is unseen.
Look at the code / Run the chain

The simulator walks on real cricket.

Notebook on GitHub. Open the Markov chain, inspect any state's transitions, run the simulation yourself.