Databricks Lakeflow for FX Pair and Carry Analysis on a China Trading Desk

Agenda

  1. Speaker background
  2. Databricks Free Edition boundary
  3. Lakeflow declarative framework
  4. China FX desk use case
  5. Pair and carry methodology
  6. Step 1: Create the Databricks Free Edition workspace
  7. Step 2: Define the source inventory
  8. Step 3: Create the Unity Catalog data model
  9. Step 4: Configure Lakeflow Connect where available
  10. Step 5: Build a file-based Free Edition fallback
  11. Step 6: Create a Lakeflow declarative pipeline
  12. Step 7: Parse the VARIANT payload
  13. Step 8: Enable and verify Variant Shredding
  14. Step 9: Understand Automatic Upgrades
  15. Step 10: Apply Row Tracking
  16. Step 11: Apply Checkpoint V2
  17. Step 12: Apply Deletion Vectors carefully
  18. Step 13: Build carry-input datasets
  19. Step 14: Build pair and carry metrics
  20. Step 15: Add CNY and CNH controls
  21. Step 16: Create data-quality expectations
  22. Step 17: Configure incremental history
  23. Step 18: Create desk research queries
  24. Step 19: Validate with a worked carry example
  25. Step 20: Monitor and maintain the pipeline
  26. Common failure modes
  27. How the Databricks capabilities help
  28. References

Key Takeaway

The speaker moved from military combat engineering into institutional-grade trading and now supports pair and carry foreign-exchange analysis for a China trading desk.

Speaker background

The speaker moved from mil ➔ Combat engineers work with ➔ The practical objective is ➔ This guide creates a gover

The speaker moved from military combat engineering into institutional-grade trading and now supports pair and carry foreign-exchange analysis for a China trading desk.

Combat engineers work with routes, constraints, load capacity, redundancy, sequencing, and rapidly changing operating conditions. An institutional FX desk applies similar discipline to currency pairs, funding curves, forward points, liquidity windows, settlement calendars, counterparty capacity, regulatory boundaries, and market-data quality.

The practical objective is not to identify the currency with the highest displayed yield. It is to determine whether a pair or carry position remains attractive after funding, forward points, hedging costs, transaction costs, liquidity impact, settlement restrictions, drawdown risk, and the applicable China foreign-exchange controls.

This guide creates a governed training and research environment in Databricks Free Edition. It uses Lakeflow declarative pipelines, Unity Catalog managed tables, semi-structured VARIANT data, automatic table upgrades, row tracking, Checkpoint V2, deletion vectors, and connector patterns to build a reusable FX pair and carry research workflow.

Databricks Free Edition boundary

Databricks Free Edition is ➔ Use Free Edition for synth ➔ Free Edition feature avail

Databricks Free Edition is a perpetual, no-cost, serverless-only cloud environment for learning, experimentation, and prototypes. It is quota-limited and does not provide a production service-level agreement.

Use Free Edition for synthetic or properly licensed delayed data, pipeline development, SQL validation, governance exercises, and controlled demonstrations. Do not use it for production order routing, portfolio management, payment instructions, live position limits, confidential counterparty data, material non-public information, or unrestricted licensed market feeds.

Free Edition feature availability can differ by cloud, region, release state, and workspace configuration. Lakeflow managed connectors, automatic upgrades, VARIANT shredding, and specific runtime-dependent functionality should be verified in the active workspace before relying on them.

Lakeflow declarative framework

Lakeflow Spark Declarative ➔ A declarative pipeline def ➔ For an FX desk, the declar ➔ Lakeflow Connect provides ➔ Connector counts and relea

Lakeflow Spark Declarative Pipelines is the Databricks framework for defining batch and streaming data transformations by describing the desired datasets rather than manually orchestrating every execution step.

A declarative pipeline defines streaming tables, materialized views, data-quality expectations, dependencies, and target schemas. Databricks determines execution order, incremental processing behavior, compute management, checkpoint handling, retry behavior, and lineage integration.

For an FX desk, the declarative approach is useful because market, rate, curve, reference, and operational sources arrive at different frequencies. A managed pipeline can incrementally update the affected outputs rather than rebuilding every dataset from the beginning.

Lakeflow Connect provides managed ingestion patterns for database CDC, SaaS applications, enterprise files, query-based sources, and streaming systems. The connector catalog includes native and partner-supported patterns for systems such as Salesforce, Workday, Workiva, Google Drive, SharePoint, MySQL, PostgreSQL, SQL Server, Kafka-compatible streams, and additional enterprise sources.

Connector counts and release states change. Treat “more than 100 connectors” as a platform catalog statement that includes connectors in different availability states, not as a guarantee that every connector is enabled in Databricks Free Edition.

China FX desk use case

The prototype supports res ➔ USD/CNH and USD/CNY basis ➔ CNH versus regional curren ➔ G10 funding and carry comp ➔ Onshore and offshore rate-

The prototype supports research for pairs such as:

  • USD/CNH and USD/CNY basis monitoring.
  • CNH versus regional currencies such as SGD, KRW, and JPY.
  • G10 funding and carry comparisons involving USD, EUR, JPY, CHF, AUD, and NZD.
  • Onshore and offshore rate-curve differences.
  • Deliverable FX, non-deliverable forwards, swaps, and research-only synthetic carry baskets.

China distinguishes between onshore CNY and offshore CNH markets. They have different liquidity, participants, operating conditions, and regulatory constraints. A price difference between CNY and CNH is not automatically transferable or executable.

The research environment must never suggest evading capital controls, reporting obligations, market-access rules, sanctions checks, counterparty limits, or settlement restrictions. Every research result should identify whether the data represents CNY, CNH, a deliverable instrument, an NDF, a swap, or a modeled synthetic position.

Pair and carry methodology

A pair trade compares two ➔ A carry trade borrows or f ➔ Define a simplified annual ➔ gross_carry_pct = target_r ➔ Define forward-implied car

A pair trade compares two related currencies or instruments and attempts to isolate relative value rather than broad market direction.

A carry trade borrows or funds in a lower-yielding currency and takes exposure to a higher-yielding currency. The expected return can be reduced or reversed by forward pricing, currency depreciation, volatility, transaction cost, drawdown, hedging cost, and liquidity stress.

Define a simplified annualized gross carry:

gross_carry_pct = target_rate_pct - funding_rate_pct

Define forward-implied carry using spot and forward prices:

forward_points_pct = (forward_price / spot_price - 1) * annualization_factor * 100

Define research net carry:

net_carry_bps = gross_carry_bps - forward_cost_bps - hedge_cost_bps - funding_basis_bps - transaction_cost_bps - expected_slippage_bps - liquidity_buffer_bps - regulatory_buffer_bps

Define expected carry value:

expected_carry_value = permitted_notional * net_carry_bps / 10000 * holding_days / 365

This value is an estimate. It is not guaranteed profit and does not include every path-dependent risk.

Step 1: Create the Databricks Free Edition workspace

Create a Databricks Free E ➔ china_fx_pair_carry_resear ➔ Confirm access to Workspac ➔ Create this workspace dire ➔ /Workspace/Users/<your-use

Create a Databricks Free Edition workspace and name the project:

china_fx_pair_carry_research_free_nonprod

Confirm access to Workspace, Catalog, SQL Editor, SQL Warehouses, Jobs and Pipelines, and Marketplace where available.

Create this workspace directory:

/Workspace/Users/<your-user>/china_fx_pair_carry

Create these folders:

  • 00_environment
  • 01_connections
  • 02_ingestion
  • 03_quality
  • 04_transformations
  • 05_pair_carry_metrics
  • 06_research_queries
  • 07_governance

Create a notebook named 00_environment_check and run:

SELECT
  current_user() AS current_user,
  current_catalog() AS current_catalog,
  current_schema() AS current_schema,
  current_timestamp() AS checked_at;

Record that the workspace is non-production, serverless-only, quota-limited, and unsuitable for execution or regulated books and records.

Step 2: Define the source inventory

Create a source register b ➔ Market and curve sources c ➔ Enterprise operating sourc ➔ Workday cost-center or app ➔ Salesforce counterparty re

Create a source register before configuring ingestion.

Market and curve sources can include properly licensed spot quotes, forward points, swap points, overnight rates, term rates, implied volatility, realized volatility, and trading calendars.

Enterprise operating sources can include:

  • Workday cost-center or approved organizational reference data.
  • Salesforce counterparty relationship metadata.
  • Workiva approved controls and reporting documents.
  • SharePoint desk procedures and regulatory research.
  • PostgreSQL or SQL Server risk-reference databases.
  • Cloud storage files containing approved delayed market observations.

Do not ingest employee payroll, unrestricted CRM records, personal data, client communications, or confidential filings merely because a connector exists. Use the minimum fields necessary for the FX research purpose.

For each source, record its owner, license, classification, refresh frequency, timestamp semantics, primary key, deletion behavior, expected latency, and authoritative status.

Step 3: Create the Unity Catalog data model

Open SQL Editor and select ➔ Create the catalog and sch ➔ If catalog creation is res ➔ Create a raw market-event ➔ Create a currency-pair ref

Open SQL Editor and select the Free Edition SQL warehouse.

Create the catalog and schemas:

CREATE CATALOG IF NOT EXISTS china_fx_lab;

CREATE SCHEMA IF NOT EXISTS china_fx_lab.raw;
CREATE SCHEMA IF NOT EXISTS china_fx_lab.silver;
CREATE SCHEMA IF NOT EXISTS china_fx_lab.gold;
CREATE SCHEMA IF NOT EXISTS china_fx_lab.reference;
CREATE SCHEMA IF NOT EXISTS china_fx_lab.governance;

If catalog creation is restricted, use the default catalog and create the same schemas there.

Create a raw market-event table with a VARIANT payload:

CREATE TABLE IF NOT EXISTS china_fx_lab.raw.fx_events (
  event_id STRING,
  event_time TIMESTAMP,
  received_time TIMESTAMP,
  source_system STRING,
  event_type STRING,
  payload VARIANT,
  source_file STRING,
  is_synthetic BOOLEAN,
  ingested_at TIMESTAMP
) USING DELTA;

Create a currency-pair reference table:

CREATE TABLE IF NOT EXISTS china_fx_lab.reference.currency_pairs (
  pair STRING,
  base_currency STRING,
  quote_currency STRING,
  market_type STRING,
  deliverability STRING,
  settlement_days INT,
  timezone STRING,
  fixing_name STRING,
  active BOOLEAN,
  reviewed_at TIMESTAMP
) USING DELTA;

Create a calendar table:

CREATE TABLE IF NOT EXISTS china_fx_lab.reference.market_calendar (
  calendar_date DATE,
  market STRING,
  currency STRING,
  is_business_day BOOLEAN,
  session_open TIMESTAMP,
  session_close TIMESTAMP,
  fixing_time TIMESTAMP,
  settlement_available BOOLEAN,
  note STRING
) USING DELTA;

Create a governed research-limit table:

CREATE TABLE IF NOT EXISTS china_fx_lab.governance.research_limits (
  strategy_id STRING,
  pair STRING,
  instrument_type STRING,
  max_research_notional_usd DECIMAL(20,2),
  min_net_carry_bps DECIMAL(12,4),
  max_expected_slippage_bps DECIMAL(12,4),
  max_data_age_seconds INT,
  manual_review_required BOOLEAN,
  permitted_for_research BOOLEAN,
  effective_from DATE,
  effective_to DATE
) USING DELTA;

Step 4: Configure Lakeflow Connect where available

Open Data Engineering and ➔ Choose a source whose use ➔ For a SaaS source such as ➔ For a database source such ➔ A query-based source requi

Open Data Engineering and select Lakeflow Connect or Add Data.

Choose a source whose use is approved in the Free Edition workspace. If a managed connector is not available, use uploaded synthetic files or another supported serverless ingestion method.

For a SaaS source such as Salesforce, Workday, or Workiva, create a Unity Catalog connection using a dedicated least-privilege service identity. Select only the required objects and fields.

For a database source such as PostgreSQL, MySQL, or SQL Server, choose CDC when log-based change capture is approved and supported. Otherwise, use a query-based connector with a monotonically increasing cursor column.

A query-based source requires a reliable cursor such as updated_at or a source sequence ID. A timestamp cursor must be consistently updated for every relevant change. If the source can update records without changing the cursor, incremental ingestion can miss data.

Set the destination to a raw Unity Catalog schema. Do not write a source directly into a curated gold schema.

Name an ingestion pipeline using this pattern:

lfc_<source>_<object>_to_china_fx_raw

For example:

lfc_postgresql_fx_reference_to_china_fx_raw

lfc_salesforce_counterparty_classification_to_china_fx_raw

Run the first ingestion and compare source and destination row counts, primary-key uniqueness, maximum update timestamp, and deletion behavior.

Step 5: Build a file-based Free Edition fallback

If the required managed co ➔ Example event: ➔ Upload the files to a Unit ➔ Create an Auto Loader or s

If the required managed connector is unavailable, create synthetic JSON files containing spot, forward, curve, and volatility events.

Example event:

{
  "event_id": "evt-000001",
  "event_time": "2026-11-05T01:00:00Z",
  "received_time": "2026-11-05T01:00:01Z",
  "source_system": "synthetic_fx_feed",
  "event_type": "FX_QUOTE",
  "payload": {
    "pair": "USD/CNH",
    "tenor": "SPOT",
    "bid": 7.1200,
    "ask": 7.1210,
    "provider": "SIM_PROVIDER_A",
    "available_notional_usd": 5000000,
    "market": "OFFSHORE"
  },
  "is_synthetic": true
}

Upload the files to a Unity Catalog volume where available.

Create an Auto Loader or streaming-table source in a Lakeflow pipeline. Use _metadata.file_name rather than the deprecated input_file_name() function on newer runtimes.

Step 6: Create a Lakeflow declarative pipeline

Open Jobs and Pipelines an ➔ Name it: ➔ china_fx_pair_carry_pipeli ➔ Choose serverless compute ➔ Create a Python source fil

Open Jobs and Pipelines and create a new ETL pipeline.

Name it:

china_fx_pair_carry_pipeline

Choose serverless compute and set the target catalog to china_fx_lab.

Create a Python source file:

from pyspark import pipelines as dp
from pyspark.sql import functions as F

@dp.table(
    name="raw.fx_events_streaming",
    comment="Raw synthetic or approved FX events ingested incrementally"
)
def fx_events_streaming():
    return (
        spark.readStream
        .format("cloudFiles")
        .option("cloudFiles.format", "json")
        .option("cloudFiles.schemaLocation", "/Volumes/china_fx_lab/raw/schema/fx_events")
        .load("/Volumes/china_fx_lab/raw/landing/fx_events")
        .withColumn("source_file", F.col("_metadata.file_name"))
        .withColumn("ingested_at", F.current_timestamp())
    )

Add expectations:

@dp.table(
    name="silver.fx_events_valid",
    comment="Validated FX events with required timestamps and identifiers"
)
@dp.expect_or_drop("event_id_present", "event_id IS NOT NULL")
@dp.expect_or_drop("event_time_present", "event_time IS NOT NULL")
@dp.expect("received_not_before_event", "received_time >= event_time")
def fx_events_valid():
    return spark.readStream.table("raw.fx_events_streaming")

Use expect when a failed row should remain visible for monitoring. Use expect_or_drop only when dropping the row is intentional and documented. Use a failure expectation only when continuing would make the dataset untrustworthy.

Step 7: Parse the VARIANT payload

Create a silver table that ➔ VARIANT allows the pipelin

Create a silver table that extracts commonly queried FX fields while retaining the original payload.

@dp.table(
    name="silver.fx_quotes",
    comment="Curated FX quote events extracted from VARIANT payloads"
)
def fx_quotes():
    source = spark.readStream.table("silver.fx_events_valid")

    return (
        source
        .filter("event_type = 'FX_QUOTE'")
        .selectExpr(
            "event_id",
            "event_time",
            "received_time",
            "source_system",
            "payload",
            "payload:pair::STRING AS pair",
            "payload:tenor::STRING AS tenor",
            "payload:bid::DECIMAL(20,8) AS bid",
            "payload:ask::DECIMAL(20,8) AS ask",
            "payload:provider::STRING AS provider",
            "payload:available_notional_usd::DECIMAL(20,2) AS available_notional_usd",
            "payload:market::STRING AS market",
            "is_synthetic",
            "ingested_at"
        )
        .withColumn("mid", (F.col("bid") + F.col("ask")) / F.lit(2))
        .withColumn(
            "spread_bps",
            (F.col("ask") - F.col("bid")) / F.col("mid") * F.lit(10000)
        )
    )

VARIANT allows the pipeline to retain changing source attributes without turning every new nested field into a breaking schema change. Curated columns still provide stable types for research calculations.

Step 8: Enable and verify Variant Shredding

Variant shredding stores c ➔ New tables created with VA ➔ Verify the table property: ➔ If the runtime and table f ➔ Enabling the property does

Variant shredding stores commonly occurring VARIANT fields as separate physical columns inside the underlying Parquet representation. This reduces the amount of data read for common paths and improves compression.

New tables created with VARIANT columns use shredding automatically when created by Databricks Runtime 17.3 or later under the documented requirements. CREATE OR REPLACE TABLE and ALTER TABLE do not automatically enable shredding for an existing table.

Verify the table property:

SHOW TBLPROPERTIES china_fx_lab.raw.fx_events;

If the runtime and table format support the feature, enable it for future writes:

ALTER TABLE china_fx_lab.raw.fx_events
SET TBLPROPERTIES ('delta.enableVariantShredding' = 'true');

Enabling the property does not rewrite existing VARIANT records. Rewrite existing data where supported:

REORG TABLE china_fx_lab.raw.fx_events APPLY (SHRED VARIANT);

Use Databricks Runtime 18.1 or later where available for improved VARIANT statistics collection and data skipping. In Free Edition, the serverless environment determines runtime behavior, so verify the effective feature support rather than attempting to select unsupported classic compute.

Shredding introduces some write overhead. It is useful when the desk repeatedly queries paths such as pair, tenor, bid, ask, provider, or market. It provides less value for rarely repeated or highly irregular fields.

Step 9: Understand Automatic Upgrades

Automatic Upgrades evaluat ➔ The service monitors table ➔ Automatic Upgrades uses se ➔ The feature can apply reco ➔ Check a table before assum

Automatic Upgrades evaluates Unity Catalog managed-table access patterns and turns on recommended generally available features only after compatibility checks.

The service monitors table access during an observation window. Current documentation uses a 50-day observation window for Public Preview upgrades and a 100-day observation window for generally available upgrades. Inactive tables are skipped, and only verified compatible workloads qualify.

Automatic Upgrades uses serverless compute in the background and does not require manual ALTER TABLE operations for the supported upgrade path.

The feature can apply recommended capabilities such as row tracking and Checkpoint V2 when compatibility conditions are met. Exact supported features can change, so inspect the Automatic Upgrades page in the active workspace.

Check a table before assuming that an upgrade occurred:

DESCRIBE DETAIL china_fx_lab.silver.fx_quotes;
SHOW TBLPROPERTIES china_fx_lab.silver.fx_quotes;

Do not describe an upgrade as immediate. Existing tables may need the required observation period and qualified workload history.

Step 10: Apply Row Tracking

Row tracking assigns a sta ➔ Enable row tracking on a n ➔ Enable it manually on an e ➔ Enabling row tracking on a ➔ Inspect hidden row metadat

Row tracking assigns a stable row ID and the last row commit version to each record. It supports row-level lineage behavior and certain incremental materialized-view operations.

Enable row tracking on a new managed table:

CREATE TABLE china_fx_lab.silver.carry_inputs (
  observation_time TIMESTAMP,
  currency STRING,
  tenor STRING,
  deposit_rate_pct DECIMAL(12,6),
  swap_implied_rate_pct DECIMAL(12,6),
  funding_basis_bps DECIMAL(12,4),
  source_system STRING,
  is_synthetic BOOLEAN
)
USING DELTA
TBLPROPERTIES ('delta.enableRowTracking' = 'true');

Enable it manually on an existing table when compatible:

ALTER TABLE china_fx_lab.silver.fx_quotes
SET TBLPROPERTIES ('delta.enableRowTracking' = 'true');

Enabling row tracking on an existing table assigns row information to existing records and can create multiple table versions. Pause continuous writers before a manual metadata upgrade because concurrent writes can fail with a metadata-change conflict.

Inspect hidden row metadata:

SELECT
  event_id,
  pair,
  _metadata.row_id,
  _metadata.row_commit_version
FROM china_fx_lab.silver.fx_quotes
LIMIT 100;

A cloned table has its own history. Do not assume row IDs are identical between an original table and its clone.

Step 11: Apply Checkpoint V2

Delta checkpoints summariz ➔ Checkpoint V2 supports mor ➔ Enable it manually where c ➔ Tables created with liquid ➔ Verify the property:

Delta checkpoints summarize transaction-log state so readers do not need to replay the entire log from the beginning.

Checkpoint V2 supports more concurrent writers and reduces write conflicts on large or frequently updated tables.

Enable it manually where compatible:

ALTER TABLE china_fx_lab.silver.fx_quotes
SET TBLPROPERTIES ('delta.checkpointPolicy' = 'v2');

Tables created with liquid clustering on supported runtimes can use Checkpoint V2 by default. Automatic Upgrades can also enable it for compatible Unity Catalog managed tables.

Verify the property:

SHOW TBLPROPERTIES china_fx_lab.silver.fx_quotes;

Checkpoint V2 improves transaction-log handling. It does not replace Structured Streaming checkpoint directories. A Delta table checkpoint and a streaming query checkpoint solve different problems.

Step 12: Apply Deletion Vectors carefully

Deletion vectors allow som ➔ This can improve write per ➔ Check whether deletion vec ➔ Enable them only after con ➔ Deletion vectors can affec

Deletion vectors allow some DELETE, UPDATE, and MERGE operations to mark changed rows without immediately rewriting every affected data file.

This can improve write performance for incremental pipelines that update a relatively small fraction of large files.

Check whether deletion vectors are enabled:

SHOW TBLPROPERTIES china_fx_lab.silver.fx_quotes;

Enable them only after confirming client compatibility:

ALTER TABLE china_fx_lab.silver.fx_quotes
SET TBLPROPERTIES ('delta.enableDeletionVectors' = 'true');

Deletion vectors can affect compatibility with external Delta clients. If data is read outside Databricks, validate the client protocol and feature support before enabling the feature manually.

Use REORG TABLE and OPTIMIZE according to the supported maintenance behavior when materializing changes into rewritten files is required.

Step 13: Build carry-input datasets

Load or generate approved ➔ Every observation should i ➔ Observation time. ➔ Currency. ➔ Curve or rate name.

Load or generate approved rate observations for USD, CNH, CNY, JPY, SGD, KRW, EUR, AUD, and NZD.

Every observation should include:

  • Observation time.
  • Currency.
  • Curve or rate name.
  • Tenor.
  • Bid and ask where available.
  • Mid rate.
  • Day-count convention.
  • Compounding convention.
  • Source.
  • Fixing or publication time.
  • Synthetic flag.

Do not directly subtract two published rates without normalizing tenor, day count, compounding, and observation time.

Create a current-rate view:

CREATE OR REPLACE VIEW china_fx_lab.gold.current_rates AS
WITH ranked AS (
  SELECT
    *,
    ROW_NUMBER() OVER (
      PARTITION BY currency, tenor
      ORDER BY observation_time DESC
    ) AS row_number
  FROM china_fx_lab.silver.carry_inputs
)
SELECT * EXCEPT (row_number)
FROM ranked
WHERE row_number = 1;

Step 14: Build pair and carry metrics

Create a strategy-input ta ➔ Create a metric view or SQ ➔ Add forward and operationa ➔ Calculate net carry only w

Create a strategy-input table:

CREATE TABLE IF NOT EXISTS china_fx_lab.reference.carry_strategies (
  strategy_id STRING,
  funding_currency STRING,
  target_currency STRING,
  pair STRING,
  tenor STRING,
  holding_days INT,
  instrument_type STRING,
  active BOOLEAN
) USING DELTA;

Create a metric view or SQL view:

CREATE OR REPLACE VIEW china_fx_lab.gold.carry_candidates AS
WITH joined AS (
  SELECT
    s.strategy_id,
    s.funding_currency,
    s.target_currency,
    s.pair,
    s.tenor,
    s.holding_days,
    s.instrument_type,
    f.deposit_rate_pct AS funding_rate_pct,
    t.deposit_rate_pct AS target_rate_pct,
    (t.deposit_rate_pct - f.deposit_rate_pct) * 100 AS gross_carry_bps
  FROM china_fx_lab.reference.carry_strategies s
  JOIN china_fx_lab.gold.current_rates f
    ON s.funding_currency = f.currency
   AND s.tenor = f.tenor
  JOIN china_fx_lab.gold.current_rates t
    ON s.target_currency = t.currency
   AND s.tenor = t.tenor
  WHERE s.active = true
)
SELECT * FROM joined;

Add forward and operational costs in a separate curated dataset. Do not substitute missing costs with zero.

CREATE TABLE IF NOT EXISTS china_fx_lab.silver.carry_costs (
  observation_time TIMESTAMP,
  strategy_id STRING,
  forward_cost_bps DECIMAL(12,4),
  hedge_cost_bps DECIMAL(12,4),
  funding_basis_bps DECIMAL(12,4),
  transaction_cost_bps DECIMAL(12,4),
  expected_slippage_bps DECIMAL(12,4),
  liquidity_buffer_bps DECIMAL(12,4),
  regulatory_buffer_bps DECIMAL(12,4),
  cost_status STRING
) USING DELTA;

Calculate net carry only when the cost model is complete:

CREATE OR REPLACE VIEW china_fx_lab.gold.net_carry_candidates AS
SELECT
  c.*,
  x.forward_cost_bps,
  x.hedge_cost_bps,
  x.funding_basis_bps,
  x.transaction_cost_bps,
  x.expected_slippage_bps,
  x.liquidity_buffer_bps,
  x.regulatory_buffer_bps,
  CASE
    WHEN x.cost_status <> 'COMPLETE' THEN NULL
    ELSE c.gross_carry_bps
      - x.forward_cost_bps
      - x.hedge_cost_bps
      - x.funding_basis_bps
      - x.transaction_cost_bps
      - x.expected_slippage_bps
      - x.liquidity_buffer_bps
      - x.regulatory_buffer_bps
  END AS net_carry_bps
FROM china_fx_lab.gold.carry_candidates c
LEFT JOIN china_fx_lab.silver.carry_costs x
  ON c.strategy_id = x.strategy_id;

Step 15: Add CNY and CNH controls

Create separate pair defin ➔ Store these fields: ➔ market_type: ONSHORE or OF ➔ deliverability: DELIVERABL ➔ fixing_name.

Create separate pair definitions for USD/CNY and USD/CNH. Never combine them under one generic USD/RMB identifier.

Store these fields:

  • market_type: ONSHORE or OFFSHORE.
  • deliverability: DELIVERABLE, NDF, or another approved category.
  • fixing_name.
  • settlement_location.
  • eligible_entity_type.
  • manual_review_required.

Create an onshore-offshore spread view:

CREATE OR REPLACE VIEW china_fx_lab.gold.cny_cnh_basis AS
WITH cny AS (
  SELECT event_time, mid AS usd_cny_mid
  FROM china_fx_lab.silver.fx_quotes
  WHERE pair = 'USD/CNY'
),
cnh AS (
  SELECT event_time, mid AS usd_cnh_mid
  FROM china_fx_lab.silver.fx_quotes
  WHERE pair = 'USD/CNH'
)
SELECT
  cny.event_time,
  cny.usd_cny_mid,
  cnh.usd_cnh_mid,
  (cnh.usd_cnh_mid - cny.usd_cny_mid)
    / NULLIF(cny.usd_cny_mid, 0) * 10000 AS offshore_basis_bps
FROM cny
JOIN cnh
  ON cny.event_time = cnh.event_time;

A nonzero basis is an analytical observation. It does not prove that capital can be transferred between the two markets, that both prices are simultaneously executable, or that the trade is permitted.

Step 16: Create data-quality expectations

Add expectations for FX qu ➔ Pair must exist in the ref ➔ Bid and ask must be positi ➔ Ask must be greater than o ➔ Event time cannot be mater

Add expectations for FX quotes:

  • Pair must exist in the reference table.
  • Bid and ask must be positive.
  • Ask must be greater than or equal to bid unless the record is quarantined for investigation.
  • Event time cannot be materially ahead of receive time.
  • Provider must be approved.
  • Currency and market type must be present.
  • Synthetic status must be explicit.

Add expectations for rates:

  • Rate source must be approved.
  • Tenor must be recognized.
  • Day-count convention must be present.
  • Observation time must be aligned within the permitted comparison window.
  • Stale values must not enter current candidate calculations.

Quarantine invalid rows:

CREATE OR REPLACE VIEW china_fx_lab.governance.quarantined_quotes AS
SELECT *
FROM china_fx_lab.silver.fx_quotes
WHERE bid <= 0
   OR ask <= 0
   OR ask < bid
   OR pair IS NULL
   OR provider IS NULL;

Step 17: Configure incremental history

For source tables with sta ➔ Use SCD Type 1 when the de ➔ Use SCD Type 2 when the de ➔ Use append-only behavior f ➔ For query-based connectors

For source tables with stable primary keys, choose the required history behavior.

Use SCD Type 1 when the desk only needs the latest corrected state.

Use SCD Type 2 when the desk must reconstruct which classification, threshold, or approval was effective at a past time.

Use append-only behavior for immutable observations such as published market events where corrections arrive as new records.

For query-based connectors, provide a monotonically increasing cursor and primary keys for merge-based behavior. Configure a soft-deletion condition where the source exposes one. Hard-deletion detection requires additional snapshot scanning and may not be supported with every history mode.

Do not infer source deletion from a missing incremental row. Absence from an incremental extract is not proof that a record was deleted.

Step 18: Create desk research queries

Identify complete net-carr ➔ Compare gross and net carr ➔ Find incomplete models: ➔ Review CNY/CNH observation ➔ Every result should displa

Identify complete net-carry candidates:

SELECT
  strategy_id,
  funding_currency,
  target_currency,
  pair,
  tenor,
  gross_carry_bps,
  net_carry_bps
FROM china_fx_lab.gold.net_carry_candidates
WHERE net_carry_bps IS NOT NULL
ORDER BY net_carry_bps DESC;

Compare gross and net carry:

SELECT
  strategy_id,
  pair,
  gross_carry_bps,
  forward_cost_bps,
  hedge_cost_bps,
  funding_basis_bps,
  transaction_cost_bps,
  expected_slippage_bps,
  liquidity_buffer_bps,
  regulatory_buffer_bps,
  net_carry_bps
FROM china_fx_lab.gold.net_carry_candidates
ORDER BY gross_carry_bps DESC;

Find incomplete models:

SELECT *
FROM china_fx_lab.gold.net_carry_candidates
WHERE net_carry_bps IS NULL;

Review CNY/CNH observations:

SELECT *
FROM china_fx_lab.gold.cny_cnh_basis
ORDER BY ABS(offshore_basis_bps) DESC;

Every result should display source timestamps, synthetic status, and model completeness.

Step 19: Validate with a worked carry example

Assume a synthetic one-yea ➔ Funding rate: 0.50 percent ➔ Target rate: 4.10 percent. ➔ Gross carry: 3.60 percent, ➔ Assume forward cost is 285

Assume a synthetic one-year research strategy funds in JPY and holds an AUD exposure.

Funding rate: 0.50 percent.

Target rate: 4.10 percent.

Gross carry: 3.60 percent, or 360 basis points.

Assume forward cost is 285 basis points, hedge cost is 12 basis points, funding basis is 8 basis points, transaction cost is 3 basis points, expected slippage is 5 basis points, liquidity buffer is 10 basis points, and regulatory buffer is 2 basis points.

Total modeled cost is 325 basis points.

Net carry is 35 basis points.

For a permitted research notional of USD 5,000,000 and a 90-day holding period:

5,000,000 * 35 / 10000 * 90 / 365 = approximately USD 4,315

This example demonstrates why a 360-basis-point headline rate difference can become a much smaller expected value after forward pricing and costs.

Apply a currency stress. If the target currency depreciates by 2 percent during the period and the exposure is unhedged, the FX loss can overwhelm the modeled carry.

Step 20: Monitor and maintain the pipeline

Review Lakeflow pipeline u ➔ Inspect connector status a ➔ Review table history: ➔ Review table details and p ➔ Check whether row tracking

Review Lakeflow pipeline updates, failed expectations, source freshness, and event counts.

Inspect connector status and source authentication before treating a missing update as a market event.

Review table history:

DESCRIBE HISTORY china_fx_lab.silver.fx_quotes;

Review table details and properties:

DESCRIBE DETAIL china_fx_lab.silver.fx_quotes;
SHOW TBLPROPERTIES china_fx_lab.silver.fx_quotes;

Check whether row tracking, Checkpoint V2, deletion vectors, or variant shredding are enabled before relying on them.

Review the compatibility of external readers after any protocol-level table feature is enabled.

Allow serverless resources to stop when idle. Free Edition quotas can interrupt long-running or high-volume demonstrations.

Common failure modes

A cursor failure occurs wh ➔ A deletion failure occurs ➔ A schema-drift failure occ ➔ A shredding assumption fai ➔ An automatic-upgrade assum

A cursor failure occurs when a query-based connector uses a timestamp that is not updated for every change. Records can be missed.

A deletion failure occurs when missing source rows are treated as deletions without a deletion signal or an approved snapshot comparison.

A schema-drift failure occurs when a new source attribute silently changes type. Preserve the VARIANT payload, enforce types in silver tables, and quarantine invalid casts.

A shredding assumption failure occurs when enabling the table property is assumed to rewrite old data. Existing records require a supported REORG TABLE ... APPLY (SHRED VARIANT) operation.

An automatic-upgrade assumption failure occurs when users expect immediate feature activation. Existing tables may require a 50-day or 100-day compatibility observation window depending on the upgrade release state.

A row-tracking conflict occurs when row tracking is manually enabled during continuous writes. Pause writers before the metadata upgrade.

A checkpoint misunderstanding occurs when Delta Checkpoint V2 is confused with a Structured Streaming checkpoint directory. They are separate mechanisms.

A carry illusion occurs when interest-rate difference is presented as expected profit without forward pricing, hedging, basis, costs, liquidity, and currency stress.

A CNY/CNH illusion occurs when the onshore-offshore basis is presented as freely executable arbitrage. Market access, instrument deliverability, conversion, settlement, entity eligibility, and regulation must be verified.

How the Databricks capabilities help

Lakeflow Connect standardi ➔ Lakeflow declarative pipel ➔ VARIANT stores evolving se ➔ Variant shredding improves ➔ Automatic Upgrades observe

Lakeflow Connect standardizes ingestion from enterprise SaaS, databases, files, and streams while placing connections and destination data under Unity Catalog governance.

Lakeflow declarative pipelines reduce manual orchestration and incrementally maintain raw, validated, and analytical datasets.

VARIANT stores evolving semi-structured source events while preserving their original fields.

Variant shredding improves common-path query performance by physically organizing repeated VARIANT fields for columnar reads.

Automatic Upgrades observes compatible workloads and safely applies recommended managed-table features without maintaining thousands of manual table-alter scripts.

Row tracking provides stable row identity and commit-version metadata for lineage and incremental processing use cases.

Checkpoint V2 improves Delta transaction-log checkpoint behavior under frequent and concurrent writes.

Deletion vectors reduce file-rewrite work for certain row-level changes when all clients support the table feature.

Unity Catalog provides permissions, lineage, managed tables, connections, and a common governance boundary.

Together, these capabilities allow a China trading desk to build a controlled research pipeline that connects enterprise context with market, curve, and carry data while distinguishing a headline rate differential from a complete, executable, and permitted net-carry hypothesis.

References

Databricks Free Edition ➔ Lakeflow Connect concepts ➔ Lakeflow query-based conne ➔ Lakeflow Spark Declarative