Contents
The Math Behind Trading: A Beginner’s Guide to Probability, Statistics,
and Backtesting for Crypto & Forex 1
How to Use This Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Part 1: Probability Theory — The Foundation . . . . . . . . . . . . . . . . . 2
Part 2: Combinatorics — Counting Your Possibilities . . . . . . . . . . . . . 3
Part 3: Statistics — Describing and Testing Data . . . . . . . . . . . . . . . 4
Part 4: Technical Indicators — Turning Price Into Numbers . . . . . . . . . 5
Part 5: Monte Carlo Simulation . . . . . . . . . . . . . . . . . . . . . . . . . 7
Part 6: Expected Value and the Kelly Criterion . . . . . . . . . . . . . . . . 8
Part 7: Backtesting Methodology . . . . . . . . . . . . . . . . . . . . . . . . 9
Part 8: Risk Management Math . . . . . . . . . . . . . . . . . . . . . . . . 10
Part 9 (Optional): Time-Series and Machine Learning Models . . . . . . . . 11
Your Step-by-Step Learning Path . . . . . . . . . . . . . . . . . . . . . . . . 12
Final Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
The Math Behind Trading: A Beginner’s Guide to Proba-
bility, Statistics, and Backtesting for Crypto & Forex
A step-by-step course from first principles to a working strategy-testing mind-
set
How to Use This Guide
This document is a learning roadmap, not a trading signal service. Every topic fol-
lows the same pattern: a plain-English definition, why it matters for trading, the
process/formula, and a simple worked example with small numbers you can check by
hand. Read it in order — each part builds on the last.
The roadmap, in order:
1. Probability theory (the foundation)
2. Combinatorics (counting your possibilities)
3. Statistics (describing and testing data)
4. Technical indicators (turning price into numbers)
5. Monte Carlo simulation (testing under randomness)
6. Expected value & Kelly criterion (turning probability into decisions)
7. Backtesting methodology (proving an idea on history)
8. Risk management math (surviving being wrong)
9. Optional: time-series & machine learning models
One honest note before you start: none of this predicts exact future prices. What
it does is let you replace guessing with measured, testable probabilities — so your
decisions are based on numbers instead of feelings. This is educational material, not
financial advice.
1
Part 1: Probability Theory — The Foundation
1.1 Definition
Probability is a number between 0 and 1 (or 0% to 100%) that measures how likely
an event is to happen.
• 0 = impossible
• 1 = certain
• 0.5 = equally likely to happen or not
Formula for a simple event:
P(event) = (number of favorable outcomes) / (total number of possible outcomes)
1.2 Simple Example
A coin flip: P(heads) = 1/2 = 0.5
A six-sided die: P(rolling a 4) = 1/6 ≈ 0.167
1.3 Why It Matters for Trading
Every trade is a bet with two rough outcomes: price goes up or price goes down
(ignoring sideways for now). If you can estimate P(price goes up | some condition is
true), you have a starting point for a decision. The “condition” is usually a technical
indicator signal, like “RSI is below 30.”
1.4 Conditional Probability
Conditional probability asks: given that something has already happened, what’s the
chance of something else happening?
P(A | B) = P(A and B) / P(B)
Read as “probability of A given B.”
Example: Out of 100 days of Bitcoin data, suppose: - On 40 days, RSI was below 30
(oversold). - Of those 40 days, price was higher 24 hours later on 26 of them.
P(price up | RSI < 30) = 26 / 40 = 0.65 (65%)
Compare this to the unconditional probability of price going up on any random day
(say it was 52 out of 100 = 0.52). Since 0.65 > 0.52, the RSI condition seems to shift
the odds in your favor — that’s the entire logic behind using indicators probabilisti-
cally.
1.5 Bayes’ Theorem
Bayes’ theorem lets you update a belief when new evidence arrives. It’s the mathe-
matical version of “how much should this new piece of information change my mind?”
2
P(A | B) = [P(B | A) × P(A)] / P(B)
Example: Say historically, price goes up on 52% of days (P(up) = 0.52). You also know
that when price goes up, RSI was below 30 beforehand 30% of the time (P(RSI<30 |
up) = 0.30). And RSI is below 30 on 25% of all days overall (P(RSI<30) = 0.25).
P(up | RSI<30) = (0.30 × 0.52) / 0.25 = 0.156 / 0.25 = 0.624 (62.4%)
So seeing RSI below 30 nudges your estimate of “price goes up next” from 52% to
about 62%. This is the mathematical backbone of “using an indicator as evidence,”
rather than as a guarantee.
1.6 The Random Walk Idea
A big reason prices are hard to predict is that short-term price changes behave a
lot like a random walk — each step is close to independent of the last, similar to
repeated coin flips. This doesn’t mean markets are perfectly random (there are small,
statistically measurable edges), but it explains why confident short-term prediction
usually fails. Your goal with probability is to find small, honest edges — not certainty.
Part 2: Combinatorics — Counting Your Possibilities
2.1 Definition
Combinatorics is the math of counting: how many ways can you arrange or choose
things? Two core tools:
• Permutations: order matters (arranging).
• Combinations: order doesn’t matter (selecting a group).
Formulas:
Permutations: nPr = n! / (n − r)!
Combinations: nCr = n! / [r! × (n − r)!]
Where n! (n factorial) = n × (n−1) × (n−2) × … × 1.
2.2 Simple Example
How many ways can you arrange 3 candlesticks (Red, Green, Blue) in order?
3! = 3 × 2 × 1 = 6 arrangements
How many ways can you choose 2 indicators out of 5 available ones (RSI, MACD,
Bollinger Bands, Volume, Moving Average) to combine into a strategy, where order
doesn’t matter?
5C2 = 5! / (2! × 3!) = 120 / (2 × 6) = 10 combinations
3
2.3 Why It Matters for Trading
Combinatorics doesn’t predict price — it tells you how large your “testing space” is. If
you have 5 indicators and want to test every possible pair, triple, etc., combinatorics
tells you exactly how many backtests that requires (2^5 − 1 = 31 total non-empty
subsets, in this case). This matters for a real risk: overfitting. If you test hundreds
of indicator combinations against the same historical data, some will look profitable
purely by chance, not because they contain a real edge. Combinatorics helps you
understand how big that “chance” risk is.
Example of the overfitting trap: If you test 30 random indicator combinations, and
each has just a 5% chance of looking “significant” by pure luck, the probability that
at least one looks falsely significant is:
P(at least one false positive) = 1 − (1 − 0.05)^30 = 1 − 0.955 ≈ 1 − 0.215 ≈ 0.785 (78.5%)
So testing many combinations almost guarantees you’ll find a “winning” pattern that
isn’t real. This is why disciplined statistical testing (Part 3) matters so much.
Part 3: Statistics — Describing and Testing Data
3.1 Core Descriptive Statistics
Mean (average):
mean = (sum of all values) / (number of values)
Example: daily returns of +1%, −2%, +3%, 0%, +1% → mean = (1−2+3+0+1)/5 =
3/5 = 0.6%
Variance and standard deviation (how spread out values are — this is “volatility”
in trading):
variance = average of (each value − mean)²
standard deviation = √variance
Using the returns above (mean = 0.6%):
deviations: 0.4, −2.6, 2.4, −0.6, 0.4
squared: 0.16, 6.76, 5.76, 0.36, 0.16
variance = (0.16+6.76+5.76+0.36+0.16)/5 = 13.2/5 = 2.64
std dev = √2.64 ≈ 1.62%
This 1.62% is the daily volatility of this small sample — a core number in almost every
trading and risk model.
Correlation (do two things move together?): a number between −1 and +1. - +1 =
move perfectly together - −1 = move perfectly opposite - 0 = no relationship
Example use: does trading volume correlate with price volatility? A correlation of 0.7
would suggest yes, moderately strongly.
4
3.2 The Normal Distribution (the “bell curve”)
Many statistical models assume returns roughly follow a bell-shaped distribution:
most days cluster near the average, with fewer extreme days on either side. In re-
ality, crypto/forex returns have “fatter tails” than a true bell curve (extreme moves
happen more often than a normal distribution predicts) — an important limitation to
remember.
3.3 Regression
Regression finds the best-fit line describing the relationship between two variables
(e.g., “as RSI decreases, does next-day return increase?”). The simplest form:
y = a + bx
Where x is your indicator value, y is the future return, a is a constant, and b tells you
the strength/direction of the relationship. If b is close to 0, the indicator likely has
little predictive value.
3.4 Hypothesis Testing (is this edge real, or luck?)
This is the statistical safeguard against the overfitting trap from Part 2. The process:
1. State a null hypothesis: “This indicator has no real effect on returns” (any
observed edge is due to chance).
2. Calculate a test statistic from your data (e.g., a t-test comparing average re-
turns after a signal vs. average returns overall).
3. Get a p-value: the probability of seeing your result (or a more extreme one) if
the null hypothesis were true.
4. If the p-value is very low (commonly below 0.05), you have some statistical ev-
idence the edge might be real — though even this isn’t proof, especially if you
tested many strategies (Part 2’s overfitting problem).
Simple example: Strategy A’s trades average +0.8% return with a p-value of 0.03
→ reasonably unlikely to be pure luck. Strategy B’s trades average +1.5% but with a
p-value of 0.40 → could easily be random noise, despite the “juicier” number. This is
exactly why raw returns alone can mislead beginners.
Part 4: Technical Indicators — Turning Price Into Numbers
Indicators convert raw price/volume into a number you can measure and test statisti-
cally. Below are the five most common, each with the exact formula and a tiny worked
example.
4.1 Simple Moving Average (SMA)
Definition: the average closing price over the last N periods. Smooths out noise to
show trend direction.
5
SMA(N) = (sum of last N closing prices) / N
Example (5-day SMA): Closes: 100, 102, 101, 105, 107
SMA(5) = (100+102+101+105+107)/5 = 515/5 = 103
4.2 Exponential Moving Average (EMA)
Definition: like SMA, but gives more weight to recent prices, so it reacts faster to
new information.
Multiplier = 2 / (N + 1)
EMA(today) = (Close(today) − EMA(yesterday)) × Multiplier + EMA(yesterday)
Example (N=5, multiplier = 2/6 ≈ 0.333): If yesterday’s EMA was 103 and today’s
close is 107:
EMA(today) = (107 − 103) × 0.333 + 103 = 1.33 + 103 = 104.33
4.3 Relative Strength Index (RSI)
Definition: measures the speed/magnitude of recent price changes on a 0–100 scale.
Above 70 is often read as “overbought,” below 30 as “oversold.”
RS = (average gain over N periods) / (average loss over N periods)
RSI = 100 − [100 / (1 + RS)]
Example (N=5): Average gain = 2, average loss = 1
RS = 2/1 = 2
RSI = 100 − [100/(1+2)] = 100 − 33.3 = 66.7
4.4 MACD (Moving Average Convergence Divergence)
Definition: shows the relationship between two EMAs to spot momentum shifts.
MACD line = EMA(12) − EMA(26)
Signal line = EMA(9) of the MACD line
Histogram = MACD line − Signal line
Example: If EMA(12) = 104.33 and EMA(26) = 101.20:
MACD line = 104.33 − 101.20 = 3.13
If the signal line is 2.50:
Histogram = 3.13 − 2.50 = 0.63 (positive → bullish momentum signal)
4.5 Bollinger Bands
Definition: a band around the SMA using standard deviation, showing how
“stretched” price is relative to its recent volatility.
6
Middle Band = SMA(N)
Upper Band = SMA(N) + (K × standard deviation)
Lower Band = SMA(N) − (K × standard deviation)
(K is usually 2)
Example: SMA(20) = 103, standard deviation = 2, K = 2:
Upper Band = 103 + (2×2) = 107
Lower Band = 103 − (2×2) = 99
If price trades above 107, some traders read this as “overextended” relative to recent
volatility.
4.6 Volume
Definition: the number of units traded in a period. Not a formula-based indicator
by itself, but it’s used to confirm signals — e.g., a price breakout on high volume
is statistically more likely to hold than one on low volume (this itself is a testable,
probabilistic claim, not a certainty).
4.7 Putting It Together
None of these indicators predicts the future on its own. What Parts 1–3 let you do
is treat each indicator signal as a conditional probability input (“given RSI < 30,
what’s the historical P(price up)?”) and test whether that input is statistically mean-
ingful rather than random noise.
Part 5: Monte Carlo Simulation
5.1 Definition
Monte Carlo simulation means running a random process thousands (or millions) of
times to see the range of possible outcomes, instead of relying on one single historical
path.
5.2 Simple Example (Estimating Pi)
A classic beginner example, unrelated to trading, to build intuition: throw random
points into a square containing a circle. The ratio of points landing inside the circle
vs. the square approximates π/4. Do this with 10 points and you get a rough, noisy
estimate; do it with 1,000,000 points and the estimate becomes stable and accurate.
This illustrates the core idea: randomness + repetition = a reliable estimate of
an uncertain quantity.
5.3 Applying It to Trading
Process: 1. Estimate your strategy’s average return and standard deviation of re-
turns per trade (from Part 3 stats). 2. Randomly generate thousands of possible
7
sequences of trade outcomes using those statistics (e.g., using a random number
generator that mimics your return distribution). 3. Look at the distribution of final
account outcomes across all simulations — not just one lucky or unlucky path.
Simple worked example: Suppose your strategy has a 55% win rate, average win
of +2%, average loss of −1.5%. Instead of assuming a smooth, steady climb, you
simulate 1,000 sequences of 100 trades each using these probabilities. You might
find: - 90% of simulated outcomes end profitable. - But 10% of simulations still show
a max drawdown of over 25%, even though the strategy has positive expected value.
This tells you something backtesting a single historical chart never can: the range of
bad luck you should be mentally and financially prepared for, even with a genuinely
good strategy.
Part 6: Expected Value and the Kelly Criterion
6.1 Expected Value (EV)
Definition: the average outcome you’d expect if you repeated a bet many times.
EV = (P(win) × amount won) − (P(loss) × amount lost)
Example: A trade setup wins 55% of the time, averaging +2% gain, and loses 45%
of the time, averaging −1.5% loss.
EV = (0.55 × 2%) − (0.45 × 1.5%) = 1.1% − 0.675% = +0.425% per trade
A positive EV means that, on average, over many repetitions, this setup should be
profitable — even though any single trade could still lose.
6.2 The Kelly Criterion
Definition: a formula for how much of your capital to risk per bet/trade to maximize
long-term growth, given your edge and odds.
Kelly % = W − [(1 − W) / R]
Where: - W = win probability (as a decimal) - R = win/loss ratio (average win size ÷
average loss size)
Example: Using the numbers above, W = 0.55, average win = 2%, average loss =
1.5%, so R = 2/1.5 = 1.333
Kelly % = 0.55 − [(1 − 0.55) / 1.333] = 0.55 − [0.45/1.333] = 0.55 − 0.3375 = 0.2125
Kelly says to risk about 21.25% of your capital on this setup. In practice, almost ev-
eryone uses a fractional Kelly (e.g., half-Kelly or quarter-Kelly) because full Kelly
assumes your win probability and payoff estimates are exactly correct — in real mar-
kets, they never are, and errors compound painfully at full Kelly sizing. A common
practical choice would be to risk 5–10% (quarter to half Kelly) instead of the full 21%.
8
6.3 Why This Combination Matters
Expected value tells you whether a setup is worth taking at all. Kelly tells you how
much to risk if it is. Skipping either step is how mathematically sound edges still blow
up accounts — usually from oversizing positions relative to the real uncertainty in the
edge.
Part 7: Backtesting Methodology
7.1 Definition
Backtesting means running your strategy’s rules against historical data to see how it
would have performed, before risking real money.
7.2 The Process, Step by Step
1. Define the strategy in exact, mechanical rules. Example: “Buy when RSI <
30 and price is above the 50-day SMA. Sell when RSI > 70 or after a 5% stop-
loss.”
2. Gather historical data. For Binance, this typically means OHLCV (open/high/low/close/volum
candle data via the Binance API. For forex, historical OHLC data from a broker
or data provider.
3. Implement the rules in code. Using Python with pandas for data handling,
and either backtrader or vectorbt for the actual simulation of trades, fees, and
slippage.
4. Run the backtest and record every trade, not just the final result — win rate,
average win/loss, max drawdown, Sharpe ratio (return per unit of risk).
5. Apply hypothesis testing (Part 3) to check whether the results are statistically
distinguishable from random luck.
6. Out-of-sample test: split your data — build/tune the strategy on one period
(e.g., 2018–2022) and test it, unchanged, on a period it never saw (e.g., 2023–
2025). A strategy that only works on the data it was tuned on is overfit (Part 2’s
trap).
7. Walk-forward and paper-trade before using real capital, to check the strategy
still behaves reasonably in current, live conditions.
7.3 Common Pitfalls (the math traps that break beginners)
• Overfitting: tuning too many parameters until the backtest looks perfect on past
data (directly related to Part 2’s combinatorics — more combinations tested =
higher chance of a false “winner”).
• Look-ahead bias: accidentally using information in the backtest that wouldn’t
have been available at the time (e.g., using a day’s closing price to make a deci-
sion that would have needed to happen at the day’s open).
• Survivorship bias: testing only on assets that still exist today, ignoring ones
that failed or got delisted.
9
• Ignoring fees/slippage: a strategy with many small trades can look profitable
until realistic trading fees and slippage are subtracted.
7.4 Simple Example (Pseudocode Logic)
import pandas as pd
data = pd.read_csv("btc_usdt_daily.csv") # OHLCV data
data['rsi'] = compute_rsi(data['close'], 14)
data['sma50'] = data['close'].rolling(50).mean()
data['signal'] = (data['rsi'] < 30) & (data['close'] > data['sma50'])
data['return'] = data['close'].pct_change().shift(-1) # next-day return
trade_returns = [Link][data['signal'], 'return']
win_rate = (trade_returns > 0).mean()
avg_win = trade_returns[trade_returns > 0].mean()
avg_loss = trade_returns[trade_returns < 0].mean()
This tiny script calculates exactly the numbers you need for Part 6’s Expected Value
and Kelly formulas — this is where all the earlier math converges into one testable
pipeline.
Part 8: Risk Management Math
8.1 Position Sizing
Definition: how much capital to commit to a single trade, based on your account size
and how much you’re willing to lose if the trade goes wrong.
Position size = (Account size × Risk per trade %) / (Entry price − Stop-
loss price)
Example: Account = $10,000. You risk 1% per trade = $100. Entry = $50, stop-loss
= $48 (a $2 risk per unit).
Position size = $100 / $2 = 50 units
8.2 Maximum Drawdown
Definition: the largest observed drop from a peak account value to a subsequent low,
usually shown as a percentage. It’s the statistic that best represents “how bad did it
get” during a strategy’s history.
Drawdown % = (Peak value − Trough value) / Peak value
Example: Account peaks at $12,000, later drops to $9,000 before recovering.
Drawdown = ($12,000 − $9,000)/$12,000 = 25%
10
8.3 Risk of Ruin
Definition: the probability that a string of losses wipes out your account entirely,
given your win rate, payoff ratio, and position sizing. This connects directly back to
the Kelly criterion (Part 6) — oversized positions dramatically increase risk of ruin
even with a positive-EV strategy, because variance (Part 3) compounds against you.
8.4 Why This Section Ties Everything Together
Probability and statistics tell you if an edge might be real. Monte Carlo shows you the
range of outcomes to expect, including bad luck. Kelly tells you a sizing ceiling. Risk
management math (this section) is what actually keeps you in the game long enough
for a real, small, statistical edge to play out over hundreds of trades — which is the
only way probability theory “works” in practice: over a large number of repetitions,
not any single trade.
Part 9 (Optional): Time-Series and Machine Learning Models
9.1 Time-Series Models (brief intuition)
• ARIMA (AutoRegressive Integrated Moving Average): models a price/return se-
ries based on its own past values and past forecast errors — useful mainly for
short-term structure, less so for genuinely unpredictable series.
• GARCH (Generalized Autoregressive Conditional Heteroskedasticity): doesn’t
try to predict direction, but predicts volatility — the size of future price swings.
This is often more reliably estimable than direction and feeds directly into
position-sizing and risk models (Part 8).
9.2 Logistic Regression (a beginner-friendly classifier)
Definition: instead of predicting a price, this predicts the probability of a binary
outcome (e.g., “will price be higher in 24 hours: yes/no?”) based on input features
like your indicators.
P(up) = 1 / (1 + e^−(b0 + b1×RSI + b2×MACD + ...))
The model learns the coefficients (b0, b1, b2…) from historical data so that its proba-
bility outputs match what actually happened. This is a direct, numerical extension of
Part 1’s conditional probability — now with many indicators combined at once instead
of one at a time.
9.3 Random Forests (a step up in complexity)
Definition: builds many decision trees (each one a simple set of if/then rules on your
indicators), each trained on a random subset of data and features, then averages
their votes. This often captures non-linear relationships (e.g., “RSI matters only when
volume is also high”) that a single regression line would miss.
11
9.4 The Realistic Expectation
Even well-built ML classifiers on financial data typically produce only a slight im-
provement over a coin flip (e.g., 52–56% accuracy is often considered meaningful in
efficient markets like major crypto pairs and forex majors). The value isn’t a crys-
tal ball — it’s a slightly-better-than-random probability estimate that, combined with
Parts 6–8 (expected value, Kelly, risk management), can be turned into a disciplined,
testable trading process.
Your Step-by-Step Learning Path
1. Probability & statistics fundamentals (Parts 1–3): learn this with simple ex-
amples (dice, coins) before ever looking at a price chart. Resources: an introduc-
tory probability/stats course (Khan Academy or an equivalent beginner course)
covering distributions, conditional probability, hypothesis testing.
2. Technical indicators (Part 4): learn what each indicator measures and how
to compute it by hand once, so you understand what your code will later do
automatically.
3. Python for data analysis: learn pandas basics (loading CSVs, rolling calcula-
tions, .pct_change()) — this is the tool that turns Parts 1–4 into working code.
4. Backtesting a strategy (Part 7): use backtrader or vectorbt with historical
Binance data (via Binance’s public API) or forex historical data, applying the
hypothesis-testing discipline from Part 3.
5. Risk management math (Part 8): learn position sizing, Kelly criterion (Part 6),
and drawdown math, and apply it to every backtest result before considering
any live capital.
6. Optional: time-series/ML models (Part 9): only after steps 1–5 are solid, since
ML on financial data amplifies overfitting risk (Part 2) if the statistical fundamen-
tals aren’t already second nature.
Suggested pace for a beginner studying part-time: 1–2 weeks each on Parts 1–3, 1
week on Part 4, 2–3 weeks setting up Python/backtesting tools and running your first
backtest (Parts 5–7), 1 week on Part 8, and treat Part 9 as an ongoing, optional deep-
dive after the rest is comfortable.
Final Notes
This document is educational, not financial advice — nothing here predicts specific
future prices, and past statistical performance never guarantees future results. The
value of this math is turning vague trading instincts into numbers you can test, ques-
tion, and manage risk around.
12