FAQ · Getting systematic research right

How do I backtest a grid or DCA trading strategy in Python?

A grid strategy rests buy limits at fixed steps below the price and sells each lot back one step above, so it profits from back-and-forth movement and loses when price trends away. Dollar-cost averaging buys a fixed amount on a schedule regardless of price. Backtest a grid with real limit fills, a cap on how many lots it can accumulate and a period with a long fall; test DCA against a lump-sum purchase on the same history.

A grid strategy rests buy limits at fixed steps below the price and sells each lot back one step above, so it profits from back-and-forth movement and loses when price trends away. Dollar-cost averaging buys a fixed amount on a schedule regardless of price. Backtest a grid with real limit fills, a cap on how many lots it can accumulate and a period with a long fall; test DCA against a lump-sum purchase on the same history.

How a grid makes and loses money

  • Each round trip earns one step, less the spread and fees, whenever price drops a level and comes back.
  • A falling market fills buy after buy. The grid holds more lots, each at a higher price than the market, with an unrealised loss that grows with every level.
  • A rising market leaves it flat. Once all lots are sold, the grid earns nothing while price trends up.

So a grid's backtest result depends mostly on whether the period ranged or trended. Test it on a stretch with a long fall, and look at the maximum number of lots held and the drawdown at that point, not only the profit.

What a grid backtest must get right

  • Limit fills. A buy limit should fill only when price trades through it. A backtest that fills on a touch of the bar's low gives a grid fills it would not have had. See market or limit orders.
  • Several fills in one bar. In a fast move, price can cross several levels inside one bar. Fills should follow the order price actually took through the bar.
  • Fees per round trip. A tight grid makes many small trades, so its edge per trade is close to the cost per trade.
  • A cap. Without a maximum number of lots, the grid's position in a crash is unbounded.

How DCA should be tested

Dollar-cost averaging is a buying schedule rather than a trading signal. The fair comparison is the same money invested at once on the first day: lump sum wins in rising markets, DCA in falling ones. Report both on the same history and the same costs.

How Reamer Research handles it

In Reamer Research, a sell limit whose quantity is smaller than the position closes that part and leaves the rest, so each grid lot can be sold on its own. Buy limits fill when the simulated ask trades through them, on a seeded tick path inside each bar. This configured object keeps one buy one step below and one sell one step above, and moves them when price changes level:

import math
import reamer_research as rr

class Grid:
    def __init__(self, step=0.25, lot=10, max_lots=6):
        self.step, self.lot, self.max_lots = step, lot, max_lots
        self.lookback, self.placed = 2, None
    def on_bar(self, d):
        price, held = d.close[-1], d.position()
        level = math.floor(price / self.step) * self.step       # the grid line below
        if (level, held) == self.placed and d.open_orders():
            return None                                          # orders still right
        self.placed = (level, held)
        orders = [rr.cancel_all()]
        if held < self.max_lots * self.lot:
            orders.append(rr.buy_limit(level, self.lot))
        if held > 0:
            orders.append(rr.sell_limit(level + 2 * self.step, min(self.lot, held)))
        return rr.orders(*orders)

result = rr.backtest(Grid(step=0.25, lot=10), 'data/SPY_5min.bin',
                     spread=0.01, commission_per_unit=0.005)
print(result.closed_trades_count, 'round trips, net', round(result.net_pnl, 2),
      'max drawdown', round(result.equity_drawdown_maximal, 2))

The buy rests on the grid line below the price and the sell on the line above the next one, so a lot bought on the way down is sold once price climbs back a step or more. closed_trades lists each partial close as its own trade. The visual trade diagnostics tool (open_viewer=True) shows the resting buy and sell levels around each trade.

DCA is a function strategy that buys on the first bar of each week, beside a buy-and-hold run for comparison:

from datetime import datetime, timezone
import reamer_research as rr

AMOUNT = 1000                                            # dollars a week

def week(ts):
    return datetime.fromtimestamp(ts, timezone.utc).isocalendar()[:2]

def dca(d):
    if d.close[0] == 0 or week(d.ts) == week(d[d.tickers[0]].ts[-2]):
        return None                                      # not the week's first bar
    return rr.buy_market(round(AMOUNT / d.close[-1], 4))

def lump_sum(d):
    if d.position() == 0:
        return rr.buy_market(round(4 * AMOUNT / d.close[-1], 4))

for name, rule in [('DCA', dca), ('lump sum', lump_sum)]:
    r = rr.backtest(rule, 'data/SPY_5min.bin', lookback=2, initial_capital=10_000,
                    spread=0.01, commission_per_unit=0.005)
    print(name, round(r.net_pnl, 2))

Each run ends with its position still open, and net_pnl values it at the last price. Either rule could also be written as a class, or as an object configured with its step or amount.

Limits to know

  • Spot holdings only. The grid and DCA here hold a position in one instrument; funding rates on perpetual futures, often used for crypto grids, would be added the way FX swap is.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. Enough to watch a grid fill and unwind on your own data; years of DCA need a licence.

A $20 month includes the full kit, so you can test your own grid steps and schedules and cancel if it does not fit.

Next questions

Should my backtest use market or limit orders?Whichever you will use live, because they test different things. A market order always fills and pays the spread and slippage. A limit order saves that cost but fills only when price comes to it, and misses the trades that run away. A backtest of limit entries is honest only if a limit fills when price trades through it, and the trades it missed stay missed.How do I backtest a Bollinger Band strategy in Python?Build the bands from a moving average and the standard deviation of the same closed bars, then choose a side. For reversion, buy below the lower band and short above the upper one, exiting at the middle. For breakouts, trade in the direction of the band that was crossed. Both need next-bar fills and realistic costs to be trusted.How do I size positions in a backtest?Choose a sizing rule and compute the quantity at each entry. Fixed fractional risks a set share of equity per trade, volatility targeting scales size so each position carries similar risk, and ATR sizing sets quantity so a stop placed a multiple of ATR away loses a fixed amount. Then check the size against your buying power.How do I run a Monte Carlo simulation on backtest results?Take the per-trade returns from your backtest, draw them at random with replacement to build thousands of alternative trade sequences, and compound each one from your starting capital. The spread of final equity and maximum drawdown across those sequences shows how much of your single result was the order the trades happened to come in.

Every answer here restates the documents that ship in the kit, which are authoritative. All questions.

Reamer Research

Your first backtest in a minute

Backtesting and live trading in Python and C++. Free to install in Evaluation Mode, with no key or sign-up.

pip install reamer-research

A licence at $20 a month removes every limit. The same code runs unchanged.

Reamer Server

The order-management core for your firm

Your venues, your risk rules on every order, one strategy per CPU core, on your own Linux servers.

$24,000 / year

Or start with a 30-day trial at $2,000.