Start a Backtest with Positions, Not Returns: One-Period Accounting for Buy-and-Hold and Momentum
A correct ending valuation does not establish that holding rules were implemented correctly. A buy-and-hold portfolio can be worth 1100 after repricing, or still 1100 immediately after cost-free trades restore equal weights. Valuation alone cannot distinguish those cases.
Using three fictional assets, this article checks whether:
- Initial quantities use execution prices.
- Quantities and cash remain unchanged without trading.
- Selecting no assets actually produces cash holdings.
- A test catches rebalancing performed without an order.
All prices are manually specified synthetic inputs. This is a small, hand-checkable accounting example, not actual ETF performance.
1. Separate signal, execution, and valuation prices
Assume this sequence:
Reference prices from 12 months earlier→ observe signal-day closes and select assets→ buy at the next trading day's execution prices→ value unchanged holdings at period-end pricesThe code does not implement dates or an exchange calendar. Each stage receives separate price inputs.
| Item | SYN_A | SYN_B | SYN_C |
|---|---|---|---|
| Reference price 12 months earlier | 80 | 120 | 100 |
| Signal-day close | 100 | 100 | 100 |
| Signal: signal/reference − 1 | 1/4 | -1/6 | 0 |
| Next trading-day execution price | 100 | 100 | 100 |
| End-of-holding-period valuation price | 120 | 90 | 120 |
Initial cash is 1000. Assume no trading costs, cash interest, dividends, splits, deposits, or withdrawals, and permit fractional quantities.
Signal and execution prices happen to match here, but have different roles: the signal determines what to buy, execution prices determine how much to buy, and ending prices determine current holding values. A later test changes only execution prices because identical inputs can conceal use of the wrong price.
2. Buy-and-hold keeps quantities fixed while weights drift
Allocate equal amounts once at entry. Each asset receives 1000 / 3 at price 100, giving:
Initial quantity = (1000 / 3) / 100 = 10 / 3Cash after entry is 0. Hold the same quantities without further trades.
| Asset | Quantity | Ending price | Ending value |
|---|---|---|---|
| SYN_A | 10/3 | 120 | 400 |
| SYN_B | 10/3 | 90 | 300 |
| SYN_C | 10/3 | 120 | 400 |
| Total | 1100 |
Quantities stay fixed, but weights become:
SYN_A: 400 / 1100 = 4/11SYN_B: 300 / 1100 = 3/11SYN_C: 400 / 1100 = 4/11Restoring each weight to 1/3 requires trading and differs from this example's buy-and-hold rule. Without trades, quantities and cash must also stay unchanged, not merely the ending valuation.
3. Apply the same accounting to momentum
The illustrative allocation rule is:
- Select assets with signals strictly above zero.
- Weight selected assets equally.
- Hold all cash if none qualify.
This educational rule is not a reproduction of an entire published strategy. Signals [1/4, -1/6, 0] select only SYN_A; SYN_C's exactly zero signal is excluded.
Target weights = [1, 0, 0]SYN_A quantity = 1000 / 100 = 10Ending value = 10 × 120 = 1200| Strategy | Initial quantities A, B, C | Ending cash | Ending value |
|---|---|---|---|
| Buy-and-hold | 10/3, 10/3, 10/3 | 0 | 1100 |
| Positive-signal momentum | 10, 0, 0 | 0 | 1200 |
These are changes of 10% and 20% from initial wealth. They are arithmetic on artificial prices, not evidence of momentum's real-world superiority. Values 1100 and 1200 are before selling the holdings; the example does not automatically liquidate at the end.
4. No order and zero target weights are different
| Input | Meaning | Existing holdings |
|---|---|---|
target=None | Value without trading | Preserve quantities and cash |
target=(0, 0, 0) | Set every asset's target weight to zero | Sell holdings and move to cash |
Both preserve cash if the account already holds only cash. With existing assets they differ. For buy-and-hold at ending prices:
No order: quantities remain (10/3, 10/3, 10/3); cash = 0; value = 1100Zero target: quantities become (0, 0, 0); cash = 1100; value = 1100With zero costs the values match, but ledger states and transactions do not.
5. A minimal implementation separating valuation and trading
Store only quantities and cash in the ledger; derive valuation and weights from prices. Functions have separate roles:
value: calculate value from holdings and cash.momentum_weights: convert signals to target weights.rebalance: update quantities and cash at execution prices.step: value unchanged holdings without a trade request, or rebalance when requested.
orders below means traded quantities, new minus old: positive for buys, negative for sells. No broker orders are sent; all quantities are assumed filled at the supplied prices.
Python's standard-library Fraction, constructed from integers, allows exact comparisons of values such as 10/3. Python documentation
from dataclasses import dataclassfrom fractions import Fraction as F@dataclass(frozen=True)class Book: qty: tuple cash: Fdef value(book, prices): if len(book.qty) != len(prices) or not prices: raise ValueError("수량과 가격의 자산 수가 맞지 않습니다") if any(p <= 0 for p in prices): raise ValueError("가격은 양수여야 합니다") return book.cash + sum( q * p for q, p in zip(book.qty, prices) )def momentum_weights(reference, signal_prices): if len(reference) != len(signal_prices) or not reference: raise ValueError("신호 입력의 자산 수가 맞지 않습니다") if any(p <= 0 for p in (*reference, *signal_prices)): raise ValueError("신호 가격은 양수여야 합니다") chosen = [ now / past - 1 > 0 for past, now in zip(reference, signal_prices) ] count = sum(chosen) return tuple( F(1, count) if yes else F(0) for yes in chosen )def rebalance(book, execution_prices, target): wealth = value(book, execution_prices) if len(target) != len(book.qty): raise ValueError("목표비중의 자산 수가 맞지 않습니다") if any(w < 0 for w in target) or sum(target) > 1: raise ValueError("공매도와 차입을 허용하지 않습니다") qty = tuple( wealth * w / p for w, p in zip(target, execution_prices) ) cash = wealth - sum( q * p for q, p in zip(qty, execution_prices) ) orders = tuple( new - old for new, old in zip(qty, book.qty) ) return Book(qty, cash), ordersdef step(book, prices, target=None): if target is None: next_book = book orders = tuple(F(0) for _ in book.qty) else: next_book, orders = rebalance(book, prices, target) return next_book, orders, value(next_book, prices)If no asset is selected, all chosen values are false and target weights become zero. The conditional expression never evaluates F(1, count) in that case, avoiding division by zero.
Inputs always use asset order A, B, C. The code checks some conditions, including length and positive prices, but is not a complete engine validating asset-ID alignment or every invalid ledger state.
6. Compare with hand calculations and introduce a faulty implementation
Append the following after the function definitions. First enter both strategies with identical initial cash and execution prices.
reference = tuple(map(F, [80, 120, 100]))signal_prices = tuple(map(F, [100, 100, 100]))execution_prices = tuple(map(F, [100, 100, 100]))end_prices = tuple(map(F, [120, 90, 120]))initial = Book((F(0), F(0), F(0)), F(1000))equal = (F(1, 3),) * 3buyhold, _, entry_value = step( initial, execution_prices, equal)weights = momentum_weights(reference, signal_prices)momentum, _, _ = step( initial, execution_prices, weights)assert buyhold.qty == (F(10, 3),) * 3assert entry_value == 1000assert buyhold.cash == 0assert weights == (F(1), F(0), F(0))assert momentum.qty == (F(10), F(0), F(0))assert step(momentum, end_prices)[2] == 1200Then check that changed prices do not change buy-and-hold quantities or cash:
def check_hold(advance): after, orders, total = advance(buyhold, end_prices) assert after.qty == buyhold.qty, ( "주문 없이 보유 수량이 바뀌었습니다" ) assert after.cash == buyhold.cash assert orders == (F(0),) * 3 assert total == 1100 actual_weights = tuple( q * p / total for q, p in zip(after.qty, end_prices) ) assert actual_weights == ( F(4, 11), F(3, 11), F(4, 11) )check_hold(step)This does not merely compare one variable with itself. It passes ending prices through the processing function, then checks quantities, cash, traded quantities, value, and weights.
No selected assets
Constructing a cash ledger directly would not test selection. Feed nonpositive signals through the actual selection rule and confirm zero targets:
no_pick = momentum_weights( signal_prices, tuple(map(F, [100, 90, 80])),)assert no_pick == (F(0),) * 3cash_only, _, _ = step( initial, execution_prices, no_pick)assert cash_only == initialassert step(cash_only, end_prices)[2] == 1000Apply the same cash-allocation request to an account with existing holdings:
liquidated, sell_orders, total = step( buyhold, end_prices, no_pick)assert liquidated == Book( (F(0),) * 3, F(1100))assert sell_orders == (F(-10, 3),) * 3assert total == 1100This is a separate liquidation-behavior test, not an assertion that the main comparison liquidates at period-end.
Different signal and execution prices
Change only SYN_A's execution price to 125. Signals remain unchanged, so A is still selected.
repriced, _, total = step( initial, (F(125), F(100), F(100)), weights,)assert repriced.qty == (F(8), F(0), F(0))assert total == 1000Quantity must be 1000 / 125 = 8. Accidentally using the signal price 100 would produce 10, which the test distinguishes. It does not establish that the next trading date was mapped correctly; date mapping needs its own implementation and tests.
Incorrect rebalancing that preserves valuation
Restoring equal weights at the ending prices produces:
rebalanced, orders, total = step( buyhold, end_prices, equal)assert rebalanced.qty == ( F(55, 18), F(110, 27), F(55, 18))assert orders == ( F(-5, 18), F(20, 27), F(-5, 18))assert total == 1100assert rebalanced.cash == 0The value remains 1100, but some A and C were sold and more B purchased.
| Check | Hold without trading | Restore equal weights |
|---|---|---|
| A quantity | 10/3 | 55/18 |
| B quantity | 10/3 | 110/27 |
| C quantity | 10/3 | 55/18 |
| Trades | None | Yes |
| Value | 1100 | 1100 |
The right-hand calculation is correct when rebalancing is explicitly requested. It is erroneous when performed without a request. Deliberately introduce that error:
def bad_step(book, prices, target=None): # 오류: 매매 요청이 없어도 동일가중으로 다시 맞춘다. return step( book, prices, equal if target is None else target, )try: check_hold(bad_step)except AssertionError as error: print("오류 구현 검출:", error)else: raise RuntimeError( "수량을 바꾸는 오류 구현을 놓쳤습니다" )Passing the faulty implementation produces this message:
오류 구현 검출: 주문 없이 보유 수량이 바뀌었습니다The Korean message says that the faulty implementation changed holding quantities without an order.
The quantity invariant catches an error that an ending-value-only check misses.
7. Results checked during this revision
The calculations and tests ran locally with Python 3.14.5 and its standard library while preparing the revision on 2026-10-24. No real market data was used.
| Check | Observed result |
|---|---|
| Initial equal-weight entry | Each quantity 10/3, cash 0, value 1000 |
| Holding without trades | Quantities/cash unchanged, trades 0, value 1100 |
| Post-holding weights | 4/11, 3/11, 4/11 |
| Strictly positive selection | Only A, quantity 10, value 1200 |
| No selections | Zero targets; initial cash 1000 preserved |
| Existing holdings moved to cash | All sold; cash 1100 |
| A execution price changed to 125 | Purchased quantity 8 |
| Explicit equal-weight rebalance | Trades occur; zero costs preserve value 1100 |
| Unrequested rebalance bug | Detected by the quantity invariant |
These findings concern the displayed synthetic inputs and implementation, not a complete monthly backtest or actual fills.
8. What remains before connecting real data?
This example covers one-period accounting. Real data also requires trading-day alignment, signal/execution date mapping, monthly scheduling, missing-data policies, and dividend/split handling.
Costs are absent. With costs, rebalancing no longer preserves value, and target quantities must reserve cash to pay them. The current rebalance function does not solve that problem.
There is no intermediate price path, so this article calculates neither maximum drawdown nor a Sharpe ratio. The holding-period length is unspecified, so no annualized return is reported.
The later calculation using actual SPY/IEF/GLD data is covered separately in the 12-month momentum baseline comparison. This remains a small example of quantities, cash, and valuation.
The next transaction-cost and risk-path exercise starts from the same requirement: explain the trades and resulting ledger changes before interpreting returns.
Report an error or share feedback
Open a draft with this article’s title and URL. Review the message and recipient before sending.
Open email draftIf no email app opens, copy these details into your usual email service.
Related posts
Quant & Data Research A 12-Month Momentum Backtest with SPY, IEF, and GLD: Comparing Baselines from 2007 to 2025
An executed 2007–2025 comparison of buy-and-hold and 12-month momentum using SPY, IEF, and GLD, with transaction records, costs, interpretation, and reproduction limits.
Quant & Data Research What Makes a Good Backtest Different? Design Validation Before Looking at Returns
Compare random and chronological splits on a changing synthetic series, examining sample composition, accuracy, interpretation limits, and subsequent validation.