All posts

Why the backtesting apps of yesteryear that you still pay for are wasting your time and money

Almost every retail backtesting platform locks you into the same slow loop: hardcode a trading rule in a script, run the simulation, check the equity curve, tweak a threshold, and run it again. That workflow puts the backtest at the beginning of the research process when it belongs at the end. A backtest tells you how much one specific rule would have made or lost, while hiding the underlying structure of the data that produced the result. Real strategy development starts by mapping how market conditions relate to forward returns, and analytical SQL is built for exactly that.

Loop of clockwise arrows from run the backtest to read the result to change the script and back to run the backtest.

This post is not financial advice or a recommendation to trade any security or strategy. The charts and code below are illustrative examples of a research workflow; past performance does not predict future results.

Why hosted backtesting platforms still push the one-run-at-a-time loop:

How DeltaForge is architected instead:

Why procedural backtest scripts resist exploration

A procedural backtest script mixes signal logic with execution plumbing: bar-by-bar loops, position-state flags, stop-loss checks and fill accounting all live interleaved in the same function. Because the hypothesis is welded to the loop machinery, every new research question requires surgery on the script.

Want to test whether an earnings blackout, a volume filter or a treasury-curve regime changes the outcome? You have to thread new state variables through the loop and re-verify that you didn't break the fill logic.

Worse, exploring how multiple conditions interact triggers a combinatorial explosion. The Python example on the right sweeps five parameters across 2,400 combinations, re-running the entire bar-by-bar loop from scratch 2,400 times. Every new filter multiplies the runtime.

Comparing variants means juggling duplicate script files or commenting blocks in and out between runs, and the script only emits whatever summary metrics you remembered to print before starting the sweep.

On top of that, standalone scripts carry environment friction: virtual environments, pinned package versions and data-loading boilerplate that break independently of your research. Yield curve data: Federal Reserve Bank of St. Louis, 10-Year Minus 2-Year Treasury Constant Maturity (T10Y2Y), via FRED.

import itertools

import pandas as pd

GRID = {
    "rsi_entry": [5, 10, 15, 20, 25, 30],
    "vix_max": [15, 20, 25, 30, 35],
    "curve_min": [-0.5, 0.0, 0.5, 1.0],
    "atr_stop": [1.0, 1.5, 2.0, 2.5, 3.0],
    "max_days": [5, 10, 15, 20],
}


def rsi(close, period):
    delta = close.diff()
    gain = delta.clip(lower=0).ewm(alpha=1 / period, adjust=False).mean()
    loss = -delta.clip(upper=0).ewm(alpha=1 / period, adjust=False).mean()
    return 100 - 100 / (1 + gain / loss)


def atr(bars, period):
    prev_close = bars["close"].shift()
    true_range = pd.concat(
        [
            bars["high"] - bars["low"],
            (bars["high"] - prev_close).abs(),
            (bars["low"] - prev_close).abs(),
        ],
        axis=1,
    ).max(axis=1)
    return true_range.rolling(period).mean()


def load(symbol):
    bars = pd.read_csv(f"bars/{symbol}.csv", index_col="date", parse_dates=True)
    vix = pd.read_csv("vix.csv", index_col="date", parse_dates=True)["close"]
    curve = pd.read_csv("t10y2y.csv", index_col="date", parse_dates=True)["value"]

    bars["sma200"] = bars["close"].rolling(200).mean()
    bars["sma5"] = bars["close"].rolling(5).mean()
    bars["rsi2"] = rsi(bars["close"], 2)
    bars["atr14"] = atr(bars, 14)
    bars["vix"] = vix.reindex(bars.index).ffill()
    bars["curve"] = curve.reindex(bars.index).ffill()
    return bars.dropna()


def backtest(bars, symbol, params):
    trades = []
    position = None

    for date, row in zip(bars.index, bars.to_dict("records")):
        if position is not None:
            position["days"] += 1
            position["low"] = min(position["low"], row["low"])  # added: worst price while open
            exit_reason = None
            if row["low"] <= position["stop"]:
                exit_price, exit_reason = position["stop"], "stop"
            elif row["close"] > row["sma5"]:
                exit_price, exit_reason = row["close"], "sma5"
            elif position["days"] >= params["max_days"]:
                exit_price, exit_reason = row["close"], "time"
            if exit_reason is not None:
                trades.append(
                    {
                        "symbol": symbol,
                        "entry_date": position["date"],
                        "exit_date": date,
                        "return": exit_price / position["price"] - 1,
                        "days": position["days"],
                        "exit": exit_reason,
                        "mae": position["low"] / position["price"] - 1,  # added
                    }
                )
                position = None
            continue

        if (
            row["close"] > row["sma200"]
            and row["rsi2"] < params["rsi_entry"]
            and row["vix"] < params["vix_max"]
            and row["curve"] > params["curve_min"]
        ):
            position = {
                "date": date,
                "price": row["close"],
                "stop": row["close"] - params["atr_stop"] * row["atr14"],
                "days": 0,
                "low": row["close"],  # added
            }

    return pd.DataFrame(trades)


if __name__ == "__main__":
    symbols = pd.read_csv("universe.csv")["symbol"]
    data = {s: load(s) for s in symbols}
    combos = [dict(zip(GRID, values)) for values in itertools.product(*GRID.values())]
    print(f"{len(combos)} combinations x {len(symbols)} symbols")

    summary = []
    for params in combos:
        trades = pd.concat(
            [backtest(bars, s, params) for s, bars in data.items()],
            ignore_index=True,
        )
        if trades.empty:
            continue
        summary.append(
            {
                **params,
                "trades": len(trades),
                "win_rate": (trades["return"] > 0).mean(),
                "avg_return": trades["return"].mean(),
                "avg_days": trades["days"].mean(),  # added
                "stop_rate": (trades["exit"] == "stop").mean(),  # added
                "worst_mae": trades["mae"].min(),  # added
            }
        )

    results = pd.DataFrame(summary).sort_values("avg_return", ascending=False)
    print(results.head(20).to_string(index=False))
The script's printout for SPY from 2008 to 2026: the combination count, then the 20 parameter sets with the highest average return, with trades, win rate, average return, days held, stop rate and worst drop while open.

Why declarative SQL maps the whole surface in one pass

Where a Python script prescribes a step-by-step procedure, SQL is declarative: you specify the relationships and groupings you want to inspect, and the query optimizer figures out how to compute them. Adding a new macro or technical regime is a single column expression; comparing outcomes across every combination of regimes is a GROUP BY.

Under the hood, a columnar analytical database reads only the columns referenced in the query, processes vectors of values inside CPU L1/L2 cache with SIMD instructions, and parallelizes automatically across every core. Scanning the full joint distribution in one vectorized query is routinely faster than looping over a handful of parameter combinations in Python.

Most importantly, SQL shifts your workflow from threshold-guessing to surface-mapping. Instead of guessing 'VIX < 15, then VIX < 20, then VIX < 25' across separate runs, you bucket or rank each day's VIX level, yield-curve slope and RSI reading alongside subsequent forward returns in a single table scan. One pass reveals the entire response surface across all variables and their interactions, showing you immediately whether a relationship is smooth, monotonic and well-populated or just an artifact of a thin threshold. Yield curve data: Federal Reserve Bank of St. Louis (T10Y2Y), via FRED.

-- Data-first: every trading day, its conditions,
-- and what happened next
WITH base AS (
    SELECT symbol, date, close,
           close - lag(close) OVER s AS d,
           -- forward return over 21 trading days
           lead(close, 21) OVER s / close - 1 AS fwd_21d
    FROM bars
    WHERE symbol IN (FROM universe)
    WINDOW s AS (PARTITION BY symbol ORDER BY date)
),
days AS (
    SELECT b.*, v.close AS vix, c.value AS curve,
           b.close / avg(b.close) OVER w200 - 1 AS vs_sma200,
           100 * list_reduce(list(greatest(d, 0)) OVER w60,
                             (a, x) -> (a + x) / 2)
               / list_reduce(list(abs(d)) OVER w60,
                             (a, x) -> (a + x) / 2) AS rsi2,
           row_number() OVER s AS n
    FROM base b
    ASOF JOIN vix v ON v.date <= b.date
    ASOF JOIN t10y2y c ON c.date <= b.date
    WINDOW s AS (PARTITION BY b.symbol ORDER BY b.date),
           w200 AS (s ROWS 199 PRECEDING),
           w60 AS (s ROWS 59 PRECEDING)
)
SELECT floor(rsi2 / 10) * 10 AS rsi2,
       floor(vix / 5) * 5 AS vix,
       floor(vs_sma200 * 20) / 20 AS vs_sma200,
       floor(curve * 2) / 2 AS curve,
       count(*) AS days,
       avg(fwd_21d) AS avg_fwd_21d,
       median(fwd_21d) AS median_fwd_21d,
       avg((fwd_21d > 0)::INT) AS share_up
FROM days
WHERE n >= 200 AND fwd_21d IS NOT NULL
GROUP BY ALL
ORDER BY ALL;
The query's output for SPY from 2008 to 2026 as a heatmap: the next 21-day return by RSI(2) band and VIX band, combined over the 200-day and yield curve bands, with cells under 20 days left blank. VIX runs from 5 to 35, where every band has data.

Hypothesis-first vs. data-first research

Log-scale line chart of growth of $1 from July 2007 to November 2026: SPY buy and hold reaches about $6.93, and an RSI(2) pullback strategy at 2x leverage reaches about $4.95, with green entry and red exit markers on each of its 153 trades.
Hypothesis-first output: a single rule set (2x leveraged RSI(2) pullback on SPY), a single run, and a single equity curve ($4.95 vs. $6.93 for SPY buy-and-hold; daily-reset 2x exposure on active trade days, total-return prices, before financing or trading costs).

Traditional backtesters force a hypothesis-first workflow: guess a complete set of entry and exit rules, run the backtest, look at one summary equity curve, nudge a parameter, and repeat. In experimental design, testing one factor at a time is notorious for missing interaction effects and encouraging p-hacking as you nudge thresholds until the equity curve looks pretty.

Even built-in 'parameter optimizers' just brute-force that same hypothesis-first loop, re-running a rigid rule template thousands of times without ever showing you whether the underlying feature space has a genuine gradient.

Heatmap of ETF weeks by trend strength versus other ETFs (x axis, z-score from -4 to 4) and trend smoothness (y axis, percentile rank 0 to 100). Each cell is colored and labeled with the average return over the next 26 weeks relative to SPY, from red (below SPY) to blue (above SPY).
Data-first output: every ETF-week in calm markets mapped by cross-sectional trend strength (x-axis: z-scored 252-day EWLR slope) and trend smoothness (y-axis: percentile rank of slope / standard error), colored by forward 26-week return minus SPY. Stars mark cells more than two standard errors from zero.

A data-first workflow turns that sequence inside out. Before committing to entry triggers or stop rules, you map candidate features across the entire cross-section and history at once to see where conditional forward returns actually separate from noise. Once you see a robust, monotonic relationship across the feature surface, you design a trading rule to capture it and use a final backtest to verify execution realism, turnover and drawdown. The backtest becomes a validation gate for an empirically grounded signal, not a blind search for parameters that flatter a guess.

Where LLMs fit: terrible market oracles, great SQL engineers

Left to answer market questions from its pre-training weights alone, an LLM is a liability: its memory is a lossy compression of internet text frozen at its training cutoff, full of folk wisdom and hallucinated statistics.

Give that same model live tool access to an analytical database, exact table schemas and working query templates, however, and it becomes a remarkably fast research engineer. The model doesn't guess what the market did; it writes the SQL to measure what the data actually shows, inspects the output tables, and iterates under your direction while you retain full control over the methodology and statistical standards.

How this works in DeltaForge Studies

We built the Studies plugin in DeltaForge specifically for this data-first loop:

Studies is available in the in-app Store with a free first month.

Try DeltaForge on your Mac

DeltaForge unifies your brokerage account and public datasets in one local database, giving your AI coding agent everything it needs to test ideas like this on your machine.

See setup steps

Nothing in this post is financial advice or a recommendation to trade. The examples illustrate a research methodology, not a live trading signal. Trading involves substantial risk of loss, including losses exceeding your initial investment when using leverage.