Skip to content

Repository files navigation

fintech-algorithms

npm docs agent skill CI zero dependencies types included license

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

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. 324 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.

Verified against published worked examples

175 of 351 topics are verified against the catalog's own published numbers (134 via { input, expected }, 11 via row fixtures, 30 via bar/checkpoint fixtures). The remaining 176 are proven to load and expose a callable entry point, but their arithmetic is not asserted here — those topics ship no machine-readable expected values in the catalog.

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 277 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

351 topics · 15 domains · 58 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
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 ConstructionTime Bars · Tick Bars · Volume Bars · Dollar Bars · Tick-Imbalance Bars · Volume-Imbalance Bars · Tick-Run Bars

Cleaning and ValidationOHLC Consistency Validator · Hampel Bad-Tick Filter · Median Absolute Deviation Outlier Filter · Stale-Quote Detector · Duplicate-Trade Resolver · Crossed/Locked Market Detector

Time SynchronizationPrevious-Tick Interpolation · Linear Quote Interpolation · Refresh-Time Sampling · Exchange-Calendar Alignment · Asynchronous Return Alignment

Data QualityMissing-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 EngineeringTrade-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 FactorsBackward Split Adjustment · Forward Split Adjustment · Cash-Dividend Total-Return Adjustment · CRSP Cumulative Price Adjustment · CRSP Cumulative Share/Volume Adjustment

Complex DistributionsRights-Issue TERP Adjustment · Spin-Off Price Adjustment · Stock-Dividend Adjustment · Special-Dividend Adjustment · Return-of-Capital Adjustment

Identity ContinuityPermanent Security Identifier Mapping · Ticker-Change Chain Resolution · Share-Class Relationship Mapping · Merger Predecessor/Successor Mapping · Delisting Return Reconstruction

Point-in-Time UniverseHistorical 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 ContinuityBase-Date/Base-Value Initialization · Index Divisor Initialization · Divisor Continuity Adjustment · Corporate-Action Divisor Bridge · Intraday Index-Level Calculation

Weighting and CappingPrice-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 WeightingFundamental-Weighted Index · Dividend-Yield-Weighted Index · Factor-Score-Weighted Index · Minimum-Volatility Index · Equal-Risk-Contribution Index · Thematic-Tilt Index

Return VariantsPrice-Return Index · Gross Total-Return Index · Net Total-Return Index · Excess-Return Index · Dividend-Point Index · Currency-Converted Index · Currency-Hedged Index

Strategy IndicesLeveraged Daily-Reset Index · Inverse Daily-Reset Index · Volatility-Control Index · Fixed-Decrement Index · Percentage-Decrement Index · Index-of-Indices

Governance and MaintenanceEligibility 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 BreadthNet Advances · Advance/Decline Ratio · Cumulative Advance/Decline Line · Normalized Advance/Decline Line · Absolute Breadth Index

McClellan FamilyTraditional 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 BreadthNew 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 PressureZweig Breadth Thrust · Arms Index (TRIN) · Advance/Decline Volume Line · Upside/Downside Volume Ratio · Cumulative TICK · Breadth-Divergence Detector

Concentration and DiffusionTop-N Index Contribution · Herfindahl Constituent Concentration · Effective Number of Constituents · Sector Diffusion Index · Factor Diffusion Index

D06 — Price Action and Candlesticks · 38 topics

Candle FoundationsCandle Anatomy · Scale-Aware Body Classification · Shadow-to-Body Ratio · Gap Classification · Trend-Context Filter

Single-Candle PatternsDoji · Dragonfly Doji · Gravestone Doji · Marubozu · Spinning Top · Hammer · Hanging Man · Inverted Hammer · Shooting Star

Two-Candle PatternsBullish Engulfing · Bearish Engulfing · Bullish Harami · Bearish Harami · Piercing Line · Dark Cloud Cover · Tweezer Top · Tweezer Bottom

Multi-Candle PatternsMorning Star · Evening Star · Three White Soldiers · Three Black Crows · Three Inside Up/Down · Three Outside Up/Down · Abandoned Baby

Candlestick Scanning and ContextUnified 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 SmoothingSimple 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 SystemsMACD · Percentage Price Oscillator (PPO) · Aroon Up, Down, and Oscillator · Directional Movement · Average Directional Index (ADX) · Ichimoku Cloud · Parabolic SAR · Supertrend

MomentumRelative Strength Index (RSI) · Stochastic Oscillator · Stochastic RSI · Williams %R · Commodity Channel Index (CCI) · Ultimate Oscillator · True Strength Index (TSI) · Connors RSI

Volatility and ChannelsTrue Range · Average True Range (ATR) · Bollinger Bands · Keltner Channels · Donchian Channels · Bollinger BandWidth

Volume IndicatorsOn-Balance Volume (OBV) · Accumulation/Distribution Line · Chaikin Money Flow · Money Flow Index · Volume Price Trend · Force Index

D08 — Geometric Chart Patterns · 37 topics

Pivots and LevelsCausal Pivot Detection · ZigZag Segmentation · Support/Resistance Clustering · Robust Trendline Fitting

Reversal StructuresDouble Top · Double Bottom · Triple Top · Triple Bottom · Head and Shoulders · Inverse Head and Shoulders

Continuation StructuresAscending Triangle · Descending Triangle · Symmetrical Triangle · Flag · Pennant · Rising/Falling Wedge

Pattern MatchingNormalized Template Matching · Dynamic-Time-Warping Pattern Match · Matrix-Profile Motif Discovery · Shapelet Pattern Classifier

Indicator Divergence DetectionPrice–Indicator Pivot Alignment · Regular Bullish/Bearish Divergence Detection · Hidden Bullish/Bearish Divergence Detection · Multi-Indicator Divergence Adapters · Divergence Strength and Quality Scoring · Divergence Confirmation and Invalidation State Machine · Multi-Indicator Divergence Confluence · Market-Wide Divergence Scanner and Ranking

Level Confluence and Zone ScoringPrice-by-Volume Profile Construction · Point of Control, Value Area, HVN, and LVN Detection · Fibonacci Retracement and Extension Projection · Psychological Round-Number Level Generation · Multi-Source Support/Resistance Zone Fusion · Support/Resistance Zone Strength and Decay Scoring · Support/Resistance Role-Reversal State Machine · Breakout and Retest Detection · Market-Wide Zone-Proximity Scanner and Ranking

D09 — Statistical Time Series · 29 topics

DiagnosticsACF · PACF · Augmented Dickey-Fuller · KPSS · Ljung-Box · Zivot-Andrews Break Test

Forecast ModelsAutoReg · ARMA · ARIMA · SARIMA/SARIMAX · Holt-Winters · Theta Forecast

Multivariate SystemsVAR · Structural VAR · VECM · Impulse-Response Analysis · Forecast-Error Variance Decomposition

State and Regime ModelsKalman Filter · Extended Kalman Filter · Unscented Kalman Filter · Hidden Markov Model · Markov-Switching Autoregression · Bayesian Change-Point Detection

Decomposition and CyclesSTL Decomposition · Hodrick-Prescott Filter · Baxter-King Filter · Christiano-Fitzgerald Filter · Fast Fourier Transform Periodogram · Wavelet Decomposition

D11 — Market Microstructure · 29 topics

Trade ClassificationTick Test · Quote Test · Lee-Ready Trade Signing · Bulk Volume Classification

Liquidity and SpreadsQuoted Spread · Effective Spread · Realized Spread · Roll Spread Estimator · Amihud Illiquidity Ratio · Corwin-Schultz Spread Estimator

Order-Flow and ImpactOrder Flow Imbalance · Queue Imbalance · Kyle Lambda · Hasbrouck Price Impact · PIN · VPIN

Order-Book DynamicsOrder-Book Slope · Depth-Weighted Midprice · Microprice · Order-Book Resiliency · Hawkes Order-Arrival Model

Market-Depth AnalyticsCumulative Bid/Ask Depth · Top-N Depth Imbalance · Depth-at-Distance Profile · Expected Market-Order Fill Price · Multi-Level Sweep Cost and Slippage · Liquidity-Wall and Concentration Detection · Depth Depletion and Replenishment · Market-Depth Heatmap Aggregation

D12 — Matching Engines and Venue Logic · 21 topics

Continuous MatchingPrice-Time Priority · Pro-Rata Matching · Size-Time Priority · Hybrid Pro-Rata/Time Matching

AuctionsMaximum-Executable-Volume Auction · Minimum-Imbalance Tie-Break · Opening-Cross Price · Closing-Cross Price · Volatility-Auction Reopening

Order ControlsTick-Size Validation · Price-Band Validation · Self-Trade Prevention · Cancel-on-Disconnect · Fat-Finger Limit · Circuit-Breaker Trigger

Order Lifecycle and Queue StateLimit-Order Lifecycle State Machine · Cancel/Replace Priority Rule · Partial-Fill and Residual-Quantity Processing · Queue Position and Ahead-Volume Calculation · Iceberg/Reserve-Order Replenishment · Marketable-Order Multi-Level Sweep

D13 — Execution and Transaction Cost Analysis · 9 topics

Schedule-Based ExecutionTWAP Execution · Historical VWAP Execution · Adaptive VWAP Execution · Percentage-of-Volume Execution

Cost/Risk OptimizationAlmgren-Chriss Optimal Execution · Implementation-Shortfall Execution · Arrival-Price Execution · Liquidity-Seeking Execution · Opportunistic Dark-Pool Execution

D21 — Credit Risk and Default · 7 topics

Probability of DefaultLogistic PD Model · Probit PD Model · Through-the-Cycle PD · Point-in-Time PD · Merton Distance-to-Default · Campbell-Hilscher-Szilagyi Distress Probability · Bharath-Shumway Naive Distance-to-Default

D25 — Digital Assets and On-Chain Finance · 10 topics

AMM PricingConstant-Product AMM · Constant-Sum AMM · StableSwap Invariant · Weighted-Product AMM · Concentrated-Liquidity Position

Liquidity and LiquidationImpermanent-Loss Calculation · Liquidity-Provider Fee APR · Collateral-Health Factor · Liquidation-Price Calculation · Liquidation Waterfall

D40 — Model Validation and Backtesting · 10 topics

Classification and Score ValidationROC Curve and ROC-AUC · Precision-Recall Curve and PR-AUC · Brier Score · Log Loss · Reliability Diagram and Expected Calibration Error · Gains, Lift, and Decile Capture · Cost-Sensitive Threshold Optimization · Score Stability and Migration Matrix · Slice-Based Validation by Sector, Country, and Regime · Rare-Event Backtest and Confidence Bounds

D46 — Earnings and Per-Share Analytics · 5 topics

Earnings and Share FoundationsStock-Split/Consolidation EPS Restatement · Basic EPS

Basic and Diluted EPSIf-Converted Convertible-Preference Dilution · Treasury-Share Method for Options/Warrants · Contingently Issuable Shares

Contributing

Implementations are generated from a catalog and cannot be patched directly in this repository — see CONTRIBUTING.md for how changes flow, and for the test, build and release workflow.

License

MIT © Islam Baraka — The Fintech Builder

About

471 provider-agnostic, zero-dependency TypeScript implementations of the algorithms behind market data, statistical and financial-mathematics foundations, technical indicators, chart patterns, corporate actions, index construction, market breadth, microstructure, credit risk and model validation.

Topics

Resources

Contributing

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages