Library/Geometric Chart Patterns/Pattern Matching/Dynamic-Time-Warping Pattern Match

D08-F04-A02 / Complete engineering topic

Dynamic-Time-Warping Pattern Match

Learn Dynamic-Time-Warping Pattern Match with an explicit mathematical contract, synthetic worked example, Python and TypeScript, edge cases, and a guided playground.

Dynamic-Time-Warping Pattern MatchD08 / D08-F04

See exactly how a constrained dynamic-programming path aligns similar shapes that unfold at different speeds. This tutorial starts with the visual intuition, converts it into one exact contract, checks a synthetic example line by line, and then lets you challenge the result in an interactive lab.

Evidence boundary: every displayed price or sequence is synthetic teaching data. A correct match proves that the implementation follows the declared rule. It does not prove prediction, profitability, or investment suitability.

Canonical synthetic result for Dynamic-Time-Warping Pattern Match

The practical question

When two analysts look at the same chart, they may agree on the broad shape and still disagree on the start, pivots, line placement, normalization, allowed deformation, confirmation, or score. Software cannot operate on “looks close.” It needs a contract whose inputs, comparisons, clocks, and failure states are observable.

Dynamic time warping accumulates local mismatch across an admissible path. Horizontal and vertical steps repeat an observation in the alignment; a radius limits how far the path may leave the diagonal.

That intuition is useful, but it is not yet an algorithm. The difficult work is deciding which information belongs to the calculation and what the output is allowed to mean.

First, identify the moving parts

Algorithm anatomy with named inputs and outputs

The package separates four layers:

  1. Evidence: finalized observations, declared roles, source identity, adjustment basis, and availability.
  2. Transformation: pivots and fitted lines for geometry, or normalization and distance for sequence matching.
  3. Decision: a full-precision threshold, tie, exclusion, radius, or crossing rule.
  4. Interpretation: a detector state or nearest match, never an automatic trade.

Mixing those layers is the fastest way to create a result that cannot be reproduced. For example, a chart can display a pivot at its event bar even though the detector needed two later bars to confirm it. A training procedure can display a clean threshold even though that threshold was selected using labels from the evaluation set. The visual is not the clock.

The canonical contract

This package selects the following rule:

D(i,j)=(a_i-b_j)^2+min(D(i-1,j),D(i,j-1),D(i-1,j-1)); report sqrt(D(n,m)) and sqrt(D(n,m)/|path|).

Dynamic time warping accumulates local mismatch across an admissible path. Horizontal and vertical steps repeat an observation in the alignment; a radius limits how far the path may leave the diagonal.

The contract is intentionally explicit about equality. The radius must at least cover the length difference. A wider path can lower in-sample distance by allowing more deformation, which is flexibility rather than proof of a better financial match. Those details are not editorial footnotes; they change output and therefore belong in code, fixtures, and tests.

Read the geometry or distance before the label

The exact synthetic calculation ledger

The canonical fixture produces:

distance=0.882877706280; path_rms=0.192659710401; path_length=21

The ledger exists so the label can be challenged. A learner should be able to hide the final state, inspect the inputs and intermediate diagnostics, predict the next transition, and then reveal the result. If a tutorial only shows the finished outline, it teaches recognition by hindsight rather than algorithmic reasoning.

A causal sequence matters

Event, availability, candidate, and result timeline

For matching topics, a live query window can only contain observations available by the evaluation time. Training transformations, shapelet thresholds, template selection, and parameter choices must be frozen before evaluation. A retrospective all-series visualization is useful for explanation only when it is labeled as retrospective.

This ordering prevents a subtle error: moving an annotation backward does not move knowledge backward. The lab makes the available prefix visible so the state cannot borrow an unrevealed observation.

Nearby methods answer different questions

Normalized Euclidean matching preserves one-to-one timing. DTW changes alignment but not the need for causal evaluation, out-of-sample testing, and a declared normalization policy.

Comparison with nearby geometric and matching methods

The method name should follow the contract, not the other way around. A converging consolidation with no qualifying pole remains a triangle under this package rather than becoming a pennant for visual excitement. A recurring subsequence is a motif under a selected distance and length; it is not a supervised shapelet unless class labels and a training procedure establish discrimination.

Reference implementation

The Python and TypeScript facades call the same family specification but execute independently. The readable implementation favors auditability over asymptotic speed. That makes every comparison and invalid state easy to inspect.

Python
# See implementations/python/algorithm.py
result = run(canonical_input)
assert result["state_or_result"] == expected

The actual facade uses the topic's selected pattern or matching function and returns the full diagnostics. Production optimization is allowed only after parity tests preserve values, nulls, errors, reasons, and deterministic ties.

Tests that matter

A single happy-path snapshot is not enough. This package tests:

  • the persisted canonical expected result;
  • malformed, missing, nonfinite, and constant inputs;
  • strict equality at a breakout, distance, or threshold boundary;
  • causal prefix behavior and delayed pivot knowledge where relevant;
  • offset and positive-scale invariance when z-normalization makes it valid;
  • deterministic earliest-index and dynamic-programming ties;
  • invalid DTW radii and matrix-profile exclusion settings;
  • training/evaluation separation for shapelets;
  • Python and TypeScript parity from one JSON fixture.

Passing those tests answers “did we implement this rule?” It does not answer whether a rule has a stable association with later returns after costs and selection effects.

Failure clinic

Near misses, invalid inputs, and misleading successes

The most important failures are often plausible-looking successes:

  • A split or roll discontinuity can look like a dramatic pole or perfect query.
  • A permissive pivot window can manufacture the six points needed for a structure.
  • A broad DTW radius can align unrelated paths by excessive deformation.
  • Omitting a matrix-profile exclusion zone can return overlapping copies of the same subsequence.
  • A constant candidate can be incorrectly called a perfect normalized match if zero variance is silently replaced with zero.
  • A shapelet threshold chosen on evaluation labels can look accurate because the answer leaked into training.
  • Repeatedly searching symbols, windows, templates, and thresholds inflates the chance of one striking result.

The correct response is not to ban flexible methods. It is to record the flexibility, predeclare evaluation, retain rejected cases, and state what the output does not prove.

Use the guided lab as an experiment

Open the guided playground. The lab begins with a complete canonical preview rather than an empty chart. Then:

  1. choose a canonical, boundary, failure, or comparison scenario;
  2. select a strict, canonical, or permissive parameter setting when the detector exposes one;
  3. predict the next state or best match;
  4. move backward or forward one meaningful observation or algorithm step;
  5. compare chart emphasis, diagnostics, guidance, and the audit trace;
  6. reset and verify that the canonical state returns deterministically.

The controls are keyboard-operable, remain at least 44 pixels high, respect reduced motion, and use text and shape in addition to color. The underlying datasets are dense enough to expose boundaries rather than merely make the screen look active.

Historical example: why it is not useful yet

A named security example is deliberately omitted from this mechanics-first package. A defensible case would require licensed point-in-time data, exact security and venue identity, sessions and time zone, adjustment basis, source revisions, parameter vintage, and a selection protocol declared before inspecting the outcome. Without that record, a historical screenshot adds storytelling but weakens verification.

Synthetic data is not inherently less rigorous. Here it lets us set a pivot, slope, distance, path, exclusion, or threshold to an exact boundary and verify both sides of the rule.

What you can now do

You can explain Dynamic-Time-Warping Pattern Match without hand-waving, reproduce the canonical result, identify material variants, inspect a failure, and implement the same behavior in Python and TypeScript. More importantly, you can refuse the wrong conclusion: a plausible pattern or small distance is not a probability, forecast, or recommendation.

Next, compare this topic with the other members of Pattern Matching and choose the algorithm whose question matches the research problem. Geometry, query search, motif discovery, and supervised classification are related tools, not interchangeable labels.

Primary references

The package records source roles, versions, access dates, and limitations in REFERENCES.md. The canonical definitions and implementation choices remain in the topic README, which is the factual source for this article.

Reasoning Flow — Dynamic-Time-Warping Pattern Match

Purpose: keep evidence, transformation, decision, and interpretation in the correct order.

Rendering system map…

Takeaway: a result is valid only under the declared data role, clock, parameters, and boundary policy.

ReferencesPrimary sources and evidence notes

Expand the source trail, evidence role, and limitations behind the engineering choices.

All web sources were accessed 2026-08-11. Package thresholds, tie rules, synthetic fixtures, and displayed calculations are implementation choices or author-derived unless a source role explicitly says otherwise.

S1 — Foundations of Technical Analysis

  • Organization or authors: Andrew W. Lo, Harry Mamaysky, and Jiang Wang
  • Source type: Original working paper and peer-reviewed article record
  • Publication or effective date: 2000
  • Version: NBER Working Paper 7613; Journal of Finance 55(4)
  • URL or DOI: https://www.nber.org/papers/w7613 and https://doi.org/10.3386/w7613
  • Accessed: 2026-08-11
  • Supports: Chart-pattern subjectivity, the need to convert visual descriptions into systematic algorithms, and separation of detection from empirical return analysis.
  • Limitations: Does not define this package's slopes, thresholds, state machine, matching distance, or profitability.

S2 — SciPy find_peaks

  • Organization or authors: SciPy project
  • Source type: Official maintained technical documentation
  • Publication or effective date: current documentation
  • Version: SciPy 1.17.0 documentation observed at access
  • URL or DOI: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html
  • Accessed: 2026-08-11
  • Supports: Local-maximum comparison and the fact that distance, prominence, width, and plateau policies are configurable peak-selection properties.
  • Limitations: SciPy's retrospective peak finder is comparison evidence; it does not define this package's causal right-window availability or financial structure rules.

S3 — The Probability of Backtest Overfitting

  • Organization or authors: David H. Bailey, Jonathan M. Borwein, Marcos López de Prado, and Qiji Jim Zhu
  • Source type: Original research paper record
  • Publication or effective date: 2015 revision
  • Version: SSRN 2326253
  • URL or DOI: https://papers.ssrn.com/sol3/Papers.cfm?abstract_id=2326253 and https://doi.org/10.2139/ssrn.2326253
  • Accessed: 2026-08-11
  • Supports: The misuse boundary around selecting many detector configurations on the same historical sample.
  • Limitations: Does not validate any pattern or matching configuration in this package.

S4 — Dynamic Programming Algorithm Optimization for Spoken Word Recognition

  • Organization or authors: Hiroaki Sakoe and Seibi Chiba
  • Source type: Original peer-reviewed paper
  • Publication or effective date: 1978
  • Version: IEEE Transactions on Acoustics, Speech, and Signal Processing 26(1)
  • URL or DOI: https://doi.org/10.1109/TASSP.1978.1163055 and https://jeffe.cs.illinois.edu/teaching/compgeom/2022/refs/Sakoe-Chiba-DTW.pdf
  • Accessed: 2026-08-11
  • Supports: Dynamic-programming time normalization, warping paths, and slope/window constraints.
  • Limitations: The paper studies speech; applying DTW to financial series is an implementation transfer, not evidence of forecasting value.

Applicability decision

The cited paper defines the algorithmic primitive. Per-window population z-normalization, deterministic earliest-index ties, squared local DTW cost, path-RMS reporting, the exact exclusion-zone default, and threshold tie-breaking are package-selected conventions. All financial-looking series are synthetic.

algorithm.ts
/** Topic facade for D08-F04-A02 — Dynamic-Time-Warping Pattern Match. */
import { dtwDistance } from "../../../shared/typescript/matching.js";
export const match = (query: number[], candidate: number[], radius?: number, normalize = true) => dtwDistance(query, candidate, radius, normalize);
Full-height labplaygroundOpen full screen