Episode 41 · AI Trading · Building a Complete Trading System

Is that AI indicator learning, or just smoothing?

Find the features, labels, loss, training loop and weights, spike-test a smooth line, and keep forecasts in a ledger that can't be quietly rewritten.

A script called “AI” or “neural”: is it really learning from data, or just smoothing the price?

This post looks in the code for features, labels, a loss function, a training loop and weights; without them, it isn’t machine learning. Then it tests a smooth line by adding one bar, and builds a model that learns in the only honest order. The easy mistake: a smooth line that looks great on history, whose points were drawn with candles that came later.

Terms used below:

  • Learned parameter: a value updated from data by a training objective, unlike an input a user picks.
  • Loss function: the number training tries to make smaller, e.g. how wrong each forecast was.
  • Weights: the learned parameters of a model.
  • Symmetric (centred) kernel: a smoothing that weighs bars on both sides of t, including the future.
  • Causal filter: a smoothing that only uses bars up to t.
  • Ablation: switching one component off to see what it adds.

What a real learning model has

Ask the AI to point at the features, the label, the loss, the training loop, the weights and the train/test split in the source. If they aren’t there, write down what the tool actually does, and don’t call it ML. For a retrospective line, check whether the weights use points to the right of the current bar. Keep a baseline with the same costs, and use ablation to see what each part adds.

Step What Why
1 Predict Using only data that exists
2 Save the prediction with its timestamp In a forecast ledger that can’t be edited
3 Wait for the label Only a finished label can be scored
4 Score Grade the forecast that was issued
5 Train Update the weights before the next prediction

After step 5, back to step 1, with no end. Keep that order: predict, save, wait for the label, score, train. Never change the order to improve the past.

A centred line looks better

  • At bar 10, the formula takes five points, bars 8–12.
  • Bars 11 and 12 don’t exist yet at bar 10.
  • Drawn back on bar 10, the line is a retrospective illustration; its value is known after bar 12 at the earliest.
  • Don’t enter at bar 10 on a mark that’s only known after bar 12.
  • A causal version needs a different formula and its own test; the old report doesn’t carry over.
Bar Status at bar 10
8, 9 Past data, available
10 Where the point is drawn; the formula uses 8–12
11, 12 Future candles, not available
After 12 The earliest moment the value is known

Worked example: a smooth line isn’t a forecast

Symmetric kernel around bar t Causal filter
Uses bars to the right of t too Only uses data that exists
The point at t is a retrospective result Can lag and look less pretty
Looks smooth and pretty The value really existed at t

A kernel line symmetric around t can use bars to the right; then the point at t is a retrospective result. A causal filter that only uses existing data can lag and look worse. Record exactly the inputs and when each value becomes known, and never choose by smoothness.

For a neural model, ask for the file that defines features and labels, the train split, the scaler, the seed and the weight version. A script called “AI” that only adds up indicator scores may have no step that learns from data. Ask what the source fits, where the weights come from, and which out-of-sample test exists.

Add a spike at the end of the series and compare the historical output. If old points change, the algorithm has to explain why. Not every change is a cheat, but a retrospective value never counts as a signal that existed in the past.

Step What
1 Run and save the historical output
2 Add a spike at the end of the series (a sudden price jump)
3 Run again and compare the historical output
4 Old points changed? Explain them by the algorithm; never use them as past signals

Both lines and the spike test, src/smoothers.py. The centred line weighs bars t−2 to t+2 (bar 10 uses 8–12); the causal one weighs t−4 to t with the right half of the same kernel:

# src/smoothers.py: a symmetric kernel line against a causal one, and the spike test that tells them apart.
#   .venv\Scripts\python src\smoothers.py
import math, random


def weights(k, bandwidth):
    return [math.exp(-(i / bandwidth) ** 2 / 2) for i in range(-k, k + 1)]


def centered(values, k=2, bandwidth=1.5):
    """Value at t uses bars t-k .. t+k: bar 10 with k=2 needs bars 8-12. Near the end it uses what exists."""
    w, out = weights(k, bandwidth), []
    for t in range(len(values)):
        pairs = [(w[i + k], values[t + i]) for i in range(-k, k + 1) if 0 <= t + i < len(values)]
        out.append(sum(a * v for a, v in pairs) / sum(a for a, _ in pairs))
    return out


def causal(values, k=4, bandwidth=1.5):
    """Value at t uses bars t-k .. t only (the right half of the kernel, mirrored to the past)."""
    w = weights(k, bandwidth)[k:]                 # weight for lag 0, 1, ..., k
    out = []
    for t in range(len(values)):
        pairs = [(w[lag], values[t - lag]) for lag in range(k + 1) if t - lag >= 0]
        out.append(sum(a * v for a, v in pairs) / sum(a for a, _ in pairs))
    return out


def spike_test(f, values, spike=50.0):
    """Run, append one spike bar, run again: how many old points moved?"""
    before = f(values)
    after = f(values + [values[-1] + spike])[:len(values)]
    return [t for t, (a, b) in enumerate(zip(before, after)) if abs(a - b) > 1e-9]


if __name__ == "__main__":
    rnd, p, closes = random.Random(4), 100.0, []
    for _ in range(200):
        p += rnd.gauss(0, 1)
        closes.append(p)
    for name, f in [("centered k=2", centered), ("causal k=4", causal)]:
        moved = spike_test(f, closes)
        print(f"{name:<13} old points moved by one new bar: {len(moved)}"
              + (f" (bars {moved[0]}..{moved[-1]} of 0..{len(closes) - 1})" if moved else ""))
    c, q = centered(closes), causal(closes)
    lag = lambda s: sum(abs(a - b) for a, b in zip(s[10:190], closes[10:190])) / 180
    print(f"mean distance from the close: centered {lag(c):.2f}, causal {lag(q):.2f}  (the causal line lags)")

.venv\Scripts\python src\smoothers.py from C:\trade-system-lab, on a made-up random walk of 200 bars:

centered k=2  old points moved by one new bar: 2 (bars 198..199 of 0..199)
causal k=4    old points moved by one new bar: 0
mean distance from the close: centered 0.41, causal 0.47  (the causal line lags)

One new bar rewrote the centred line’s last two points; the causal line kept all of its history. The centred line also sits closer to the price, which is exactly why it looks so convincing on a chart.

A model that learns, in order

src/online_model.py is a small logistic regression on two features (the 5- and 20-bar returns) with a 3-bar label. On every bar it first scores and trains on the predictions whose label has just closed, then predicts with the weights as they are, and writes each step to an append-only ledger. Every line carries the hash of the one before, so editing an old forecast breaks the chain. verify checks the chain, that no bar is predicted twice, and that no prediction is scored before its label closed. learn=False is the ablation: the same features with hand-set weights that never change.

# src/online_model.py: a model that really learns, in the only honest order:
# predict -> write the prediction to a ledger -> wait for the label -> score it -> train -> next prediction.
# The ledger is append-only JSON lines; each line carries the hash of the one before, so an edit breaks the chain.
#   .venv\Scripts\python src\online_model.py data\xauusd_h1_utc.csv
import csv, hashlib, json, math, sys

H, LR, COST = 3, 0.05, 0.0002


def feats(c, t):
    r5 = c[t] / c[t - 5] - 1
    r20 = c[t] / c[t - 20] - 1
    return [1.0, r5 * 100, r20 * 100]               # bias, 5-bar and 20-bar return in %


class Ledger:
    def __init__(self, path):
        self.path, self.prev = path, "0" * 16
        open(path, "w").close()

    def write(self, rec):
        rec["prev"] = self.prev
        line = json.dumps(rec, sort_keys=True)
        self.prev = hashlib.sha256(line.encode()).hexdigest()[:16]
        with open(self.path, "a") as f:
            f.write(line + "\n")


def run(c, ledger_path, learn=True, start=25):
    """learn=False is the ablation: the same features with hand-set weights that never change."""
    w = [0.0, 0.0, 0.0] if learn else [0.0, 1.0, 1.0]
    version, pending = 0, []
    led = Ledger(ledger_path)
    for t in range(start, len(c)):
        # 1. score and train on every pending prediction whose label is now complete (j + H <= t)
        for j, x, prob in [p for p in pending if p[0] + H <= t]:
            y = 1.0 if c[j + H] > c[j] else 0.0
            led.write(dict(kind="score", t=t, of=j, label=y, logloss=round(-math.log(prob if y else 1 - prob), 4)))
            if learn:
                w = [wi + LR * (y - prob) * xi for wi, xi in zip(w, x)]
                version += 1
            pending = [p for p in pending if p[0] != j]
        # 2. predict with the weights as they are now, and write it down before anything else happens
        if t + H < len(c):
            x = feats(c, t)
            prob = 1 / (1 + math.exp(-sum(wi * xi for wi, xi in zip(w, x))))
            led.write(dict(kind="predict", t=t, version=version, p_up=round(prob, 4)))
            pending.append((t, x, prob))


def verify(path):
    """The chain is intact; each score comes after its prediction and after its label closed; no prediction is rewritten."""
    prev, predicted, problems = "0" * 16, {}, []
    for n, line in enumerate(open(path), 1):
        rec = json.loads(line)
        if rec["prev"] != prev:
            problems.append(f"line {n}: chain broken (edited or reordered)")
        prev = hashlib.sha256(line.rstrip("\n").encode()).hexdigest()[:16]
        if rec["kind"] == "predict":
            if rec["t"] in predicted:
                problems.append(f"line {n}: bar {rec['t']} predicted twice")
            predicted[rec["t"]] = n
        elif rec["kind"] == "score":
            if rec["of"] not in predicted:
                problems.append(f"line {n}: score for bar {rec['of']} with no earlier prediction")
            if rec["t"] < rec["of"] + H:
                problems.append(f"line {n}: bar {rec['of']} scored before its label closed")
    return problems


def evaluate(c, path):
    preds = [json.loads(l) for l in open(path) if '"predict"' in l]
    trades = [(1 if p["p_up"] > 0.5 else -1, p["t"]) for p in preds if p["p_up"] != 0.5]
    hits = sum(s == (1 if c[t + H] > c[t] else -1) for s, t in trades)
    net = [s * (c[t + H] / c[t] - 1) - COST for s, t in trades]
    return len(trades), (hits / len(trades) if trades else 0), (sum(net) / len(net) if net else 0)


if __name__ == "__main__":
    with open(sys.argv[1], newline="") as f:
        c = [float(r["close"]) for r in csv.DictReader(f)][:4000]
    for name, learn, path in [("learned ON ", True, "logs/forecast_on.jsonl"), ("learned OFF", False, "logs/forecast_off.jsonl")]:
        run(c, path, learn)
        n, hit, net = evaluate(c, path)
        print(f"{name}: {n} trades | hit {hit:.1%} | net per trade {net:+.4%} | ledger check: {verify(path) or 'OK'}")
    m = [json.loads(l) for l in open("logs/forecast_on.jsonl") if '"predict"' in l]
    mom = [(1 if c[r['t']] > c[r['t'] - 5] else -1, r['t']) for r in m]
    hit = sum(s == (1 if c[t + H] > c[t] else -1) for s, t in mom) / len(mom)
    net = sum(s * (c[t + H] / c[t] - 1) - COST for s, t in mom) / len(mom)
    print(f"baseline, sign of the 5-bar return: {len(mom)} trades | hit {hit:.1%} | net per trade {net:+.4%}")

The first lines of logs/forecast_on.jsonl: three predictions at 0.5 with version 0, then the first score at bar 28, the earliest moment bar 25’s label exists, then the first prediction made with trained weights (version 1):

{"kind": "predict", "p_up": 0.5, "prev": "0000000000000000", "t": 25, "version": 0}
{"kind": "predict", "p_up": 0.5, "prev": "ae10321656d6d41c", "t": 26, "version": 0}
{"kind": "predict", "p_up": 0.5, "prev": "2949ff8cc72fe740", "t": 27, "version": 0}
{"kind": "score", "label": 1.0, "logloss": 0.6931, "of": 25, "prev": "a42e96463de7edbe", "t": 28}
{"kind": "predict", "p_up": 0.506, "prev": "bbeaecedfab6fee1", "t": 28, "version": 1}
{"kind": "score", "label": 1.0, "logloss": 0.6931, "of": 26, "prev": "46455a5459125c60", "t": 29}

On the first 4,000 bars of the made-up series from the tuning post, .venv\Scripts\python src\online_model.py data\xauusd_h1_utc.csv:

learned ON : 3968 trades | hit 49.1% | net per trade -0.0276% | ledger check: OK
learned OFF: 3971 trades | hit 50.1% | net per trade -0.0224% | ledger check: OK
baseline, sign of the 5-bar return: 3972 trades | hit 52.4% | net per trade -0.0054%

The model really learns: its weights change from data, under a loss, in the right order, and the ledger proves it. That doesn’t make it useful. Learned ON does no better than learned OFF, and neither beats the plain 5-bar baseline after costs. On a random walk, that’s the right answer. On your real data, this is the comparison to make before believing any “AI” label.

The tests, tests/test_learning.py:

# tests/test_learning.py: the spike test, and the ledger's order rules.
import json, random

from src.online_model import H, run, verify
from src.smoothers import causal, centered, spike_test


def series(n=120, seed=2):
    rnd, p, out = random.Random(seed), 100.0, []
    for _ in range(n):
        p *= 1 + rnd.gauss(0, 0.003)
        out.append(p)
    return out


def test_centered_line_at_bar_10_uses_bars_8_to_12():
    v = [0.0] * 20
    v[12] = 1.0                                   # only bar 12 is non-zero
    assert centered(v)[10] > 0                    # bar 10's value already moved: it looked 2 bars ahead
    assert causal(v)[10] == 0                     # the causal line can't see bar 12 at bar 10


def test_spike_moves_old_centered_points_only():
    s = series()
    assert spike_test(centered, s) == [len(s) - 2, len(s) - 1]
    assert spike_test(causal, s) == []


def test_ledger_is_in_order(tmp_path):
    path = tmp_path / "f.jsonl"
    run(series(200), path)
    assert verify(path) == []
    lines = [json.loads(l) for l in open(path)]
    first_score = next(r for r in lines if r["kind"] == "score")
    assert first_score["t"] == first_score["of"] + H


def test_an_edited_prediction_breaks_the_chain(tmp_path):
    path = tmp_path / "f.jsonl"
    run(series(200), path)
    lines = open(path).read().splitlines()
    rec = json.loads(lines[10]); rec["p_up"] = 0.99          # "improve" one old forecast
    lines[10] = json.dumps(rec, sort_keys=True)
    path.write_text("\n".join(lines) + "\n")
    assert any("chain broken" in p for p in verify(path))

Run .venv\Scripts\python -m pytest -q tests; you should see 4 passed.

Optional: a full ML platform to read, not to run

Outside this post’s main path. To see a quantitative ML platform that covers every step (data, features, training, backtest), and compare it with the steps above, there’s Microsoft’s Qlib (open source, MIT licence). As of 2026-11-23, version 0.9.7 on PyPI only has prebuilt packages for Python 3.8–3.12, not the Python 3.14 used here, so read its code and documentation to learn how it’s organised. Its sample data is stocks, scraped from Yahoo Finance by a script, in the same grey area as yfinance. The official dataset is paused, and the project points to a community dataset merged from several sources with no stated terms of use. So don’t download any of those datasets, don’t run the project’s data-fetching scripts, and don’t use Qlib as evidence for gold or forex.

Try it: what does an “AI” indicator actually learn?

Read the indicator code with "AI" in its name and the attached public, licensed libraries. Build a table: the deterministic parts, features and scaler, architecture and weights, the objective, the training window, the prediction time, when labels are available, score-before-train, warm-up and fallback. Tell apart a retrospective analysis line, unfinished points at the right edge, and causal forecasts that were issued. If a dependency has no source or can't be run, stop your conclusion at the caller's level and say so; don't invent functions. Design a learned OFF/ON ablation on the same data, a baseline that doesn't learn, and an immutable forecast ledger. Write 6 test cases: changed history, reload, changed input, a missing bar, a late label, and a model without enough samples yet. Don't treat the author's confidence numbers or intervals as calibrated probabilities without your own check; don't send orders.

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:

  1. List each import, its version, licence and job: computing, drawing, training or inference; if a library is missing, record it as unchecked.
  2. Mark the steps predict → save prediction and timestamp → wait for the label → score → train; never change the order to improve the past.
  3. Compare the model with a simple baseline and with the learned part off; keep issued forecasts in an immutable log to check them forward.

Key takeaways

  • At bar 10, a formula that takes bars 8–12 is only known after bar 12; a version that only uses existing data needs its own test.
  • Add a price jump at the end of the series and compare: if old points follow it, never use those values as past signals.
  • Save every forecast with its issue time in a ledger that can’t be edited; redrawing history doesn’t prove a forecast existed back then.

Comments