kNN lets the k most similar past points vote. Which points, and which labels, are allowed to take part?
This post computes L1 distances by hand, drops samples whose label isn’t complete yet, and counts the votes of the remaining k neighbours. The easy mistake: scaling features with statistics from both train and test. It’s a leak even though it never touches a label.
Terms used below:
- Feature: an input that’s already known at the prediction time.
- Label: the target outcome, only known once its horizon has passed.
- Horizon: the number of bars a label looks ahead, e.g. the return over the next 3 bars.
- kNN (k nearest neighbours): find the k past points closest to now and let their labels vote.
- L1 distance: the sum of absolute differences between two points’ features.
- Baseline: a simple rule without machine learning to compare against.
The choices to lock before running kNN
Start with two features with clear units, for example the closed return and a normalised ATR. Fit the scaler on train only. If the label is the return over the next 5 bars, a point only joins the labelled set once those 5 bars have closed. Lock k, the distance metric and the voting rule, and run a baseline without machine learning to compare.
| Step | Who | Choice |
|---|---|---|
| 1 | You | Features: two with clear units, e.g. closed return and normalised ATR |
| 2 | You | Scaling: fit on train only, then transform what comes after |
| 3 | You | Distance: e.g. L1, the sum of absolute differences |
| 4 | You | Lock k and the voting rule |
| 5 | Compare with a baseline that uses no machine learning |
Features, scaling, distance and k all change the result directly; explain each step before optimising anything.
Three neighbours vote
L1 by hand. The current point is Q = (0.2, 0.6):
| Point | Calculation | L1 |
|---|---|---|
| A = (0.1, 0.5) | abs(0.2 − 0.1) + abs(0.6 − 0.5) = 0.1 + 0.1 | 0.2, closer |
| B = (0.8, 0.4) | abs(0.2 − 0.8) + abs(0.6 − 0.4) = 0.6 + 0.2 | 0.8, further |
A is closer than B, but A is still dropped if its label isn’t complete.
- After filtering by time, the three closest points have labels +1, +1, −1.
- A simple majority gives +1, unless you’ve set other weights.
- A point from just 3 bars ago doesn’t have its 5-bar label yet, so it’s dropped.
- Accuracy doesn’t account for risk or commission. Write entry and exit rules separately to judge the net result, with a causality test.
Two votes out of three isn’t a calibrated probability. A correct direction isn’t a profit after costs either; compare with a baseline.
Hour of day as a feature
To make 23:00 and 00:00 close together in kNN’s distance, encode the hour as
two numbers: the sine and cosine of its angle on a 24-hour circle. This
removes the jump between the end and the start of the day. As raw numbers,
23 and 0 are 23 units apart although they’re one hour apart.
src/hour_distance.py computes it:
# src/hour_distance.py: hour of day as a point on a 24-hour circle, and what L1 and Euclid make of it.
import math
def enc(h):
a = 2 * math.pi * h / 24
return math.sin(a), math.cos(a)
def l1(p, q):
return sum(abs(a - b) for a, b in zip(p, q))
def euclid(p, q):
return math.dist(p, q)
for a, b in [(23, 0), (0, 1), (2, 3), (0, 9), (0, 12)]:
print(f"{a:>2}h-{b:>2}h raw {abs(a - b):>2} Euclid {euclid(enc(a), enc(b)):.3f} L1 {l1(enc(a), enc(b)):.3f}")23h- 0h raw 23 Euclid 0.261 L1 0.293
0h- 1h raw 1 Euclid 0.261 L1 0.293
2h- 3h raw 1 Euclid 0.261 L1 0.366
0h- 9h raw 9 Euclid 1.848 L1 2.414
0h-12h raw 12 Euclid 2.000 L1 2.000With Euclidean (straight-line) distance, 23–0 is 0.261, the same as 0–1 and 2–3: every one-hour step is equal. L1 keeps 23–0 equal to 0–1 (0.293), but it doesn’t keep the order around the circle. From 0:00, 9:00 (2.414) counts as further than 12:00 (2.000), and a one-hour step is 0.293 at 0–1 but 0.366 at 2–3. So measure a sine/cosine pair with Euclid; if you keep L1, write the limitation down. With a linear model one sine/cosine pair may not be enough, and one-hot hours can do better.
Take candles from your own MT5 demo CSV, not through yfinance: it’s a community library not affiliated with Yahoo, not an official Yahoo API, and in a grey area under Yahoo’s terms.
Worked example: a three-bar label that isn’t finished yet
Say the features at the close of t are RSI 14 and the 5-bar return, and the label is the sign of the return from t to t+3. At time t, the label of a past sample j can only be used if j+3 ≤ t, by the close convention you wrote down. Samples near the end whose outcome isn’t complete don’t join the neighbours.
Scale the features with statistics from the valid train set, never with the mean and standard deviation of the whole series including test. If one feature has a much larger scale, it can dominate the distance; explain each choice of feature, scaling, distance and k before optimising.
Prefix test: adding future data to the file must not change a prediction already made at t. Compare with a simple baseline and with the usual predictions. Prediction accuracy isn’t P/L after costs; the entry and exit rules and the size are separate parts to check.
| Bar | What | Usable? |
|---|---|---|
| 90 | A sample starts; its features are known; its label needs 24 bars | |
| 100 | The prediction | Sample 90’s label isn’t complete: not yet |
| 114 | Sample 90’s label is complete | Only from here does sample 90 join the neighbours |
A sample that started in the past isn’t enough; its outcome also has to be known at the moment of prediction.
The model, src/knn.py. predict asserts that every neighbour’s label ended
by bar t. The leak_labels switch exists only to show what the leak does:
# src/knn.py: a kNN signal that only uses what was known when it predicts.
# Features at the close of bar t: RSI 14 and the 5-bar return. Label: the sign of the return from t to t+H.
# A past bar j may vote at time t only if its label is complete: j + H <= t.
import math
H, K = 3, 15
def rsi(closes, n=14):
out, gain, loss = [None] * len(closes), 0.0, 0.0
for i in range(1, len(closes)):
ch = closes[i] - closes[i - 1]
g, l = max(ch, 0), max(-ch, 0)
if i <= n:
gain, loss = gain + g / n, loss + l / n
else:
gain, loss = (gain * (n - 1) + g) / n, (loss * (n - 1) + l) / n
if i >= n:
out[i] = 100.0 if loss == 0 else 100 - 100 / (1 + gain / loss)
return out
def features(closes):
r = rsi(closes)
return [None if t < 14 or r[t] is None else (r[t], closes[t] / closes[t - 5] - 1) for t in range(len(closes))]
def label(closes, j, h=H):
"""Sign of the return from j to j+h; None while bar j+h hasn't closed."""
if j + h >= len(closes):
return None
d = closes[j + h] - closes[j]
return (d > 0) - (d < 0)
class Scaler:
"""Mean and standard deviation per feature, fitted on the rows you give it, and only those."""
def __init__(self, rows):
cols = list(zip(*rows))
self.mean = [sum(c) / len(c) for c in cols]
self.std = [math.sqrt(sum((x - m) ** 2 for x in c) / (len(c) - 1)) for c, m in zip(cols, self.mean)]
def __call__(self, row):
return [(x - m) / s for x, m, s in zip(row, self.mean, self.std)]
def predict(closes, feats, t, scaler, k=K, h=H, leak_labels=False):
"""+1, -1 or 0 (tie) at the close of bar t, and the neighbours used."""
last = t - 1 if leak_labels else t - h # leak_labels: also use bars whose label isn't complete
q = scaler(feats[t])
cands = []
for j in range(14, last + 1):
lab = label(closes, j, h)
if feats[j] is None or lab is None or lab == 0:
continue
cands.append((sum(abs(a - b) for a, b in zip(q, scaler(feats[j]))), j, lab)) # L1 distance
near = sorted(cands)[:k]
if not leak_labels:
assert all(j + h <= t for _, j, _ in near), "a neighbour's label ends after the prediction"
votes = sum(lab for _, _, lab in near)
return (votes > 0) - (votes < 0), nearA run against two baselines, and the same run with two classic leaks,
src/knn_run.py:
# src/knn_run.py: kNN against two baselines out of sample, then the same run with two classic leaks.
# .venv\Scripts\python src\knn_run.py data\xauusd_h1_utc.csv
import csv, sys
from knn import H, Scaler, features, label, predict
COST = 0.0002 # 0.02% of price per round trip
def score(closes, preds):
hits = [p == label(closes, t) for t, p in preds if p != 0]
pnl = [p * (closes[t + H] / closes[t] - 1) - COST for t, p in preds if p != 0]
return f"{sum(hits) / len(hits):6.1%} on {len(hits):>4} | net per trade {sum(pnl) / len(pnl):+.4%}"
def main(path):
with open(path, newline="") as f:
closes = [float(r["close"]) for r in csv.DictReader(f)][:3000]
feats = features(closes)
split = 2000 # train: bars before 2000; test: 2000 .. end
train_rows = [feats[j] for j in range(14, split) if feats[j] is not None]
scaler = Scaler(train_rows) # fitted on train only
leaky_scaler = Scaler([x for x in feats if x is not None]) # fitted on everything, test included
test = range(split, len(closes) - H)
runs = {
"kNN, complete labels only": [(t, predict(closes, feats, t, scaler)[0]) for t in test],
"baseline: always up": [(t, 1) for t in test],
"baseline: last 5-bar return": [(t, 1 if feats[t][1] > 0 else -1) for t in test],
"LEAK: incomplete labels vote": [(t, predict(closes, feats, t, scaler, leak_labels=True)[0]) for t in test],
"LEAK: scaler fitted on all": [(t, predict(closes, feats, t, leaky_scaler)[0]) for t in test],
}
print(f"test bars {test.start}..{test.stop - 1}, k=15, horizon {H} bars, cost {COST:.2%} per trade")
for name, preds in runs.items():
print(f"{name:<30} hit rate {score(closes, preds)}")
a, b = runs["kNN, complete labels only"], runs["LEAK: scaler fitted on all"]
print(f"the leaky scaler changed {sum(x[1] != y[1] for x, y in zip(a, b))} of {len(a)} predictions")
# prefix check: predict again from only the data that existed at the close of t
sample = range(split, split + 200)
for name, leak in [("complete labels only", False), ("incomplete labels vote", True)]:
differ = sum(predict(closes, feats, t, scaler, leak_labels=leak)[0]
!= predict(closes[:t + 1], features(closes[:t + 1]), t, scaler, leak_labels=leak)[0]
for t in sample)
print(f"prefix check, {name:<23}: {differ} of {len(sample)} predictions change when the future is cut off")
if __name__ == "__main__":
main(sys.argv[1])On a made-up random walk (the first 3,000 bars of the series from the tuning
post), train on bars 0–1999 and predict 2000 onward,
.venv\Scripts\python src\knn_run.py data\xauusd_h1_utc.csv:
test bars 2000..2996, k=15, horizon 3 bars, cost 0.02% per trade
kNN, complete labels only hit rate 48.1% on 997 | net per trade -0.0193%
baseline: always up hit rate 47.5% on 997 | net per trade -0.0235%
baseline: last 5-bar return hit rate 53.0% on 997 | net per trade -0.0062%
LEAK: incomplete labels vote hit rate 49.5% on 997 | net per trade -0.0124%
LEAK: scaler fitted on all hit rate 48.5% on 997 | net per trade -0.0163%
the leaky scaler changed 8 of 997 predictions
prefix check, complete labels only : 0 of 200 predictions change when the future is cut off
prefix check, incomplete labels vote : 1 of 200 predictions change when the future is cut offWhat it says:
- No edge, as there shouldn’t be: on a random walk, kNN’s 48.1% and the momentum baseline’s 53.0% are both noise. Two standard errors on 997 predictions is about 3.2 points either side of 50%. All five rules lose money after a 0.02% cost.
- The leaks didn’t stand out: letting unfinished labels vote moved the hit rate by 1.4 points, and the leaky scaler changed 8 predictions. Both pass for noise when you only read the score.
- The prefix check caught one: the clean model never changes when the future is cut off; the label leak did, once in 200. A leak doesn’t have to move the score to make the result wrong. The scaler leak needs its own check: the scaler must only ever see train rows.
The tests, tests/test_knn.py:
# tests/test_knn.py: the neighbours are only those with finished labels, and the future never changes a prediction.
import random
import pytest
from src.knn import H, Scaler, features, label, predict
@pytest.fixture(scope="module")
def series():
rnd, p, out = random.Random(1), 100.0, []
for _ in range(400):
p *= 1 + rnd.gauss(0, 0.004)
out.append(p)
return out
def test_hand_l1():
q, a, b = (0.2, 0.6), (0.1, 0.5), (0.8, 0.4)
l1 = lambda x, y: sum(abs(i - j) for i, j in zip(x, y))
assert round(l1(q, a), 10) == 0.2 and round(l1(q, b), 10) == 0.8
def test_unfinished_label_is_none():
closes = [1, 2, 3, 4, 5]
assert label(closes, 1) == 1 and label(closes, 2) is None # 2 + 3 = 5 is past the last bar (4)
def test_neighbours_have_finished_labels(series):
feats = features(series)
sc = Scaler([f for f in feats[:300] if f])
for t in range(300, 390, 7):
_, near = predict(series, feats, t, sc)
assert near and all(j + H <= t for _, j, _ in near)
def test_future_data_never_changes_a_prediction(series):
feats = features(series)
sc = Scaler([f for f in feats[:300] if f])
for t in range(300, 390, 7):
cut = series[:t + 1] # what existed at the close of t
assert predict(series, feats, t, sc)[0] == predict(cut, features(cut), t, sc)[0]
def test_prefix_test_catches_the_label_leak(series):
feats = features(series)
sc = Scaler([f for f in feats[:300] if f])
differ = 0
for t in range(300, 390):
cut = series[:t + 1]
full = predict(series, feats, t, sc, leak_labels=True)[0]
prefix = predict(cut, features(cut), t, sc, leak_labels=True)[0]
differ += full != prefix
assert differ > 0
def test_scaler_uses_only_its_rows():
sc = Scaler([(1.0, 10.0), (3.0, 30.0)])
assert sc.mean == [2.0, 20.0] and sc((2.0, 20.0)) == [0.0, 0.0]Run .venv\Scripts\python -m pytest -q tests; you should see 6 passed.
Try it: kNN explained on a five-row table
Explain kNN to someone who hasn't learned programming, using a table of 5 rows, 3 features and k = 3. Show the scaler fitted on train only, compute each L1 distance, drop rows whose label isn't complete, and handle missing data with a flag. Only after the example, propose a Python skeleton that reads a local CSV, with no API connection and no orders. Required schema: timestamp, feature_available_at, label_end_at, features, target, source_version. With a 24-bar horizon, assert that every neighbour has label_end_at before the prediction time. Compare with a baseline that doesn't use kNN, and state the limits: small samples, a label touching both barriers in one bar, costs and overlap. Don't call the share of neighbours a calibrated probability. Write tests that catch a deliberately leaked future label and a scaler fitted on the whole dataset.Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.
The order to work in:
- Draw the timeline feature(t) → label(t+h), and keep each column’s known time separately.
- Learn on 2 scaled features: Q = (0.2, 0.6), A = (0.1, 0.5), B = (0.8, 0.4). L1(Q, A) = 0.1 + 0.1 = 0.2; L1(Q, B) = 0.6 + 0.2 = 0.8. A is closer, but still dropped if its label isn’t complete.
- Compare kNN with the same raw signal unfiltered, then add costs and an out-of-time sample before reading anything into a grade.
Key takeaways
- L1 distance is the sum of absolute differences: Q (0.2, 0.6) is 0.2 from A (0.1, 0.5) and 0.8 from B (0.8, 0.4).
- Predicting at bar 100, a sample from bar 90 with a 24-bar label is only complete after bar 114, so it can’t be used yet.
- Two votes out of three isn’t a tested probability; a correct direction isn’t profit after costs; compare with a baseline.
Comments