如何用兩筆交易和現金帳本測試 Delta 對沖回測
How to Test a Delta-Hedge Backtest With Two Trades and a Cash Ledger
文章以兩筆股票交易和現金帳本,示範如何測試 Delta 對沖回測的記帳正確性。模擬器買入行使價為 $100 的跨式期權,支付 $600 權利金,並在中途按模型 Delta 對沖;以每股 $0.05 手續費計算,股價由 $108 回到 $100 時,盈虧為 +$32,若賣出成交價改為 $107.60,盈虧則為零。程式只使用 Python 標準庫,並以兩套獨立帳目核對結果。
A hedge simulator gets two stock fills. It sells 80 shares at $108 and buys them back at $100. The options cost $600 and expire worthless. Charge five cents per share on both stock trades and the simulator should return +$32. Change just the sell fill to $107.60 and the answer becomes exactly zero. Those two runs can expose a surprising number of bookkeeping errors.
This article was drafted with AI assistance. All prices, fills and probabilities below belong to a constructed example. The Python program uses only the standard library.
Give the simulator something it can get wrong
Buy one call and one put with the same $100 strike and expiry. Each contract has a multiplier of 100. Both settle in cash at expiry, so the pair pays 100 times the absolute distance between the final stock price and $100. Its opening price is $6 per share for the pair, or $600 in total. The stock starts at $100. There is one scheduled hedge decision between entry and expiry. At expiry we close any stock position. Set interest, dividends, borrow fees and option execution costs to zero for this test. The stock is available to borrow. Options Industry Council on the long straddle
We can generate the price and hedge size from the same model. At the hedge decision, the stock is $92, $100 or $108 with respective pricing weights of 5/32, 22/32 and 5/32. The remaining move to expiry is independent and uniformly distributed over −$10 to +$10. Writing x for the mid-period stock price minus the strike, in dollars, averaging the absolute terminal payoff gives a per-share option value of 5 + x²/20 for |x| ≤ 10. Its slope is x/10. The three mid-period marks are $8.20, $5 and $8.20. Their weighted average gives the $6 opening price. The symmetry gives an opening delta of zero, so we begin with no stock.
At $108 the model delta is +0.80 per share of the underlying. The option position therefore has the local directional exposure of 80 shares, and the hedge order sells 80. At $92 the sign reverses and the hedge buys 80. These quantities are available before the expiry price is known. Keep the fill price in a separate field so you can change execution without retroactively changing the order size. Options Industry Council on delta
Keep two independent accounts of the same path
The cash ledger starts at minus the premium. For each stock fill, subtract the signed quantity times its fill price and subtract the fee. A sale has a negative quantity and therefore adds cash. At expiry add the option settlement. With the stock flattened, the final cash balance equals net profit or loss measured from immediately before entry.
The second account starts at zero and tracks gains since entry. For each interval, use the stock position held at its start times the change in the reference stock price. Add the change in the option mark. At the end of the interval, execution contributes the signed trade quantity times (reference price minus fill price), less fees. The fill adjustment makes the second account work even if the stock sale receives a worse price than the hedge signal saw. The same fee enters each independent calculation once.
Save the following as hedge_replay.py and run python3 hedge_replay.py. Prices passed to the replay are integers or exact decimal values. The model schedules full fills and uses whole-share targets at each of its three decision prices.
from decimal import Decimal as D
from typing import NamedTuple
STRIKE = D("100")
MULTIPLIER = D("100")
WIDTH = D("10")
FEE = D("0.05")
NODES = [(D("92"), D(5) / 32), (D("100"), D(22) / 32),
(D("108"), D(5) / 32)]
def quote(spot):
offset = spot - STRIKE
if abs(offset) > WIDTH:
return abs(offset), D(1) if offset > 0 else D(-1)
value = WIDTH / 2 + offset**2 / (2 * WIDTH)
return value, offset / WIDTH
PREMIUM = MULTIPLIER * sum(quote(spot)[0] * weight for spot, weight in NODES)
class Result(NamedTuple):
cash: D
marked: D
shares_traded: D
fees: D
def replay(mid, close, *, mid_fill=None, hedge=True, fee=FEE):
mid_value, delta = quote(mid)
target = -MULTIPLIER * delta if hedge else D(0)
settlement = MULTIPLIER * abs(close - STRIKE)
events = [
(mid, mid_value * MULTIPLIER, target, mid if mid_fill is None else mid_fill),
(close, settlement, D(0), close),
]
stock, shares_traded, fees = D(0), D(0), D(0)
cash, marked = -PREMIUM, D(0)
last_spot, last_option = STRIKE, PREMIUM
for spot, option_value, next_stock, fill in events:
marked += stock * (spot - last_spot) + (option_value - last_option)
change = next_stock - stock
cost = abs(change) * fee
cash -= change * fill + cost
marked += change * (spot - fill) - cost
shares_traded += abs(change)
fees += cost
stock, last_spot, last_option = next_stock, spot, option_value
cash += settlement
assert stock == 0 and cash == marked
return Result(cash, marked, shares_traded, fees)
def conditional_mean(mid):
# The terminal P&L is linear on either side of the strike.
lo, hi = mid - WIDTH, mid + WIDTH
knots = [lo] + ([STRIKE] if lo < STRIKE < hi else []) + [hi]
integral = D(0)
for left, right in zip(knots, knots[1:]):
endpoints = replay(mid, left).cash + replay(mid, right).cash
integral += (right - left) * endpoints / 2
return integral / (hi - lo)
up, flat, down = (replay(mid, STRIKE) for mid in (108, 100, 92))
assert PREMIUM == 600
assert up == down == Result(D(32), D(32), D(160), D(8))
assert flat == Result(D(-600), D(-600), D(0), D(0))
assert replay(108, 100, hedge=False) == flat
assert replay(108, 100, fee=D("0.25")).cash == 0
assert replay(108, 100, mid_fill=D("107.60")).cash == 0
assert replay(108, 100, mid_fill=D("107.59")).cash == D("-0.80")
assert replay(108, 108).cash == 192 # $800 option settlement, zero stock gain
mean = sum(weight * conditional_mean(mid) for mid, weight in NODES)
assert mean == D("-2.50")
print(f"up and back {up.cash:+.2f} | flat {flat.cash:+.2f} | "
f"down and back {down.cash:+.2f} | model mean {mean:+.2f}")
The output is up and back +32.00 | flat -600.00 | down and back +32.00 | model mean -2.50.
Catch the right error for the right reason
On the move from $100 to $108, the account has zero stock. The option mark rises from $600 to $820. On the way back, the account is short 80 shares and earns $640 on stock while the option gives up $820. Interval gains are +$220 and −$180 before fees. A spreadsheet that uses the newly computed short position on the first interval invents a $640 loss on shares it had yet to sell. At $92, a sign error that always sells stock fails the mirror-path test. The separate $108 expiry test exercises a positive option settlement, which the two headline examples cannot test.
The up-and-back path earns $40 before costs and trades 160 shares counting both sides. Its break-even fee is $40/160, or $0.25 per share per side. At five cents per share in fees, a 40-cent deterioration in the sale price consumes the remaining $32. We hold the original 80-share order fixed for that exercise. A model that recomputes delta from the worse fill is testing a different decision rule. In a KAEL AI review of this example, I would ask for the decision quote and the execution report side by side. With both records in hand, another researcher can vary either price and explain the difference.
Give the winning path its proper weight
To calculate the last number in the output, assume the simulated paths follow the same probabilities used to price the option. At fixed midpoint, the expiry cash result is piecewise linear in the closing price, with a kink at the strike. The integral in the program splits there and takes one trapezoid per linear segment. That gives an exact average over the continuous terminal distribution and removes random sampling error.
There is a short independent check. The expected option settlement equals the initial premium. The stock's conditional expected move after the hedge is zero. Trading occurs at the $92 and $108 nodes, with a combined probability of 10/32, and each round trip costs $8. Expected net P&L is therefore −$2.50 per pair. That number belongs to these pricing and path assumptions. With live data, the first things an engineer needs to reproduce an observed result are the original hedge timestamp, the pre-trade position, the fills, and the two option marks bounding each interval.
來源:DEV Community · dev.to