progress

~/problems / Order books / Market and strategy simulations

Backtest a band trader

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A mean-reversion idea: buy when the price dips to a "cheap" level, sell when it climbs to a "rich" one, and never hold too much. A backtest replays it over a recorded price tape.

Implement band_trader(prices, low, high, lot, max_pos, fee) -> tuple[int, int, int, int]. Start flat. For each price p, apply at most one rule:

  1. If p <= low: buy min(lot, max_pos - position) shares, if more than 0.
  2. Else if p >= high: sell min(lot, max_pos + position) shares, if more than 0 (shorting down to -max_pos is fine).

Each trade pays a flat fee: a buy of q costs q·p + fee, a sell brings in q·p - fee. Size-0 trades don't happen.

Return (position, cash, pnl, trades) with pnl = cash + position · last_price (pnl = cash for an empty tape).

band_trader([100, 97, 96, 99, 104, 105, 103], low=97, high=104, lot=2, max_pos=3, fee=1)
# 97:  buy 2          pos 2   cash -195
# 96:  buy 1 (limit)  pos 3   cash -292
# 104: sell 2         pos 1   cash -85
# 105: sell 2         pos -1  cash 124
# pnl = 124 + (-1)·103 = 21
# -> (-1, 124, 21, 4)

band_trader([], 10, 20, 1, 1, 0)   # (0, 0, 0, 0)

Up to 10^5 prices; all values are integers up to 10^6, low < high. Cash and PnL can exceed 32 bits.

Show hint

running totals for position, cash and trades; work out the allowed size first, and trade (and charge the fee) only when it's positive.

Topic: Market and strategy simulations. Execution, backtests, allocation rules: careful state and event ordering.

0:00
Ctrl ' run · Ctrl ↵ submit
esc