The governed definitions this build depends on. Read them first if a term is unfamiliar.
- PrimaryTop-N Index ContributionTop-N Index Contribution is the combined index-return contribution of the N constituents selected by a declared contribution ranking.
- PrerequisiteBase ValueBase value is the chosen numerical level assigned to an index at its base date.
- PrerequisiteIndex ConstituentAn index constituent is an instrument included in an index for a specified effective interval.
- PrerequisiteIndex ContributionIndex Contribution is a constituent's signed contribution to an index return over a declared period.
- ImportantContribution ShareContribution Share is the selected contributors' absolute contribution divided by total absolute constituent contribution.
- ImportantDominant ConstituentDominant Constituent is the constituent with the largest value under a declared weight, exposure, or contribution basis.
The operational question
Market breadth is not one idea. A headline move can be driven by a few constituents, a weight vector can be concentrated before any return occurs, and a signal can spread across sectors or factor sleeves without those components being independent. Top-N Index Contribution owns one precise question: how much of one period's index return came from its strongest n constituent contributors?
The headline return says how far the index moved; this diagnostic identifies which constituents supplied the move and whether detractors made the leaders' share exceed 100%. That is a diagnostic and governance outcome, not a forecast, recommendation, legal classification, or promise of diversification.
Intuition before notation
Multiply each beginning-period constituent weight by its same-period return, rank signed contributions, then separate the strongest N names from the full index result. Unlike concentration metrics, Top-N contribution combines weights with realized returns. A large weight can contribute little when its return is near zero.
The family map prevents a category error. Contribution combines beginning weight and realized return. HHI and effective N inspect the weight vector before returns. Diffusion scores direction across a fixed component panel. Choosing the wrong branch may produce valid arithmetic that answers the wrong question.
Freeze the series identity
The selected formula is:
Rank signed constituent contributions from largest to smallest, sum the first N, and report the share only when total index contribution is nonzero. Beginning-period weights must share one index, return basis, currency, and interval; weights sum to one within tolerance. The relevant primary source establishes the underlying convention; the exact diagnostic, translated universe, and parameters remain package choices where stated.
The snapshot needs unique identifiers, finite values, complete coverage, and one point-in-time methodology. as_of is not enough in production: retain observation, availability, and knowledge times plus source owner, revision, and finality. A later corrected roster or classification must not overwrite what was knowable at the earlier cutoff.
Required input
| Field | Type | Unit and rule |
|---|---|---|
as_of | ISO date | beginning/effective snapshot date; retain availability and knowledge time separately |
security_id | string | nonempty, unique point-in-time constituent identifier |
weight | finite number | nonnegative beginning-period fraction; the complete vector sums to 1 within 1e-9 |
return | finite number | decimal constituent return on one price/total-return, currency, and interval basis |
ready | boolean | false means the required component is unavailable and calculation is refused |
top_n | integer parameter | 1 <= top_n <= roster size |
Output and refusal behavior
Return top_contribution, total_contribution, the ordered leaders, and share. share is null when |total_contribution| < 1e-15; it may exceed 1 or be negative in other denominator regimes.
The reference API raises on malformed, non-normalized, duplicate, or unready input. The lab converts its intentionally incomplete teaching scenario into a visible incomplete state; both surfaces refuse to invent a number.
Read the mathematics, not only the score
Each c_i is a percentage-point contribution in decimal form. The sum of every c_i reconciles to the one-period index return under the frozen beginning-weight convention. Ranking ties break by security_id for deterministic output.
sum(contribution_i) == total_contributionwithin numerical tolerance.leaderscontains exactlytop_ndistinct identifiers in deterministic order.- A share above 100% means positive leaders outweighed a smaller net result after detractors; it is not a data error by itself.
- A negative total makes the ratio sign-sensitive. Report the raw diagnostic with its numerator and denominator, never as an unlabeled “percent of the move.”
The output must travel with its series identity and diagnostic trace. A bare number strips away the universe, methodology, horizon, tolerance, and evidence status needed to interpret it.
Work the synthetic example
The following is labelled synthetic and all arithmetic is author-derived:
| Rank | Security | Weight | Return | Contribution |
|---|---|---|---|---|
| 1 | S01 | 0.178218 | 6.50% | 0.01158416 |
| 2 | S02 | 0.138614 | 4.10% | 0.00568317 |
| 3 | S03 | 0.108911 | 2.80% | 0.00304950 |
| 4 | S05 | 0.069307 | 1.90% | 0.00131683 |
| 5 | S08 | 0.044554 | 1.40% | 0.00062376 |
The exact expected result is:
{
"status": "resolved",
"top_n": 5,
"top_contribution": 0.02225742574257426,
"total_contribution": 0.021676237623762376,
"share": 1.0268122230850045,
"leaders": [
{
"security_id": "S01",
"contribution": 0.011584158415841586
},
{
"security_id": "S02",
"contribution": 0.005683168316831684
},
{
"security_id": "S03",
"contribution": 0.00304950495049505
},
{
"security_id": "S05",
"contribution": 0.001316831683168317
},
{
"security_id": "S08",
"contribution": 0.0006237623762376239
}
]
}
The visual keeps the distribution beside the aggregate. That matters because two identical aggregate values can conceal different component states. The values are synthetic teaching inputs; the displayed result is author-derived arithmetic.
Compare nearby methods
| Variant | What it ranks or divides | Best use | Main limitation |
|---|---|---|---|
| Signed Top-N contribution (selected) | w_i r_i, largest to smallest | identify strongest drivers and reconcile to total return | the share is sign-sensitive and not bounded to 0–100% |
| Absolute Top-N contribution | ` | w_i r_i | ` |
| Share of positive contribution | positive Top-N divided by all positive contribution | bounded comparison among gain contributors | no longer reconciles directly to net index return |
| Top-N weight | weights only | static concentration at a chosen cutoff | ignores realized return |
The comparison is part of the contract. A different numerator, denominator, component universe, weighting rule, tolerance, or signal horizon is not a cosmetic option—it defines a different series.
Implementation walkthrough
The reference algorithm validates before aggregating:
validate complete beginning-weight roster and same-basis returns
validate top_n and sum(weights) = 1
for each constituent: contribution = beginning_weight * period_return
rank by signed contribution descending, then security_id
sum the first top_n and reconcile all contributions
if abs(total) < epsilon: share = null
else: share = top_contribution / total
return leaders and reconciliation trace
Validate one complete normalized weight vector, reject mixed return bases, sort ties by identifier, and return both numerator and denominator so the ratio remains auditable.
Python and TypeScript consume the same JSON fixture and return the same resolved fields. Invalid or incomplete input raises rather than being repaired. The playground deliberately translates its failure fixture into a visible withheld state because its job is to teach the refusal boundary.
Guided lab
Open the guided playground. Start from the informative canonical state, switch to Comparison, then Failure / boundary. Use Back and Step to inspect how each component enters the result. Change N and compare a leader-driven rally, an evenly shared move, and an invalid weight snapshot. Reset restores the exact canonical state, and reduced-motion Play advances one deterministic observation without starting a timer.
The calculation flow shows why point-in-time validation precedes aggregation.
Put the diagnostic into an operating workflow
Use the diagnostic after an index move to answer who drove it, then inspect the long tail and detractors. Store the beginning roster, return variant, currency, interval, and contribution trace together so later rebalances cannot rewrite the explanation.
A robust dashboard retains the input snapshot, formula version, parameters, component trace, and refusal reason. It should make methodology or taxonomy changes visible as breaks in series identity rather than quietly splicing them into history.
Edge cases and misuse boundaries
Do not use ending weights, mix price and total returns, or divide by a near-zero total and call the resulting ratio economically meaningful. Missing components are neither zero nor unchanged. A different roster, taxonomy, factor provider, share-class policy, currency, return basis, horizon, or tolerance defines a different series.
Main takeaway: A net-return share is a reconciliation ratio, not a bounded participation percentage.
Passing implementation tests proves that the code matches the selected definition. It does not prove association with future returns, usefulness after costs, causation, or suitability for an investment decision.
Evidence and historical boundary
The source records in REFERENCES.md establish only the claims mapped to them. They do not establish the synthetic numbers or silently define this package's translated universe and parameters.
A named historical case is deferred until licensed point-in-time membership, beginning weights, same-basis constituent returns, corporate-action treatment, correction lineage, and redistribution permission. Deferral is a publication boundary, not a missing-data invitation: the public tutorial uses a transparent synthetic case rather than an irreproducible observed value.
Summary and handoff
You can now calculate c_i=w_i r_i,\quad C_N=\sum_{i\in\operatorname{TopN}(c)}c_i,\quad S_N=C_N/\sum_i c_i, identify the series-defining choices, interpret its edge regimes, preserve the audit trace, and reject incomplete snapshots. Continue with Herfindahl Constituent Concentration.
Primary sources and exact limitations are recorded in REFERENCES.md.
Rendered from the canonical Mermaid sources linked by this article.
Calculation Flow — Top-N Index Contribution
Purpose: validate series identity before producing the diagnostic.
Takeaway: Missing evidence is a state, never a zero contribution or neutral component.
ReferencesPrimary sources and evidence notesExpand the source trail, evidence role, and limitations behind the engineering choices.
Expand the source trail, evidence role, and limitations behind the engineering choices.
Claim-to-source map
| Material claim | Evidence | Classification |
|---|---|---|
| Methodology-specific weights and weighted component returns must share a declared basis | SPDJI-MATH | sourced provider convention |
| Signed Top-N ranking and denominator epsilon | definition contract | implementation choice |
| Canonical values | datasets/canonical-fixture.json | synthetic input and author-derived calculation |
Every external source ID mapped above is expanded below. Provider or institutional conventions are not presented as universal laws; package translations and parameters remain labelled as implementation choices.
SPDJI-MATH — S&P Dow Jones Indices: Index Mathematics Methodology
- Organization or authors: S&P Dow Jones Indices
- Source type: Official index methodology
- Publication or effective date: 2026
- Version: Current methodology retrieved 2026-07-26
- URL or DOI: https://www.spglobal.com/spdji/en/documents/methodologies/methodology-index-math.pdf
- Accessed: 2026-07-26
- Jurisdiction: Global methodology unless the limitation states otherwise
- Supports: Index weights, weighted component returns, index calculation, capping, and the importance of methodology-specific weights.
- Limitations: Defines S&P DJI conventions; it does not define this package's Top-N diagnostic, HHI, or diffusion thresholds.
Full dependency-light reference implementations in both supported languages.
type Row = Record<string, unknown>;
const numberValue = (value: unknown, name: string): number => {
if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`${name} must be a finite number`);
return value;
};
const validateRows = (rows: Row[], weighted: boolean): void => {
if (!rows.length) throw new Error("rows must not be empty");
const seen = new Set<string>();
for (const row of rows) {
const key = row[weighted ? "security_id" : "component_id"];
if (typeof key !== "string" || !key || seen.has(key)) throw new Error("component identifiers must be nonempty and unique");
seen.add(key);
if (row.ready === false) throw new Error("incomplete_component");
}
};
export function calculate(rows: Row[], topN = 5) {
validateRows(rows, true);
if (!Number.isInteger(topN) || topN < 1 || topN > rows.length) throw new Error("top_n must be an integer within the roster");
const weights = rows.map(row => numberValue(row.weight, "weight"));
if (weights.some(w => w < 0) || Math.abs(weights.reduce((a,b)=>a+b,0)-1) > 1e-9) throw new Error("weights must be nonnegative and sum to one");
const ranked = rows.map((row,i)=>({security_id: row.security_id as string, contribution: weights[i]*numberValue(row.return,"return")})).sort((a,b)=>b.contribution-a.contribution || a.security_id.localeCompare(b.security_id));
const total = ranked.reduce((s,x)=>s+x.contribution,0), top = ranked.slice(0,topN).reduce((s,x)=>s+x.contribution,0);
return {status:"resolved", top_n:topN, top_contribution:top, total_contribution:total, share:Math.abs(total)<1e-15?null:top/total, leaders:ranked.slice(0,topN)};
}
The embedded lab now expands to its full document height, keeping the article as the only scroll surface.