Synthetic Financial Data Generation with SDT Tutorial

In modern banking, fintech, and quantitative analytics, data teams face a constant bottleneck: production financial records are locked behind strict privacy and compliance regulations such as GDPR, PCI-DSS, and internal data governance policies. Yet machine learning engineers, QA pipelines, and external auditors still need realistic transaction logs, credit profiles, and account balances to build fraud detectors, test ETL pipelines, and validate risk models. Simple anonymization—such as hashing customer IDs or adding random noise—either leaves re-identification risks intact or destroys the cross-column correlations that make the data useful.

Synthetic data generation solves this problem by learning the joint statistical structure of a sensitive dataset and generating brand-new, artificial records that contain zero real customer identities. However, raw statistical generators often struggle with financial data because monetary amounts are heavily right-skewed and account fields must obey strict accounting identities. This tutorial explains how Synthetic Data Transformation (SDT) patterns wrap around SDV (Synthetic Data Vault) synthesizers to preserve domain invariants, shows how to configure metadata and constraints, and builds a complete Python pipeline that generates, validates, and audits synthetic financial transactions.

What Is Synthetic Data Transformation (SDT)?

Synthetic Data Transformation (SDT) is a deterministic pre-processing and post-processing architecture applied around generative tabular models. Instead of feeding raw financial columns directly into a copula or neural synthesizer, SDT transforms skewed and constrained variables into clean, unconstrained representations before training, and maps generated samples back into valid business units afterward.

It is often compared with two older test-data techniques. While all three aim to supply non-production environments with data, they solve very different problems:

ApproachQuestion it answersHow it worksWeakness on its own
Rule-based mocking (Faker)Does the schema look right?Generates names, dates, and numbers independently from random distributionsMisses cross-column correlations such as income vs. credit limit
Data masking / subsettingCan we reuse sanitized production rows?Redacts PII columns or samples a small slice of real recordsVulnerable to linkage attacks; shrinks rare fraud classes
Generative synthesis + SDTCan we mirror real statistical behavior safely?Learns joint distributions in a transformed feature space and enforces invariantsRequires metadata setup, transformation logic, and quality gates

The key difference is that rule-based generators produce structurally valid noise, while generative synthesis paired with SDT preserves joint multivariate relationships (such as higher transaction-to-limit ratios correlating with fraud) while guaranteeing 100% mathematical compliance with financial rules.

Two Layers of the Financial Synthesis Stack

A production synthetic financial data pipeline separates statistical learning from deterministic domain rules:

  • SDT (Synthetic Data Transformation) layer: Handles reversible mathematical mappings—such as log1p scaling for heavy-tailed wire transfers and ratio parameterization (utilization_ratio = current_balance / credit_limit)—so the model never generates impossible states like a balance exceeding a credit limit.
  • SDV (Synthetic Data Vault) synthesizer layer: Learns the joint probability distribution across all transformed columns using statistical copulas (GaussianCopulaSynthesizer) or deep generative networks (CTGANSynthesizer, TVAESynthesizer), supporting conditional sampling for rare events.

The Five Pillars of Synthetic Financial Data Quality

Before releasing a synthetic dataset to downstream analytics or ML teams, every generated table should pass five core quality checks:

PillarQuestionTypical metricExample failure it catches
Domain InvariantsDo accounting equations hold?Violation count (balance > limit, amount <= 0)A synthetic card account has a $12,000 balance on a $5,000 limit
Marginal FidelityDoes each column match real distributions?Kolmogorov-Smirnov (KS) complement (1 - KS)Transaction amounts cluster around the median and miss large transfers
Correlation PreservationAre cross-column relationships intact?Mean Absolute Error (MAE) of correlation matricesCredit limits no longer scale with annual income or account tier
Downstream UtilityCan ML models train on synthetic data?Train-on-Synthetic, Test-on-Real (TSTR) PR-AUCFraud classifier trained on synthetic rows fails on real transactions
Privacy ProtectionAre real customer records safe from memorization?Distance to Closest Record (DCR) and exact-match countA synthetic row duplicates an actual customer's exact financial profile

Domain Invariants

Financial tables contain hard mathematical relationships. A credit card's current_balance cannot exceed its credit_limit, tx_amount must be strictly positive, and annual_income must sit above minimum underwriting thresholds. Post-hoc clipping (forcing any balance above the limit down to 100%) creates an artificial spike right at the boundary. Parameterizing ratios inside the SDT layer preserves smooth, realistic distributions.

Marginal Fidelity

Marginal fidelity measures how closely the distribution of each individual synthetic column matches the real dataset. For continuous financial features like transaction amounts, the two-sample Kolmogorov-Smirnov (KS) statistic compares the empirical cumulative distribution functions of the real and synthetic columns. A complement score (1 - KS) above 0.85 indicates strong distributional alignment.

Correlation Preservation

Even when every single column looks realistic on its own, a dataset is useless for risk modeling if correlations break down. Pairwise Pearson or Spearman correlation matrices verify that key economic drivers—such as account tier driving income, income driving credit limit, and international high-value transactions driving fraud probability—remain consistent.

Downstream Utility (TSTR)

The ultimate test for machine learning workflows is Train on Synthetic, Test on Real (TSTR). A fraud detection or credit scoring model is trained exclusively on the synthetic dataset and evaluated against a held-out real test split. Comparing TSTR performance against a baseline model trained on real data (TRTR) quantifies how much predictive signal transferred safely.

Privacy Protection

Generative models with high capacity can occasionally memorize outlier rows from small training tables. Measuring the Euclidean Distance to Closest Record (DCR) between standardized synthetic rows and real training rows ensures that generated records lie near the true data manifold without replicating real individuals.

How an SDT + SDV Financial Pipeline Works

Whether you build a custom Python module or deploy an automated data-sharing service, the workflow follows six steps:

  1. Profile schema and PII. Identify primary keys, customer identifiers, timestamps, categorical flags, and continuous monetary columns.
  2. Apply SDT pre-transformations. Compress skewed monetary amounts with log1p and convert bounded balances into [0, 1] utilization ratios.
  3. Configure SDV metadata. Register primary keys and regex formats for IDs so the generative model never attempts to memorize high-cardinality identifiers.
  4. Fit the synthesizer. Train a GaussianCopulaSynthesizer (for fast continuous portfolios) or CTGANSynthesizer (for complex multi-modal fraud patterns) on the transformed table.
  5. Sample and inverse-transform. Generate synthetic rows—optionally oversampling rare fraud classes via conditional sampling—and apply the inverse SDT mapping to restore original financial units.
  6. Run quality and privacy gates. Verify zero invariant violations, check KS and correlation drift, and confirm healthy DCR privacy distances before publishing.

Installing Dependencies and Structuring Metadata

The implementation requires sdv alongside standard scientific Python libraries:

Bash
pip install sdv pandas numpy scipy scikit-learn

When configuring SDV metadata, always separate synthetic identifier generation from statistical modeling:

Python
SDV metadata setup for financial transaction tables
from sdv.metadata import SingleTableMetadata


def build_financial_metadata(transformed_df):
    """Define semantic types and anonymized ID formats for SDV."""
    metadata = SingleTableMetadata()
    metadata.detect_from_dataframe(data=transformed_df)

    # Anonymized identifiers with deterministic regex patterns
    metadata.update_column(column_name="transaction_id", sdtype="id", regex_format="TX_[0-9]{8}")
    metadata.update_column(column_name="customer_id", sdtype="id", regex_format="CUST_[0-9]{6}")
    metadata.set_primary_key(column_name="transaction_id")

    # Explicit categorical flags
    metadata.update_column(column_name="is_international", sdtype="categorical")
    metadata.update_column(column_name="is_fraud", sdtype="categorical")

    metadata.validate()
    return metadata

Python End-to-End Synthetic Financial Data Pipeline

The script below puts all components together. It generates a realistic 5,000-row seed transaction dataset with domain correlations, transforms it through FinancialSDTTransformer, trains an SDV GaussianCopulaSynthesizer, performs conditional sampling for rare fraud scenarios, and runs automated fidelity and privacy checks.

Python
Python script implementing SDT transformations, SDV synthesis, conditional fraud sampling, and validation checks
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
from sklearn.metrics import pairwise_distances
from sklearn.preprocessing import StandardScaler
from sdv.metadata import SingleTableMetadata
from sdv.sampling import Condition
from sdv.single_table import GaussianCopulaSynthesizer


def build_seed_financial_data(n_rows=5_000, seed=42):
    """Create a realistic retail banking transaction dataset with domain correlations."""
    rng = np.random.default_rng(seed)

    account_tier = rng.choice(["Standard", "Gold", "Platinum"], size=n_rows, p=[0.60, 0.28, 0.12])
    tier_income = {"Standard": 48_000, "Gold": 85_000, "Platinum": 155_000}
    annual_income = np.array([
        max(18_000.0, rng.normal(tier_income[t], tier_income[t] * 0.22))
        for t in account_tier
    ]).round(2)

    tier_mult = {"Standard": 0.25, "Gold": 0.40, "Platinum": 0.60}
    credit_limit = np.array([
        round(inc * tier_mult[t] * rng.uniform(0.85, 1.15), -2)
        for inc, t in zip(annual_income, account_tier)
    ])

    # Current balance strictly bounded by credit limit
    utilization = rng.beta(a=2.0, b=5.0, size=n_rows)
    current_balance = (credit_limit * utilization).round(2)

    # Right-skewed transaction amounts
    tx_amount = np.clip(np.exp(rng.normal(loc=3.8, scale=1.15, size=n_rows)), 1.50, 25_000.00).round(2)
    merchant_category = rng.choice(
        ["Groceries", "Dining", "Electronics", "Travel", "Utilities", "Online_Retail"],
        size=n_rows,
        p=[0.28, 0.22, 0.12, 0.10, 0.13, 0.15],
    )
    is_international = rng.choice([0, 1], size=n_rows, p=[0.91, 0.09])

    # Fraud probability driven by transaction-to-limit ratio and international risk
    risk_logit = (
        -5.2
        + 0.00035 * tx_amount
        + 1.6 * is_international
        + np.isin(merchant_category, ["Electronics", "Online_Retail"]).astype(float) * 0.9
        + (tx_amount / np.maximum(credit_limit, 1.0)) * 3.5
    )
    fraud_prob = np.clip(1.0 / (1.0 + np.exp(-risk_logit)), 0.001, 0.85)
    is_fraud = rng.binomial(1, fraud_prob)

    return pd.DataFrame({
        "transaction_id": [f"TX_{i:08d}" for i in range(1, n_rows + 1)],
        "customer_id": [f"CUST_{i:06d}" for i in range(1, n_rows + 1)],
        "timestamp": pd.date_range("2026-01-01", periods=n_rows, freq="3min"),
        "account_tier": account_tier,
        "annual_income": annual_income,
        "credit_limit": credit_limit,
        "current_balance": current_balance,
        "tx_amount": tx_amount,
        "merchant_category": merchant_category,
        "is_international": is_international,
        "is_fraud": is_fraud,
    })


class FinancialSDTTransformer:
    """Deterministic pre- and post-processor for financial tabular invariants."""

    CANONICAL_COLUMNS = [
        "transaction_id",
        "customer_id",
        "timestamp",
        "account_tier",
        "annual_income",
        "credit_limit",
        "current_balance",
        "tx_amount",
        "merchant_category",
        "is_international",
        "is_fraud",
    ]

    def fit_transform(self, df):
        out = df.copy()
        out["log_tx_amount"] = np.log1p(out["tx_amount"])
        out["log_annual_income"] = np.log1p(out["annual_income"])
        out["utilization_ratio"] = np.clip(
            out["current_balance"] / np.maximum(out["credit_limit"], 1.0),
            0.0,
            1.0,
        )
        return out.drop(columns=["tx_amount", "annual_income", "current_balance"])

    def inverse_transform(self, synth_df):
        out = synth_df.copy()
        out["tx_amount"] = np.maximum(1.00, np.expm1(out["log_tx_amount"])).round(2)
        out["annual_income"] = np.maximum(12_000.00, np.expm1(out["log_annual_income"])).round(2)
        clipped_ratio = np.clip(out["utilization_ratio"], 0.0, 1.0)
        out["current_balance"] = (out["credit_limit"] * clipped_ratio).round(2)
        out = out.drop(columns=["log_tx_amount", "log_annual_income", "utilization_ratio"])
        return out[self.CANONICAL_COLUMNS]


def validate_synthetic_data(real_df, synth_df):
    """Evaluate business invariants, statistical fidelity, and privacy distance."""
    num_cols = ["annual_income", "credit_limit", "current_balance", "tx_amount"]

    balance_violations = int((synth_df["current_balance"] > synth_df["credit_limit"]).sum())
    amount_violations = int((synth_df["tx_amount"] <= 0).sum())

    ks_similarity = {
        col: round(1.0 - ks_2samp(real_df[col], synth_df[col]).statistic, 4)
        for col in num_cols
    }

    corr_mae = float(np.mean(np.abs(real_df[num_cols].corr().values - synth_df[num_cols].corr().values)))

    scaler = StandardScaler()
    real_scaled = scaler.fit_transform(real_df[num_cols].sample(min(1000, len(real_df)), random_state=7))
    synth_scaled = scaler.transform(synth_df[num_cols].sample(min(1000, len(synth_df)), random_state=7))
    min_dists = pairwise_distances(synth_scaled, real_scaled).min(axis=1)

    print("Synthetic Financial Data Quality Report")
    print(f"  Invariant violations: balance_over_limit={balance_violations}, non_positive_tx={amount_violations}")
    print(f"  Marginal KS similarity: {ks_similarity}")
    print(f"  Correlation matrix MAE: {corr_mae:.4f}")
    print(f"  Privacy median DCR: {np.median(min_dists):.4f} (exact matches: {int((min_dists < 1e-4).sum())})")


if __name__ == "__main__":
    real_data = build_seed_financial_data()
    sdt = FinancialSDTTransformer()
    transformed_data = sdt.fit_transform(real_data)

    metadata = SingleTableMetadata()
    metadata.detect_from_dataframe(data=transformed_data)
    metadata.update_column(column_name="transaction_id", sdtype="id", regex_format="TX_[0-9]{8}")
    metadata.update_column(column_name="customer_id", sdtype="id", regex_format="CUST_[0-9]{6}")
    metadata.set_primary_key(column_name="transaction_id")
    metadata.update_column(column_name="is_international", sdtype="categorical")
    metadata.update_column(column_name="is_fraud", sdtype="categorical")

    synthesizer = GaussianCopulaSynthesizer(
        metadata=metadata,
        enforce_min_max_values=True,
        enforce_rounding=True,
        default_distribution="norm",
    )
    synthesizer.fit(transformed_data)

    # Standard population sampling + inverse SDT
    synthetic_data = sdt.inverse_transform(synthesizer.sample(num_rows=5_000))
    validate_synthetic_data(real_data, synthetic_data)

    # Conditional sampling to augment rare international fraud cases
    fraud_condition = Condition(num_rows=250, column_values={"is_fraud": 1, "is_international": 1})
    synthetic_fraud = sdt.inverse_transform(synthesizer.sample_from_conditions([fraud_condition]))
    print(f"Generated {len(synthetic_fraud)} conditional fraud records (mean tx: ${synthetic_fraud['tx_amount'].mean():,.2f}).")

Output

Running the script prints the quality and privacy audit summary:

TEXT
Synthetic Financial Data Quality Report
  Invariant violations: balance_over_limit=0, non_positive_tx=0
  Marginal KS similarity: {'annual_income': 0.9712, 'credit_limit': 0.9648, 'current_balance': 0.9584, 'tx_amount': 0.9690}
  Correlation matrix MAE: 0.0184
  Privacy median DCR: 0.3412 (exact matches: 0)
Generated 250 conditional fraud records (mean tx: $1,482.65).

How the Pipeline Works

  • build_seed_financial_data() creates 5,000 realistic banking transactions where annual_income scales with account_tier, credit_limit scales with income, current_balance stays strictly within the credit limit, and is_fraud responds to high transaction-to-limit ratios and international flags.
  • FinancialSDTTransformer.fit_transform() applies log1p compression to heavy-tailed monetary columns (tx_amount, annual_income) and replaces current_balance with utilization_ratio bounded in [0, 1]. Because the transformed distributions are near-normal and unconstrained, the copula model fits accurately without boundary distortion.
  • GaussianCopulaSynthesizer models marginal distributions and pairwise correlations across the transformed feature space, while SingleTableMetadata ensures transaction_id and customer_id are generated from regex patterns rather than memorized.
  • FinancialSDTTransformer.inverse_transform() maps generated log values back to currency units via expm1 and reconstructs current_balance = credit_limit * utilization_ratio, guaranteeing zero accounting violations.
  • sample_from_conditions() generates 250 targeted international fraud rows so ML teams can balance minority classes during classifier training without oversampling real customer records.
  • validate_synthetic_data() acts as an automated release gate, checking invariant violations, marginal KS similarity, correlation drift MAE, and Distance to Closest Record (DCR).

Choosing the Right Synthesizer

Different financial datasets call for different generative architectures behind the SDT layer:

SynthesizerMechanismBest suited forTrade-off
GaussianCopulaSynthesizerParametric marginals + multivariate Gaussian copulaCredit portfolios, loan books, continuous financial tablesFast CPU training; assumes monotonic rank correlations
CTGANSynthesizerConditional Tabular GAN with mode-specific normalizationComplex multi-modal fraud logs, high-cardinality merchant categoriesCaptures non-linear clusters; needs larger datasets and more compute
TVAESynthesizerTabular Variational AutoencoderSmooth continuous distributions with mixed categorical attributesFaster convergence than GANs; slightly narrower tail coverage

Best Practices for Synthetic Financial Data

  • Transform accounting identities before training. Encode ratio invariants (balance / limit, principal + interest = total_payment) inside the SDT layer instead of clipping out-of-bounds values after sampling.
  • Exclude real identifiers from statistical learning. Always mark account numbers, SSNs, emails, and transaction IDs as id or anonymized PII fields in metadata so they are never fed into the generative distribution.
  • Use conditional sampling responsibly. When generating balanced datasets for fraud model training, document the synthetic class ratio clearly and always evaluate final model metrics on an unaugmented, real holdout test set.
  • Automate statistical and privacy gates in CI/CD. Block synthetic dataset publication if marginal KS similarity drops below 0.85, correlation MAE exceeds 0.05, or any exact-row matches appear in the DCR check.
  • Match synthesizer capacity to table size. Use GaussianCopulaSynthesizer for reference tables under 2,000 rows; reserve deep generative models (CTGANSynthesizer) for larger datasets where neural networks can generalize without memorizing outliers.

Common Mistakes

  • Training directly on raw heavy-tailed currency columns: without log1p scaling in the SDT layer, synthesizers struggle to capture both $5 coffee purchases and $20,000 wire transfers in the same column.
  • Post-hoc clipping of violated constraints: clamping current_balance to credit_limit after generation creates an artificial pile-up at 100% utilization instead of preserving natural beta-like utilization curves.
  • Evaluating synthetic data by visual inspection alone: a table can look plausible in the first ten rows while silently losing the correlation between credit utilization and default risk.
  • Testing ML models on synthetic validation splits: evaluating a fraud classifier on synthetic test rows inflates precision and recall; always measure utility on held-out real records (TSTR).
  • Skipping privacy distance checks on small cohorts: high-net-worth or rare-merchant cohorts have fewer neighbors in feature space and require explicit DCR auditing before sharing.

Summary

Synthetic Data Transformation (SDT) turns generative tabular modeling into a reliable engineering pattern for regulated financial teams. By pairing reversible mathematical transformations (log1p scaling and bounded ratio parameterization) with SDV synthesizers and automated quality gates, data engineers can produce privacy-preserving datasets that respect accounting rules and preserve multivariate risk correlations. Start by identifying your table's core domain invariants, wrap them in a deterministic SDT transformer, and enforce statistical fidelity and DCR privacy thresholds before every release.