fintech-algorithms
Using a coding agent? Give it the skill: npx skills add IslamBaraka90/Fintech-Algorithms-Library What it does →

Expected Value

Install and import#

bash
npm install fintech-algorithms
ts
import { expectedValue } from "fintech-algorithms/foundations/probability-and-random-variables/expected-value";

Signature#

expectedValue(input)

Weights each value of a discrete random variable by its probability and sums the result, keeping the individual products so the total can be read term by term.

Parameters#

NameTypeNotes
input{ pA: number; pB: number; pAB: number; randomValues: number[]; probabilities: number[] }randomValues is the support and probabilities the mass on each point, position by position. 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) · probabilities: same length as `randomValues`, every entry nonnegative, summing to 1 within 1e-12

Returns#

{ expectedValue: number; contributions: number[] }

expectedValue is the probability-weighted sum, and contributions holds each value * probability term in support order, so one outcome dominating the mean is visible rather than buried.

Errors#

  • When input is null, an array, or not an object — throws TypeError
  • When pA, pB, or pAB falls outside [0, 1], or pAB exceeds min(pA, pB) — throws RangeError
  • When randomValues or probabilities is missing, empty, or holds a non-finite entry — throws RangeError
  • When randomValues and probabilities differ in length, a probability is negative, or the probabilities do not sum to one within 1e-12 — throws RangeError

Complexity: time O(n), space O(n).

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#

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#

expectedValue(input)

Returns#

object with 2 fields: expectedValue, contributions

{
  "expectedValue": 1.1,
  "contributions": [0, 0.5, 0.6]
}

Diagrams#

Expected Value — article hero
Expected Value — calculation ledger
Expected Value — concept anatomy
Expected Value — failure boundary
Expected Value — method map
Expected Value — scenario contrast

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.

Read the article →

References#

The rest of the Probability and Random Variables family#