Data Engineering Interview Preparation #3: Building a Financial Data Pipeline with Python, DuckDB and Parquet

Summary: Learn about building a repeatable financial data engineering pipeline using Python, Pandas, NumPy and DuckDB. This post covers deterministic data generation, CSV ingestion, SQL transformations, canonical schema design, data-quality checks, Parquet export, and CSV-versus-Parquet validation.

Financial data engineering involves much more than loading records from a CSV file into a database. A reliable pipeline must handle source data consistently, maintain predictable schemas, validate records, and produce outputs that can be used confidently by downstream applications and analytical workflows.

In this hands-on exercise, I created a small but practical financial data pipeline using Python, Pandas, NumPy and DuckDB. We start with supplied CSV files, inspect and clean the source data, transform raw trade records into a canonical structure, apply data-quality checks, and export validated data to Parquet.

Run the hands-on notebook: DE Interview Prep #3: Financial Data Engineering on Kaggle. This is the third notebook in the Data Engineering interview-preparation series. You can also access the shared DataEngineering dataset on Kaggle and attach it to the notebook using Add Input.

The notebook uses three input files from the shared dataset:

  • financial_transactions.csv: a small deterministic transaction sample used for reproducibility and DuckDB ingestion.
  • raw_trades.csv: raw trade records used for canonical schema mapping and validation.
  • large_data.csv: a 25,000-row dataset used to compare CSV and Parquet storage.

Reproducible ingestion and execution

Reproducibility is an important requirement in data engineering. Given the same input data and execution environment, a pipeline should produce consistent results. This makes it easier to debug failures, validate transformations, compare results, and investigate data issues.

1. Dependency management

Python data pipelines commonly use libraries such as Pandas, NumPy and DuckDB. It is important to know which versions are installed and to document the dependencies required by the workflow.

In this notebook, the environment setup checks whether DuckDB is available and installs it when necessary. It also reports the installed library versions and creates a dependency manifest with minimum version requirements.

requirements_content = """
pandas>=2.2.0
duckdb>=1.3.0
numpy>=1.26.0
"""

These are minimum version requirements, not exact version pins. For a production deployment that requires stricter reproducibility, use exact package versions and a controlled environment or lockfile.

2. Deterministic data generation

Data engineering pipeline validations often use generated sample data to test ingestion and transformation logic. Without a fixed random seed, each execution may produce different values, making it harder to compare results.

The notebook uses seed 42 to recreate the supplied financial transaction amounts. It then compares the regenerated sample with the input CSV to verify that the data matches the expected values.

SEED = 42
rng = np.random.RandomState(SEED)

recreated_transactions = pd.DataFrame({
    "tx_id": range(100, 110),
    "amount": rng.uniform(10.0, 500.0, size=10),
})

The fixed seed makes the sample repeatable. The notebook also uses assertions to check that the regenerated transaction identifiers and amounts match the supplied data.

3. Idempotent execution and state management

Notebook environments retain variables and objects in memory while cells are executed. This can create problems when cells are run out of order or when an earlier result remains in memory after the code has changed.

A useful data engineering practice is to make ingestion and transformation operations idempotent. An idempotent operation can be executed repeatedly with the same input without creating unintended duplicate results.

For example, DuckDB supports CREATE OR REPLACE TABLE. The statement replaces an existing table instead of appending another copy of the same records.

CREATE OR REPLACE TABLE portfolio_raw AS
SELECT * FROM financial_transactions;

The notebook uses this approach for its raw and canonical tables. For reliable execution, run the notebook from the beginning in a clean session and verify that each stage completes without depending on manually executed cells.

DuckDB basics for data ingestion

DuckDB is an embedded analytical database that works directly with Python, Pandas, CSV and Parquet files. It is particularly useful for practical data engineering exercises because SQL queries can run inside the same notebook where the source data is loaded and inspected.

1. Load and clean CSV data

Before ingesting a CSV file, inspect its columns and identify fields that do not belong to the business dataset. For example, a Pandas DataFrame exported using the default index=True setting can contain an additional column such as Unnamed: 0.

This exported index is not necessarily a business identifier. The notebook detects and removes such index artifacts, then converts the transaction identifier and amount into explicit numeric types.

After cleaning the file, DuckDB can ingest the CSV using read_csv_auto. The function automatically detects the CSV structure and infers column types.

CREATE OR REPLACE TABLE raw_tx AS
SELECT *
FROM read_csv_auto(
    'financial_transactions_clean.csv',
    header = true
);

2. Inspect the schema

Schema inspection should be performed before building transformations. It helps identify unexpected column names, incorrect data types and other source-data issues.

DuckDB provides the DESCRIBE statement to inspect a table's structure.

DESCRIBE raw_tx;

The notebook displays the column names, inferred data types and nullability information. This provides a useful starting point before applying SQL transformations.

3. Filter and aggregate transaction data

SQL filtering and aggregation are common operations in financial data pipelines. Filtering selects records that meet specific conditions, while aggregation calculates summary metrics such as transaction count and total transaction volume.

In this exercise, we select transactions where tx_id is less than 106 and calculate the total amount and number of transactions.

SELECT
    SUM(amount) AS total_volume,
    COUNT(*) AS tx_count
FROM raw_tx
WHERE tx_id < 106
HAVING SUM(amount) > 100;

This query returns a single aggregate result for the filtered records. A GROUP BY amount clause is not required here because the objective is to calculate one total, not one result for each distinct transaction amount.

4. Export data to Parquet

Parquet is a columnar storage format commonly used in analytical data platforms and data lakes. It supports compression and efficient column-based access. Its actual storage and performance benefits depend on the dataset, compression settings and query patterns, so it is useful to measure the results rather than assume a fixed improvement.

DuckDB supports Parquet export through the COPY statement. In this notebook, the populated canonical table is written to a Parquet file using Zstandard compression.

COPY canonical_portfolio
TO 'portfolio_transactions.parquet'
(FORMAT PARQUET, COMPRESSION ZSTD);

The notebook verifies that the file exists, reads it back through DuckDB, and checks its row count and contents against the source table. This is important because successfully creating a file does not, by itself, prove that the exported data is correct.

Canonical data design for ingestion

Raw source systems often use inconsistent column names, abbreviations and data types. A canonical dataset provides a standardized structure that downstream transformations and analytical processes can rely on.

The objective is to separate the structure of the analytical data from inconsistencies in the original source files.

1. Map source fields to a stable schema

My raw_trades.csv file contains abbreviated source columns such as:

  • id: transaction identifier
  • dt: trade date
  • symbol: security symbol
  • qty: quantity
  • val: source value
  • status: trade status

The notebook maps these fields into a more descriptive canonical structure:

  • transaction_id
  • trade_date
  • ticker
  • share_count
  • price_usd
  • is_settled

Explicit casting ensures that the canonical table uses predictable data types. The status field is also converted into a Boolean value: S becomes TRUE, while P becomes FALSE.

CREATE OR REPLACE TABLE canonical_portfolio AS
SELECT
    CAST(id AS INTEGER) AS transaction_id,
    CAST(dt AS DATE) AS trade_date,
    CAST(symbol AS VARCHAR) AS ticker,
    CAST(qty AS DOUBLE) AS share_count,
    CAST(price_usd AS DOUBLE) AS price_usd,
    CASE
        WHEN status = 'S' THEN TRUE
        WHEN status = 'P' THEN FALSE
        ELSE NULL
    END AS is_settled
FROM raw_portfolio;

Note: the notebook maps the source field val to price_usd. This is a field mapping and type conversion, not an actual currency conversion. A real foreign-exchange conversion would require additional information, such as the source currency, target currency, applicable exchange rate and conversion date.

2. Follow predictable naming conventions

Consistent column naming improves readability and makes SQL transformations easier to maintain. The notebook demonstrates several useful naming conventions:

  • Identifiers: Use an _id suffix, such as transaction_id.
  • Dates: Use a descriptive _date suffix, such as trade_date.
  • Boolean fields: Use prefixes such as is_, as shown by is_settled.

Descriptive names make the canonical schema easier to understand and reduce ambiguity when data from multiple sources is combined.

If you want any of the following, send a message using the Contact Us (left pane) or message Inder P Singh (7 years' experience in Data Engineering, Gen AI, Agentic AI and ML) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

  • Production-oriented Data Engineering templates with playbooks
  • Working Data Engineering projects for your portfolio
  • Deep-dive hands-on Data Engineering Training
  • Data Engineering resume updates

Ingestion sanity checks and data quality

Successful ingestion does not automatically mean that the data is valid. Data-quality checks should run immediately after ingestion and before the data is used in downstream transformations.

The notebook applies several checks to the raw trade data. These checks help detect missing identifiers, duplicate records, invalid values and unexpected status codes.

1. Row count and schema checks

A row count check verifies that the target table contains data. Schema inspection helps identify whether expected columns exist and whether their data types are appropriate for subsequent transformations.

The notebook also converts source fields into explicit types while constructing the canonical table. This reduces the risk of downstream logic depending on inconsistent source representations.

2. Null and duplicate checks

Mandatory identifiers should not be missing. Duplicate transaction identifiers can also lead to incorrect totals or repeated business records, depending on the source system's data contract.

The notebook checks for null transaction IDs and calculates the number of duplicate identifier rows.

row_count = con.execute(
    "SELECT COUNT(*) FROM raw_trades"
).fetchone()[0]

null_id_count = con.execute(
    "SELECT COUNT(*) FROM raw_trades WHERE id IS NULL"
).fetchone()[0]

duplicate_id_rows = con.execute("""
    SELECT COUNT(*) - COUNT(DISTINCT id)
    FROM raw_trades
""").fetchone()[0]

3. Validate values and status codes

Business rules should be translated into executable checks wherever possible. For example, a transaction value should not be negative, and the source status should belong to an expected set of values.

The notebook uses assertions to stop execution when key validation rules fail.

assert row_count > 0
assert null_id_count == 0
assert duplicate_id_rows == 0
assert minimum_value is not None and minimum_value >= 0
assert observed_statuses.issubset(allowed_statuses)

This approach prevents invalid records from silently progressing through the example pipeline. In a production system, additional checks could cover freshness, schema changes, business-specific constraints, referential integrity and reconciliation against source totals.

Notebook engineering for repeatable pipelines

A well-designed data engineering notebook should be easy to read, execute, debug and maintain. Notebook engineering means treating the notebook as a structured data workflow rather than as an unorganized collection of code cells.

1. Use modular cells

Each cell should perform a focused task, such as loading source data, applying a transformation, inspecting a schema or validating a result. Smaller cells make failures easier to isolate and help another engineer understand the sequence of operations.

My Kaggle notebook follows this approach by separating environment setup, input discovery, data loading, deterministic sampling, DuckDB ingestion, canonicalization, validation and export into distinct stages.

2. Use Markdown for documentation

Markdown cells explain the purpose of each stage and provide context for the code that follows. A clear heading structure makes the notebook easier to navigate and helps readers understand the complete pipeline.

A practical structure includes:

  • Environment setup: Import libraries and record dependency versions.
  • Input discovery and ingestion: Locate the source files and load the raw data.
  • Transformation: Clean the data, inspect schemas and create canonical structures.
  • Validation: Run sanity checks and verify important business rules.
  • Export: Write validated data to Parquet and verify the result.

3. Execute the notebook from beginning to end

A notebook should not depend on variables left over from previous executions or on cells being run in a particular manual order. Execute it from the first cell to the last cell in a clean runtime to verify that the complete workflow is reproducible.

Idempotent SQL operations, such as CREATE OR REPLACE TABLE, help make repeated execution predictable. Avoid relying on old in-memory objects or tables that were created by an earlier, incomplete run.

4. Add quick verification checks

After an important operation, verify that it succeeded before moving to the next stage. Useful checks include printing the row count, displaying a small data sample, inspecting the schema, confirming that an output file exists and using assertions to validate expected results.

These quick checks act as smoke tests. They provide early feedback and make it easier to locate the stage where an unexpected result was introduced.

CSV versus Parquet: Compare storage and data integrity

The notebook includes a separate comparison using the 25,000-row large_data.csv input. It writes the data to CSV and compressed Parquet, then reports the resulting file sizes.

The comparison uses the user_id, status and score fields. It also reads both files back and checks that the row counts and values match the original dataset.

Note: a smaller output file is not necessarily a correct output file. File-size measurements should be accompanied by data-integrity checks, particularly when a new storage format is introduced into a pipeline.

What to practise for a Data Engineering interview

After running the notebook, try answering these questions in your own words:

  • Why should a DataFrame's default index normally be excluded when exporting business data to CSV?
  • What is the difference between CREATE TABLE and CREATE OR REPLACE TABLE in a repeatable ingestion workflow?
  • Why is GROUP BY amount unnecessary for a single aggregate over filtered transactions?
  • Why should a canonical table be populated and validated before it is exported to Parquet?
  • How would you handle duplicate transaction IDs if they were allowed across different source systems?
  • Why should a CSV-versus-Parquet comparison include round-trip validation instead of only comparing file sizes?
  • What additional information would be required to implement a genuine currency conversion?

The point is that a reliable data pipeline requires more than successful ingestion. It needs repeatable execution, clear schemas, controlled transformations, automated validation and verified outputs. These are practical data engineering habits that can be demonstrated in a small notebook and extended to larger production workflows.

Continue the Data Engineering interview-preparation series:

Run the notebook, experiment with the queries, modify the validation rules and use the interview checkpoints to test your understanding. The objective is to build practical Data Engineering skills through runnable examples.

Comments

Popular posts from this blog

Generative AI Chatbot to learn about Generative AI by Inder P Singh

The Internet of Things (IoT): Connecting the Physical to the Digital World for a Better Future

Machine Learning in the Fourth Industrial Revolution