<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Piotr Gruszecki on Medium]]></title>
        <description><![CDATA[Stories by Piotr Gruszecki on Medium]]></description>
        <link>https://medium.com/@piotr.gruszecki_22364?source=rss-c2cbb15c14cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z6VMDOS8w5LdqFpJ3xW3Wg.jpeg</url>
            <title>Stories by Piotr Gruszecki on Medium</title>
            <link>https://medium.com/@piotr.gruszecki_22364?source=rss-c2cbb15c14cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:24:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@piotr.gruszecki_22364/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testing Snowflake’s Newest Features When They Haven’t Reached Your Region Yet]]></title>
            <link>https://medium.com/@piotr.gruszecki_22364/testing-snowflakes-newest-features-when-they-haven-t-reached-your-region-yet-3e294565d6c0?source=rss-c2cbb15c14cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e294565d6c0</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Piotr Gruszecki]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 14:14:40 GMT</pubDate>
            <atom:updated>2026-06-24T11:53:28.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*9sAopOcsIj9n4huIebaTFw.png" /></figure><p>A week after Snowflake Summit, my feed was full of features I wanted to try. Some of them weren’t live in my region yet — and that may well be your situation too. So what do you do when the thing you want to test hasn’t reached your region? Every vendor rolls out region by region; some regions simply get new capabilities weeks before others. Anyone who has worked with cloud platforms knows the rhythm. I went and checked what my options were.</p><p>None of this is a setup I engineered to look clever — it’s just how things are. We work with a range of clients, and each Snowflake account sits wherever makes business sense; for this one, that’s Frankfurt (AWS eu-central-1), on Enterprise. Data residency, contracts, latency — settled, and not what this piece is about. The other plain fact: Snowflake rolls features out region by region, so Oregon gets some of them weeks before Frankfurt. Put the two together, and the question is narrow and practical — how do I get a few real datasets somewhere I can safely try the new features? No grand discovery here, just an engineering path through an everyday situation.</p><h3>Why a trial account in Oregon</h3><p>Testing happens off production. Not because safeguards are impossible — resource monitors, credit limits, a separate warehouse would all work — but that’s disproportionate configuration effort for what are essentially unit-scale tests. And the decisive argument: the features I want to evaluate aren’t in my production region anyway. So: a trial account in a region where features land first. Closed, limited, fully isolated. If an experiment fails and burns credits, they’re sandbox credits.</p><p>One caveat worth knowing before you plan your tests: trial accounts don’t get every new feature either (Cortex Code, at the time of writing, is one example). Check availability first.</p><p>A note on the screenshots ahead: to keep this concrete, I ran the whole thing on an account where auto-fulfillment wasn’t set up yet — which had the side benefit of letting me capture the errors you’ll hit along the way, not just the happy path.</p><h3>Why real data, and why not CSV</h3><p>You can absolutely test a feature on fake data — sometimes that’s the right call, and I’ve written about <a href="https://towardsdatascience.com/synthetic-data-in-practice-a-shopify-case-study-79b0af024880/">synthetic data for exactly this purpose</a>. But when I can use <em>real</em> data, the experiment sits in my own reality: I’m not testing the feature in the abstract, I’m asking “these are my data, and I plan to use feature X” — then checking it on a subset of the real thing. The conclusions are far likelier to hold for my case. (And it’s not about freshness — a test environment doesn’t need real-time data; the sharing mechanism lets you dial that in, as you’ll see.)</p><p>The real reason is metadata. Snowflake tables carry far more than a CSV can: column descriptions, data types, and in my case a semantic model built on top. My tables have dozens of columns, annotated for semantic-layer work. Export to CSV (or Parquet) and you’re rebuilding file formats and metadata by hand on the other side. A 1:1 live copy skips all of it. The scope stays small by design — three datasets, not a replicated environment.</p><p>There’s also a simpler, almost hygienic reason: I’d rather not move CSVs of a client’s data around at all. Even when it can be done safely, a native sharing mechanism is the cleaner default — and it scales. Once you’ve worked the mechanism out, it stops mattering whether the data is small, medium, or far past what CSVs and stage uploads comfortably handle; the path is the same. For a tiny one-off file, sure, just upload it — otherwise native sharing should be the first choice. And the reason for real data here isn’t volume; it’s that the features I want to test lean on the data <em>and</em> its metadata — building on a semantic model, for instance.</p><p>A word on the three datasets, since they shape what follows. The first is <strong>GTmetrix</strong> data, pulled via its API — GTmetrix measures site speed from the outside, so you can point it at any site: your own, a client’s, even a competitor’s (the owner doesn’t necessarily know they’re being watched). The second is also site-speed data, but from an internal tracking system. The third sits a little apart — <strong>FX rates</strong>, currency conversion factors pulled from an external source and used when building dashboards — included to give the demo a second database to reach into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*CT8wQfYNsx1JgLSTnn2mXg.png" /><figcaption><em>The metadata a CSV throws away — every column carries its description. These travel with the share.</em></figcaption></figure><h3>Trap #1: replication is the heavy path</h3><p>The obvious move is to turn on replication to the other account:</p><pre>ALTER DATABASE share_db ENABLE REPLICATION<br>  TO ACCOUNTS my_org.other_account;<br>​<br>-- Error: Replication is not enabled for your account.</pre><p>That error isn&#39;t an edition wall — database replication is available on Enterprise; it just has to be enabled at the org level first. But replication is the heavy path: replication groups, a second account you manage in the target region, the whole machinery — and toward a throwaway sandbox it simply wasn&#39;t a route I wanted to take. (Failover, the disaster-recovery layer on top, is the part that actually needs Business Critical; I needed none of it.) So I left replication alone and went the lighter way.</p><p>The lighter route, already on Enterprise, is <strong>Cross-Cloud Auto-Fulfillment</strong> — part of the data-sharing and listings infrastructure, not database replication. You wrap your share in a listing, point it at a consumer account in another region, and Snowflake handles the cross-region copy behind the scenes.</p><h3>Trap #2: auto-fulfillment is off by default</h3><p>Cross-region auto-fulfillment isn’t on out of the box — you enable it once, as ORGADMIN. The function takes your account name only (no org prefix):</p><pre>USE ROLE ORGADMIN;<br>SELECT SYSTEM$ENABLE_GLOBAL_DATA_SHARING_FOR_ACCOUNT(&#39;my_account&#39;);</pre><p>(Skip this enable step and the error surfaces downstream, when you try to set up the listing:)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*MbyMWMZgR0Ux48tKy1OhIA.png" /><figcaption><em>What you get if auto-fulfillment was never enabled on the account.</em></figcaption></figure><p>It returns only a terse “Statement executed successfully”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Le-Y97kHSoCAAywwY8Vvwg.png" /><figcaption><em>The only feedback the enable call gives you.</em></figcaption></figure><p>That message doesn’t actually confirm the feature is on, so check the state directly:</p><pre>SELECT SYSTEM$IS_GLOBAL_DATA_SHARING_ENABLED_FOR_ACCOUNT(&#39;my_account&#39;);<br>-- TRUE</pre><p>That enable is a one-time step.</p><h3>Trap #3: a shared view has to be SECURE</h3><p>Sharing a view means sharing a <em>secure</em> view. This isn’t a cross-region quirk — it holds for any share: SECURE_OBJECTS_ONLY defaults to TRUE. You can set it to FALSE to share plain views, but it&#39;s a one-way switch — you can&#39;t set it back, and SHOW SHARES won&#39;t display the value, so record it in the share comment.</p><p>In a dbt project there’s a practical wrinkle: you can’t just ALTER VIEW ... SET SECURE on a model, because dbt recreates its views on every run and the change is gone by the next build. So the views I share sit in a dedicated schema dbt doesn&#39;t manage:</p><pre>CREATE SCHEMA IF NOT EXISTS share_db.SHARING;<br>​<br>-- explicit column list (not SELECT *) so the comments live on the view —<br>-- which is what the consumer, and a semantic model on top, will read.<br>CREATE OR REPLACE SECURE VIEW share_db.SHARING.site_speed_v (<br>    parsed_date  COMMENT &#39;Date the site-speed sample was recorded.&#39;,<br>    cleaned_url  COMMENT &#39;Normalized page URL.&#39;,<br>    device_type  COMMENT &#39;Device category (desktop, mobile, …).&#39;,<br>    -- … the remaining metric columns, each commented …<br>) AS<br>    SELECT parsed_date, cleaned_url, device_type, /* … */<br>    FROM share_db.WEB_PERF.site_speed;</pre><p>Naming and commenting the columns puts the descriptions on the view, and they travel with the share — the point being that a semantic model reads them on the other side. (A view that reaches into a <em>second</em> database needs one more grant, REFERENCE_USAGE — covered in the working sequence.)</p><p>Try to share a plain view and Snowflake names the switch for you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*4yW1T82_XuRJxVYh8PVkwQ.png" /><figcaption><em>The error names the very switch — </em><em>secure_objects_only.</em></figcaption></figure><h3>Live in production, insulated in the demo</h3><p>One honest question: if a secure view can sit straight on a production table and reflect whatever’s current at the next refresh, why copy/clone anything?</p><p>For a production share, you wouldn’t. You’d point the secure view at the live pipeline, set the listing to refresh — on a schedule, or triggered at the end of the dbt run — and each refresh ships the current state.</p><p>This is a demo, so I wanted one more layer of insulation: production left untouched, and a snapshot that can’t shift under me mid-write-up. The three source tables are zero-copy clones of the real ones — instant, no storage until they diverge, and the column comments come across intact, which is exactly what the semantic model needs. The secure views and the share then sit on the clones.</p><pre>-- the demo&#39;s source tables are zero-copy clones of production<br>CREATE OR REPLACE TABLE share_db.WEB_PERF.site_speed<br>    CLONE analytics_prod.web.site_speed;</pre><h3>The working sequence</h3><p>Two roles split the work: <strong>ORGADMIN</strong> is needed once, for the one-time enable — while <strong>ACCOUNTADMIN</strong> owns everything else: the secure views, the share, the grants, and the listing. So, on the provider side — Frankfurt, the giver — as ACCOUNTADMIN, create the share and grant the objects:</p><pre>CREATE SHARE IF NOT EXISTS dev_share;<br>​<br>GRANT USAGE  ON DATABASE share_db                    TO SHARE dev_share;<br>GRANT USAGE  ON SCHEMA   share_db.SHARING            TO SHARE dev_share;<br>​<br>-- a table goes in directly:<br>GRANT SELECT ON TABLE share_db.WEB_PERF.GTMETRIX     TO SHARE dev_share;<br>-- a secure view over a local table, the same way:<br>GRANT SELECT ON VIEW  share_db.SHARING.site_speed_v  TO SHARE dev_share;</pre><p>A secure view that reaches into a <em>second</em> database is where the REFERENCE_USAGE catch lands. Grant it as-is and it fails immediately — at grant time, not at publish or query:</p><pre>GRANT SELECT ON VIEW share_db.SHARING.fx_rates TO SHARE dev_share;<br>-- Error: A view or function being shared cannot reference objects from other databases.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*GaExnvUuxw4vMARhzBmnoA.png" /><figcaption><em>The cross-DB view is refused at grant time — before </em><em>REFERENCE_USAGE.</em></figcaption></figure><p>The fix is one grant on the other database — and the order matters, REFERENCE_USAGE first:</p><pre>GRANT REFERENCE_USAGE ON DATABASE ref_db       TO SHARE dev_share;<br>GRANT SELECT ON VIEW share_db.SHARING.fx_rates TO SHARE dev_share;  -- now it goes through</pre><p>A quick SHOW GRANTS TO SHARE confirms what&#39;s in the share before publishing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OB1AJsTWOhkUIC_R1MAIQ.png" /></figure><p><em>The finished share: usage grants, the table, the two secure views, and the </em><em>REFERENCE_USAGE that let the cross-DB one in.</em></p><p>Then, still as <strong>ACCOUNTADMIN</strong> (the role can manage auto-fulfillment once it’s enabled on the account), wrap the share in a listing that auto-fulfills to the consumer’s region:</p><pre>CREATE EXTERNAL LISTING dev_listing<br>SHARE dev_share AS<br>$$<br>  title: &quot;Dev cross-region share&quot;<br>  targets:<br>    accounts: [&quot;consumer_org.consumer_account&quot;]<br>  auto_fulfillment:<br>    refresh_type: &quot;SUB_DATABASE&quot;<br>    refresh_schedule: &quot;ON_DEMAND&quot;<br>$$ PUBLISH=TRUE REVIEW=TRUE;</pre><p>That’s the provider side done. Now switch hats to the consumer.</p><h3>On the receiving side (Oregon)</h3><p>This side is worth walking step by step, because the sequence is the point.</p><ol><li><strong>An email says a share is waiting.</strong> The provider publishes, and the consumer admin gets a “a listing has been shared with you” notification.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*jR60LEgmjWxz5cFOdMNvOg.png" /><figcaption><em>First email — the provider has shared a listing with the Oregon account.</em></figcaption></figure><p><strong>2. Accept it — and only now does data move.</strong> In Snowsight, under Data Products → Private Sharing (External sharing), the listing is sitting there with a <strong>Get</strong> button. Clicking Get is what triggers the actual fulfillment. The replication is <em>lazy</em>: nothing crosses the region border until the consumer accepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*sj1uuSxqOhRY1iOx1aQMpA.png" /><figcaption><em>The listing on the consumer side, ready to Get.</em></figcaption></figure><p>The dialog warns it may take up to ten minutes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*dUC1_11S0j6UQjQNkFknqw.png" /><figcaption><em>Fulfillment running — mine finished in about two minutes.</em></figcaption></figure><p><strong>3. A second email confirms the sync is done.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*-bf28MxLa7C3JNsCpUfS7A.png" /></figure><p><strong>4. Get it, and check what landed.</strong> You name the consumer database (and optionally pick which roles, beyond ACCOUNTADMIN, can read it), and a read-only copy appears with every shared object in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*K5GnQuhKrOAurVlvnSEp2A.png" /><figcaption><em>Naming the consumer database and granting access to a role.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*0ujV4aQX9jz3zzZ26C_qqQ.png" /><figcaption><em>All three on the consumer side: the table, the local secure view, and the cross-DB view.</em></figcaption></figure><p>And it all queries like local data — the table, the local secure view, and the cross-DB view, which auto-fulfilled across the region border once REFERENCE_USAGE was in place. The column comments came across with it. That&#39;s the &quot;why not CSV&quot; argument made concrete.</p><h3>Freshness is a dial</h3><p>Refresh is set per listing, through the manifest’s refresh_schedule: a fixed interval (a number plus a unit — hours, days, or weeks), a cron schedule, or ON_DEMAND, where you trigger the sync yourself with SYSTEM$TRIGGER_LISTING_REFRESH from your ETL. In production you&#39;d set this to whatever the business needs — tight when the consumer depends on near-current data, looser when a daily or weekly copy is fine.</p><p>I set it to ON_DEMAND, for two reasons. The first is cost: every scheduled refresh moves data, and the provider pays for that replication — no reason to fund a sync the sandbox doesn&#39;t need. The second one settles it — there&#39;s a clone under the hood, and a clone is a point-in-time snapshot. It doesn&#39;t change on its own, so a schedule would just re-ship the same frozen rows on every tick: cost, no new data. On demand runs the sync only when I ask — which is also the practical choice while I&#39;m still building the share, since a newly added object reaches the consumer the moment I trigger it, instead of waiting for the next scheduled tick.</p><h3>Who pays for what</h3><p>The cost is simple and “lazy”. The provider pays for replication compute, transfer, and storage of the replicated copy, which lives in a Snowflake-managed Secure Share Area in the target region. The consumer pays only their own query compute. Two details keep provider costs small:</p><ul><li>Replication is lazy: nothing crosses the region border until a consumer in that region actually accepts the share.</li><li>Only the shared objects and their dependencies replicate (SUB_DATABASE mode, the current default) — not the whole database.</li><li>Each refresh moves data, and that costs — worth keeping in mind, as it will use provider’s credits.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*gut5V26YIBkJ_YUtC9VvuA.png" /><figcaption><em>Snowflake says it in the setup dialog: no storage or replication cost until a consumer actually gets the data.</em></figcaption></figure><p>For a dev/test scenario — small datasets, infrequent refresh, single consumer — the running costs are a rounding error. The drivers that would change that: large data volumes, short refresh intervals, many consumer regions.</p><h3>Takeaways</h3><ul><li><strong>Cross-region sharing</strong> — works on Enterprise via Cross-Cloud Auto-Fulfillment (a listing); no replication needed.</li><li><strong>One-time setup</strong> — SYSTEM$ENABLE_GLOBAL_DATA_SHARING_FOR_ACCOUNT; ORGADMIN, account name only.</li><li><strong>Roles</strong> — ORGADMIN only for the one-time enable; ACCOUNTADMIN for the share, grants, views, and the listing.</li><li><strong>Views in shares</strong> — SECURE required by default (SECURE_OBJECTS_ONLY); wrap dbt views in a dedicated schema.</li><li><strong>Tables in shares</strong> — no SECURE requirement.</li><li><strong>Cross-DB views</strong> — GRANT REFERENCE_USAGE on the other database first; fails at grant time without it.</li><li><strong>Metadata</strong> — column comments travel with the share to the consumer region; no rebuild.</li><li><strong>Cost</strong> — provider pays; lazy replication; shared objects only.</li><li><strong>Trial accounts</strong> — can consume auto-fulfilled data; cannot provide it.</li></ul><p>All of it is documented — across several pages, and a good chunk of it falls within the SnowPro Advanced exam scope. I just thought it was worth having the whole workflow described in one place. End to end, the setup is about an hour of work.</p><h3>References (official docs)</h3><ul><li><a href="https://docs.snowflake.com/en/collaboration/provider-understand-cost-auto-fulfillment">Auto-fulfillment costs</a></li><li><a href="https://docs.snowflake.com/en/collaboration/provider-listings-auto-fulfillment">Auto-fulfillment for listings</a></li><li><a href="https://docs.snowflake.com/en/collaboration/provider-listings-auto-fulfillment-setup">Using auto-fulfillment</a></li><li><a href="https://docs.snowflake.com/en/user-guide/secure-data-sharing-across-regions-platforms">Share data securely across regions and cloud platforms</a></li><li><a href="https://docs.snowflake.com/en/user-guide/data-sharing-intro">About Secure Data Sharing</a></li><li><a href="https://docs.snowflake.com/en/sql-reference/functions/system_enable_global_data_sharing_for_account">SYSTEM$ENABLE_GLOBAL_DATA_SHARING_FOR_ACCOUNT</a></li><li><a href="https://docs.snowflake.com/en/sql-reference/functions/system_is_global_data_sharing_enabled_for_account">SYSTEM$IS_GLOBAL_DATA_SHARING_ENABLED_FOR_ACCOUNT</a></li><li><a href="https://docs.snowflake.com/en/user-guide/data-sharing-views">Share data in non-secured views (SECURE_OBJECTS_ONLY)</a></li><li><a href="https://docs.snowflake.com/en/progaccess/listing-manifest-reference">Listing manifest reference</a></li><li><a href="https://docs.snowflake.com/en/user-guide/account-replication-intro">Introduction to replication and failover (edition requirements)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e294565d6c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inequality in Practice: E-commerce Portfolio Analysis]]></title>
            <link>https://medium.com/data-science/inequality-in-practice-e-commerce-portfolio-analysis-adc3d0876acd?source=rss-c2cbb15c14cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc3d0876acd</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[concentration]]></category>
            <category><![CDATA[ecommerce]]></category>
            <dc:creator><![CDATA[Piotr Gruszecki]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 18:30:18 GMT</pubDate>
            <atom:updated>2025-01-31T18:30:18.708Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Mathematical Theory to Actionable Insights: A 6-Year Shopify Case Study</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fc3aEYB3InUBz1IgfXGFtA.png" /><figcaption>Image generated by DALL-E, based on author’s prompt, inspired by “The Bremen Town Musicians”</figcaption></figure><p>Are your top-selling products making or breaking your business?</p><p>It’s terrifying to think your entire revenue might collapse if one or two products fall out of favor. Yet spreading too thin across hundreds of products often leads to mediocre results and brutal price wars.</p><p>Discover how a 6-year Shopify case study uncovered the perfect balance between focus and diversification.</p><h4>Why bother?</h4><p>Understanding concentration in your product portfolio is more than simply an intellectual exercise; it has a direct impact on crucial business choices. From inventory planning to marketing spend, understanding how your revenue is distributed among goods impacts your approach.</p><p>This post walks through practical strategies for monitoring concentration, explaining what these measurements actually mean and how to get useful insights from your data.</p><p>I’ll take you through fundamental metrics and advanced analysis, including interactive visualisations that bring the data to life.</p><p>I am also sharing chunks of R code used in this analysis. Use it directly or adapt the logic to your preferred programming language.</p><h3>The Concentration Question</h3><p>Looking at market analysis or investment theory, we often focus on concentration — how value is distributed across different elements. In e-commerce, this translates into a fundamental question: How much of your revenue should come from your top products?</p><p>Is it better to have several strong sellers or a broad product range? This isn’t just a theoretical question …</p><p>Having most of your revenue tied to few products means your operations are streamlined and focused. But what happens when market preferences shift? Conversely, spreading revenue across hundreds of products might seem safer, but it often means you lack any real competitive advantage.</p><p>So where’s the optimal point? Or rather what is the optimal range, and how various ratios describe it.</p><p>What makes this analysis particularly valuable is that it is based on real data from a business that kept expanding its product range over time.</p><h3>Getting the Data Right</h3><h4>On Datasets</h4><p>This analysis was done for a real US-based e-commerce store — one of our clients who kindly agreed to share their data for this article. The data spans six years of their growth, giving us a rich view of how product concentration evolves as business matures.</p><p>While working with actual business data gives us genuine insights, I’ve also created a synthetic dataset in one of the later sections. This small, artificial dataset helps illustrate the relationships between various ratios in a more controlled setting — showing patterns “counting on fingers”.</p><p>To be clear: this synthetic data was created entirely from scratch and only loosely mimics general patterns seen in real e-commerce — it has no direct connection to our client’s actual data. This is different from my previous article, where I generated synthetic data based on real patterns using Snowflake functionality.</p><h4>Data Export</h4><p>The main analysis draws from real data, but that small artificial dataset serves an important purpose — it helps explain relationships between various ratios in a way that’s easy to grasp. And trust me, having such a micro dataset with clear visuals comes in really handy when explaining complex dependencies to stakeholders ;-)</p><p>The raw transaction export from Shopify contains everything we require, but we must arrange it properly for concentration analysis. The data contains all of the products for each transaction, but the date is only in one row per transaction, thus we must propagate it to all products while retaining the transaction id. Probably not for the first iteration of the study, but if we want to fine-tune it, we should consider how to handle discounts, returns, and so on. In the case of foreign sales, conduct a global and country-specific study.</p><p>We have a product name and an SKU, both of which should adhere to some naming convention and logic when dealing with variants. If we have a master catalogue with all of these descriptions and codes, we are very fortunate. If you have it, use it, but compare it to the ‘ground truth’ with actual transaction data.</p><h4>Product Variants</h4><p>In my case, the product names were structured with a base name and a variant separated by a dash. Very simple to use, divided into main product and variants. Exceptions? Of course, they are always present, especially when dealing with 6 years of highly successful ecommerce data:). For instance, some names (e.g. “All-purpose”) included a dash, while others did not. Then, some did have variants, while some did not. So expect for some tweaks here, but this is a critical stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y43-dSaq6CDyS199Y7sDaw.png" /><figcaption>Number of unique products, with and without variants — all charts rendered by author, with own R code</figcaption></figure><p>If you’re wondering why we need to exclude variations from concentration analysis, the figure above illustrates it clearly. The values are considerably different, and we would expect radically different results if we analysed concentration with variants.</p><p>The analysis is based on transactions, counting number of products with/without variants in a given month. But if we have a large number of variants, not all of them will be present in one-month transactions. Yes, that is correct — so let us consider a larger time range, one year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1b8DIQG-h76T5mvsyuXsQ.png" /><figcaption>Products, their variants, by transaction date, yearly</figcaption></figure><p>I calculated the number of variants per base product in a calendar year based on what we have in transactions. The number of variants per base product is divided into several bins. Let’s take the year 2024. The plot shows that we have somewhat around 170 base items, with less than half having only one variant (light green bar). However, the other part had more than one version, and what is noteworthy (and, I believe, non-obvious, unless you work in apparel ecommerce) is that we have products with a really large number of versions. The black bin contains items that come in 100 or more different variants.</p><p>If you guessed that they were increasing their offerings by introducing new products while keeping old ones available, you are correct. But wouldn’t it be interesting to know whether the differences stem from heritage or new products? What if we just included products introduced in the current year? We may check it by using the date of product introduction rather than transactions. Because our only dataset is a transaction dump, the first transaction for each product is taken as the introduction date. And for each product, we take all versions that appeared in transactions, with no time constraints (from product introduction to the most current record).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ch7oF2keDcCoQ6gzE0c3Bw.png" /><figcaption>Products, their variants, by product introduction date, yearly</figcaption></figure><p>Now let’s have these two plots side by side for easy comparison. Taking transactions dates we have more products in each year, and the difference grows — since there are also transactions with products introduced previously. No suprises here, as expected. If you were wondering why data for 2019 differ — nice catch. In fact, shop started operation in 2018, but I removed these few initial months; still, it is their impact what makes the difference in 2019.</p><p>Products variants and it’s impact on revenue is not our focus in this article. But as it is often in real analysis, there are ‘branching’ options, as we progress, even in the initial phase. We haven’t even finished data preparation, and it is already getting interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nArp6wNLllnrf2S1y5p-gA.png" /><figcaption>Products, their variants, by product introduction and transaction, yearly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITy37GAbGtmB_HDyPYBAIw.png" /><figcaption>Same data as above, facet by bin</figcaption></figure><p>Understanding the product structure is critical for conducting meaningful concentration analyses. Now that our data is appropriately formatted, we can examine actual concentration measurements and what they reveal about ideal portfolio structure. In the following part, we’ll look at these measurements and what they mean for e-commerce businesses.</p><h3>Measuring Concentration — theory meets practice</h3><p>When it comes to determining concentration, economists and market analysts have done the heavy lifting for us. Over decades of research into markets, competitiveness, and inequality, they’ve produced powerful analytical methods that have proven useful in a variety of sectors. Rather than developing novel metrics for e-commerce portfolio analysis, we can use existing time-tested methods.</p><p>Let’s see how theoretical frameworks can shed light on practical e-commerce questions.</p><h4>Herfindahl-Hirschman Index</h4><p>HHI (Herfindahl-Hirschman Index) is probably the most common way to measure concentration. Regulators use it to check if a market isn’t becoming too concentrated — they take percentages of each company’s market share, square them, and add up. Simple as that. The result can be anywhere from nearly 0 (many small players) to 10,000 (one company takes it all).</p><p>Why use HHI for e-commerce portfolio analysis? The logic is straightforward — instead of companies competing in a market, we have products competing for revenue. The math works exactly the same way — we take each product’s share of total revenue, square it, and sum up. High HHI means revenue depends on few products, while low HHI shows revenue is spread across many products. This gives us a single number to track portfolio concentration over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*pSKS6UCeEO4qgcx4WsBbZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEwXiTaYv3FZfZpNBwKymQ.png" /><figcaption>HHI, and Products for context</figcaption></figure><h4>Pareto</h4><p>Who has not heard of Pareto’s rules? In 1896, Italian economist Vilfredo Pareto observed that 20% of the population held 80% of Italy’s land. Since then, this pattern has been found in a variety of fields, including wealth distribution and retail sales.</p><p>While popularly referred to as the “80/20 rule,” the Pareto principle is not limited to these figures. We can use any x-axis criterion (for example, the top 30% of products) to determine the appropriate y value (revenue contribution). The Lorenz curve, formed by linking these locations, provides a complete picture of concentration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVqu8_U3-8wr3ffTSEcUZg.png" /><figcaption>Pareto lines for different revenue share thresholds</figcaption></figure><p>The chart above shows how many products do we need to achieve certain revenue share (of the monthly revenue). I took arbitrarily cuts at .2, .3, .5, .8, .95, and of course also including 1 — which means total number of products, contributing to 100% of revenue in a given month.</p><h4>Lorenz curve</h4><p>If we sort products by their revenue contribition, and chart the line, we get Lorenz curve. On both axis we have percentages, of products and their reveue share. I case of perfectly uniform revenue distribution, we’d have a straight line, while in case of “perfect concentration”, very steep curve, climbing close to 100% revenue, and then rapidly turning right, to include some residual revenue from other products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeEkn91odOdGXEp6zaeHNg.png" /><figcaption>Lorenz curve</figcaption></figure><p>It is interesting to see that line, but in most cases it will look quite similar, like a “bended stick”. So let us now compare these lines for few previous months, and also few years back (sticking to October). The monthly lines are quite similar, and if you think — it would be good to have some interactivity in this plot, you are absolutely right. The yearly comparison shows more differences (we still have monthly data, taking October in each year), and this is understandable, since these measurements are more distant in time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYR5EHAK-bGtkXtzCe4Q2w.png" /><figcaption>Lorenz curve — comparing periods</figcaption></figure><p>So we do see differences between the lines, but can’t we quantify them somehow, not to rely entirely on visual similarity? Definitely, and there is a ratio for that — Gini Ratio. And by the way, we will have quite a lot of ratios in next chapters.</p><h4>Gini Ratio</h4><p>To translate shape of Lorenz curve into numeric value, we can use Gini ratio — defined as a ratio between two areas, above and below the equality line. On a plot below it is a ratio between dark and light blue areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ba_RTnDMuR85j4b2CsstHQ.png" /><figcaption>Gini ratio visualization</figcaption></figure><p>Let us then visualize for two periods — October 2019, and October 2024, exact same periods, as we have on one of the plots before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReycwUGFFZ-_8KLWaohERw.png" /><figcaption>Gini ratio, comparing two periods</figcaption></figure><p>Once we have good understanding, with visuals, how the Gini ratio is calculated, let’s plot it, over the whole period.</p><p>I use R for analysis, so I have Gini ratio easily available (as well as other ratios, which I will show later). The initial data table (x3a_dt) contains revenue per product, per month. The resulting one has Gini ratio per month.</p><pre>#-- calculate Gini ratio, monthly<br>library(data.table, ineq)<br>x3a_ineq_dt &lt;- x3a_dt[, .(gini = ineq::ineq(revenue, type = &quot;Gini&quot;)), month]</pre><p>Good we have all these packages for heavy lifting. The math behind is not super complicated, but our time is precious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*LKhVbIWbaoGXl8sJjyxNkw.png" /></figure><p>The plot below shows the result of calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CimWZmU2eqdNGRNW89oJQ.png" /><figcaption>Gini over time</figcaption></figure><p>I haven’t included a smoothing line, with its confidence interval channel, since we do not have measurement points, but the result of Gini calculation, with its own errors distribution. To be very strict and precise on math, we’d need to calculate the confidence interval, and based on that plot smoothed line. The results are below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95EgMTxRiFtVDWeAhbUjSw.png" /><figcaption>Gini over time, with trend line</figcaption></figure><p>Since we do not use directly statistical significance of calculated ratio, this super strict approach is a little bit an overkill. I haven’t done it while charting trend line for HHI, nor will do in next plots. But it is good to be aware of this nuance.</p><p>We have seen so far two ratios — HHI and Gini, and they are far from being identical. Lorenz curve closer to diagonal indicates more uniform distribution, which is what we have for October 2019, but the HHI is higher, than for 2024, indicating more concentration in 2019. Maybe I made a mistake in calculations, even worse, early on during data preparation? That would be really unfortunate. Or the data is ok, but we are struggling with proper interpretation?</p><p>I have quite often moments of such doubts, especially when moving with the analysis really quick. So how do we cope with that, tightening grip on data and our understanding of dependencies? Bear in mind, that whatever analysis you do, there is always first time. And quite often we do not have a luxury of ‘leisure’ research, it is more often already work for a Client (or a superior, stakeholder, whoever requested it, even ourselves, if it is our initiative).</p><h3>Tightening grip</h3><p>We need to have a good understanding of how to interpret all these ratios, including dependencies between them. If you plan to present your results to others, questions here are guaranteed, so better to be well prepared. We can work with an existing dataset, or we can generate a small set, where it will be easier to catch dependencies. Let us follow the latter approach.</p><p>Let us start with creating a small dataset,</p><pre>library(data.table)<br><br>#-- Create sample revenue data<br>revenue &lt;- list(<br>  &quot;2021&quot; = rep(15, 10),                    # 10 values of 15<br>  &quot;2022&quot; = c(rep(100, 5), rep(10, 25)),    # 5 values of 100, 25 values of 10<br>  &quot;2023&quot; = rep(25, 50),                    # 50 values of 25<br>  &quot;2024&quot; = c(rep(100, 30), rep(10, 70))    # 30 values of 100, 70 values of 10<br>)</pre><p>combining it into a data.table.</p><pre>#-- Convert to data.table in one step<br>x_dt &lt;- data.table(<br>  year = rep(names(revenue), sapply(revenue, length)),<br>  revenue = unlist(revenue)<br>)</pre><p>A quick overview of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yGLMQ3zbEYErqdfYthQ9g.png" /><figcaption>Example dataset</figcaption></figure><p>It seems we have what we needed — a simple dataset, but still quite realistic. Now we are proceeding with calculations and charts, similar to what we had for a real dataset before.</p><pre>#-- HHI, Gini<br>xh_dt &lt;- x_dt[, .(hhi = ineq::Herfindahl(revenue), <br>                  gini = ineq::Gini(revenue)), year]</pre><pre>#-- Lorenz<br>xl_dt &lt;- x_dt[order(-revenue), .(<br>  cum_prod_pct = seq_len(.N)/.N, <br>  cum_rev_pct = cumsum(revenue)/sum(revenue)), year]</pre><p>And rendering plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oLSyYXq5Eh9-bCDeOesqQ.png" /><figcaption>Ratios comparison</figcaption></figure><p>These charts help a lot in understanding ratios, relations between them and to data. It is always a good idea to have such micro analysis, for ourselves and for stakeholders — as ‘back pocket’ slides, or even sharing them upfront.</p><p>Nerdy detail — how to slightly shift the line, so it doesn’t overlap, and add labels within a plot? Render a plot, and then make manual fine tuning, expecting several iterations.</p><pre>#-- shift the line<br>xl_dt[year == &quot;2021&quot;, `:=` (cum_rev_pct = cum_rev_pct - .01)]</pre><p>For labelling I use ggrepel, but as a default, it will label all the points, while we need only one per line. An in addition deciding which one, for good looking chart.</p><pre>#-- decide which points to label<br>labs_key2_dt &lt;- data.table(<br>  year = c(&quot;2021&quot;, &quot;2022&quot;, &quot;2023&quot;, &quot;2024&quot;), position = c(4, 5, 25, 30))<br><br>#-- set keys<br>list(xl_dt, labs_key2_dt) |&gt; lapply(setkey, year)<br><br>#-- join<br>label_positions2 &lt;- xl_dt[<br>  labs_key2_dt, on = .(year), # join on &#39;year&#39; <br>  .SD[get(&#39;position&#39;)],       # Use get(&#39;position&#39;) to reference the position from labs_key_dt<br>  by = .EACHI]                # for each year</pre><p>Render the plot.</p><pre>#-- render plot<br>plot_22b &lt;- xl_dt |&gt;<br>  ggplot(aes(cum_prod_pct, cum_rev_pct, color = year, group = year, label = year)) +<br>  geom_line(linewidth = .2) +<br>  geom_point(alpha = .8, shape = 21) +<br>  theme_bw() +<br>  scale_color_viridis_d(option = &quot;H&quot;, begin = 0, end = 1) +<br>  ggrepel::geom_label_repel(<br>    data = label_positions2, force = 10, <br>    box.padding = 2.5, point.padding = .3, <br>    seed = 3, direction = &quot;x&quot;) +<br>... additional styling </pre><h3>More Ratios</h3><p>I began with HHI, the Lorenz curve, and the accompanying Gini ratios, as they appeared to be good starting points for concentration and inequality measurements. However, there are numerous different ratios used to define distributions, whether for inequality or in general. It’s unlikely that we’d employ all of them at once, therefore select the subset that provides the most insights for your specific challenge.</p><p>With a proper structure of a dataset, it is quite straightforward to calculate them. I am sharing code snippets, with several ratios calculated monthly. We use a dataset, we already have — monthly revenue per product (base products, excluding variants).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zcGxwJX7S25viHBFKbg4A.png" /></figure><p>Starting with ratios from the ineq package.</p><pre>#---- inequality ----<br>x3_ineq_dt &lt;- x3a_dt[, .(<br>  # Classical inequality/concentration measures<br>  gini     = ineq::ineq(revenue, type = &quot;Gini&quot;),      # Gini coefficient<br>  hhi      = ineq::Herfindahl(revenue),               # Herfindahl-Hirschman Index<br>  hhi_f    = sum((rev_pct*100)^2),                    # HHI - formula<br>  atkinson = ineq::ineq(revenue, type = &quot;Atkinson&quot;),  # Atkinson index<br>  theil    = ineq::ineq(revenue, type = &quot;Theil&quot;),     # Theil entropy index<br>  kolm     = ineq::ineq(revenue, type = &quot;Kolm&quot;),      # Kolm index<br>  rs       = ineq::ineq(revenue, type = &quot;RS&quot;),        # Ricci-Schutz index<br>  entropy  = ineq::entropy(revenue),                  # Entropy measure<br>  hoover   = mean(abs(revenue - mean(revenue)))/(2 * mean(revenue)), # Hoover (Robin Hood) index</pre><p>Diustribution shape and top/bottom shares and ratios.</p><pre> # Distribution shape measures<br>  cv       = sd(revenue)/mean(revenue),               # Coefficient of Variation<br>  skewness = moments::skewness(revenue),              # Skewness<br>  kurtosis = moments::kurtosis(revenue),              # Kurtosis<br><br>  # Ratio measures<br>  p90p10   = quantile(revenue, 0.9)/quantile(revenue, 0.1),   # P90/P10 ratio<br>  p75p25   = quantile(revenue, 0.75)/quantile(revenue, 0.25), # Interquartile ratio<br>  palma    = sum(rev_pct[1:floor(.N*.1)])/sum(rev_pct[floor(.N*.6):(.N)]), # Palma ratio</pre><pre>  # Concentration ratios and shares<br>  top1_share  = max(rev_pct),                         # Share of top product<br>  top3_share  = sum(head(sort(rev_pct, decreasing = TRUE), 3)),  # CR3<br>  top5_share  = sum(head(sort(rev_pct, decreasing = TRUE), 5)),  # CR5<br>  top10_share = sum(head(sort(rev_pct, decreasing = TRUE), 10)), # CR10<br>  top20_share = sum(head(sort(rev_pct, decreasing = TRUE), floor(.N*.2))),  # Top 20% share<br>  mid40_share = sum(sort(rev_pct, decreasing = TRUE)[floor(.N*.2):floor(.N*.6)]), # Middle 40% share<br>  bottom40_share = sum(tail(sort(rev_pct), floor(.N*.4))),      # Bottom 40% share<br>  bottom20_share = sum(tail(sort(rev_pct), floor(.N*.2))),      # Bottom 20% share</pre><p>Basic statistics, quantiles.</p><pre> # Basic statistics<br>  unique_products = .N,                              # Number of unique products<br>  revenue_total = sum(revenue),                      # Total revenue<br>  mean_revenue = mean(revenue),                      # Mean revenue per product<br>  median_revenue = median(revenue),                  # Median revenue<br>  revenue_sd = sd(revenue),                          # Revenue standard deviation<br><br>  # Quantile values<br>  q20 = quantile(revenue, 0.2),                      # 20th percentile<br>  q40 = quantile(revenue, 0.4),                      # 40th percentile<br>  q60 = quantile(revenue, 0.6),                      # 60th percentile<br>  q80 = quantile(revenue, 0.8),                      # 80th percentile</pre><p>Count measures.</p><pre> # Count measures<br>  above_mean_n = sum(revenue &gt; mean(revenue)),        # Number of products above mean<br>  above_2mean_n = sum(revenue &gt; 2*mean(revenue)),     # Number of products above 2x mean<br>  top_quartile_n = sum(revenue &gt; quantile(revenue, 0.75)), # Number of products in top quartile<br>  zero_revenue_n = sum(revenue == 0),                 # Number of products with zero revenue<br>  within_1sd_n = sum(abs(revenue - mean(revenue)) &lt;= sd(revenue)),    # Products within 1 SD<br>  within_2sd_n = sum(abs(revenue - mean(revenue)) &lt;= 2*sd(revenue)),  # Products within 2 SD</pre><p>Revenue above (or below) the threshold.</p><pre>  # Revenue above threshold<br>  rev_above_mean = sum(revenue[revenue &gt; mean(revenue)])  # Revenue from products above mean<br>), month]</pre><p>The resulting table has 40 columns, and 72 rows (months).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*Inr7l_VcHVZ06golm7617w.png" /></figure><p>As mentioned earlier, it is difficult to imagine, one would work with 40 ratios, so I am rather showing a method how to calculate them, and one should pick relevant ones. As always, it is good to visualize and see how they relate to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmHk8wkHqUxRy7hqyKzn0A.png" /><figcaption>Selected ratios over time</figcaption></figure><p>We can calculate correlation matrix between all ratios, or selected subset.</p><pre># Select key metrics for a clearer visualization<br>key_metrics &lt;- c(&quot;gini&quot;, &quot;hhi&quot;, &quot;atkinson&quot;, &quot;theil&quot;, &quot;entropy&quot;, &quot;hoover&quot;, <br>                 &quot;top1_share&quot;, &quot;top3_share&quot;, &quot;top5_share&quot;, &quot;unique_products&quot;)<br><br>cor_matrix &lt;- x3_ineq_dt[, .SD, .SDcols = key_metrics] |&gt; cor()</pre><p>Change column names to more friendly names.</p><pre># Make variable names more readable<br>pretty_names &lt;- c(<br>  &quot;Gini&quot;, &quot;HHI&quot;, &quot;Atkinson&quot;, &quot;Theil&quot;, &quot;Entropy&quot;, &quot;Hoover&quot;,<br>  &quot;Top 1%&quot;, &quot;Top 3%&quot;, &quot;Top 5%&quot;, &quot;Products&quot;<br>)<br>colnames(cor_matrix) &lt;- rownames(cor_matrix) &lt;- pretty_names</pre><p>And render the plot.</p><pre>corrplot::corrplot(cor_matrix, <br>         type = &quot;upper&quot;,<br>         method = &quot;color&quot;,<br>         tl.col = &quot;black&quot;,<br>         tl.srt = 45,<br>         diag = F,<br>         order = &quot;AOE&quot;) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iyvX_gR04Kfv7t1ahCc6KA.jpeg" /><figcaption>Correlation matrix, selected ratios</figcaption></figure><p>And then we can plot some interesting pairs. Of course, some of them have positive or negative correlation <em>by definition</em>, while in other cases it is not that obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1ctrG2MEWkMYWyRtjOtHA.png" /><figcaption>Selected ratios, with negative correlation</figcaption></figure><h3>Show me the money</h3><p>We started analysis with ratios and Lorenz curve as a top-down overview. It is a good start, but there are two complications — the ratios have a relatively broad range, when the business is doing ok, and there is hardly connection to actionable insights. Even if we notice that the ratio is on the edge, or outside of the safe range, it is unclear what we should do. And instructions like “decrease concentration” are a little ambiguous.</p><p>E-commerce talks and breaths products, so to make analysis relatable, we need to reference to particular products. People would also like to understand which products constitute core 50%, 80% of revenue, and equally important, if these products stay consistently as top contributors.</p><p>Let us take one month, August 2024 and see which products contributed to 50% revenue in that month. Then, we check revenue from these exact products in other months. There are 5 products, generating (at least) 50% revenue in August.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8ZHqjLaijjb899rKiqRWw.png" /><figcaption>Products revenue, facets by product</figcaption></figure><p>We can also render more visually appealing plot with a streamgraph. Both plots show exact same dataset, but they complement each other nicely — bar plots for precision, while streamgraph for a story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o235vagWj4DgV5wAU22JEQ.png" /><figcaption>Products revenue, stream graph</figcaption></figure><p>The red line indicated selected month. If you feel “itching” to shift that line, like in an old-fashioned radio, you are absolutely right — that should be an interactive chart, and actually it is, along with a slider for revenue share percentage (we produced it for a Client).</p><p>So what if we shift that red ‘tuning line’ a little bit backwards, maybe to 2020? The logic in data preparation is very similar — get products contributing to a certain revenue share threshold, and check the revenue from these products in other months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9d3PGlyU3c7BGbwpkXTGKw.png" /><figcaption>Products revenue, stream graph</figcaption></figure><p>With interactivity on two elements — revenue contribution percentage and the date, one can learn a lot about the business, and this is exactly the point of these charts. One can look from different angles:</p><ul><li>concentration, how many products do we need for certain revenue threshold,</li><li>products themselves, do they stay in certain revenue contribution bin, or do they change and why? Is it seasonality, a valid replacement, lost supplier or something else?</li><li>time window, whether we look at one month or a whole year,</li><li>seasonality, comparing similar time of a year with previous periods.</li></ul><h3>Summary</h3><h4>What the Data Tells Us</h4><p>Our 6-year dataset reveals the evolution of an e-commerce business from high concentration to balanced growth. Here are the key patterns and lessons:</p><p>With 6 years of data, I had a unique chance to watch concentration metrics evolve as the business grew. Starting with just a handful of products, I saw exactly what you’d expect — sky-high concentration. But as new products entered the mix, things got more interesting. The business found its rhythm with a dozen or so top performers, and the HHI settled into a comfortable 700–800 range.</p><p>Here’s something fascinating I discovered: concentration and inequality might sound like twins, but they’re more like distant cousins. I noticed this while comparing HHI against Lorenz curves and their Gini ratios. Trust me, you’ll want to get comfortable with the math before explaining these patterns to stakeholders — they’ll smell uncertainty from a mile away.</p><p>Want to really understand these metrics? Do what I did: create a dummy dataset so simple it’s almost embarrassing. I’m talking basic patterns that a fifth-grader could grasp. Sounds like overkill? Maybe, but it saved me countless hours of head-scratching and misinterpretation. Keep these examples in your back pocket — or better yet, share them upfront. Nothing builds confidence like showing you’ve done your homework.</p><p>Look, calculating these ratios isn’t rocket science. The real magic happens when you dig into how each product contributes to your revenue. That’s why I added the “show me the money” section — I don’t believe in quick fixes or magic formulas. It’s about rolling up your sleeves and understanding how each product really behaves.</p><p>As you’ve probably noticed yourself, these streamgraphs I showed you are practically begging for interactivity. And boy, does that add value! Once you’ve got your keys and joins sorted out, it’s not even that complicated. Give your users an interactive tool, and suddenly you’re not drowning in one-off questions anymore — they’re finding insights themselves.</p><p>Here’s a pro tip: use this concentration analysis as your foot in the door with stakeholders. Show your product teams that streamgraph, and I guarantee their eyes will light up. When they start asking for interactive versions, you’ve got them hooked. The best part? They’ll think it was their idea all along. That’s how you get real adoption — by letting them discover the value themselves.</p><h4>Data Engineering Takeaways</h4><p>While quite often we generally know what to expect in a dataset, it is almost guaranteed that there will be some nuances, exceptions, or maybe even surprises. It’s good to spend some time reviewing datasets, using dedicated functions (like str, glimpse in R), looking for empty fields, outliers, but also simply scrolling through to understand the data. I like comparisons, and in this case, I’d compare to smelling fish on a market before jumping to prepare sushi :-)</p><p>Then, if we work with a raw data export, quite likely there will be several columns in the data dump; after all, if we click ‘export all’, wouldn’t we expect exactly that? For most analysis we will need a subset of these columns, so it’s good to trim and keep only what we need. I assume we work with a script, so if it turns out, we need more, not an issue, just add missed column and rerun that chunk.</p><p>In the dataset dump there was a timestamp in one row per transaction, while we needed it per each product. Hence some light data wrangling to propagate these timestamps to all the products.</p><p>After cleaning the dataset, it’s important to consider the context of analysis, including the questions to be answered and the necessary changes to the data. This “contextual cleaning/wrangling” is critical since it determines whether the analysis succeeds or fails. In our situation, the goal was to analyse product concentration, therefore filtering out variants (size, colour, etc.) was essential. If we had skipped that, the outcome would have been radically different.</p><p>Quite often we can expect some “traps”, where initially it seems we can apply simple approach, while actually, we should add a bit of sophistication. As an example — Lorenz curve, where we need to calculate how many products do we need to get to a certain revenue threshold. This is where I use rolling joins, which fit here perfectly.</p><p>The core logic to produce streamgraphs is to find products which constitute certain revenue percentage in a given month, then “freeze” them and get their revenue in other months. The toolset I used was adding extra column, with a product number, after sorting per month, and then playing with keys and joins.</p><p>An important element of this analysis was adding interactivity, allowing users to play with some parameters. That raises the bar, as we need all these operations to be performed lightning fast. The ingredients we need are right data structure, additional columns, proper keys and joins. Prepare as much as possible, precalculating in a data warehouse, so the dashboarding tool is not overloaded. Take caching into account.</p><h4>How to Start?</h4><p>Strike a balance between delivering what stakeholders request and exploring potentially valuable insights they haven’t asked for yet. The analysis I presented follows this pattern — getting initial concentration ratios is straightforward, while building an interactive streamgraph optimized for lightning-fast operation requires significant effort.</p><p>Start small and engage others. Share basic findings, discuss what you could learn together, and only then proceed with more labor-intensive analysis once you’ve secured genuine interest. And always maintain a solid grip on your raw data — it’s invaluable for answering those inevitable ad-hoc questions quickly.</p><p>Building a prototype before full production allows for validation of interest and feedback without devoting too much time. In my case, such simple concentration ratios sparked debates that eventually led to the more advanced interactive studies on which stakeholders rely today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NY0rj41RpxDXdtECXz-Ykw.png" /><figcaption>Start small, secure genuine interest … :-)) / image generated by DALL-E, based on author’s prompt.</figcaption></figure><h3>Appendix — data preparation &amp; wrangling</h3><p>I’ll show you how I prepared the data at each step of this analysis. Since I used R, I’ll include the actual code snippets — they’ll help you get started faster, even if you’re working in a different language. This is the code I used for the study, though you’ll probably need to adapt it to your specific needs rather than just copying it over. I decided to keep the code separate from the main analysis, to make it more streamlined and readable for both technical and business users.</p><p>While I am presenting analysis based on Shopify export, there is no limitation for a particular platform, we just need transactions data.</p><h4>Shopify export</h4><p>Let’s start with getting our data from Shopify. The raw export needs some work before we can dive into concentration analysis — here’s what I had to deal with first.</p><p>We start with export of raw transactions data from Shopify. It might take some time, and when ready, we get an email with links to download.</p><pre>#-- 0. libs<br>pacman::p_load(data.table)<br><br>#-- 1.1 load data; the csv files are what we get as a full export from Shopify<br>xs1_dt &lt;- fread(file = &quot;shopify_raw/orders_export_1.csv&quot;)<br>xs2_dt &lt;- fread(file = &quot;shopify_raw/orders_export_2.csv&quot;)<br>xs3_dt &lt;- fread(file = &quot;shopify_raw/orders_export_3.csv&quot;)</pre><p>Once we have data, we need to combine these files into one dataset, trim columns and perform some cleansing.</p><pre>#-- 1.2 check all columns, limit them to essential (for this analysis) and bind into one data.table<br>xs1_dt |&gt; colnames()<br># there are 79 columns in full export, <br># so we select a subset, relevant for this analysis<br>sel_cols &lt;- c(&quot;Name&quot;, &quot;Email&quot;, &quot;Paid at&quot;, &quot;Fulfillment Status&quot;, &quot;Accepts Marketing&quot;, &quot;Currency&quot;, &quot;Subtotal&quot;,<br>              &quot;Lineitem quantity&quot;, &quot;Lineitem name&quot;, &quot;Lineitem price&quot;, &quot;Lineitem sku&quot;, &quot;Discount Amount&quot;,<br>              &quot;Billing Province&quot;, &quot;Billing Country&quot;)<br><br>#-- combine into one data.table, with a subset of columns<br>xs_dt &lt;- data.table::rbindlist(l = list(xs1_dt, xs2_dt, xs3_dt), <br>    use.names = T, fill = T, idcol = T) %&gt;% .[, ..sel_cols]</pre><p>Some data preparations.</p><pre>#-- 2. data prep<br>#-- 2.1 replace spaces in column names, for easier handling<br>sel_cols_new &lt;- sel_cols |&gt; stringr::str_replace(pattern = &quot; &quot;, replacement = &quot;_&quot;)<br>setnames(xs_dt, old = sel_cols, new = sel_cols_new)<br><br>#-- 2.2 transaction as integer<br>xs_dt[, `:=` (Transaction_id = stringr::str_remove(Name, pattern = &quot;#&quot;) |&gt; as.integer())]</pre><p>Anonymize emails, as we don’t need/want to deal with real emails during analysis.</p><pre>#-- 2.3 anonymize email <br>new_cols &lt;- c(&quot;Email_hash&quot;)<br>xs_dt[, (new_cols) := .(digest::digest(Email, algo = &quot;md5&quot;)), .I]</pre><p>Change column types; this depends on personal preferences.</p><pre>#-- 2.4 change Accepts_Marketing to logical column<br>xs_dt[, `:=` (Accepts_Marketing_lgcl = fcase(<br>    Accepts_Marketing == &quot;yes&quot;, TRUE, <br>    Accepts_Marketing == &quot;no&quot;, FALSE, <br>    default = NA))]</pre><p>Now we focus on transactions dataset. In the export files, the transaction amount and timestamp is in only one row per all items in the basket. We need to get these timestamps and propagate to all items.</p><pre>#-- 3 transactions dataset<br>#-- 3.1 subset transactions<br>#-- limit columns to essential for transaction only<br>trans_sel_cols &lt;- c(&quot;Transaction_id&quot;, &quot;Email_hash&quot;, &quot;Paid_at&quot;, <br>  &quot;Subtotal&quot;, &quot;Currency&quot;, &quot;Billing_Province&quot;, &quot;Billing_Country&quot;)<br><br>#-- get transactions table based on requirement of non-null payment - as payment (date, amount) is not for all products, it is only once per basket<br>xst_dt &lt;- xs_dt[!is.na(Paid_at) &amp; !is.na(Transaction_id), ..trans_sel_cols]</pre><pre>#-- date columns<br>xst_dt[, `:=` (date = as.Date(`Paid_at`))]<br>xst_dt[, `:=` (month = lubridate::floor_date(date, unit = &quot;months&quot;))]</pre><p>Some extra information, as I call them, <em>derivatives</em>.</p><pre>#-- 3.2 is user returning? their n-th transaction<br>setkey(xst_dt, Paid_at)<br>xst_dt[, `:=` (tr_n = 1)][, `:=` (tr_n = cumsum(tr_n)), Email_hash]<br><br>xst_dt[, `:=` (returning = fcase(tr_n == 1, FALSE, default = TRUE))]</pre><p>Do we have any NA’s in the dataset?</p><pre>xst_dt[!complete.cases(xst_dt), ]</pre><p>Products dataset.</p><pre>#-- 4 products dataset<br>#-- 4.1 subset of columns<br>sel_prod_cols &lt;- c(&quot;Transaction_id&quot;, &quot;Lineitem_quantity&quot;, &quot;Lineitem_name&quot;, <br>  &quot;Lineitem_price&quot;, &quot;Lineitem_sku&quot;, &quot;Discount_Amount&quot;)</pre><p>Now we join these two datasets, to have transaction characteristics (trans_sel_cols) for all the products.</p><pre>#-- 5 join two datasets<br>list(xs_dt, xst_dt) |&gt; lapply(setkey, Transaction_id)<br>x3_dt &lt;- xs_dt[, ..sel_prod_cols][xst_dt]</pre><p>Let’s check which columns we have in x3_dt dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zy7rfApUuDEUhyX9UGfxtQ.png" /></figure><p>And it is also a moment to inspect the dataset.</p><pre>x3_dt |&gt; str()<br>x3_dt |&gt; dplyr::glimpse()<br>x3_dt |&gt; head()</pre><p>Time for data cleaning. First up: splitting the Lineitem_name into base products and their variants. In theory, these are separated by a dash (“-”). Simple, right? Not quite — some product names, like ‘All-Purpose’, contain dashes as part of their name. So we need to handle these special cases first, temporarily replacing problematic dashes, doing the split, and then restoring the original product names.</p><pre>#-- 6. cleaning, aggregation on product names<br>#-- 6.1 split product name into base and variants<br>#-- split product names into core and variants<br>product_cols &lt;- c(&quot;base_product&quot;, &quot;variants&quot;)<br>#-- with special treatment for &#39;all-purpose&#39;<br>x3_dt[stringr::str_detect(string = Lineitem_name, pattern = &quot;All-Purpose&quot;), <br>  (product_cols) := {<br>    tmp = stringr::str_replace(Lineitem_name, &quot;All-Purpose&quot;, &quot;AllPurpose&quot;)<br>    s = stringr::str_split_fixed(tmp, pattern = &quot;[-/]&quot;, n = 2)<br>    s = stringr::str_replace(s, &quot;AllPurpose&quot;, &quot;All-Purpose&quot;)<br>    .(s[1], s[2])<br>  }, .I]</pre><p>It is good to make validation after each step.</p><pre># validation<br>x3_dt[stringr::str_detect(<br>  string = Lineitem_name, pattern = &quot;All-Purpose&quot;), .SD, <br>  .SDcols = c(&quot;Transaction_id&quot;, &quot;Lineitem_name&quot;, product_cols)]</pre><p>We keep moving with data cleaning — the exact steps depend of course on a particular dataset, but I share my flow, as an example.</p><pre>#-- two scenarios, to cope with `(32-ounce)` in prod name; we don&#39;t want that hyphen to cut the name<br>x3_dt[stringr::str_detect(string = `Lineitem_name`, pattern = &quot;ounce&quot;, negate = T) &amp; <br>  stringr::str_detect(string = `Lineitem_name`, pattern = &quot;All-Purpose&quot;, negate = T), <br>  (product_cols) := {<br>    s = stringr::str_split_fixed(string = `Lineitem_name`, pattern = &quot;[-/]&quot;, n = 2); .(s[1], s[2])<br>  }, .I]<br><br>x3_dt[stringr::str_detect(string = `Lineitem_name`, pattern = &quot;ounce&quot;, negate = F) &amp; <br>  stringr::str_detect(string = `Lineitem_name`, pattern = &quot;All-Purpose&quot;, negate = T), <br>  (product_cols) := {<br>    s = stringr::str_split_fixed(string = `Lineitem_name`, pattern = &quot;\\) - &quot;, n = 2); .(paste0(s[1], &quot;)&quot;), s[2])<br>  }, .I]<br><br>#-- small patch for exceptions<br>x3_dt[stringr::str_detect(string = base_product, pattern = &quot;\\)\\)$&quot;, negate = F), <br>  base_product := stringr::str_replace(string = base_product, pattern = &quot;\\)\\)$&quot;, replacement = &quot;)&quot;)]</pre><p>Validation.</p><pre># validation<br>x3_dt[stringr::str_detect(string = `Lineitem_name`, pattern = &quot;ounce&quot;)<br>  ][, .SD, .SDcols = c(eval(sel_cols[6]), product_cols)<br>  ][, .N, c(eval(sel_cols[6]), product_cols)]<br><br>x3_dt[stringr::str_detect(string = `Lineitem_name`, pattern = &quot;All&quot;)<br>  ][, .SD, .SDcols = c(eval(sel_cols[6]), product_cols)<br>  ][, .N, c(eval(sel_cols[6]), product_cols)]<br><br>x3_dt[stringr::str_detect(string = base_product, pattern = &quot;All&quot;)]</pre><p>We use eval(sel_cols[6]) to get the name of a column sel_cols[6] which is Currency.</p><p>We also need to deal with NA’s, but with an understanding of a dataset — where we could have NA’s and where they are not supposed to be, indicating an issue. In some columns, like `Discount_Amount`, we have values (actual discount), zeros, but also sometimes NA’s. Checking final price, we conclude they are zeros.</p><pre>#-- deal with NA&#39;a - replace them with 0<br>sel_na_cols &lt;- c(&quot;Discount_Amount&quot;)<br>x3_dt[, (sel_na_cols) := lapply(.SD, fcoalesce, 0), .SDcols = sel_na_cols]</pre><p>For consistency and convenience, changing all column names to lowercase.</p><pre>setnames(x3_dt, tolower(names(x3_dt)))</pre><p>And verification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPOuZvk3rrOR9j89VLpiAw.png" /></figure><p>Of course review dataset, with some test aggregations, and also just printing it out.</p><p>Save dataset as both Rds (native R format) and csv.</p><pre>x3_dt |&gt; fwrite(file  = &quot;data/products.csv&quot;)<br>x3_dt |&gt; saveRDS(file = &quot;data/x3_dt.Rds&quot;)</pre><p>Conducting steps above we should have a clean dataset, for futher analysis. The code should serve as a guideline, but also can be used directly, if you work in R.</p><h4>Versions</h4><p>As a first glimpse, we will check number of products per month, both base_product, and including all versions.</p><p>As a small cleaning, I take only complete months.</p><pre>month_last &lt;- x3_dt[, max(month)] - months(1)</pre><p>Then we count monthly numbers, storing in temporary table, which are then joined.</p><pre>x3_a_dt &lt;- x3_dt[month &lt;= month_last, .N, .(base_product, month)<br>  ][, .(base_products = .N), keyby = month]<br><br>x3_b_dt &lt;- x3_dt[month &lt;= month_last, .N, .(lineitem_name, month)<br>  ][, .(products = .N), keyby = month]<br><br>x3_c_dt &lt;- x3_a_dt[x3_b_dt]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GCjLL37Bjv5oZVT3sfpoA.png" /></figure><p>Some data wrangling.</p><pre>#-- names, as we want them on plot<br>setnames(x3_c_dt, old = c(&quot;base_products&quot;, &quot;products&quot;), new = c(&quot;base&quot;, &quot;all, with variants&quot;))<br><br>#-- long form<br>x3_d_dt &lt;- x3_c_dt[, melt.data.table(.SD, id.vars = &quot;month&quot;, variable.name = &quot;Products&quot;)]<br><br>#-- reverse factors, so they appear on plot in a proper order<br>x3_d_dt[, `:=` (Products = forcats::fct_rev(Products))]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aX9j3L4UjJbQLrZyb7HeZQ.png" /></figure><p>We are ready to plot the dataset.</p><pre>plot_01_w &lt;- x3_d_dt |&gt;<br>  ggplot(aes(month, value, color = Products, fill = Products)) +<br>  geom_line(show.legend = FALSE) +<br>  geom_area(alpha = .8, position = position_dodge()) +<br>  theme_bw() +<br>  scale_fill_viridis_d(direction = -1, option = &quot;G&quot;, begin = 0.3, end = .7) +<br>  scale_color_viridis_d(direction = -1, option = &quot;G&quot;, begin = 0.3, end = .7) +<br>  labs(x = &quot;&quot;, y = &quot;Products&quot;, <br>    title = &quot;Unique products, monthly&quot;, subtitle = &quot;Impact of aggregation&quot;) +<br>  theme(... additional styling)</pre><p>The next plot shows the number of variants grouped into bins. This gives us a chance to talk about chaining operations in R, particularly with the data.table package. In data.table, we can chain operations by opening a new bracket right after closing one — resulting in ][ syntax. It creates a compact, readable chain that’s still easy to debug since you can execute it piece by piece. I prefer succinct code, but that’s just my style — use whatever approach works best for you. We can write code in one line, or multi-line, with logical steps.</p><p>On one of the plots we look at a date, when each product was first seen. To get that date, we set a key on date, and then take the first occurrence date[1] per each base_product.</p><pre>#-- versions per year, product, with a date, when it was 1st seen<br>x3c_dt &lt;- x3_dt[, .N, .(base_product, variants)<br>  ][, .(variants = .N), base_product][order(-variants)]<br><br>x3_dt |&gt; setkey(date)<br>x3d_dt &lt;- x3_dt[, .(date = date[1]), base_product]</pre><pre>list(x3c_dt, x3d_dt) |&gt; lapply(setkey, base_product)<br><br>x3e_dt &lt;- x3c_dt[x3d_dt][order(variants)<br>  ][, `:=` (year = year(date) |&gt; as.factor())][year != 2018<br>  ][, .(products = .N), .(variants, year)][order(-variants)<br>  ][, `:=` (<br>    variant_bin = cut(<br>      variants,<br>      breaks = c(0, 1, 2, 5, 10, 20, 100, Inf),<br>      include.lowest = TRUE,<br>      right = FALSE<br>    ))<br>  ][, .(total_products = sum(products)), .(variant_bin, year)<br>  ][order(variant_bin)<br>  ][, `:=` (year_group = fcase(<br>    year %in% c(2019, 2020, 2021), &quot;2019-2021&quot;,<br>    year %in% c(2022, 2023, 2024), &quot;2022-2024&quot;<br>  ))<br>  ][, `:=` (variant_bin = forcats::fct_rev(variant_bin))]</pre><p>The resulting table is exactly as we need it for charting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlKAv8CwioGfl_q1yf4fTw.png" /></figure><p>The second plot uses transaction date, so the data wrangling is similar, but without date[1] step.</p><p>If we want to have a couple of plots combined, we can produce them separately, and combine using for example ggpubr::ggarrange() or we can blend tables into one dataset and then use faceting functionality. The former is when plots are of completely different nature, while latter is useful, when we can naturally have combined dataset.</p><p>As an example, few more lines from my script.</p><pre>x3h_dt &lt;- data.table::rbindlist(<br>  l = list(<br>    introduction = x3e_dt[, `:=` (year = as.numeric(as.character(year)))], <br>    transaction  = x3g_dt), <br>  use.names = T, fill = T, idcol = T)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbIeipanxC15SQGKoRWVVg.png" /></figure><p>And a plot code.</p><pre>plot_04_w &lt;- x3h_dt |&gt;<br>  ggplot(aes(year, total_products, <br>    color = variant_bin, fill = variant_bin, group = .id)) +<br>  geom_col(alpha = .8) +<br>  theme_bw() +<br>  scale_fill_viridis_d(direction = 1, option = &quot;G&quot;) +<br>  scale_color_viridis_d(direction = 1, option = &quot;G&quot;) +<br>  labs(x = &quot;&quot;, y = &quot;Base Products&quot;, <br>    title = &quot;Products, and their variants&quot;, <br>    subtitle = &quot;Yearly&quot;,<br>    fill = &quot;Variants&quot;,    <br>    color = &quot;Variants&quot;) +<br>  facet_wrap(&quot;.id&quot;, ncol = 2) +<br>  theme(... other styling options)</pre><p>Faceting has massive advantage, because we operate on one table, which helps a lot in assuring data consistency.</p><h4>Pareto</h4><p>The essence of Pareto calculation is to find how many products do we need to achieve certain revenue percentage. We need to prepare the dataset, in a couple of steps.</p><pre>#-- calculate quantity and revenue per base_product, monthly<br>x3a_dt &lt;- x3_dt[, {<br>  items = sum(lineitem_quantity, na.rm = T); <br>  revenue = sum(lineitem_quantity * lineitem_price); <br>  .(items, revenue)}, keyby = .(month, base_product)<br>  ][, `:=` (i = 1)][order(-revenue)][revenue &gt; 0, ]<br><br>#-- calculate percentage share, and cumulative percentage<br>x3a_dt[, `:=` (<br>  rev_pct = revenue / sum(revenue), <br>  cum_rev_pct = cumsum(revenue) / sum(revenue), prod_n = cumsum(i)), month]</pre><p>In case we’d need to mask exact product names, let us create a new variable.</p><pre>#-- products name masking<br>x3a_dt[, masked_name := paste(&quot;Product&quot;, .GRP), by = base_product]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_SeZMFX0b-L1H6Q6ELmEA.png" /></figure><p>And dataset printout, with a subset of columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMvF8pIgpnzTp6iLnkkmhg.png" /></figure><p>And filtered for one month, showing few lines from top and from the bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OCNYsMDvAs0NxFmN4b43Ng.png" /></figure><p>The essential column is cum_rev_pct, which indicates cumulative percentage revenue from products 1-n. We need to find which prod_n covers revenue percentage threshold, as in the pct_thresholds_dt table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hiMmEfB5ulXitoyqiFyqRA.png" /></figure><p>So we are ready for actual Pareto calculation. The code below, with comments.</p><pre>#-- pareto<br>#-- set percentage thresholds<br>pct_thresholds_dt &lt;- data.table(cum_rev_pct = c(0, .2, .3, .5, .8, .95, 1))<br><br>#-- set key for join<br>list(x3a_dt, pct_thresholds_dt) |&gt; lapply(setkey, cum_rev_pct)<br><br>#-- subset columns (optional)<br>sel_cols &lt;- c(&quot;month&quot;, &quot;cum_rev_pct&quot;, &quot;prod_n&quot;)<br><br>#-- perform a rolling join - crucial step!<br>x3b_dt &lt;- x3a_dt[, .SD[pct_thresholds_dt, roll = -Inf], month][, ..sel_cols]</pre><p>Why do we perform a rolling join? We need to find the first cum_rev_pct to cover each threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYeG09CtMzUeVqHhsaqNfw.png" /></figure><p>We need 2 products for 20% revenue, 4 products for 30% and so on. And to have 100% revenue, of course we need contribution from all 72 products.</p><p>And a plot.</p><pre>#-- data prep<br>x3b1_dt &lt;- x3b_dt[month &lt; month_max, <br>  .(month, cum_rev_pct = as.factor(cum_rev_pct) |&gt; forcats::fct_rev(), prod_n)]<br><br>#-- charting<br>plot_07_w &lt;- x3b1_dt |&gt;<br>  ggplot(aes(month, prod_n, color = cum_rev_pct, fill = cum_rev_pct)) +<br>  geom_line() +<br>  theme_bw() +<br>  geom_area(alpha = .2, show.legend  = F, position = position_dodge(width = 0)) +<br>  scale_fill_viridis_d(direction = -1, option = &quot;G&quot;, begin = 0.2, end = .9) +<br>  scale_color_viridis_d(direction = -1, option = &quot;G&quot;, begin = 0.2, end = .9,<br>                        labels = function(x) scales::percent(as.numeric(as.character(x)))  # Convert factor to numeric first<br>  ) +<br>  ... other styling options ...</pre><h4>Lorenz curve</h4><p>To plot Lorenz curve, we need to sort products by it’s contribution to total revenue, and normalize both number of products and revenue.</p><p>Before the main code, a handy method to pick n-th month from the dataset, from beginning or from the end.</p><pre>month_sel &lt;- x3a_dt$month |&gt; unique() |&gt; sort(decreasing = T) |&gt; dplyr::nth(2)</pre><p>And the code.</p><pre>xl_oct24_dt &lt;- x3a_dt[month == month_sel, <br>  ][order(-revenue), .(<br>    cum_prod_pct = seq_len(.N)/.N, <br>    cum_rev_pct = cumsum(revenue)/sum(revenue))]</pre><p>To chart separate lines per each time period, we need to modify accordingly.</p><pre>#-- Lorenz curve, yearly aggregation<br>xl_dt &lt;- x3a_dt[order(-revenue), .(<br>    cum_prod_pct = seq_len(.N)/.N, <br>    cum_rev_pct = cumsum(revenue)/sum(revenue)), month]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rg-afsXUM77JY4tVMspyvg.png" /></figure><p>The xl_dt dataset is ready for charting.</p><h4>Indices, ratios</h4><p>The code is straightforward here, assuming sufficient prior data preparation. The logic and some snippets in the main body of this article.</p><h4>Streamgraph</h4><p>The streamgraph shown earlier is an example of a chart that may appear difficult to render, especially when interactivity is required. One of the reasons I included it in this blog is to show how we can simplify tasks with keys, joins, and data.table syntax in particular. Using keys, we can achieve very effective filtering for interactivity. Once we have a handle on the data, we’re virtually done; all that remains are some settings to fine-tune the plot.</p><p>We start with thresholds table.</p><pre>#-- set percentage thresholds<br>pct_thresholds_dt &lt;- data.table(cum_rev_pct = c(0, .2, .3, .5, .8, .95, 1))</pre><p>Since we want joins performed monthly, it is good to create a data subset covering one month, to test the logic, before extending for a full dataset.</p><pre>#-- test logic for one month<br>month_sel &lt;- as.Date(&quot;2020-01-01&quot;)<br>sel_a_cols &lt;- c(&quot;month&quot;, &quot;rev_pct&quot;, &quot;cum_rev_pct&quot;, &quot;prod_n&quot;, &quot;masked_name&quot;)<br>x3a1_dt &lt;- x3a_dt[month == month_sel, ..sel_a_cols]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJO-Q3hCcC92WDgRWNAmJg.png" /></figure><p>We have 23 products in January 2020, sorted by revenue percentage, and we also have cumulative revenue, reaching 100% with the last, 23rd product.</p><p>Now we need to create an intermediate table, telling us how many products do we need to achieve each revenue threshold.</p><pre>#-- set key for join<br>list(x3a1_dt, pct_thresholds_dt) |&gt; lapply(setkey, cum_rev_pct)<br><br>#-- perform a rolling join - crucial step!<br>sel_b_cols &lt;- c(&quot;month&quot;, &quot;cum_rev_pct&quot;, &quot;prod_n&quot;)<br>x3b1_dt &lt;- x3a1_dt[, .SD[pct_thresholds_dt, roll = -Inf], month][, ..sel_b_cols]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qM7tovjciF1EH1MVwEUG2A.png" /></figure><p>Because we work with a one-month data subset (and picking month with not that many products), it is very easy to check the outcome — comparing x3a1_dt and x3b1_dt tables.</p><p>And now we need to get products names, for selected threshold.</p><pre>#-- get products<br>#-- set keys<br>list(x3a1_dt, x3b1_dt) |&gt; lapply(setkey, month, prod_n)<br><br>#-- specify threshold<br>x3b1_dt[cum_rev_pct == .8][x3a1_dt, roll = -Inf, nomatch = 0]<br><br>#-- or, an equivalent, specify table&#39;s row<br>x3b1_dt[5, ][x3a1_dt, roll = -Inf, nomatch = 0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0P1WNBScfSivJ7aQf9vdcg.png" /></figure><p>To achieve 80% revenue, we need 7 products, and from the join above, we get their names.</p><p>I think you already see, why we use rolling joins, and can’t use simle &lt; or &gt; logic.</p><p>Now, we need to extend the logic for all months.</p><pre>#-- extend for all months<br><br>#-- set key for join<br>list(x3a_dt, pct_thresholds_dt) |&gt; lapply(setkey, cum_rev_pct)<br><br>#-- subset columns (optional)<br>sel_cols &lt;- c(&quot;month&quot;, &quot;cum_rev_pct&quot;, &quot;prod_n&quot;)<br><br>#-- perform a rolling join - crucial step!<br>x3b_dt &lt;- x3a_dt[, .SD[pct_thresholds_dt, roll = -Inf], month][, ..sel_cols]</pre><p>Get the products.</p><pre>#-- set keys, join<br>list(x3a_dt, x3b_dt) |&gt; lapply(setkey, month, prod_n)<br>x3b6_dt &lt;- x3b_dt[cum_rev_pct == .8][x3a_dt, roll = -Inf, nomatch = 0][, ..sel_a_cols]</pre><p>And verify, for the same month as in a test data subset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqXWWKuGlz02iDeE0stYcQ.png" /></figure><p>If we want to freeze products for a certain month, and see revenue from them in the whole period (what second streamgraphs shows), we can set key on product name and perform a join.</p><pre>#-- freeze products<br>x3b6_key_dt &lt;- x3b6_dt[month == month_sel, .(masked_name)]<br>list(x3a_dt, x3b6_key_dt) |&gt; lapply(setkey, masked_name)<br><br>sel_b2_cols &lt;- c(&quot;month&quot;, &quot;revenue&quot;, &quot;masked_name&quot;)<br>x3a6_dt &lt;- x3a_dt[x3b6_key_dt][, ..sel_b2_cols]</pre><p>And we get exactly, what we needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWFvf02hi4_YY9Q5OneNaw.png" /></figure><p>Using joins, including rolls, and deciding what can be precalculated in a warehouse, and what is left for dynamic filtering in a dashboard does require some practice, but it definitely pays off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*vC4zfvenDCAZ18zh7KtacQ.png" /><figcaption>Image generated by DALL-E, based on author’s prompt, inspired by “The Bremen Town Musicians”</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc3d0876acd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/inequality-in-practice-e-commerce-portfolio-analysis-adc3d0876acd">Inequality in Practice: E-commerce Portfolio Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synthetic Data in Practice: A Shopify Case Study]]></title>
            <link>https://medium.com/data-science/synthetic-data-in-practice-a-shopify-case-study-79b0af024880?source=rss-c2cbb15c14cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/79b0af024880</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <dc:creator><![CDATA[Piotr Gruszecki]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 13:02:24 GMT</pubDate>
            <atom:updated>2024-12-10T13:02:24.891Z</atom:updated>
            <content:encoded><![CDATA[<h4>Testing new Snowflake functionality with a 30k records dataset</h4><figure><img alt="Image created with DALL·E." src="https://cdn-images-1.medium.com/max/1024/1*ReC2-bh_PXCLA463IFvTrw.png" /><figcaption>Image created with DALL·E, based on author’s prompt</figcaption></figure><p>Working with data, I keep running into the same problem more and more often. On one hand, we have growing requirements for data privacy and confidentiality; on the other — the need to make quick, data-driven decisions. Add to this the modern business reality: freelancers, consultants, short-term projects.</p><p>As a decision maker, I face a dilemma: I need analysis right now, the internal team is overloaded, and I can’t just hand over confidential data to every external analyst.</p><p>And this is where synthetic data comes in.</p><p>But wait — I don’t want to write another theoretical article about what synthetic data is. There are enough of those online already. Instead, I’ll show you a specific comparison: 30 thousand real Shopify transactions versus their synthetic counterpart.</p><p>What exactly did I check?</p><ul><li>How faithfully does synthetic data reflect real trends?</li><li>Where are the biggest discrepancies?</li><li>When can we trust synthetic data, and when should we be cautious?</li></ul><p>This won’t be another “how to generate synthetic data” guide (though I’ll show the code too). I’m focusing on what really matters — whether this data is actually useful and what its limitations are.</p><p>I’m a practitioner — less theory, more specifics. Let’s begin.</p><h3>Data Overview</h3><p>When testing synthetic data, you need a solid reference point. In our case, we’re working with real transaction data from a growing e-commerce business:</p><ul><li>30,000 transactions spanning 6 years</li><li>Clear growth trend year over year</li><li>Mix of high and low-volume sales months</li><li>Diverse geographical spread, with one dominant market</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8ox81HH7nauOwVruUermw.png" /><figcaption>All charts created by author, using his own R code</figcaption></figure><p>For practical testing, I focused on transaction-level data such as order values, dates, and basic geographic information. Most assessments require only essential business information, without personal or product specifics.</p><p>The procedure was simple: export raw Shopify data, analyze it to maintain only the most important information, produce synthetic data in Snowflake, then compare the two datasets side by side. One can think of it as generating a “digital twin” of your business data, with comparable trends but entirely anonymized.</p><p><em>[Technical note: If you’re interested in the detailed data preparation process, including R code and Snowflake setup, check the appendix at the end of this article.]</em></p><h3>Monthly Revenue Analysis</h3><p>The first test for any synthetic dataset is how well it captures core business metrics. Let’s start with monthly revenue — arguably the most important metric for any business (for sure in top 3).</p><p>Looking at the raw trends (Figure 1), both datasets follow a similar pattern: steady growth over the years with seasonal fluctuations. The synthetic data captures the general trend well, including the business’s growth trajectory. However, when we dig deeper into the differences, some interesting patterns emerge.</p><p>To quantify these differences, I calculated a monthly delta:</p><pre>Δ % = (Synthetic - Shopify) / Shopify</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6SQOkplSmuKufgBZQ0Qaw.png" /></figure><p>We see from the plot, that monthly revenue delta varies — sometimes original is bigger, and sometimes synthetic. But the bars seem to be symmetrical and also the differences are getting smaller with time. I added number of records (transactions) per month, maybe it has some impact? Let’s dig a bit deeper.</p><p>The deltas are indeed quite well balanced, and if we look at the cumulative revenue lines, they are very well aligned, without large variations. I am skipping this chart.</p><h3>Sample Size Impact</h3><p>The deltas are getting smaller, and we intuitively feel it is because of larger number of records. Let us check it — next plot shows absolute values of revenue deltas as a function of records per month. While the number of records does grow with time, the X axis is not exactly time — it’s the records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmLmfIHF9a4P7cHzP8M1Vw.png" /></figure><p>The deltas (absolute values) do decrease, as the number of records per month is higher — as we expected. But there is one more thing, quite intriguing, and not that obvious, at least at first glance. Above around 500 records per month, the deltas do not fall further, they stay at (in average) more or less same level.</p><p>While this specific number is derived from our dataset and might vary for different business types or data structures, the pattern itself is important: there exists a threshold where synthetic data stability improves significantly. Below this threshold, we see high variance; above it, the differences stabilize but don’t disappear entirely — synthetic data maintains some variation by design, which actually helps with privacy protection.</p><p>There is a noise, which makes monthly values randomized, also with larger samples. All, while preserves consistency on higher aggregates (yearly, or cumulative). And while reproducing overall trend very well.</p><p>It would be quite interesting to see similar chart for other metrics and datasets.</p><p>We already know revenue delta depends on number of records, but is it just that more records in a given month, the higher the revenue of synthetic data? Let us find out …</p><p>So we want to check how revenue delta depends on number of records delta. And we mean by delta Synthetic-Shopify, whether it is monthly revenue or monthly number of records.</p><p>The chart below shows exactly this relationship. There is some (light) correlation - if number of records per month differ substantially between Synthetic and Shopify, or vice-versa (high delta values), the revenue delta follows. But it is far from simple linear relationship - there is extra noise there as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uowxnpem0fi8ARwt1cAC0A.png" /></figure><h3>Dimensional Analysis</h3><p>When generating synthetic data, we often need to preserve not just overall metrics, but also their distribution across different dimensions like geography. I kept country and state columns in our test dataset to see how synthetic data handles dimensional analysis.</p><p>The results reveal two important aspects:</p><ol><li>The reliability of synthetic data strongly depends on the sample size within each dimension</li><li>Dependencies between dimensions are not preserved</li></ol><p>Looking at revenue by country:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eM6A4uibaVRhPz2c1Rf08g.png" /></figure><p>For the dominant market with thousands of transactions, the synthetic data provides a reliable representation — revenue totals are comparable between real and synthetic datasets. However, for countries with fewer transactions, the differences become significant.</p><p>A critical observation about dimensional relationships: in the original dataset, state information appears only for US transactions, with empty values for other countries. However, in the synthetic data, this relationship is lost — we see randomly generated values in both country and state columns, including states assigned to other countries, not US. This highlights an important limitation: synthetic data generation does not maintain logical relationships between dimensions.</p><p>There is, however, a practical way to overcome this country-state dependency issue. Before generating synthetic data, we could preprocess our input by concatenating country and state into a single dimension (e.g., ‘US-California’, ‘US-New York’, while keeping just ‘Germany’ or ‘France’ for non-US transactions). This simple preprocessing step would preserve the business logic of states being US-specific and prevent the generation of invalid country-state combinations in the synthetic data.</p><p>This has important practical implications:</p><ul><li>Synthetic data works well for high-volume segments</li><li>Be cautious when analyzing smaller segments</li><li>Always check sample sizes before drawing conclusions</li><li>Be aware that logical relationships between dimensions may be lost, consider pre-aggregation of some columns</li><li>Consider additional data validation if dimensional integrity is crucial</li></ul><h3>Transaction value distribution</h3><p>One of the most interesting findings in this analysis comes from examining transaction value distributions. Looking at these distributions year by year reveals both the strengths and limitations of synthetic data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcqaaWBf3uZMtRUo38mzxA.png" /></figure><p>The original Shopify data shows what you’d typically expect in e-commerce: highly asymmetric distribution with a long tail towards higher values, and distinct peaks corresponding to popular single-product transactions, showing clear bestseller patterns.</p><p>The synthetic data tells an interesting story: it maintains very well the overall shape of the distribution, but the distinct peaks from bestseller products are smoothed out. The distribution becomes more “theoretical”, losing some real-world specifics.</p><p>This smoothing effect isn’t necessarily a bad thing. In fact, it might be preferable in some cases:</p><ul><li>For general business modeling and forecasting</li><li>When you want to avoid overfitting to specific product patterns</li><li>If you’re looking for underlying trends rather than specific product effects</li></ul><p>However, if you’re specifically interested in bestseller analysis or single-product transaction patterns, you’ll need to factor in this limitation of synthetic data.</p><p>Knowing, the goal is product analysis, we’d prepare original dataset differently.</p><p>To quantify how well the synthetic data matches the real distribution, we’ll look at statistical validation in the next section.</p><h3>Statistical Validation (K-S Test)</h3><p>Let’s validate our observations with the Kolmogorov-Smirnov test — a standard statistical method for comparing two distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KX0VJkKY-l0-iK-nNER5NQ.png" /></figure><p>The findings are positive, but what do these figures mean in practice? The Kolmogorov-Smirnov test compares two distributions and returns two essential metrics: D = 0.012201 (smaller is better, with 0 indicating identical distributions), and p-value = 0.0283 (below the normal 0.05 level, indicating statistically significant differences).</p><p>While the p-value indicates some variations between distributions, the very low D statistic (nearly to 0) verifies the plot’s findings: a near-perfect match in the middle, with just slight differences at the extremities. The synthetic data captures crucial patterns while keeping enough variance to ensure anonymity, making it suitable for commercial analytics.</p><p>In practical terms, this means:</p><ul><li>The synthetic data provides an excellent match in the most important mid-range of transaction values</li><li>The match is particularly strong where we have the most data points</li><li>Differences appear mainly in edge cases, which is expected and even desirable from a privacy perspective</li><li>The statistical validation confirms our visual observations from the distribution plots</li></ul><p>This kind of statistical validation is crucial before deciding to use synthetic data for any specific analysis. In our case, the results suggest that the synthetic dataset is reliable for most business analytics purposes, especially when focusing on typical transaction patterns rather than extreme values.</p><h3>Conclusions</h3><p>Let’s summarize our journey from real Shopify transactions to their synthetic counterpart.</p><p>Overall business trends and patterns are maintained, including transactions value distributions. Spikes are ironed out, resulting in more theoretical distributions, while maintaining key characteristics.</p><p>Sample size matters, by design. Going too granular we will get noise, preserving confidentiality (in addition to removing all PII of course).</p><p>Dependencies between columns are not preserved (country-state), but there is an easy walk around, so I think it is not a real issue.</p><p>It is important to understand how the generated dataset will be used — what kind of analysis we expect, so that we can take it into account while reshaping the original dataset.</p><p>The synthetic dataset will work perfectly for applications testing, but we should manually check edge cases, as these might be missed during generation.</p><p>In our Shopify case, the synthetic data proved reliable enough for most business analytics scenarios, especially when working with larger samples and focusing on general patterns rather than specific product-level analysis.</p><h3>Future Work</h3><p>This analysis focused on transactions, as one of key metrics and an easy case to start with.</p><p>We can proceed with products analysis and also explore multi-table scenarios.</p><p>It is also worth to develop internal guidelines how to use synthetic data, including check and limitations.</p><h3>Appendix: Data Preparation and Methodology</h3><p>You can scroll through this section, as it is quite technical on how to prepare data.</p><h4>Raw Data Export</h4><p>Instead of relying on pre-aggregated Shopify reports, I went straight for the raw transaction data. At Alta Media, this is our standard approach — we prefer working with raw data to maintain full control over the analysis process.</p><p>The export process from Shopify is straightforward but not immediate:</p><ul><li>Request raw transaction data export from the admin panel</li><li>Wait for email with download links</li><li>Download multiple ZIP files containing CSV data</li></ul><h4>Data Reshaping</h4><p>I used R for exploratory data analysis, processing, and visualization. The code snippets are in R, copied from my working scripts, but of course one can use other languages to achieve the same final data frame.</p><p>The initial dataset had dozens of columns, so the first step was to select only the relevant ones for our synthetic data experiment.</p><p><em>Code formatting is adjusted, so that we don’t have horizontal scroll.</em></p><pre>#-- 0. libs<br>pacman::p_load(data.table, stringr, digest)<br><br>#-- 1.1 load data; the csv files are what we get as a <br># full export from Shopify<br>xs1_dt &lt;- fread(file = &quot;shopify_raw/orders_export_1.csv&quot;)<br>xs2_dt &lt;- fread(file = &quot;shopify_raw/orders_export_2.csv&quot;)<br>xs3_dt &lt;- fread(file = &quot;shopify_raw/orders_export_3.csv&quot;)<br><br>#-- 1.2 check all columns, limit them to essential (for this analysis) <br># and bind into one data.table<br>xs1_dt |&gt; colnames()<br># there are 79 columns in full export, so we select a subset, <br># relevant for this analysis<br>sel_cols &lt;- c(<br>&quot;Name&quot;, &quot;Email&quot;, &quot;Paid at&quot;, &quot;Fulfillment Status&quot;, &quot;Accepts Marketing&quot;, <br>&quot;Currency&quot;, &quot;Subtotal&quot;, <br>&quot;Lineitem quantity&quot;, &quot;Lineitem name&quot;, &quot;Lineitem price&quot;, &quot;Lineitem sku&quot;, <br>&quot;Discount Amount&quot;, &quot;Billing Province&quot;, &quot;Billing Country&quot;)</pre><p>We need one data frame, so we need to combine three files. Since we use data.table package, the syntax is very simple. And we pipe combined dataset to trim columns, keeping only selected ones.</p><pre>xs_dt &lt;- data.table::rbindlist(<br>  l = list(xs1_dt, xs2_dt, xs3_dt), <br>  use.names = T, fill = T, idcol = T) %&gt;% .[, ..sel_cols]</pre><p>Let’s also change column names to single string, replacing spaces with underscore “_” — we don’t need to deal with extra quotations in SQL.</p><pre>#-- 2. data prep<br>#-- 2.1 replace spaces in column names, for easier handling<br>sel_cols_new &lt;- sel_cols |&gt; <br>  stringr::str_replace(pattern = &quot; &quot;, replacement = &quot;_&quot;)<br><br>setnames(xs_dt, old = sel_cols, new = sel_cols_new)</pre><p>I also change transaction id from character “#1234”, to numeric “1234”. I create a new column, so we can easily compare if transformation went as expected.</p><pre>xs_dt[, `:=` (Transaction_id = stringr::str_remove(Name, pattern = &quot;#&quot;) |&gt; <br>              as.integer())]</pre><p>Of course you can also overwrite.</p><h4>Extra experimentation</h4><p>Since this was an experiment with Snowflake’s synthetic data generation, I made some additional preparations. The Shopify export contains actual customer emails, which would be masked in Snowflake while generating synthetic data, but I hashed them anyway.</p><p>So I hashed these emails using MD5 and created an additional column with numerical hashes. This was purely experimental — I wanted to see how Snowflake handles different types of unique identifiers.</p><p>By default, Snowflake masks text-based unique identifiers as it considers them personally identifiable information. For a real application, we’d want to remove any data that could potentially identify customers.</p><pre>new_cols &lt;- c(&quot;Email_hash&quot;, &quot;e_number&quot;)<br>xs_dt[, (new_cols) := .(digest::digest(Email, algo = &quot;md5&quot;),<br>                        digest::digest2int(Email, seed = 0L)), .I]</pre><p>I was also curious how logical column will be handled, so I changed type of a binary column, which has “yes/no” values.</p><pre>#-- 2.3 change Accepts_Marketing to logical column<br>xs_dt[, `:=` (Accepts_Marketing_lgcl = fcase(<br>    Accepts_Marketing == &quot;yes&quot;, TRUE, <br>    Accepts_Marketing == &quot;no&quot;, FALSE, <br>    default = NA))]</pre><h4>Filter transactions</h4><p>The dataset contains records per each item, while for this particular analysis we need only transactions.</p><pre>xs_dt[Transaction_id == 31023, .SD, .SDcols = c(<br>  &quot;Transaction_id&quot;, &quot;Paid_at&quot;, &quot;Currency&quot;, &quot;Subtotal&quot;, &quot;Discount_Amount&quot;, <br>  &quot;Lineitem_quantity&quot;, &quot;Lineitem_price&quot;, &quot;Billing_Country&quot;)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnC2MAtaPPjofu_t8uqaGA.png" /></figure><p>Final subset of columns and filtering records with total amount paid.</p><pre>trans_sel_cols &lt;- c(<br>  &quot;Transaction_id&quot;, &quot;Email_hash&quot;, &quot;e_number&quot;, &quot;Paid_at&quot;, &quot;Subtotal&quot;, <br>  &quot;Currency&quot;, &quot;Billing_Province&quot;, &quot;Billing_Country&quot;,<br>  &quot;Fulfillment_Status&quot;, &quot;Accepts_Marketing_lgcl&quot;)<br>xst_dt &lt;- xs_dt[!is.na(Paid_at), ..trans_sel_cols]</pre><h4>Export dataset</h4><p>Once we have a dataset, we nee to export it as a csv file. I export full dataset, and I also produce a 5% sample, which I use for initial test run in Snowflake.</p><pre>#-- full dataset<br>xst_dt |&gt; fwrite(file = &quot;data/transactions_a.csv&quot;)<br>#-- a 5% sample<br>xst_5pct_dt &lt;- xst_dt[sample(.N, .N * .05)]<br>xst_5pct_dt |&gt; fwrite(file = &quot;data/transactions_a_5pct.csv&quot;)</pre><p>And also saving in Rds format, so I don’t need to repeat all the preparatory steps (which are scripted, so they are executed in seconds anyway).</p><pre>#-- 3.3 save Rds file<br>list(xs_dt = xs_dt, xst_dt = xst_dt, xst_5pct_dt = xst_5pct_dt) |&gt; <br>  saveRDS(file = &quot;data/xs_lst.Rds&quot;)</pre><h3>Appendix: Data generation in Snowflake</h3><p>Once we have our dataset, prepared according to our needs, generation of it’s synthetic “sibling” is straightforward. One needs to upload the data, run generation, and export results. For details follow Snowflake guidelines. Anyway, I will add here short summary, for complteness of this article.</p><p>First, we need to make some preparations — role, database and warehouse.</p><pre>USE ROLE ACCOUNTADMIN;<br>CREATE OR REPLACE ROLE data_engineer;<br>CREATE OR REPLACE DATABASE syndata_db;<br>CREATE OR REPLACE WAREHOUSE syndata_wh WITH<br>  WAREHOUSE_SIZE = &#39;MEDIUM&#39;<br>  WAREHOUSE_TYPE = &#39;SNOWPARK-OPTIMIZED&#39;;<br><br>GRANT OWNERSHIP ON DATABASE syndata_db TO ROLE data_engineer;<br>GRANT USAGE ON WAREHOUSE syndata_wh TO ROLE data_engineer;<br>GRANT ROLE data_engineer TO USER &quot;PIOTR&quot;;<br>USE ROLE data_engineer;</pre><p>Create schema and stage, if not defined yet.</p><pre>CREATE SCHEMA syndata_db.experimental;<br><br>CREATE STAGE syn_upload <br> DIRECTORY = ( ENABLE = true ) <br> COMMENT = &#39;import files&#39;;</pre><p>Upload csv files(s) to stage, and then import them to table(s).</p><p>Then, run generation of synthetic data. I like having a small “pilot”, somethiong like 5% records to make initial check if it goes through. It is a time saver (and costs too), in case of more complicated cases, where we might need some SQL adjustment. In this case it is rather pro-forma.</p><pre>-- generate synthetic<br>-- small file, 5% records<br>call snowflake.data_privacy.generate_synthetic_data({<br>    &#39;datasets&#39;:[<br>    {<br>        &#39;input_table&#39;:  &#39;syndata_db.experimental.transactions_a_5pct&#39;,<br>        &#39;output_table&#39;: &#39;syndata_db.experimental.transactions_a_5pct_synth&#39;    <br>    }<br>    ],<br>    &#39;replace_output_tables&#39;:TRUE<br>});</pre><p>It is good to inspect what we have as a result — checking tables directly in Snowflake.</p><p>And then run a full dataset.</p><pre>-- large file, all records<br>call snowflake.data_privacy.generate_synthetic_data({<br>    &#39;datasets&#39;:[<br>    {<br>        &#39;input_table&#39;:  &#39;syndata_db.experimental.transactions_a&#39;,<br>        &#39;output_table&#39;: &#39;syndata_db.experimental.transactions_a_synth&#39;    <br>    }<br>    ],<br>    &#39;replace_output_tables&#39;:TRUE<br>});</pre><p>The execution time is non-linear, for the full dataset it is way, way faster than what data volume would suggest.</p><p>Now we export files.</p><p>Some preparations:</p><pre>-- export files to unload stage<br>CREATE STAGE syn_unload <br> DIRECTORY = ( ENABLE = true ) <br> COMMENT = &#39;export files&#39;;<br><br>CREATE OR REPLACE FILE FORMAT my_csv_unload_format<br>  TYPE = &#39;CSV&#39;<br>  FIELD_DELIMITER = &#39;,&#39;<br>  FIELD_OPTIONALLY_ENCLOSED_BY = &#39;&quot;&#39;;</pre><p>And export (small and full dataset):</p><pre>COPY INTO @syn_unload/transactions_a_5pct_synth <br>FROM syndata_db.experimental.transactions_a_5pct_synth<br>FILE_FORMAT = my_csv_unload_format<br>HEADER = TRUE;<br><br>COPY INTO @syn_unload/transactions_a_synth <br>FROM syndata_db.experimental.transactions_a_synth<br>FILE_FORMAT = my_csv_unload_format<br>HEADER = TRUE;</pre><p>So now we have both original Shopify dataset and Synthetic. Time to analyze, compare, and make some plots.</p><h3>Appendix: Data comparison &amp; charting</h3><p>For this analysis, I used R for both data processing and visualization. The choice of tools, however, is secondary — the key is having a systematic approach to data preparation and validation. Whether you use R, Python, or other tools, the important steps remain the same:</p><ul><li>Clean and standardize the input data</li><li>Validate the transformations</li><li>Create reproducible analysis</li><li>Document key decisions</li></ul><p>The detailed code and visualization techniques could indeed be a topic for another article.</p><p>If you’re interested in specific aspects of the implementation, feel free to reach out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79b0af024880" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/synthetic-data-in-practice-a-shopify-case-study-79b0af024880">Synthetic Data in Practice: A Shopify Case Study</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>