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

Weighted Mean

Install and import#

bash
npm install fintech-algorithms
ts
import { weightedMean } from "fintech-algorithms/foundations/location-ranking-and-exploratory-summaries/weighted-mean";

Signature#

weightedMean(input)

Computes a weighted average of values using the parallel weights series, dividing the sum of value-times-weight products by the total weight.

Parameters#

NameTypeNotes
input{ values: number[]; weights: number[] }values holds the observations and weights the importance attached to each one, position by position. Both are coerced with Number and must be finite; the weights are not normalised for you, the function divides by their sum.
weights: same length as `values`, and the weights must not sum to zero

Returns#

{ weightedMean: number; weightSum: number }

weightedMean is the weighted average and weightSum is the denominator that was used, which is what tells you whether the weights were proportions or raw counts.

Errors#

  • When input is null, an array, or not an object — throws TypeError
  • When values is missing, is not an array, or is empty — throws RangeError
  • When any entry of values does not coerce to a finite number — throws RangeError
  • When weights is missing, empty, or holds a non-finite entry — throws RangeError
  • When weights and values differ in length, or the weights sum to exactly zero — throws RangeError

Complexity: time O(n log 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
{
  "values": [1, 2, 2, 4, 9],
  "weights": [1, 1, 2, 1, 1],
  "trimProportion": 0.2,
  "bins": 4
}

Call#

weightedMean(input)

Returns#

object with 2 fields: weightedMean, weightSum

{
  "weightedMean": 3.3333333333333335,
  "weightSum": 6
}

Diagrams#

Weighted Mean — article hero
Weighted Mean — calculation ledger
Weighted Mean — comparison map
Weighted Mean — concept anatomy
Weighted Mean — mistake contrast
Weighted Mean — scenario map

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#

  • average
  • Historical-example decision

The rest of the Location, Ranking, and Exploratory Summaries family#