Multi-currency portfolio P&L in PythonΒΆ

Author: Artur Sepp / First recorded: 2026-11-08

Implemented in qis β€” Quantitative Investment Strategies. Software citation: CITATION.cff.

Use QIS to compare an asset’s local and reference-currency returns, then account for a portfolio’s positions, cash and FX hedges. The offline workflow below shows local, excess local, USD and excess USD returns together, followed by an account with an explicit hedge reset and delayed settlement. Further cases compare monthly cash measurement across grids and signed local financing. All prices, spots and rates are synthetic teaching inputs.

Choose the calculationΒΆ

Task

Public entry point

Result

Supply currency spots and domestic rates

FxRatesData

Provider-neutral input panels with currency IDs such as USD, EUR and CHF.

Convert asset returns or compute FX payoffs

compute_fx_returns

Typed panels selected by return kind, coordinate, reference currency and frequency.

Track positions, financing and settled P&L

backtest_fx_account

FxAccountData: monetary capital, cash flows, held units, financing balances and FX contracts.

A converted return panel describes intervals. The account additionally records how trades are funded, how many units remain held, and when a fixed hedge payoff becomes spendable cash. The return conventions and self-financed accounting chapters define these contracts.

Run the existing offline exampleΒΆ

Start with an installed QIS core package. From a repository checkout, run:

python examples/fx/fx_returns_and_accounting_example.py

With only the installed package, save the complete example source as fx_returns_and_accounting_example.py and run python fx_returns_and_accounting_example.py. The same source is included at the end of this page. Execution requires no provider access, credentials, optional extras or local data files, and writes no output files.

The example uses the frozen synthetic-price generator with seed 20260725 over 31 January–30 April 2024. Two generated asset paths are assigned the illustrative quote currencies EUR and CHF; they do not represent observed European or Swiss investments.

Input

Example convention

Asset prices

Local total-return levels, including reinvested distributions.

Currency IDs

SYN_EUR maps to EUR; SYN_CHF maps to CHF; the reporting currency is USD.

Spots

USD per currency unit; the USD column is one.

Rates

Annual decimal quotes: USD 0.05, EUR 0.03 and CHF 0.01.

Cash accrual

Opening-known rates, one-quote lag, actual calendar days divided by 365.

Analytical frequency

B for business-day intervals and ME for month-end intervals.

Additional hedging

The four asset-return views are unhedged; the later account has an explicit EUR hedge.

Keep the same currency IDs when supplying spots and rates from another provider. Normalise spot direction and annual rate units before constructing FxRatesData, and align asset/currency metadata to the prices. Currency identifies the price quote, not the issuer’s domicile. The FX data contract covers input alignment and availability.

Read the four return viewsΒΆ

FxAssetReturnsRequest selects the economic quantity through FxReturnType and its coordinate through FxReturnCoordinate. compute_fx_returns returns one FxReturnsData per requested frequency; .values is its return or payoff DataFrame.

Return kind

Interpretation in this example

LOCAL_TOTAL

Total return of the asset in its quote currency.

LOCAL_EXCESS

Local return relative to the local cash leg, in the selected coordinate.

REFERENCE_TOTAL

Total return after translating the asset into USD.

REFERENCE_EXCESS

USD return relative to the USD cash leg, in the selected coordinate.

In SIMPLE, excess means total return minus the interval cash return. In LOG, excess means log asset growth minus log cash growth. Applying a logarithm to one plus SIMPLE excess does not generally produce LOG excess. The separate CASH_RELATIVE_SIMPLE coordinate is the cash-relative wealth return; the example checks its relation to LOG excess.

From a checkout, the existing function also returns its results for further analysis:

from examples.fx.fx_returns_and_accounting_example import run_example

workflow = run_example(verbose=False)
return_kinds = ["local_total", "local_excess", "reference_total", "reference_excess"]
monthly = workflow["comparisons"]["ME", "simple"]
last_month = monthly.iloc[-1].unstack(0)[return_kinds]
print((100 * last_month).round(4).to_string())

# Checked rounded values behind the table below; decimals, before percentage display.
assert last_month.loc["SYN_EUR"].round(6).tolist() == [0.019533, 0.017067, 0.026284, 0.022174]
assert last_month.loc["SYN_CHF"].round(6).tolist() == [-0.009996, -0.010818, -0.014343, -0.018452]

The last completed monthly interval ends on 30 April 2024. These are interval returns in percent, without annualisation:

Synthetic asset

Local

Excess local

USD

Excess USD

SYN_EUR

1.9533%

1.7067%

2.6284%

2.2174%

SYN_CHF

-0.9996%

-1.0818%

-1.4343%

-1.8452%

Use workflow["comparisons"]["B", "simple"] for business-day returns, or replace "simple" with "log" for the four LOG views. The extra columns translated_local_excess_pnl and fx_forward_pnl remain SIMPLE payoffs per opening reference notional in every comparison. They are not LOG returns even when displayed beside LOG asset returns. In the shared notation, the former is the translated self-financed payoff \(p^{L\to R}\) and the latter is the forward FX return \(\varphi\), long local currency through a forward. The API names remain LOCAL_EXCESS_TRANSLATED and FX_FORWARD; see the notation and conventions.

Pitfall

With the default PERIOD_OPENING policy, the analytical frequency sets the cash and additional-hedge reset intervals. Business-day cash includes intervening calendar days. A month-end request recomputes those intervals; it does not just sum daily excess returns. Resampling the reporting of an already completed account leaves that account’s trading and settlement events intact.

Sample one monthly cash index at different frequenciesΒΆ

The same runnable example includes a changing-rate case under FxCashPolicy(accrual=FxCashAccrual.MONTHLY_INDEX). compute_monthly_cash_index builds one ACT/365 Fixed account, with simple interest within each calendar month and reinvestment at month-end. Daily observations sample that account without resetting it. Annual decimal quotes and their provider basis remain unchanged; opening quotes are never backfilled.

The example checks daily, monthly and quarterly LOG excess returns on the same unhedged wealth path against independent USD cash deposits: 2% for 31 days, 8% for 29 days and 3% for 31 days. January, February and March cash factors multiply, giving cash growth of 1.01063409 (to eight decimals). The quarterly opening-rate convention instead holds 2% over all 91 days.

import numpy as np

cash_demo = workflow["monthly_cash"]
comparison = cash_demo["comparison"]
np.testing.assert_allclose(comparison.iloc[:3], comparison.iloc[0], rtol=0, atol=1e-14)
assert abs(comparison.iloc[-1] - comparison.iloc[-2]) > 1e-4
print(comparison.round(8).to_string())

LOG excess aggregates because it is the log ratio of the same wealth and cash indices. Arithmetic excess returns do not generally sum or compound to longer-interval arithmetic excess. MONTHLY_INDEX is an excess-return measurement policy only: it does not change forward strikes, analytical hedge resets, local financing or the account’s cash schedule. Changing hedge reset frequency can still change the underlying wealth path. The library keeps PERIOD_OPENING as its default; this demonstration opts in explicitly.

Follow the account through reset and settlementΒΆ

The account starts with USD capital 100 and uses reference-currency financing. Targets on 31 January allocate 70% to SYN_EUR and 30% to SYN_CHF; 29 February changes them to 40% and 60%; 30 April closes both positions. Target notionals use the fixed initial capital. Held units stay fixed between target dates while price and FX movements change their value. Resizing can leave positive or negative USD cash balances.

The EUR hedge is sized from current EUR asset value after the corresponding equity trade. Each contract keeps its quantity and strike until fixing. The first contract fixes on 29 February but pays on 4 March; a new contract opens on 29 February and fixes and pays on 30 April. Its marked value and its cash payment enter the ledger at their respective dates.

Hedge input

Sign convention

Return request hedge_ratios=1.0

An additional full opening-principal short-local hedge.

Account contract notional_weight=-1.0 with asset_currency_value

A short-local hedge sized to the current currency asset exposure.

Those inputs belong to different APIs. Account contracts also require explicit trade, fixing and settlement dates. Embedded instrument or share-class hedges remain in the supplied prices and should not be added again.

Reuse the existing ledger rather than reconstructing P&L from return panels:

account = workflow["account"]
print(account.accounts.tail(1).round(6).to_string())
assert account.contracts.paid.all()
assert account.asset_units.iloc[-1].eq(0).all()
assert round(float(account.nav.iloc[-1]), 6) == 91.520313
assert abs(float(account.nav.iloc[-1] - 100.0 - account.pnl.to_numpy().sum())) < 1e-10

The terminal capital is USD 91.520313, with positions closed and both contracts paid. The account’s additive monetary P&L reconciles to the capital change. Negative cash is a financing balance; a fixed but unpaid forward payoff remains a marked claim until settlement. Opening cash earns or pays interest once, under the specified financing policy.

Object from workflow

What to reuse

comparisons[(frequency, coordinate)]

Four asset-return views and two explicitly SIMPLE payoff panels.

monthly_cash

Common cash index and daily/monthly/quarterly LOG excess comparison.

local_accounts

Zero/nonzero-net locally financed books and explicit settlement histories.

cash_relative

Typed monthly cash-relative result; read its .values.

normalized_forward_index

Optional synthetic forward-payoff index starting at 100 under the declared normalisation.

account.accounts and account.nav

Monetary balances and marked reference-currency capital.

account.pnl and account.cash_flows

Additive P&L components and actual cash movements.

account.asset_units and account.contracts

Held asset quantities and the FX contract lifecycle.

An optional payoff index is not account capital and does not add collateral cash. A signed portfolio can have zero net target exposure while requiring positive capital and financing balances; net exposure is not a return denominator. See the account-capital rules for that case.

Compare zero and nonzero net local financingΒΆ

workflow["local_accounts"] contains two locally financed signed books, with opening weights [0.5, -0.5] and [0.7, -0.3]. Both use USD capital 100 and fixed-capital notionals. The account holds units between 31 January and 30 April; local financing is swept on 29 February and at final closure on 30 April. Annual rates accrue on the explicit valuation intervals using ACT/365 Fixed. These are teaching schedules, not daily resets.

for ledger in workflow["local_accounts"].values():
    assert ledger.nav.iloc[0] == 100.0
    assert ledger.asset_units.iloc[-1].eq(0).all()
    np.testing.assert_allclose(ledger.local_balances.iloc[-1], 0, rtol=0, atol=1e-10)
    np.testing.assert_allclose(ledger.pnl.to_numpy().sum(), ledger.nav.iloc[-1] - 100.0)

The runnable source independently calculates both local debt balances, their interest, translated sweeps and reference-cash interest. It checks the full three-date NAV path. Zero opening net exposure still requires capital and can develop nonzero marked exposure. The preceding reference-financed example separately covers hedge resets and delayed payment.

Checks and scopeΒΆ

The canonical example independently checks endpoint price/spot conversions, opening cash accrual, translated local-excess and FX-forward payoffs, and cash/P&L reconciliation. The page’s executable snippets check the displayed values. These establish implementation correctness for the supplied inputs, not a forecast of future risk or investment performance.

The example uses synthetic covered-interest-parity forwards and the account’s stated financing rules. It does not model market forward basis, transaction costs, segregated collateral, margin calls or credit constraints. Rate and reset schedules are explicit inputs. Equity risk-model development is a separate research activity; this workflow does not activate an equity model or change a production allocation.

Complete runnable sourceΒΆ

Open the canonical source on GitHub. The rendered site includes that file directly, so the page and example share one implementation. In a Markdown viewer that displays the include directive as text, follow the source link.

  1"""Offline EUR/CHF return coordinates, exact notional payoffs and settled FX accounting.
  2
  3Uses the typed FX, monthly cash and accounting APIs. Frozen synthetic
  4asset paths are assigned illustrative quote currencies; spots/rates are teaching inputs.
  5No downloads, file outputs, optional dependencies or production allocations are used.
  6"""
  7
  8from enum import Enum
  9
 10import numpy as np
 11import pandas as pd
 12import qis
 13from qis.datasets.synthetic import generate_synthetic_prices
 14
 15
 16def run_example(verbose: bool = True) -> dict:
 17    """Compute four return views, common monthly cash and explicit funded/signed accounts.
 18
 19    Args:
 20        verbose: Print the last completed return per mode and account cash flows.
 21
 22    Returns:
 23        Typed comparisons, cash-relative/index results and reference/local-financed ledgers.
 24    """
 25    prices = generate_synthetic_prices(
 26        start="2024-01-31",
 27        end="2024-04-30",
 28        seed=20260725,
 29        apply_quirks=False,
 30    )[["SEQ_EU", "SEQ_US"]].rename(columns={"SEQ_EU": "SYN_EUR", "SEQ_US": "SYN_CHF"})
 31    dates = prices.index
 32    ccys = pd.Series({"SYN_EUR": "EUR", "SYN_CHF": "CHF"})
 33    step = np.arange(len(dates))
 34    spots = pd.DataFrame(
 35        {"USD": 1.0, "EUR": 1.1 * np.exp(0.0003 * step), "CHF": 1.15 * np.exp(-0.0002 * step)},
 36        index=dates,
 37    )
 38    rates = pd.DataFrame({"USD": 0.05, "EUR": 0.03, "CHF": 0.01}, index=dates)
 39    fx = qis.FxRatesData(spots, rates)
 40    comparisons = {}
 41    for freq in ("B", "ME"):
 42        for coordinate in (qis.FxReturnCoordinate.SIMPLE, qis.FxReturnCoordinate.LOG):
 43            results = {}
 44            for kind in (
 45                qis.FxReturnType.LOCAL_TOTAL,
 46                qis.FxReturnType.LOCAL_EXCESS,
 47                qis.FxReturnType.REFERENCE_TOTAL,
 48                qis.FxReturnType.REFERENCE_EXCESS,
 49            ):
 50                reference = "USD" if kind.value.startswith("reference") else None
 51                results[kind.value] = qis.compute_fx_returns(
 52                    fx,
 53                    qis.FxAssetReturnsRequest(
 54                        prices=prices,
 55                        local_ccys=ccys,
 56                        return_type=kind,
 57                        coordinate=coordinate,
 58                        reference_ccy=reference,
 59                        frequency=freq,
 60                        cash_policy=qis.FxCashPolicy(quote_lag=1),
 61                    ),
 62                )[freq].values
 63            translated = qis.compute_fx_returns(
 64                fx,
 65                qis.FxAssetReturnsRequest(
 66                    prices=prices,
 67                    local_ccys=ccys,
 68                    return_type=qis.FxReturnType.LOCAL_EXCESS_TRANSLATED,
 69                    coordinate=qis.FxReturnCoordinate.SIMPLE,
 70                    reference_ccy="USD",
 71                    frequency=freq,
 72                ),
 73            )[freq]
 74            forward = qis.compute_fx_returns(
 75                fx,
 76                qis.FxCurrencyReturnsRequest(
 77                    ("EUR", "CHF"),
 78                    "USD",
 79                    qis.FxReturnType.FX_FORWARD,
 80                    frequency=freq,
 81                ),
 82            )[freq]
 83            forward_by_asset = pd.DataFrame({a: forward.values[c] for a, c in ccys.items()})
 84            results["translated_local_excess_pnl"] = translated.values
 85            results["fx_forward_pnl"] = forward_by_asset
 86            assert translated.synthetic_index is None and forward.synthetic_index is None
 87
 88            # Independent endpoint prices, terminal spot and opening deposit cash flows.
 89            grid = translated.values.index
 90            p = prices.reindex(grid, method="ffill")
 91            s = pd.DataFrame({a: spots[c] for a, c in ccys.items()}).reindex(grid, method="ffill")
 92            local = p / p.shift(1) - 1
 93            spot_change = s / s.shift(1) - 1
 94            dt = grid.to_series().diff().dt.days / 365.0
 95            local_cash = pd.DataFrame({a: rates[c] for a, c in ccys.items()})
 96            local_cash = local_cash.reindex(grid, method="ffill").shift(1).mul(dt, axis=0)
 97            usd_cash = rates.USD.reindex(grid, method="ffill").shift(1) * dt
 98            usd = (1 + local) * (1 + spot_change) - 1
 99            if coordinate is qis.FxReturnCoordinate.SIMPLE:
100                expected = [local, local - local_cash, usd, usd.sub(usd_cash, axis=0)]
101            else:
102                expected = [
103                    np.log1p(local),
104                    np.log1p(local) - np.log1p(local_cash),
105                    np.log1p(usd),
106                    np.log1p(usd).sub(np.log1p(usd_cash), axis=0),
107                ]
108            for actual, reference in zip(list(results.values())[:4], expected):
109                np.testing.assert_allclose(actual, reference, atol=1e-12, equal_nan=True)
110            np.testing.assert_allclose(
111                translated.values,
112                (local - local_cash) * (1 + spot_change),
113                atol=1e-12,
114                equal_nan=True,
115            )
116            forward_ratio = (1 + local_cash).rdiv(1 + usd_cash, axis=0)
117            np.testing.assert_allclose(
118                forward_by_asset, 1 + spot_change - forward_ratio, atol=1e-12, equal_nan=True
119            )
120            comparison = pd.concat(results, axis=1)
121            comparisons[freq, coordinate.value] = comparison
122            if verbose:
123                print(
124                    f"\n{freq} / {coordinate.value}: four returns; last two kinds ALWAYS SIMPLE P&L"
125                )
126                print(comparison.iloc[-1].unstack(0).round(6).to_string())
127
128    cash_relative = qis.compute_fx_returns(
129        fx,
130        qis.FxAssetReturnsRequest(
131            prices=prices,
132            local_ccys=ccys,
133            return_type=qis.FxReturnType.REFERENCE_EXCESS,
134            coordinate=qis.FxReturnCoordinate.CASH_RELATIVE_SIMPLE,
135            reference_ccy="USD",
136            frequency="ME",
137        ),
138    )["ME"]
139    log_excess = comparisons["ME", "log"]["reference_excess"]
140    np.testing.assert_allclose(
141        cash_relative.values, np.expm1(log_excess), atol=1e-12, equal_nan=True
142    )
143    normalization = qis.FxIndexNormalization(
144        100.0, 1.0, "capital_proportional", "ME", "each_interval", "as_returned", "stop"
145    )
146    normalized = forward.to_index(normalization)
147    assert normalized.iloc[0].eq(100.0).all()  # Synthetic forward index; no collateral added.
148
149    trade_dates = pd.to_datetime(["2024-01-31", "2024-02-29", "2024-04-30"])
150    targets = pd.DataFrame(
151        [[0.7, 0.3], [0.4, 0.6], [0.0, 0.0]], index=trade_dates, columns=prices.columns
152    )
153    contracts = pd.DataFrame(
154        [
155            [
156                trade_dates[0],
157                trade_dates[1],
158                pd.Timestamp("2024-03-04"),
159                "EUR",
160                -1.0,
161                "asset_currency_value",
162            ],
163            [trade_dates[1], trade_dates[2], trade_dates[2], "EUR", -1.0, "asset_currency_value"],
164        ],
165        columns=[
166            "trade_date",
167            "fixing_date",
168            "settlement_date",
169            "currency",
170            "notional_weight",
171            "notional_basis",
172        ],
173        index=["initial_hedge", "reset_hedge"],
174    )
175    account = qis.backtest_fx_account(
176        prices,
177        ccys,
178        targets,
179        fx,
180        spec=qis.FxAccountSpec("USD", 100.0, "reference", "fixed", "reference"),
181        local_settlement_dates=pd.DatetimeIndex([]),
182        spot_is_observed=spots.notna(),
183        forwards=contracts,
184    )
185    assert account.contracts.paid.all() and account.asset_units.iloc[-1].eq(0).all()
186    assert account.accounts.forward_value.iloc[-1] == 0
187    np.testing.assert_allclose(
188        account.nav.iloc[-1] - 100.0, account.pnl.to_numpy().sum(), atol=1e-10
189    )
190    np.testing.assert_allclose(
191        account.accounts.cash, 100.0 + account.cash_flows.sum(axis=1).cumsum(), atol=1e-10
192    )
193    if verbose:
194        print(
195            "\nAccount: funded units, explicit EUR hedge reset, fixing then delayed cash payment."
196        )
197        print(
198            account.accounts.loc[pd.to_datetime(["2024-02-29", "2024-03-04", "2024-04-30"])]
199            .round(6)
200            .to_string()
201        )
202        print(
203            "Reporting resampling preserves this ledger; "
204            "return frequency sets analytical hedge resets."
205        )
206    monthly_cash = run_monthly_cash_example(verbose=verbose)
207    local_accounts = run_local_financing_example(verbose=verbose)
208    return {
209        "monthly_cash": monthly_cash,
210        "local_accounts": local_accounts,
211        "comparisons": comparisons,
212        "cash_relative": cash_relative,
213        "normalized_forward_index": normalized,
214        "account": account,
215    }
216
217
218def run_monthly_cash_example(verbose: bool = True) -> dict:
219    """Measure one unhedged wealth path against the same monthly-reset cash account."""
220    dates = pd.date_range("2023-12-31", "2024-03-31", freq="D")
221    prices = generate_synthetic_prices(
222        start="2023-12-29", end="2024-03-31", apply_quirks=False)[["SEQ_EU"]]
223    prices = prices.reindex(dates, method="ffill")
224    rates = pd.DataFrame({"USD": .02, "EUR": .05}, index=dates)
225    rates.loc["2024-01-31":, "USD"] = .08
226    rates.loc["2024-02-29":, "USD"] = .03
227    spots = pd.DataFrame({"USD": 1., "EUR": 1.1 * np.exp(.0002 * np.arange(len(dates)))},
228                         index=dates)
229    fx = qis.FxRatesData(spots, rates)
230    policy = qis.FxCashPolicy(accrual=qis.FxCashAccrual.MONTHLY_INDEX)
231    measured = {}
232    for frequency in ("D", "ME", "QE"):
233        request = qis.FxAssetReturnsRequest(
234            prices=prices, local_ccys="EUR", reference_ccy="USD",
235            return_type=qis.FxReturnType.REFERENCE_EXCESS,
236            coordinate=qis.FxReturnCoordinate.LOG, frequency=frequency, cash_policy=policy)
237        measured[frequency] = qis.compute_fx_returns(fx, request)[frequency].values
238    cash = qis.compute_monthly_cash_index(fx, "USD", dates)
239    # Independent opening deposits: 31 January days, 29 February days, 31 March days.
240    expected_cash = (1 + .02 * 31/365) * (1 + .08 * 29/365) * (1 + .03 * 31/365)
241    np.testing.assert_allclose(cash.iloc[-1], expected_cash, rtol=0, atol=1e-14)
242    expected_excess = np.log(
243        (prices.iloc[-1, 0] * spots.EUR.iloc[-1]) /
244        (prices.iloc[0, 0] * spots.EUR.iloc[0])) - np.log(expected_cash)
245    np.testing.assert_allclose(
246        [measured["D"].iloc[1:, 0].sum(), measured["ME"].iloc[1:, 0].sum(),
247         measured["QE"].iloc[-1, 0]], expected_excess, rtol=0, atol=1e-14)
248    opening_request = qis.FxAssetReturnsRequest(
249        prices=prices, local_ccys="EUR", reference_ccy="USD",
250        return_type=qis.FxReturnType.REFERENCE_EXCESS,
251        coordinate=qis.FxReturnCoordinate.LOG, frequency="QE", cash_policy=qis.FxCashPolicy())
252    opening = qis.compute_fx_returns(fx, opening_request)["QE"].values
253    comparison = pd.Series({
254        "daily log excess sum": measured["D"].iloc[1:, 0].sum(),
255        "monthly log excess sum": measured["ME"].iloc[1:, 0].sum(),
256        "quarterly monthly-index log excess": measured["QE"].iloc[-1, 0],
257        "quarterly period-opening log excess": opening.iloc[-1, 0],
258    })
259    assert abs(comparison.iloc[-1] - comparison.iloc[-2]) > 1e-4
260    if verbose:
261        print("\nSame unhedged wealth path, changing rates; decimal log excess:")
262        print(comparison.round(8).to_string())
263    return {"returns": measured, "cash_index": cash, "comparison": comparison}
264
265
266def run_local_financing_example(verbose: bool = True) -> dict:
267    """Check zero/nonzero-net books against two independent local debt settlements."""
268    dates = pd.to_datetime(["2024-01-31", "2024-02-29", "2024-04-30"])
269    prices = generate_synthetic_prices(
270        start="2024-01-31", end="2024-04-30", apply_quirks=False)[["SEQ_EU", "SEQ_US"]]
271    prices = prices.reindex(dates)
272    ccys = pd.Series({"SEQ_EU": "EUR", "SEQ_US": "CHF"})
273    spots = pd.DataFrame({"USD": 1., "EUR": [1.1, 1.15, 1.12],
274                          "CHF": [1.15, 1.12, 1.14]}, index=dates)
275    rates = pd.DataFrame({"USD": .05, "EUR": .03, "CHF": .01}, index=dates)
276    fx = qis.FxRatesData(spots, rates)
277    results = {}
278    for label, weights in (("zero_net", [.5, -.5]), ("nonzero_net", [.7, -.3])):
279        targets = pd.DataFrame([weights, [0., 0.]], index=dates[[0, 2]], columns=prices.columns)
280        account = qis.backtest_fx_account(
281            prices, ccys, targets, fx,
282            spec=qis.FxAccountSpec("USD", 100., "local", "fixed", "reference"),
283            local_settlement_dates=dates[1:], spot_is_observed=spots.notna())
284        # Independent two-period cash flows, not another general ledger/backtester.
285        s = spots[list(ccys)].to_numpy()
286        p = prices.to_numpy()
287        r = rates[list(ccys)].iloc[0].to_numpy()
288        dt1, dt2 = np.diff(dates).astype("timedelta64[D]").astype(float) / 365.
289        units = 100. * np.asarray(weights) / (p[0] * s[0])
290        debt0 = -units * p[0]
291        sweep1 = ((units * p[1] + debt0 * (1 + r * dt1)) * s[1]).sum()
292        debt1 = -units * p[1]
293        sweep2 = ((units * p[2] + debt1 * (1 + r * dt2)) * s[2]).sum()
294        cash1 = 100. * (1 + .05 * dt1) + sweep1
295        cash2 = cash1 * (1 + .05 * dt2) + sweep2
296        np.testing.assert_allclose(account.nav, [100., cash1, cash2], rtol=0, atol=1e-10)
297        np.testing.assert_allclose(account.local_balances.iloc[-1], 0., rtol=0, atol=1e-10)
298        np.testing.assert_allclose(account.pnl.to_numpy().sum(), cash2 - 100., atol=1e-10)
299        assert account.asset_units.iloc[-1].eq(0.).all()
300        results[label] = account
301    if verbose:
302        print("\nLocal financing, fixed USD capital 100, explicit intermediate/final sweeps:")
303        print(pd.DataFrame({k: v.nav for k, v in results.items()}).round(6).to_string())
304    return results
305
306
307class Locals(Enum):
308    """Offline example selection."""
309
310    RETURNS_AND_ACCOUNT = "returns_and_account"
311
312
313def run_local(local: Locals):
314    """Run the selected offline teaching workflow."""
315    if local is not Locals.RETURNS_AND_ACCOUNT:
316        raise ValueError(local)
317    return run_example()
318
319
320if __name__ == "__main__":
321    run_local(local=Locals.RETURNS_AND_ACCOUNT)

Further readingΒΆ