The smallest useful test of a currency-hedged equity ledger has two answers for the same month. Value a €10.3 million closing equity portfolio at $1.0400 per euro and it shows a $288,000 loss. Let the original €10 million pass through a forward at $1.0950, and the portfolio shows a $262,000 gain. The test also needs to reproduce that gain using the cash actually delivered. One of those calculations will catch an accounting error the other can conceal.
This article was drafted with AI assistance. The market values, trades and dates below are synthetic. The example uses same-day spot conversion and deliverable forwards at one common maturity. It excludes funding costs, explicit trading fees, taxes and external cash flows.
Keep quote direction in the input
The accounting unit is US dollars per euro. Multiplying the euro market value by that rate gives dollars. If a price feed supplies euros per dollar, divide by that rate or invert it before use. The code stores quote direction explicitly and normalizes once. It tests the inverse-quote path with an exactly representable reciprocal. The ledger compares both values at cent precision after conversion. A rounded market quote and its reciprocal can differ slightly, so record the original quote and precision convention.
With two equity observations and spot quotes, the unhedged P&L can be broken into local equity change at opening spot, FX on the opening euro value, and an interaction on the change in euro value. The interaction is −$18,000 here. The sum has to match the direct difference of the two dollar valuations. S&P DJI documents the same multiplicative logic for unhedged index returns. S&P DJI index mathematics
Reconcile contractual delivery and forward P&L
In the delivery view, sum each trade’s promised dollar proceeds. Then convert the euro balance left after delivery at the closing spot rate. A negative balance makes the scan of cash movements explicit. The account has to buy euros to make good on the original delivery. In the other view, convert the full closing asset value at spot, then add each forward’s notional times its price difference against closing spot. Both result in the same closing dollar total. The threshold and backtest examples use the original traded rate rather than a mark that moves with the market.
Dates in the fixture enforce a single maturity. A top-up is sized using a market-value observation that has the same date as the fill. The program cannot use a future closing observation to size the earlier trade if that timestamp is passed through correctly. With real intraday data, retain full timestamps rather than calendar dates and join on the latest eligible snapshot.
Save as fx_hedge.py and run python3 fx_hedge.py. The example uses only the standard library and expects decimal rates and amounts supplied as exact strings.
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
D = Decimal
@dataclass(frozen=True)
class Quote:
rate: Decimal
units: str = "usd_per_eur"
def usd_per_eur(self) -> Decimal:
if self.rate <= 0:
raise ValueError("an FX rate must be positive")
if self.units == "usd_per_eur":
return self.rate
if self.units == "eur_per_usd":
return D(1) / self.rate
raise ValueError("expected usd_per_eur or eur_per_usd")
@dataclass(frozen=True)
class Equity:
observed: date
euros: Decimal
@dataclass(frozen=True)
class Forward:
traded: date
maturity: date
euros_to_sell: Decimal
rate: Quote
@dataclass(frozen=True)
class Settlement:
pnl: Decimal
residual_euros: Decimal
forward_pnl: Decimal
def size_top_up(
snapshot: Equity, traded: date, maturity: date,
existing: tuple[Forward, ...], fill_rate: Quote,
) -> Forward:
if snapshot.observed != traded or traded >= maturity:
raise ValueError("use an observed value from the trade date")
if any(f.traded >= traded or f.maturity != maturity for f in existing):
raise ValueError("expected earlier forwards with the same maturity")
euros = snapshot.euros - sum(f.euros_to_sell for f in existing)
if euros <= 0:
raise ValueError("this top-up sells a positive EUR balance")
return Forward(traded, maturity, euros, fill_rate)
def settle(
opening: Equity, closing: Equity, opening_quote: Quote,
closing_quote: Quote, forwards: tuple[Forward, ...] = (),
) -> Settlement:
if closing.observed <= opening.observed:
raise ValueError("the close must follow the opening")
for f in forwards:
if f.maturity != closing.observed or not opening.observed <= f.traded < f.maturity:
raise ValueError("forward falls outside this settlement interval")
if f.euros_to_sell <= 0:
raise ValueError("a sell forward needs positive EUR notional")
start, end = opening_quote.usd_per_eur(), closing_quote.usd_per_eur()
opening_usd = opening.euros * start
residual = closing.euros - sum(f.euros_to_sell for f in forwards)
promised = sum(f.euros_to_sell * f.rate.usd_per_eur() for f in forwards)
delivered = promised + residual * end
payoff = sum(
(f.euros_to_sell * (f.rate.usd_per_eur() - end) for f in forwards), D(0)
)
marked = closing.euros * end + payoff
if delivered.quantize(D('.01')) != marked.quantize(D('.01')):
raise ArithmeticError('settlement ledgers disagree to the cent')
return Settlement(delivered - opening_usd, residual, payoff)
if __name__ == "__main__":
opening_day, mid_day, close_day = (
date(2029, 1, 2), date(2029, 1, 16), date(2029, 2, 2)
)
opening = Equity(opening_day, D("10000000"))
halfway = Equity(mid_day, D("10200000"))
ending = Equity(close_day, D("10300000"))
lower_equity = Equity(close_day, D("9700000"))
start, end, rebound = Quote(D("1.1000")), Quote(D("1.0400")), Quote(D("1.1600"))
first = (Forward(opening_day, close_day, opening.euros, Quote(D("1.0950"))),)
top_up = size_top_up(halfway, mid_day, close_day, first, Quote(D("1.0700")))
adjusted = first + (top_up,)
unhedged = settle(opening, ending, start, end)
fixed = settle(opening, ending, start, end, first)
reset = settle(opening, ending, start, end, adjusted)
overhedge = settle(opening, lower_equity, start, end, first)
assert unhedged.pnl == -288_000
assert fixed == Settlement(262_000, 300_000, 550_000)
assert reset == Settlement(268_000, 100_000, 556_000)
assert overhedge == Settlement(-362_000, -300_000, 550_000)
assert settle(opening, ending, start, rebound, first).pnl == 298_000
assert settle(opening, ending, start, rebound, adjusted).pnl == 280_000
assert settle(opening, ending, start, Quote(D("1.05")), first).pnl - fixed.pnl == 3_000
assert Quote(D(".80"), "eur_per_usd").usd_per_eur() == D("1.25")
equity_change = ending.euros - opening.euros
spot_change = end.usd_per_eur() - start.usd_per_eur()
local_at_start = equity_change * start.usd_per_eur()
fx_on_principal = opening.euros * spot_change
interaction = equity_change * spot_change
assert (local_at_start, fx_on_principal, interaction) == (330_000, -600_000, -18_000)
assert local_at_start + fx_on_principal + interaction == unhedged.pnl
worse_fill = size_top_up(halfway, mid_day, close_day, first, Quote(D("1.0694")))
assert settle(opening, ending, start, end, first + (worse_fill,)).pnl == 267_880
try:
size_top_up(ending, mid_day, close_day, first, Quote(D("1.0700")))
except ValueError:
pass
else:
raise AssertionError("look-ahead snapshot was accepted")
print(f"unhedged {unhedged.pnl:.0f} | opening hedge {fixed.pnl:.0f} | top-up {reset.pnl:.0f}")
print(
f"remaining EUR {fixed.residual_euros:.0f} -> {reset.residual_euros:.0f} | "
f"overhedged EUR {overhedge.residual_euros:.0f}"
)
The outputs are unhedged -288000 | opening hedge 262000 | top-up 268000 and remaining EUR 300000 -> 100000 | overhedged EUR -300000. The one-cent exchange-rate test verifies that €300,000 of residual exposure is worth $3,000 per cent of spot movement when the ending euro equity value is fixed.
Vary execution and maturity inputs independently
One test changes the final spot from $1.0400 to $1.1600 and leaves both forward prices alone. The original hedge returns $298,000, and the top-up version returns $280,000. Another test keeps closing spot unchanged and changes only the top-up fill from $1.0700 to $1.0694. Dollar P&L is then $267,880. The $120 difference comes from the 0.0006 rate difference on €200,000. In both tests the opening contract still delivers dollars at $1.0950.
In a KAEL AI research review, I would keep the original equity snapshots, spot quote convention, maturity and execution records together with the backtest output. Those records allow a reviewer to change the closing spot, the filled rate or the rebalancing timestamp one at a time. For statements between trade date and maturity, value each forward against the remaining term and reconcile any actual cash movements separately.
Top comments (0)