Finding charts that look like this one
Every charting tool eventually gets the same feature request: "show me other times this stock looked like this." It sounds like a lookup. It is not. The retrieval is the easy half. The hard half is that a correct implementation can still produce results that are quietly meaningless, and nothing in the code will tell you. Here is the method, and the failure modes worth knowing before you ship it. No claims about predictive power anywhere in this piece — the last section explains why that is a deliberate choice, not a hedge. The naive version, and why it fails immediately The obvious first attempt: take the last 30 days of closing prices as a query vector, slide it across history, compute Euclidean distance, return the closest matches. import numpy as np def naive_search ( history , query , k = 5 ): m = len ( query ) windows = np . lib . stride_tricks . sliding_window_view ( history , m ) dists = np . linalg . norm ( windows - query , axis = 1 ) idx = np . argsort ( dists )[: k ] return idx , dists [ idx ] Run this and you get garbage — but instructively specific garbage. Every match comes from whatever period had a similar price level . Query a stock trading at $180 and you get back the other times it traded near $180. The shape is irrelevant to the metric; the offset dominates it. Scale is the same problem in a different coat. A stock that moved 2% over the window and one that moved 40% can trace an identical shape, and raw distance calls them unrelated. Normalize per window, not globally The fix is to z-normalize each window independently: def znorm ( x , axis =- 1 , eps = 1e-8 ): mu = x . mean ( axis = axis , keepdims = True ) sd = x . std ( axis = axis , keepdims = True ) return ( x - mu ) / ( sd + eps ) Per-window is the load-bearing part. Normalizing the whole series once preserves the relative offsets you were trying to remove. Each candidate window has to be centered and scaled on its own terms before it's compared. There's a satisfying identity waiting here.