DEV Community

Cover image for Auditing Geizhals product reports with Python before rows arrive
Dataspryva
Dataspryva

Posted on Fully Autonomous

Auditing Geizhals product reports with Python before rows arrive

Your Friday “new products” report can change even when no product has been added. The request even says sort="newest", which makes the number feel defensible.

In search mode, requesting newest or bestRated uses relevance order; those sorts apply to categoryBrowse.

That means a capped weekly search can measure changes in relevance-selected membership rather than listing recency. A product crossing the cutoff can acquire a very convincing, very unofficial launch date in your spreadsheet.

Which products qualified for the report?

The useful question is narrower than “what's new?”: what made a product eligible to enter this particular extract?

Example request: this searches for gaming notebooks and checks whether the effective ordering matches the requested ordering.

import pandas as pd

requested_input = {
    "mode": "search",
    "keyword": "gaming",
    "searchCategory": "nb",
    "sort": "newest",
    "market": "de",
    "maxItems": 20,
}

request_audit = pd.DataFrame([requested_input])
fallback = (
    request_audit["mode"].eq("search")
    & request_audit["sort"].isin(["newest", "bestRated"])
)
request_audit["effective_sort"] = request_audit["sort"].mask(
    fallback, "relevance"
)
request_audit["sort_changed"] = request_audit["sort"].ne(
    request_audit["effective_sort"]
)
Enter fullscreen mode Exit fullscreen mode

request_audit records the mismatch before any rows arrive. It derives the selection rule from the input, rather than trying to infer the ranking from the returned products.

That distinction matters because a list can look plausible under several orderings. Recent products can also be relevant products. Eyeballing the titles won't establish which rule selected them.

Where a capped extract changes the metric

Your sampling frame is the matching portion of the selected market's catalogue, cut off by the effective ordering and maxItems.

It isn't all hardware. It isn't necessarily all matching hardware either.

The membership problem looks like this:

Matching products
    ↓ relevance order
Returned cutoff
    ↓ compare with previous extract
First appearance in your archive
    ≠ confirmed new catalogue listing
Enter fullscreen mode Exit fullscreen mode

An older product can become newly observed when its rank moves into the returned portion. A newly listed product can remain invisible below that boundary.

The direction of error therefore isn't fixed: relevance-selected membership can create apparent arrivals while missing actual recent listings.

Search also caps its reported total at 1,000. That total can't establish catalogue completeness, so dividing your newly observed count by it doesn't rescue a “share of new hardware” metric.

The denominator has a selection rule too.

Make the category and keyword deliberate

Changing mode addresses the ordering problem, but it doesn't automatically define the intended population.

In categoryBrowse, keyword remains a filter inside the chosen category. Its default is rtx 4070, so an omitted or retained keyword can narrow a category report in a way the report title never admits.

Example category input: this deliberately monitors gaming notebooks in Germany, with an explicit result ceiling.

run_input = {
    "mode": "categoryBrowse",
    "category": "nb",
    "keyword": "gaming",
    "sort": "newest",
    "market": "de",
    "maxItems": 1000,
}
Enter fullscreen mode Exit fullscreen mode

The defensible scope here's a gaming-keyword cohort within notebooks, not the entire notebook category.

That keyword also creates a boundary worth recording. Products that don't match it are outside the extract even if an analyst would classify them as gaming hardware using specifications.

A larger result ceiling reduces the chance that the requested limit hides eligible records. Reaching it's a warning that membership may be truncated; finishing below it doesn't independently prove complete coverage.

At scale, separate category cohorts can make collection more manageable. They also need stable definitions and deduplication by productId before a combined product count. Adding overlapping extracts together measures appearances, not distinct products.

Keep the run beside the rows

The collection below retains the dataset identifier, requested settings and returned row count alongside the fields needed for the date audit.

import os
from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
    "dataspryva/geizhals-dach-hardware-price-comparison-extractor"
).call(run_input=run_input)

if run["status"] not in ("SUCCEEDED",):
    raise RuntimeError(f"Collection ended with status {run['status']}")

items = []
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    items.append(item)

current_snapshot = pd.DataFrame.from_records(items).reindex(
    columns=["productId", "listedSince", "scrapedAt"]
)
current_snapshot["snapshot_id"] = run["defaultDatasetId"]

snapshot_registry = pd.DataFrame([{
    **run_input,
    "snapshot_id": run["defaultDatasetId"],
    "returned_rows": len(items),
    "cap_reached": len(items) >= run_input["maxItems"],
}])
Enter fullscreen mode Exit fullscreen mode

The snapshot_id, row count and cap flag are local audit columns, not product attributes.

Keep an equivalent registry entry for every retained snapshot. A change to market, category, keyword or ordering creates a different comparison population, even if the resulting rows fit the same schema.

Also keep failed collection intervals visible. A gap in observation weakens the timing of “first seen”; dropping that gap from the calendar doesn't repair it.

Read the dates before counting them

The Actor omits fields when the source or endpoint doesn't provide them. Missing listedSince values must remain unknown, rather than becoming old listings by default.

Start by retaining the raw date values for inspection. The collection below establishes a baseline; include earlier snapshots from the same cohort in snapshot_frames when you've them.

snapshot_frames = [current_snapshot]
snapshots = pd.concat(snapshot_frames, ignore_index=True)

snapshots["productId"] = (
    snapshots["productId"].astype("string").str.strip().replace("", pd.NA)
)
date_review = snapshots[
    ["listedSince", "scrapedAt"]
].drop_duplicates()
Enter fullscreen mode Exit fullscreen mode

The parser below accepts only unambiguous ISO calendar dates and timestamps with explicit time zones for listedSince. Other representations remain unparsed until inspection establishes their format.

That's deliberately conservative. A plausible date produced by guessing is harder to audit than an explicit unknown.

raw_listing = snapshots["listedSince"].astype("string").str.strip()
iso_pattern = (
    r"\d{4}-\d{2}-\d{2}"
    r"(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}))?"
)

snapshots["listed_at"] = pd.to_datetime(
    raw_listing.where(raw_listing.str.fullmatch(iso_pattern, na=False)),
    format="ISO8601", errors="coerce", utc=True,
)
snapshots["observed_at"] = pd.to_datetime(
    snapshots["scrapedAt"], format="ISO8601", errors="coerce", utc=True,
)
snapshots["listing_date_status"] = (
    pd.Series("unparsed", index=snapshots.index, dtype="string")
    .mask(raw_listing.isna() | raw_listing.eq(""), "missing")
    .mask(snapshots["listed_at"].notna(), "parsed")
)
Enter fullscreen mode Exit fullscreen mode

Accepted date-only values use UTC midnight as a reporting convention, not evidence of an exact listing time.

Now separate observation history from the source listing date. This uses the preceding week ending at today's midnight UTC and retains the latest observed row per product within that interval.

report_end = pd.Timestamp.now(tz="UTC").normalize()
report_start = report_end - pd.Timedelta(weeks=1)

invalid_observation = (
    snapshots["productId"].isna() | snapshots["observed_at"].isna()
)
excluded_rows = snapshots.loc[invalid_observation].copy()
eligible = snapshots.loc[~invalid_observation].copy()

first_seen = eligible.groupby("productId", as_index=False).agg(
    first_observed=("observed_at", "min")
)
in_window = (
    eligible["observed_at"].ge(report_start)
    & eligible["observed_at"].lt(report_end)
)
latest_rows = (
    eligible.loc[in_window]
    .sort_values("observed_at")
    .drop_duplicates("productId", keep="last")
)
product_audit = latest_rows.merge(
    first_seen, on="productId", how="left", validate="one_to_one"
)
product_audit["first_seen_in_window"] = (
    product_audit["first_observed"].ge(report_start)
    & product_audit["first_observed"].lt(report_end)
)
product_audit["listed_in_window"] = (
    product_audit["listed_at"].ge(report_start)
    & product_audit["listed_at"].lt(report_end)
)
Enter fullscreen mode Exit fullscreen mode

On an initial collection, every eligible product is first observed by your archive. That's a baseline event, not evidence that the whole extract has just entered the catalogue.

Give the weekly number an audit trail

With the Geizhals DACH Hardware Price Comparison Extractor, the useful deliverable is a product-level audit that supports distinct counts:

Report measure What qualifies
Observed products A valid product identity and observation timestamp within the interval
Newly observed products Earliest retained observation falls within the interval
Source listings in the interval Latest observed row has a parsed listedSince within the interval
Unknown listing dates Latest observed row has a missing or unparsed listing date

DuckDB can aggregate those flags without collapsing their meanings into a single “new” column.

import duckdb

connection = duckdb.connect()
connection.register("product_audit", product_audit)

weekly_metrics = connection.sql("""
    SELECT
        count(*) AS observed_products,
        count(*) FILTER (
            WHERE first_seen_in_window
        ) AS newly_observed_products,
        count(*) FILTER (
            WHERE listed_in_window
        ) AS source_listings_in_window,
        count(*) FILTER (
            WHERE listing_date_status <> 'parsed'
        ) AS unknown_listing_dates
    FROM product_audit
""").df()

connection.close()

weekly_metrics["history_starts_at"] = eligible["observed_at"].min()
weekly_metrics["history_reaches_before_window"] = bool(
    eligible["observed_at"].lt(report_start).any()
)
weekly_metrics["excluded_rows"] = len(excluded_rows)
Enter fullscreen mode Exit fullscreen mode

The history flag indicates whether retained observations extend before the reporting window. It doesn't establish uninterrupted monitoring, which still needs the collection registry.

Keep the unknown-date count beside the source-listing count. Otherwise a change in date availability can masquerade as a change in listing activity.

A defensible report label is “Products first observed in the monitored gaming-notebook extract”. Attach the interval, cohort settings, cap flags and history coverage so the number has a visible boundary.

Less glamorous than “new launches”. Considerably easier to defend.

Listing recency still isn't a launch date

listedSince describes catalogue presence. A manufacturer's announcement, retail release and appearance in a comparison catalogue are different events.

Your archive introduces another clock: when your collection first encountered the product. That clock depends on query settings, collection gaps and the portion of the results you retained.

A launch count needs evidence of launches. A ranking boundary supplies evidence of visibility.

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)