fintech-algorithms
Corporate actions, index construction, market breadth, market microstructure, matching engines, execution algorithms and technical indicators — as plain TypeScript functions with zero dependencies.
📖 Documentation → docs.thefintechbuilder.com — a reference page for every algorithm, with a worked example whose output was produced by running the code. Start with the quick start.
Split and dividend adjustment factors, capped free-float index weighting, McClellan breadth internals, dollar and imbalance bars, and the usual moving averages. Most npm packages in this space stop at indicators; the harder back-office arithmetic is the reason this one exists.
npm install fintech-algorithms
How the pieces fit together
Five things carry this library's name, and it is worth knowing which one answers which question before you go looking.
flowchart TD
CAT[("private catalog<br/><i>the single source of truth</i><br/>article · implementation · tests · fixtures")]
CAT -->|"scripts/sync.mjs"| REPO["<b>this repository</b><br/>src/ generated · optimised/ hand-written<br/>github.com/IslamBaraka90/Fintech-Algorithms-Library"]
CAT -->|"article build"| SITE["<b>thefintechbuilder.com</b><br/>the lesson — why the algorithm<br/>exists and how to read it"]
REPO -->|"push a v* tag<br/>CI publishes with provenance"| NPM["<b>npm: fintech-algorithms</b><br/>what you install<br/>zero dependencies"]
REPO -->|"docs.json on main<br/>rebuilds the site"| DOCS["<b>docs.thefintechbuilder.com</b><br/>the reference — signature, contract,<br/>worked example, verification tier"]
REPO -->|"ships inside the package"| SKILL["<b>the agent skill</b><br/>skills/fintech-algorithms/<br/>lookup instead of guessing"]
NPM -.->|"node_modules/…/docs.json"| SKILL
DOCS -.->|"same subpath, same URL"| NPM
style CAT stroke-dasharray: 4 3
| Answers | Updated by | |
|---|---|---|
| npm | Give me the function. | A v* tag — CI publishes, never a laptop |
| docs.thefintechbuilder.com | What are the arguments, what comes back, is the arithmetic verified? | Every push to main — no release needed |
| thefintechbuilder.com | What is this algorithm and why would I use it? | The article, on its own schedule |
| this repository | How is it built, and how do I contribute? | Pull requests — see CONTRIBUTING.md |
| the agent skill | Which import path and which field name? | Ships inside the package |
Two of those links are worth spelling out, because they are the ones people assume and get wrong:
- A documentation URL and an import path are the same string. Swap
https://docs.thefintechbuilder.com/forfintech-algorithms/and you have the import. That is enforced by a test, not a convention. - Docs do not wait for a release. The site builds from
docs.jsononmain, so a corrected sentence ships immediately while the version on npm stays put. Check the two agree withversion.json.
Writing this code with an agent? Install the skill first
npx skills add IslamBaraka90/Fintech-Algorithms-Library
This is the single highest-value thing you can do before asking an agent to use this library. Several hundred algorithms is more API than any model has read, and the failure mode is not refusal — it is a plausible import path, a plausible parameter and a plausible field name on the result, none of which exist. The skill replaces every one of those guesses with a lookup.
It ships in the Agent Skills format, so Claude Code,
Codex, Cursor and some seventy other agents load it on demand. It carries the
routing rules for every topic, the five input shapes with executed examples,
the data-ingestion patterns for wiring up a provider, the failure modes that do
not throw — the category that otherwise produces a confident wrong number — and
a lookup script that answers from the installed docs.json, offline:
node <skill-dir>/scripts/lookup.mjs show rsi
# → signature, parameters, warm-up (p leading nulls), errors, executed example
The skill is skills/fintech-algorithms/ here and
also ships inside the npm tarball, version-matched to the docs.json beside it,
so a project that already depends on the package already has it.
📘 The agent skill → docs.thefintechbuilder.com/guides/agent-skill/ · Background on how an agent should read this library: Using this library from an agent.
Adjust a price history for a 2-for-1 split
import { calculate } from "fintech-algorithms/corporate-actions-and-security-master-data/adjustment-factors/backward-split-adjustment";
calculate({
prices: [120, 123, 60, 62],
volumes: [1000, 1200, 2400, 2000],
eventIndex: 2,
postSplitSharesPerPreSplitShare: 2,
});
// adjustedPrices: [60, 61.5, 60, 62]
// adjustedVolumes: [2000, 2400, 2400, 2000]
Pre-split prices are divided and volumes multiplied, so the series is continuous across the event and returns computed over it are correct.
Indicators work the same way — plain arrays in, plain arrays out:
import { calculateEma } from "fintech-algorithms/technical-indicators/trend-smoothing/ema";
calculateEma([10, 13, 16, 19], 3); // → [null, null, 13, 16]
null marks a warm-up observation where the indicator is not yet defined.
Bring your own data
The library ships no data provider. No Yahoo client, no exchange SDK, no
node:fs, no network calls, zero runtime dependencies. Every algorithm takes
plain arrays and plain objects, so the same code runs in Node, the browser, a
Worker, Deno or Bun.
Adapting a provider is a short mapping function that you own:
// Your provider's payload → the library's Trade contract. You own this file.
const toTrades = (payload: ProviderResponse): Trade[] =>
payload.results.map((r) => ({
tradeId: r.id,
timestamp: new Date(r.t).toISOString(),
session: "S1",
symbol: r.sym,
price: r.p,
volume: r.s,
currency: "USD",
}));
When a vendor changes their API you edit one adapter; the algorithms never move.
Requires Node ≥ 22.12 — the require condition resolves to the same ES module,
and require(esm) is unflagged from 22.12 onward.
Verified against published worked examples
329 of 403 topics have their arithmetic replayed and asserted on every build
(145 via { input, expected }, 143 via a separate input and expected-output
pair, 11 via row fixtures, 30 via bar/checkpoint fixtures).
Worth being precise about what that proves. The expected values come from the catalog, computed by a Python implementation written alongside the TypeScript rather than derived from it — so this is a cross-language parity check, not an independent third-party figure. It catches transcription and generation errors, which is the failure mode that has actually occurred here. It would not catch both implementations sharing a misreading of the source material.
The remaining 74 load and expose a callable entry point, but ship no machine-readable expected values, so nothing asserts their numbers. That gap is stated per topic rather than averaged away.
Every algorithm accompanies a published article that walks through a worked example by hand. Where that article ships machine-readable numbers, the test suite replays them and asserts the output matches exactly — so a green run means the package, the article and the standalone repo agree on the arithmetic.
It is an honest split, not a marketing number. Each algorithm's reference page states which tier it is in, and every worked example shown there is a fixture the test suite asserts — so those numbers cannot drift.
Import paths mirror article URLs
The subpath of every module is exactly the path of its article:
| Article | https://thefintechbuilder.com/technical-indicators/trend-smoothing/ema/ |
| Import | fintech-algorithms/technical-indicators/trend-smoothing/ema |
One mental model for the site, the standalone repos and the package. It also
means the 63 topics that each export a function named calculate never collide —
they live in separate namespaces.
The five shapes
Every topic is an instance of one of five archetypes:
| Archetype | Signature | Count | Example |
|---|---|---|---|
record-transform |
(input) → output |
329 | backward-split-adjustment |
series-transform |
(values, ...params) → (number|null)[] |
37 | ema, rsi, macd |
row-classify |
(rows, config?) → verdict[] |
24 | ohlc-consistency-validator |
tape-aggregate |
(trades, config) → bar[] |
7 | time-bars, volume-bars |
snapshot-evaluate |
(snapshot, policy) → result |
6 | price-source-consensus-check |
Classifiers return a verdict per row instead of throwing, so one bad tick cannot abort a batch.
The registry
The package root exports metadata only — never algorithm code — so importing it stays light. Use it to enumerate the library, build docs, or dispatch dynamically.
import { topics, topic, byDomain, byFamily, byArchetype, load, runner } from "fintech-algorithms";
topics.length; // every topic in the catalog
topic("D07-F01-A02")?.path; // "technical-indicators/trend-smoothing/ema"
byFamily("D01-F01").map(t => t.slug);
// ["time-bars", "tick-bars", "volume-bars", ...]
const run = await runner("D07-F01-A01");
run([1, 2, 3, 4, 5], 3); // [null, null, 2, 3, 4]
Every module also exports a uniform run alias for its primary function, plus a
meta object carrying its catalog id, domain, family, shape, article URL and
repo URL.
Coverage
403 topics · 16 domains · 64 families
| Domain | Topics | Families | Name |
|---|---|---|---|
| D01 | 31 | 5 | Market Data Engineering |
| D02 | 20 | 4 | Corporate Actions and Security Master Data |
| D03 | 40 | 6 | Index and Benchmark Engineering |
| D04 | 28 | 5 | Market Breadth and Internals |
| D06 | 38 | 5 | Price Action and Candlesticks |
| D07 | 37 | 5 | Technical Indicators |
| D08 | 37 | 6 | Geometric Chart Patterns |
| D09 | 29 | 5 | Statistical Time Series |
| D11 | 29 | 5 | Market Microstructure |
| D12 | 21 | 4 | Matching Engines and Venue Logic |
| D13 | 9 | 2 | Execution and Transaction Cost Analysis |
| D18 | 52 | 6 | Fundamental Analysis and Valuation |
| D21 | 7 | 1 | Credit Risk and Default |
| D25 | 10 | 2 | Digital Assets and On-Chain Finance |
| D40 | 10 | 1 | Model Validation and Backtesting |
| D46 | 5 | 2 | Earnings and Per-Share Analytics |
Every algorithm
Each name links to its reference page — signature, worked example, verification tier, diagrams and source.
Full reference for every algorithm →
D01 — Market Data Engineering · 31 topics
Bar Construction — Time Bars · Tick Bars · Volume Bars · Dollar Bars · Tick-Imbalance Bars · Volume-Imbalance Bars · Tick-Run Bars
Cleaning and Validation — OHLC Consistency Validator · Hampel Bad-Tick Filter · Median Absolute Deviation Outlier Filter · Stale-Quote Detector · Duplicate-Trade Resolver · Crossed/Locked Market Detector
Time Synchronization — Previous-Tick Interpolation · Linear Quote Interpolation · Refresh-Time Sampling · Exchange-Calendar Alignment · Asynchronous Return Alignment
Data Quality — Missing-Bar Gap Classifier · Feed-Latency Monitor · Price-Source Consensus Check · Schema-Drift Detector · Point-in-Time Availability Guard · Provider Adjustment-Basis Drift Detector
Order-Book Feed Engineering — Trade-and-Quote Event Normalization · Level-2 Snapshot-and-Delta Reconstruction · Level-3 Order-by-Order Reconstruction · Sequence-Gap Detection and Recovery · Price-Level Quantity Aggregation · Snapshot/Incremental-Feed Reconciliation · Multi-Venue Best-Quote and Book Consolidation
D02 — Corporate Actions and Security Master Data · 20 topics
Adjustment Factors — Backward Split Adjustment · Forward Split Adjustment · Cash-Dividend Total-Return Adjustment · CRSP Cumulative Price Adjustment · CRSP Cumulative Share/Volume Adjustment
Complex Distributions — Rights-Issue TERP Adjustment · Spin-Off Price Adjustment · Stock-Dividend Adjustment · Special-Dividend Adjustment · Return-of-Capital Adjustment
Identity Continuity — Permanent Security Identifier Mapping · Ticker-Change Chain Resolution · Share-Class Relationship Mapping · Merger Predecessor/Successor Mapping · Delisting Return Reconstruction
Point-in-Time Universe — Historical Constituent Reconstruction · Survivorship-Bias Guard · IPO Availability Timestamping · Filing-Revision Versioning · Corporate-Action Status and Effective-Date Reconciliation
D03 — Index and Benchmark Engineering · 40 topics
Index Initialization and Continuity — Base-Date/Base-Value Initialization · Index Divisor Initialization · Divisor Continuity Adjustment · Corporate-Action Divisor Bridge · Intraday Index-Level Calculation
Weighting and Capping — Price-Weighted Index · Total-Market-Cap Index · Free-Float Market-Cap Index · Capped Free-Float Market-Cap Index · Modified Market-Cap Index · Equal-Weight Index · Iterative Cap Redistribution · Group-Level Capping
Alternative Weighting — Fundamental-Weighted Index · Dividend-Yield-Weighted Index · Factor-Score-Weighted Index · Minimum-Volatility Index · Equal-Risk-Contribution Index · Thematic-Tilt Index
Return Variants — Price-Return Index · Gross Total-Return Index · Net Total-Return Index · Excess-Return Index · Dividend-Point Index · Currency-Converted Index · Currency-Hedged Index
Strategy Indices — Leveraged Daily-Reset Index · Inverse Daily-Reset Index · Volatility-Control Index · Fixed-Decrement Index · Percentage-Decrement Index · Index-of-Indices
Governance and Maintenance — Eligibility Screen · Liquidity Screen · Free-Float Factor Calculation · IPO Fast-Entry Rule · Reconstitution Algorithm · Rebalancing Algorithm · Turnover Buffer Rule · Index Replication-Cost Estimator
D04 — Market Breadth and Internals · 28 topics
Advance/Decline Breadth — Net Advances · Advance/Decline Ratio · Cumulative Advance/Decline Line · Normalized Advance/Decline Line · Absolute Breadth Index
McClellan Family — Traditional McClellan Oscillator · Ratio-Adjusted McClellan Oscillator · Traditional McClellan Summation Index · Ratio-Adjusted Summation Index (RASI) · McClellan Volume Oscillator · McClellan Volume Summation Index
High/Low and Trend Breadth — New Highs–New Lows · High-Low Ratio · High-Low Index · Percent Above 20-Day MA · Percent Above 50-Day MA · Percent Above 200-Day MA
Thrust and Pressure — Zweig Breadth Thrust · Arms Index (TRIN) · Advance/Decline Volume Line · Upside/Downside Volume Ratio · Cumulative TICK · Breadth-Divergence Detector
Concentration and Diffusion — Top-N Index Contribution · Herfindahl Constituent Concentration · Effective Number of Constituents · Sector Diffusion Index · Factor Diffusion Index
D06 — Price Action and Candlesticks · 38 topics
Candle Foundations — Candle Anatomy · Scale-Aware Body Classification · Shadow-to-Body Ratio · Gap Classification · Trend-Context Filter
Single-Candle Patterns — Doji · Dragonfly Doji · Gravestone Doji · Marubozu · Spinning Top · Hammer · Hanging Man · Inverted Hammer · Shooting Star
Two-Candle Patterns — Bullish Engulfing · Bearish Engulfing · Bullish Harami · Bearish Harami · Piercing Line · Dark Cloud Cover · Tweezer Top · Tweezer Bottom
Multi-Candle Patterns — Morning Star · Evening Star · Three White Soldiers · Three Black Crows · Three Inside Up/Down · Three Outside Up/Down · Abandoned Baby
Candlestick Scanning and Context — Unified Candlestick Pattern Registry · Candlestick Pattern Occurrence Contract · Market-Wide Candlestick Pattern Scanner · Contextual Candlestick Confidence Score · Support/Resistance Pattern Context · Trend, Volatility, and Volume Pattern Context · Overlapping-Pattern Conflict Resolver · Candlestick Confirmation and Invalidation State Machine · Candlestick Scanner Ranking and Deduplication
D07 — Technical Indicators · 37 topics
Trend Smoothing — Simple Moving Average (SMA) · Exponential Moving Average (EMA) · Weighted Moving Average (WMA) · Wilder RMA · Double Exponential Moving Average (DEMA) · Triple Exponential Moving Average (TEMA) · Hull MA · Kaufman Adaptive Moving Average (KAMA) · MESA Adaptive Moving Average (MAMA)
Trend Systems — MACD · Percentage Price Oscillator (PPO) · Aroon Up, Down, and Oscillator · Directional Movement · Average Directional Index (ADX) · Ichimoku Cloud · Parabolic SAR · Supertrend
Momentum — Relative Strength Index (RSI) · Stochastic Oscillator · Stochastic RSI · Williams %R · Commodity Channel Index (CCI) · Ultimate Oscillator · True Strength Index (TSI) · Connors RSI
Volatility and Channels — True Range · Average True Range (ATR) · Bollinger Bands · Keltner Channels · Donchian Channels · Bollinger BandWidth
Volume Indicators — On-Balance Volume (OBV) · Accumulation/Distribution Line · [Chaikin Money Flow](https
No comments yet
Be the first to share your take.