Bayes' Theorem and Base Rates
Install and import#
npm install fintech-algorithmsimport { bayesTheoremAndBaseRates } from "fintech-algorithms/foundations/probability-and-random-variables/bayes-theorem-and-base-rates";Signature#
bayesTheoremAndBaseRates(input)Turns a prior, a true-positive rate, and a false-positive rate into the posterior probability of the condition given a positive result, along with the unconditional probability of that result.
Parameters#
| Name | Type | Notes |
|---|---|---|
input | { pA: number; pB: number; pAB: number; prior: number; sensitivity: number; falsePositiveRate: number } | prior is the base rate of the condition, sensitivity the chance of a positive result when the condition holds, and falsePositiveRate the chance of a positive result when it does not. The family-wide pA, pB, and pAB are validated on every call even though this topic does not use their values.pA: 0 <= pA <= 1 · pB: 0 <= pB <= 1 · pAB: 0 <= pAB <= min(pA, pB) · prior: 0 <= prior <= 1 · sensitivity: 0 <= sensitivity <= 1 · falsePositiveRate: 0 <= falsePositiveRate <= 1 |
Returns#
{ posterior: number; evidenceProbability: number }
evidenceProbability is sensitivity * prior + falsePositiveRate * (1 - prior), the total chance of a positive result, and posterior is sensitivity * prior divided by it.
Errors#
- When
inputis null, an array, or not an object — throws TypeError - When
pA,pB, orpABfalls outside [0, 1], orpABexceedsmin(pA, pB)— throws RangeError - When
prior,sensitivity, orfalsePositiveRatefalls outside [0, 1] — throws RangeError - When the evidence probability works out to exactly zero, leaving the posterior undefined — throws RangeError
Complexity: time O(1),
space O(1).
Worked example#
verified This is the worked example published in the article, replayed by the test suite on every run. The output cannot drift.
Input#
{
"pA": 0.6,
"pB": 0.5,
"pAB": 0.3,
"outcomes": ["up", "flat", "down"],
"event": ["up", "flat"],
"prior": 0.01,
"sensitivity": 0.9,
"falsePositiveRate": 0.05,
"randomValues": [0, 1, 2],
"probabilities": [0.2, 0.5, 0.3],
"randomVariableKind": "discrete",
"joint": [
{
"x": 0,
"y": 0,
"p": 0.3
},
{
"x": 0,
"y": 1,
"p": 0.2
},
{
"x": 1,
"y": 0,
"p": 0.1
}
],
"conditionY": 1
}Call#
bayesTheoremAndBaseRates(input)Returns#
object with 2 fields: posterior, evidenceProbability
{
"posterior": 0.15384615384615385,
"evidenceProbability": 0.0585
}Diagrams#
How it works#
This page states the contract — how to call it correctly. The article explains the concept: why it works, and where it breaks.
References#
- Probability Distributions — NIST/SEMATECH e-Handbook
- Probability Distributions — SciPy User Guide
- Historical-example decision