<?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 Konrad Maliszewski on Medium]]></title>
        <description><![CDATA[Stories by Konrad Maliszewski on Medium]]></description>
        <link>https://medium.com/@konrad.maliszewski?source=rss-945d51cfa739------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QzjiFHkBj7EAo_iW--0Z-w.jpeg</url>
            <title>Stories by Konrad Maliszewski on Medium</title>
            <link>https://medium.com/@konrad.maliszewski?source=rss-945d51cfa739------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:13:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@konrad.maliszewski/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[Working with Google Analytics API]]></title>
            <link>https://medium.com/atheon-analytics/working-with-google-analytics-api-50def41ef229?source=rss-945d51cfa739------2</link>
            <guid isPermaLink="false">https://medium.com/p/50def41ef229</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Konrad Maliszewski]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 15:34:59 GMT</pubDate>
            <atom:updated>2024-11-25T15:36:33.557Z</atom:updated>
            <content:encoded><![CDATA[<p>Google Analytics (GA) is a rich and powerful data source, offering insights into website performance and user behaviour. But, if you want to leverage this data along with some other data sets from your business, you’re going to need to extract, transform and visualise it on your own. For an extension to the existing project, I had the opportunity to play with the API to see what’s possible. The aim is to distil GA’s richness into a set of key metrics. These metrics should offer a solid foundation for e-commerce monitoring and some ideas for future experiments and trials. In this post, I’ll walk you through what I discovered about working with the GA’s API as well as offer some ideas on what the final set of KPIs could look like. Of course, I keep testing the Cursor IDE and the LLMs that come with it, so expect some mentions of these features!</p><h3>Getting set up</h3><p>In short, you’ll need a service account on Google Cloud Platform (GCP), which must be added to the selected property in GA. This <a href="https://www.lupagedigital.com/blog/google-analytics-api-python/">linked article</a> provides detailed instructions on setting it up. It is relatively simple and painless, especially if you’re an existing user of GCP and already have a project there. I think that same account can be reused across multiple GA accounts, if you’re working with multiple clients / organisations, which is very efficient as well.</p><h3>Connecting to the API</h3><p>This is very easy as well. Once you have your service account credentials and have been added to GA, you define these variables and using the GA Python package, <a href="https://pypi.org/project/google-analytics-data/">google-analytics-data</a>, you can very easily connect to the API. In fact, all you need to do is:</p><pre>from google.analytics.data_v1beta import BetaAnalyticsDataClient<br>import json<br><br><br># set your GA4 property ID<br>property_id = &quot;[your property ID]&quot;<br># load your service account info<br>service_account_info = json.load(open(‘[path to your credentials]’))<br># create a client to connect to GA4 API<br>client = BetaAnalyticsDataClient.from_service_account_info(service_account_info)</pre><h3>Using the Reporting API</h3><p>Given the aim of this project, for the time being, I’m only interested in the core reporting functionality. This means we’re only going to need the <a href="https://developers.google.com/analytics/devguides/reporting/data/v1/rest#rest-resource:-v1beta.properties">runReport endpoint</a>. The core elements of this endpoint include Dimensions and Metrics, which is a pretty standard approach. All of the available dimensions and metrics are well <a href="https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics">documented</a>.</p><p>The main challenge though is that the grains of data and associated available metrics and dimensions, as far as I can tell, are not documented anywhere. This means that a bit of trial and error is needed to get to the data that’s needed. Some of the dimensions behave quite strangely (again, to me, a GA novice!) at different levels of aggregation and I couldn’t really find any explanation in the official documentation. Claude and other LLMs were useless for that as well and the good old Google search and patching information from multiple sources was my last resort. I’ll explain in more detail.</p><h4>Creating e-commerce reports</h4><p>In order to create a flexible report for core e-commerce metrics, I thought that, ideally, I’d like a data set which is at a session level grain. With that I could create flexible time period selectors and attach a number of dimensions (e.g. info about the customer) and metrics (e.g. was this a transaction, was this a bounced session, etc.). This would enable me to create a comprehensive and flexible report. This was the requirement that I posed to Claude. It kept coming up with different ways to include session_id but it turns out there’s no such field and therefore no such grain available in the GA4 API.</p><p>After a bit of trial and error, I discovered that I could get data at a transaction_id grain. This means I’ll need to limit this data set to just actual sales but that’s fine. Here’s the configuration I managed to get for this report:</p><pre>dimensions:<br> - name: date<br>   column_name: Date<br>   type: string<br> - name: signedInWithUserId<br>   column_name: User ID<br>   type: string<br> - name: transactionId<br>   column_name: Transaction ID<br>   type: string<br> - name: sessionDefaultChannelGroup<br>   column_name: Session Default Channel Group<br>   type: string<br> - name: sessionSource<br>   column_name: Session Source<br>   type: string<br> - name: sessionMedium<br>   column_name: Session Medium<br>   type: string<br> - name: itemName<br>   column_name: Item Name<br>   type: string<br> - name: city<br>   column_name: City<br>   type: string<br> - name: country<br>   column_name: Country<br>   type: string<br><br><br>metrics:<br> - name: itemRevenue<br>   column_name: Item Revenue<br>   type: float<br> - name: itemDiscountAmount<br>   column_name: Item Discount Amount<br>   type: float<br> - name: itemsPurchased<br>   column_name: Items Purchased<br>   type: int</pre><p>Interestingly, while I was allowed to get information about city and country, dimensions such as gender or age bracket were not allowed with this combination of metrics and dimensions.</p><p>Still this data allows me to create basic KPI reporting along with some insight about where the revenue comes from as well as how it evolved over time. We can add additional filters and levels of detail, e.g. to allow the user to drill down into revenue channels and understand specific mediums and sources of revenue, e.g. Instagram: Instagram Stories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*knRwAzl3NLXE6tar" /><figcaption>Example KPI dashboard for e-commerce performance.</figcaption></figure><h4>Tracking site performance</h4><p>Another aspect that’s worth keeping an eye on is overall site performance. These metrics were the easiest to get from the GA4 API. Although, I had to be quite mindful of the grain of data.</p><pre>dimensions:<br> - name: isoYearIsoWeek<br>   column_name: Year Week<br>   type: string<br><br><br>metrics:<br> - name: purchaseRevenue<br>   column_name: Purchase Revenue<br>   type: float<br> - name: bounceRate<br>   column_name: Bounce Rate<br>   type: float<br> - name: addToCarts<br>   column_name: Add to Carts<br>   type: float<br> - name: sessions<br>   column_name: Sessions<br>   type: int<br> - name: purchaserRate<br>   column_name: Purchaser Rate<br>   type: float<br> - name: transactions<br>   column_name: Transactions<br>   type: int<br> - name: firstTimePurchaserRate<br>   column_name: First Time Purchaser Rate<br>   type: float<br> - name: purchaseToViewRate<br>   column_name: Purchase to View Rate<br>   type: float<br> - name: totalPurchasers<br>   column_name: Total Purchasers<br>   type: int<br> - name: firstTimePurchasers<br>   column_name: First Time Purchasers<br>   type: int</pre><p>A number of useful metrics can be retrieved for the required time dimension aggregation. Thanks to them, we can monitor the whole visitor / shopper journey — from a session, through bounce rates, abandoned basket rates through to successfully completed transactions. However, the tricky bit is that most of these metrics cannot be aggregated. For example, if I get a bounce rate (% of visitors who left the site without doing anything on it) at a daily grain, I cannot easily create a monthly bounce rate. I mustn’t add or average out these numbers as it’s going to be a different output to a monthly bounce rate. The problem here is that it’s a ratio metric (bounces / sessions).</p><p>Let’s use a simple example.</p><pre># Day 1:<br>Sessions: 1000<br>Bounces: 400<br>Bounce Rate: 40%<br><br># Day 2:<br>Sessions: 100<br>Bounces: 50<br>Bounce Rate: 50%<br><br># Wrong way (averaging daily rates):<br>Monthly Bounce Rate = (40% + 50%) / 2 = 45%<br><br># Correct way (using total bounces and total sessions):<br>Total Sessions: 1100<br>Total Bounces: 450<br>Monthly Bounce Rate = 450/1100 = 41%</pre><p>The difference occurs because:</p><ul><li>Each day has different session volumes.</li><li>Days with more sessions should have more weight in the final rate.</li><li>The correct calculation needs to maintain the relationship between the numerator (bounces) and denominator (sessions).</li></ul><p>So while in my core e-commerce reporting, I can get the lowest grain of data and then present it in many various ways. Here, the final presentation requirements drive data requirements. If I need to show monthly data, this is how I need to retrieve it. If I want to show weekly data by channel, again, this is the grain of data at which I need to retrieve and model the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aV655ii-BJlBTB49" /><figcaption>An example dashboard for tracking site performance KPIs.</figcaption></figure><h4>Understanding demographic data</h4><p>When working with Google Analytics API, one particularly interesting aspect is the ability to segment visitor data by demographics. The API offers metrics breakdown by gender, age brackets, and “Branding Interest” categories, providing valuable insights into who your visitors are.</p><p>While exploring demographics data, I discovered some interesting patterns in data availability across different time granularities. Here’s what I found:</p><ul><li>Daily data — attempting to pull daily demographics yielded sparse results with only a small fraction of total sessions represented.</li><li>Weekly data — moving to weekly aggregation improved coverage but still showed significant gaps.</li><li>Monthly data — the sweet spot appeared to be monthly data, where I obtained: The most comprehensive data for the previous complete month, partial data for the current month and limited data for two months ago.</li></ul><p>Regardless of the time granularity, I get very random numbers for metrics such as purchase revenue, transactions, total purchasers or first time purchasers. They’re tiny in only one month. I guess, it is theoretically possible that all of the people who purchased couldn’t be tracked, especially that only a fraction of sessions ends in a purchase. But then, I’d expect to see some, not nearly zero.</p><p>I also led myself to believe that I’m getting pretty good coverage of sessions (c. 60%) by summing up sessions at the grain of gender / age bracket / branding interest. However, when I removed the branding interest dimension, a new “unknown” category showed up in the gender dimension. Then it turned out that c. 80% of sessions don’t capture any demographic information about the visitor. This must mean that users belong to multiple branding interest categories and one mustn’t sum these values… More questions than answers wherever I look! Is there sampling involved? Is this data trustworthy? At what grain?</p><p>I found this <a href="https://www.analyticsmania.com/post/missing-demographic-data-in-google-analytics-4/">post</a> to explain at least some fundamentals about demographics data:</p><ol><li><strong>Google Signals </strong>— this feature must be enabled to collect demographics data. If you’re seeing any demographics data, that’s a good indication your Google Signals is properly configured.</li><li><strong>Data retention</strong> — the default retention window for demographics data is 2 months. This explains the limited historical data availability and why attempting to pull a year’s worth of data yielded incomplete results.</li><li><strong>Privacy considerations </strong>— the varying coverage at different time granularities likely relates to privacy protection measures. More granular (daily) data might be intentionally limited to prevent individual user identification.</li></ol><p>I assume that the last point explains a lot of what I’m seeing but it would be helpful if this were documented somewhere. For now, I think this needs more exploration before it becomes usable and useful at all. It might turn into its own post!</p><h3>Conclusions</h3><p>Working with the Google Analytics (GA) API has been a fascinating yet challenging experience. While the API provides access to a wealth of data, transforming it into actionable insights requires significant effort, trial, and error. Here are the key takeaways from this project:</p><ol><li><strong>Flexibility and Power, but at a Cost</strong> — the GA API offers remarkable flexibility, enabling the creation of tailored reports to meet specific business needs. However, this comes with a steep learning curve, particularly in understanding how dimensions and metrics interact and the levels of granularity available. The lack of clear documentation on certain behaviours (such as grain-specific metrics) necessitates patience and experimentation.</li><li><strong>Granularity Matters</strong> — selecting the correct data granularity is crucial, especially for ratio metrics like bounce rate or conversion rate. Misinterpreting how these metrics aggregate can lead to significant inaccuracies in reports. Always align the granularity of your data with your reporting requirements, whether daily, weekly, or monthly.</li><li><strong>E-commerce Insights Are Promising</strong> — for e-commerce reporting, using transaction-level data provides a rich dataset that facilitates flexible KPI monitoring and deeper insights into revenue sources and performance trends. While this level of granularity might initially seem restrictive, it is well-suited to tracking actual sales performance.</li><li><strong>Demographic Data Needs Caution</strong> — demographic insights offer exciting opportunities to better understand your audience. However, the data is fraught with inconsistencies and gaps, particularly at finer levels of granularity. The nuances of Google Signals and retention policies introduce further complexity. Proceed with caution, and validate assumptions rigorously before relying on this data for decision-making.</li><li><strong>Documentation and Support Gaps </strong>— while GA’s documentation is extensive, it falls short in several critical areas. This project relied heavily on external resources, community insights, and experimentation to uncover the nuances of the API. Some questions remain unanswered, particularly concerning the validity and sampling of demographic data.</li></ol><h4><strong>Closing Thoughts</strong></h4><p>The Google Analytics API opens up new possibilities for custom reporting and insights that go beyond the capabilities of the GA interface. However, harnessing its potential effectively requires clear goals, careful planning around data granularity, and a willingness to experiment. For e-commerce businesses and digital marketers, the effort pays dividends in more meaningful and actionable analytics, but always with an awareness of the data’s limitations and quirks.</p><p>If you’ve encountered similar challenges or found solutions to these hurdles, I’d love to hear your thoughts in the comments. Let’s keep the conversation going!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50def41ef229" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atheon-analytics/working-with-google-analytics-api-50def41ef229">Working with Google Analytics API</a> was originally published in <a href="https://medium.com/atheon-analytics">Atheon Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Food Standards Agency hygiene ratings data]]></title>
            <link>https://medium.com/atheon-analytics/leveraging-food-standards-agency-hygiene-ratings-data-be97fb87dad2?source=rss-945d51cfa739------2</link>
            <guid isPermaLink="false">https://medium.com/p/be97fb87dad2</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[open-data]]></category>
            <category><![CDATA[cursor-ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Konrad Maliszewski]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 18:49:58 GMT</pubDate>
            <atom:updated>2024-10-30T18:56:28.328Z</atom:updated>
            <content:encoded><![CDATA[<p>Open data sets are an analyst’s playground, rich with possibilities to enhance insights and tell compelling stories. One data set I’ve been fascinated with for a while is the Food Standards Agency (FSA) ratings data. It’s a straightforward but powerful collection of hygiene ratings from food outlets across the UK, gathered during mandatory inspections. In this post, I’ll walk you through how I retrieved and modelled this data using the FSA API and built a simple app with Streamlit. I’ll also reflect on my experience of revisiting this project with some new AI-powered tools.</p><h3>Getting to Know the FSA Ratings Data</h3><p>The FSA ratings data gives us a snapshot of the hygiene standards of food-selling outlets across the UK, from cosy cafes through bustling takeaways to large supermarkets. There are currently 599,000 records covering inspections by 363 local authorities. Interestingly, not every establishment has a rating — some are marked as “Exempt,” which hints at unique cases worth investigating.</p><p>The data is accessible through the <a href="https://ratings.food.gov.uk/open-data">FSA’s open API</a>, which provides hygiene ratings by local authority. To get the full picture, you can loop through all the authorities and retrieve the complete data set, which is what I did here. This data set is also covered by the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/">Open Government Licence</a>, which means you can do pretty much anything you want with it.</p><h3>Retrieving data from the API</h3><p>I wanted all the data saved locally for further analysis. At a high-level, my approach involved:</p><ol><li>Retrieving the list of local authority IDs from the API.</li><li>Using these IDs to find the link to each authority’s specific data file.</li><li>Assembling these links and downloading each data file.</li></ol><p>API documentation is available <a href="https://api.ratings.food.gov.uk/Help">here</a>. Let’s now look at the code required for each step.</p><h4>Retrieve IDs of local authorities</h4><p>From the Authorities endpoint, we’re able to get all of the basic information about all local authorities including their unique ID.</p><pre>def get_authorities() -&gt; List[str]:<br>    &quot;&quot;&quot;<br>    Fetch list of authority codes from the FSA API.<br>    <br>    Returns:<br>        List[str]: List of authority codes<br>    &quot;&quot;&quot;<br>    try:<br>        url = f&quot;{API_BASE_URL}/Authorities/basic&quot;<br>        response = requests.get(url, headers=HEADERS)<br>        response.raise_for_status()<br>        <br>        authorities = response.json()[&#39;authorities&#39;]<br>        authority_codes = [<br>            authority[&#39;links&#39;][0][&#39;href&#39;].split(&#39;/&#39;)[-1]<br>            for authority in authorities<br>            if authority.get(&#39;links&#39;)<br>        ]<br>        <br>        logger.info(f&quot;Retrieved {len(authority_codes)} authority codes&quot;)<br>        return authority_codes<br>        <br>    except Exception as e:<br>        logger.error(f&quot;Error fetching authorities: {e}&quot;)<br>        return []</pre><h4>Retrieve data files URL</h4><p>Next we pass each local authority ID to the Authorities endpoint to get detailed information about each local authority. Here we’re able to find the data file under the <em>FileName </em>key.</p><p>At this stage, I have also decided to introduce an asynchronous approach as the regular loop was taking quite a bit of time to execute. However, chunking was required in order to avoid overloading the API.</p><pre>async def get_authority_data(<br>    session: aiohttp.ClientSession,<br>    authority_code: str<br>) -&gt; Optional[str]:<br>    &quot;&quot;&quot;<br>    Fetch data file URL for a specific authority.<br>    <br>    Args:<br>        session: Aiohttp client session<br>        authority_code: Authority identifier<br>        <br>    Returns:<br>        Optional[str]: URL of the data file if found<br>    &quot;&quot;&quot;<br>    try:<br>        url = f&quot;{API_BASE_URL}/Authorities/{authority_code}&quot;<br>        logger.debug(f&quot;Fetching data for authority: {authority_code}&quot;)<br>        <br>        async with session.get(url, headers=HEADERS) as response:<br>            if response.status == 429:  # Too Many Requests<br>                logger.warning(f&quot;Rate limited for authority {authority_code}&quot;)<br>                await asyncio.sleep(RETRY_DELAY)<br>                return await get_authority_data(session, authority_code)<br>            <br>            if response.status != 200:<br>                logger.error(f&quot;Error {response.status} for authority {authority_code}&quot;)<br>                return None<br>                <br>            data = await response.json()<br>            file_name = data.get(&#39;FileName&#39;)<br>            <br>            if file_name:<br>                logger.debug(f&quot;Found filename: {file_name}&quot;)<br>                return file_name<br>            else:<br>                logger.warning(f&quot;No filename found for authority {authority_code}&quot;)<br>                return None<br>                <br>    except Exception as e:<br>        logger.error(f&quot;Error processing authority {authority_code}: {e}&quot;)<br>        return None<br><br>async def get_authority_data_files(authority_codes: List[str]) -&gt; List[str]:<br>    &quot;&quot;&quot;<br>    Fetch all authority data files URLs asynchronously.<br>    <br>    Args:<br>        authority_codes: List of authority codes to process<br>        <br>    Returns:<br>        List[str]: List of valid file URLs<br>    &quot;&quot;&quot;<br>    ssl_context = ssl.create_default_context()<br>    ssl_context.check_hostname = False<br>    ssl_context.verify_mode = ssl.CERT_NONE<br><br>    connector = aiohttp.TCPConnector(ssl=ssl_context, limit=5)<br>    timeout = aiohttp.ClientTimeout(total=30)<br>    <br>    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:<br>        logger.info(f&quot;Processing {len(authority_codes)} authority codes&quot;)<br>        results = []<br>        <br>        # Process in chunks to avoid overwhelming the API<br>        for i in range(0, len(authority_codes), CHUNK_SIZE):<br>            chunk = authority_codes[i:i + CHUNK_SIZE]<br>            chunk_tasks = [get_authority_data(session, code) for code in chunk]<br>            chunk_results = await asyncio.gather(*chunk_tasks, return_exceptions=True)<br>            results.extend(chunk_results)<br>            await asyncio.sleep(1)<br>        <br>        valid_files = [f for f in results if f is not None and isinstance(f, str)]<br>        logger.info(f&quot;Found {len(valid_files)} valid files out of {len(authority_codes)} attempts&quot;)<br>        return valid_files</pre><h4>Download data files</h4><p>Finally, we can download each file from the retrieved URL and save to a local directory.</p><pre>async def download_file(<br>    session: aiohttp.ClientSession,<br>    url: str,<br>    save_dir: Path<br>) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Download a single file asynchronously.<br>    <br>    Args:<br>        session: Aiohttp client session<br>        url: URL of the file to download<br>        save_dir: Directory to save the file<br>        <br>    Returns:<br>        bool: True if download was successful<br>    &quot;&quot;&quot;<br>    try:<br>        filename = os.path.basename(url)<br>        full_path = save_dir / filename<br>        <br>        async with session.get(url) as response:<br>            if response.status == 200:<br>                save_dir.mkdir(parents=True, exist_ok=True)<br>                <br>                with open(full_path, &#39;wb&#39;) as f:<br>                    while True:<br>                        chunk = await response.content.read(8192)<br>                        if not chunk:<br>                            break<br>                        f.write(chunk)<br>                        <br>                logger.info(f&quot;Successfully downloaded {filename}&quot;)<br>                return True<br>            else:<br>                logger.error(f&quot;Failed to download {filename}: HTTP {response.status}&quot;)<br>                return False<br>                <br>    except Exception as e:<br>        logger.error(f&quot;Error downloading {url}: {e}&quot;)<br>        return False<br><br>async def download_data_files(file_urls: List[str]) -&gt; None:<br>    &quot;&quot;&quot;<br>    Download all data files asynchronously.<br>    <br>    Args:<br>        file_urls: List of URLs to download<br>    &quot;&quot;&quot;<br>    ssl_context = ssl.create_default_context()<br>    ssl_context.check_hostname = False<br>    ssl_context.verify_mode = ssl.CERT_NONE<br><br>    connector = aiohttp.TCPConnector(ssl=ssl_context, limit=5)<br>    timeout = aiohttp.ClientTimeout(total=60)<br>    <br>    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:<br>        tasks = []<br>        <br>        for i in range(0, len(file_urls), DOWNLOAD_CHUNK_SIZE):<br>            chunk = file_urls[i:i + DOWNLOAD_CHUNK_SIZE]<br>            chunk_tasks = [download_file(session, url, SAVE_DIR) for url in chunk]<br>            results = await asyncio.gather(*chunk_tasks, return_exceptions=True)<br>            tasks.extend(results)<br>            await asyncio.sleep(RETRY_DELAY)<br>        <br>        successful = sum(1 for result in tasks if result is True)<br>        logger.info(f&quot;Successfully downloaded {successful} files out of {len(file_urls)} attempts&quot;)</pre><h4>Bringing it all together</h4><p>We can then wrap it all up into the main function.</p><pre>def main() -&gt; None:<br>    &quot;&quot;&quot;Main execution function.&quot;&quot;&quot;<br>    try:<br>        # Get authority codes<br>        authority_codes = get_authorities()<br>        if not authority_codes:<br>            logger.error(&quot;No authority codes found&quot;)<br>            return<br><br>        # Get data file URLs<br>        authority_data_files = asyncio.run(get_authority_data_files(authority_codes))<br>        if not authority_data_files:<br>            logger.error(&quot;No data files found&quot;)<br>            return<br><br>        # Download files<br>        asyncio.run(download_data_files(authority_data_files))<br>        <br>    except Exception as e:<br>        logger.error(f&quot;Error in main execution: {e}&quot;)</pre><h3>Formatting data for further use</h3><p>The data is available in XML format, which poses its own challenge. For each food-selling outlet, there is an XML record that contains details like business name, address, and hygiene rating. Converting these XML files into a workable format was the next step — I wrote a script to extract the data into a pandas DataFrame and saved it as a CSV for easier analysis.</p><p>This is the header of an XML file along with data for one outlet.</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;&lt;FHRSEstablishment xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;<br>&lt;Header&gt;<br>&lt;ExtractDate&gt;2024-10-30&lt;/ExtractDate&gt;<br>&lt;ItemCount&gt;4740&lt;/ItemCount&gt;<br>&lt;ReturnCode&gt;Success&lt;/ReturnCode&gt;<br>&lt;/Header&gt;<br>&lt;EstablishmentCollection&gt;<br><br>&lt;EstablishmentDetail&gt;<br>    &lt;FHRSID&gt;1663902&lt;/FHRSID&gt;<br>    &lt;LocalAuthorityBusinessID&gt;23/00241/FTAKO&lt;/LocalAuthorityBusinessID&gt;<br>    &lt;BusinessName&gt;@homePizza&lt;/BusinessName&gt;<br>    &lt;BusinessType&gt;Takeaway/sandwich shop&lt;/BusinessType&gt;<br>    &lt;BusinessTypeID&gt;7844&lt;/BusinessTypeID&gt;<br>    &lt;AddressLine1&gt;152A High Street&lt;/AddressLine1&gt;<br>    &lt;AddressLine2&gt;Chesham&lt;/AddressLine2&gt;<br>    &lt;AddressLine3&gt;Buckinghamshire&lt;/AddressLine3&gt;<br>    &lt;PostCode&gt;HP5 1EF&lt;/PostCode&gt;<br>    &lt;RatingValue&gt;4&lt;/RatingValue&gt;<br>    &lt;RatingKey&gt;fhrs_4_en-GB&lt;/RatingKey&gt;<br>    &lt;RatingDate&gt;2024-01-19&lt;/RatingDate&gt;<br>    &lt;LocalAuthorityCode&gt;021&lt;/LocalAuthorityCode&gt;<br>    &lt;LocalAuthorityName&gt;Buckinghamshire&lt;/LocalAuthorityName&gt;<br>    &lt;LocalAuthorityWebSite&gt;http://www.buckinghamshire.gov.uk&lt;/LocalAuthorityWebSite&gt;<br>    &lt;LocalAuthorityEmailAddress&gt;environmentalhealth@buckinghamshire.gov.uk&lt;/LocalAuthorityEmailAddress&gt;<br>    &lt;Scores&gt;<br>        &lt;Hygiene&gt;5&lt;/Hygiene&gt;<br>        &lt;Structural&gt;10&lt;/Structural&gt;<br>        &lt;ConfidenceInManagement&gt;5&lt;/ConfidenceInManagement&gt;<br>    &lt;/Scores&gt;<br>    &lt;SchemeType&gt;FHRS&lt;/SchemeType&gt;<br>    &lt;NewRatingPending&gt;False&lt;/NewRatingPending&gt;<br>    &lt;Geocode&gt;<br>        &lt;Longitude&gt;-0.6112168&lt;/Longitude&gt;<br>        &lt;Latitude&gt;51.7078007&lt;/Latitude&gt;<br>    &lt;/Geocode&gt;<br>&lt;/EstablishmentDetail&gt;</pre><p>In order to turn this data into a nicely formatted dataframe we do the following:</p><ol><li>Define the fields and extraction methods.</li><li>Clean some fields in the dataframe.</li><li>Repeat for all XML files.</li><li>Save to a csv.</li></ol><h4>Define the fields and extraction methods</h4><p>We use the xml package to go through the file structure and pull out the required data point from under the EstablishmentDetail.</p><pre>ESTABLISHMENT_FIELDS = {<br>    &#39;FHRSID&#39;: str,<br>    &#39;LocalAuthorityBusinessID&#39;: str,<br>    &#39;BusinessName&#39;: str,<br>    &#39;BusinessType&#39;: str,<br>    &#39;BusinessTypeID&#39;: str,<br>    &#39;AddressLine1&#39;: str,<br>    &#39;AddressLine2&#39;: str,<br>    &#39;AddressLine3&#39;: str,<br>    &#39;PostCode&#39;: str,<br>    &#39;RatingValue&#39;: str,<br>    &#39;RatingKey&#39;: str,<br>    &#39;RatingDate&#39;: str,<br>    &#39;LocalAuthorityCode&#39;: str,<br>    &#39;LocalAuthorityName&#39;: str,<br>    &#39;LocalAuthorityWebSite&#39;: str,<br>    &#39;LocalAuthorityEmailAddress&#39;: str,<br>    &#39;SchemeType&#39;: str,<br>    &#39;NewRatingPending&#39;: str,<br>}<br><br>SCORES_FIELDS = {<br>    &#39;Hygiene&#39;: (&#39;.//Scores/Hygiene&#39;, str),<br>    &#39;Structural&#39;: (&#39;.//Scores/Structural&#39;, str),<br>    &#39;ConfidenceInManagement&#39;: (&#39;.//Scores/ConfidenceInManagement&#39;, str),<br>}<br><br>GEOCODE_FIELDS = {<br>    &#39;Longitude&#39;: (&#39;.//Geocode/Longitude&#39;, str),<br>    &#39;Latitude&#39;: (&#39;.//Geocode/Latitude&#39;, str),<br>}<br><br>def extract_establishment_data(establishment: ET.Element) -&gt; Dict:<br>    &quot;&quot;&quot;<br>    Extract data from an establishment XML element.<br>    <br>    Args:<br>        establishment: XML element containing establishment details<br>        <br>    Returns:<br>        Dict: Extracted establishment data<br>    &quot;&quot;&quot;<br>    data = {}<br>    <br>    # Extract basic fields<br>    for field, field_type in ESTABLISHMENT_FIELDS.items():<br>        value = establishment.findtext(field)<br>        data[field] = field_type(value) if value is not None else None<br>    <br>    # Extract nested score fields<br>    for field, (xpath, field_type) in SCORES_FIELDS.items():<br>        value = establishment.findtext(xpath)<br>        data[field] = field_type(value) if value is not None else None<br>    <br>    # Extract geocode fields<br>    for field, (xpath, field_type) in GEOCODE_FIELDS.items():<br>        value = establishment.findtext(xpath)<br>        data[field] = field_type(value) if value is not None else None<br>    <br>    return data<br><br>def process_xml_file(file_path: Path) -&gt; List[Dict]:<br>    &quot;&quot;&quot;<br>    Process a single XML file and extract establishment data.<br>    <br>    Args:<br>        file_path: Path to the XML file<br>        <br>    Returns:<br>        List[Dict]: List of extracted establishment data<br>    &quot;&quot;&quot;<br>    try:<br>        tree = ET.parse(file_path)<br>        root = tree.getroot()<br>        establishments = root.findall(&#39;.//EstablishmentDetail&#39;)<br>        <br>        data = [extract_establishment_data(est) for est in establishments]<br>        logger.info(f&quot;Processed {file_path.name}: {len(data)} establishments&quot;)<br>        return data<br>        <br>    except Exception as e:<br>        logger.error(f&quot;Error processing {file_path}: {e}&quot;)<br>        return []</pre><h4>Clean some fields in the dataframe</h4><p>We apply some light cleaning on certain columns where there are known issues with the data.</p><pre>def clean_dataframe(df: DataFrame) -&gt; DataFrame:<br>    &quot;&quot;&quot;<br>    Clean and process the DataFrame.<br>    <br>    Args:<br>        df: Raw DataFrame<br>        <br>    Returns:<br>        DataFrame: Cleaned DataFrame<br>    &quot;&quot;&quot;<br>    # Convert coordinates to float<br>    df[&#39;Latitude&#39;] = pd.to_numeric(df[&#39;Latitude&#39;], errors=&#39;coerce&#39;)<br>    df[&#39;Longitude&#39;] = pd.to_numeric(df[&#39;Longitude&#39;], errors=&#39;coerce&#39;)<br>    <br>    # Convert scores to numeric<br>    score_columns = [&#39;Hygiene&#39;, &#39;Structural&#39;, &#39;ConfidenceInManagement&#39;]<br>    for col in score_columns:<br>        df[col] = pd.to_numeric(df[col], errors=&#39;coerce&#39;)<br>    <br>    # Clean postcodes<br>    df[&#39;PostCode&#39;] = df[&#39;PostCode&#39;].str.strip().str.upper()<br>    <br>    # Convert rating date to datetime<br>    df[&#39;RatingDate&#39;] = pd.to_datetime(df[&#39;RatingDate&#39;], errors=&#39;coerce&#39;)<br>    <br>    # Remove duplicates<br>    df = df.drop_duplicates(subset=[&#39;FHRSID&#39;])<br>    <br>    # Sort by business name<br>    df = df.sort_values(&#39;BusinessName&#39;)<br>    <br>    return df</pre><h4>Repeat for all XML files</h4><p>Once we have the extraction and cleaning methods, we can loop through all 363 files to load their data and assemble into a single dataframe.</p><pre>def load_xml_files_to_df() -&gt; Optional[DataFrame]:<br>    &quot;&quot;&quot;<br>    Load and process all XML files into a single DataFrame.<br>    <br>    Returns:<br>        Optional[DataFrame]: Processed DataFrame or None if error<br>    &quot;&quot;&quot;<br>    try:<br>        # Ensure directories exist<br>        PROCESSED_DATA_DIR.mkdir(parents=True, exist_ok=True)<br>        <br>        # Get all XML files<br>        xml_files = list(RAW_DATA_DIR.glob(&quot;*.xml&quot;))<br>        if not xml_files:<br>            logger.error(f&quot;No XML files found in {RAW_DATA_DIR}&quot;)<br>            return None<br>            <br>        logger.info(f&quot;Processing {len(xml_files)} XML files&quot;)<br>        <br>        # Process all files<br>        all_establishments = []<br>        for xml_file in xml_files:<br>            establishments = process_xml_file(xml_file)<br>            all_establishments.extend(establishments)<br>        <br>        if not all_establishments:<br>            logger.error(&quot;No establishments data extracted&quot;)<br>            return None<br>        <br>        # Create and clean DataFrame<br>        df = pd.DataFrame(all_establishments)<br>        df = clean_dataframe(df)<br>        <br>        logger.info(f&quot;Total establishments processed: {len(df)}&quot;)<br>        return df<br>        <br>    except Exception as e:<br>        logger.error(f&quot;Error loading XML files: {e}&quot;)<br>        return None</pre><h4>Save to a csv</h4><p>Finally, we save the output to a local csv file.</p><pre>def save_dataframe(df: DataFrame, filename: str) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Save DataFrame to CSV file.<br>    <br>    Args:<br>        df: DataFrame to save<br>        filename: Output filename<br>        <br>    Returns:<br>        bool: True if successful<br>    &quot;&quot;&quot;<br>    try:<br>        output_path = PROCESSED_DATA_DIR / filename<br>        df.to_csv(output_path, index=False)<br>        logger.info(f&quot;Data saved to {output_path}&quot;)<br>        return True<br>        <br>    except Exception as e:<br>        logger.error(f&quot;Error saving data: {e}&quot;)<br>        return False</pre><h3>Bringing this data to life with Streamlit</h3><p>Years ago, I built a small app that helped identify food outlets within a certain radius of a given postcode. The idea was simple — users could enter a postcode and a radius, and the app would return a list of food outlets, along with their distances and hygiene ratings. This was particularly useful for small food producers we worked with, who wanted to explore potential distribution opportunities.</p><p>This time, I chose to rebuild it in Streamlit. Compared to my earlier work in R and Shiny, Streamlit made things refreshingly straightforward. The intuitive syntax and built-in components meant I could quickly put together the interface — users could see the outlets on a map, filter based on criteria, and even download the curated data. While I originally relied on the in-built map component, I ultimately swapped it out for something with richer hover functionality, which provided a better user experience.</p><p>The app’s purpose was to provide local insights, whether you wanted to explore potential partnerships near an existing store or gauge the competitive landscape around a successful Tesco, it helped small producers make informed decisions. The great thing is that it goes beyond just supermarket channels and covers all other businesses that sell food — restaurants, takeaways, etc.</p><p>I’ll post the full code on GitHub and for now, I just include a simplified version of the app.</p><pre># Page configuration - MUST be the first Streamlit command<br>st.set_page_config(page_title=&quot;UK Food Selling Outlets&quot;, layout=&quot;wide&quot;)<br><br># Initialize data<br>df, color_map = load_data()<br><br>def main():<br>    &quot;&quot;&quot;Main application function.&quot;&quot;&quot;<br>    # Page title and divider<br>    st.title(&quot;Food selling outlets - UK&quot;)<br>    st.divider()<br><br>    # Render filters and get values<br>    filter_values = render_filters()<br>    <br>    # Apply filters<br>    filtered_df = apply_filters(df, *filter_values)<br>    <br>    # Render data table<br>    display_df = render_data_table(filtered_df)<br>    st.divider()<br><br>    # Map and Legend section<br>    st.subheader(&quot;Locations of food selling outlets&quot;)<br>    col1, col2 = st.columns([3, 1])<br>    <br>    with col1:<br>        render_map(filtered_df)<br>    <br>    with col2:<br>        render_legend(filtered_df)<br>        st.divider()<br>        st.download_button(<br>            label=&quot;Download selected data as CSV&quot;,<br>            data=display_df.to_csv(index=False).encode(&#39;utf-8&#39;),<br>            file_name=&quot;food_establishments.csv&quot;,<br>            mime=&quot;text/csv&quot;<br>        )<br><br>    # Footer<br>    st.divider()<br>    st.markdown(<br>        &quot;&quot;&quot;&lt;div style=&#39;text-align: center; color: gray; padding: 20px;&#39;&gt;<br>        The data you see comes from Food Standards Agency website, and is available <br>        through Open Government Licence.&lt;/div&gt;&quot;&quot;&quot;,<br>        unsafe_allow_html=True<br>    )</pre><p>The result is an interactive app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67P74mcJlgFcmlgYLiH0sw.png" /><figcaption>Top part of the app with inputs and a table.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5negv1b5o-MlrfMqqYKhw.png" /><figcaption>Bottom part of the app with the map and data download option.</figcaption></figure><h3>Reflections using Cursor and Claude</h3><p>What surprised me most during this process was how much had changed since I first built this app. Back then, pulling it all together took days. This time, armed with the <a href="https://www.cursor.com/">Cursor</a> IDE and Claude, I replicated the whole project in just a few hours. Having an LLM like Claude integrated directly into the IDE felt seamless. It worked equally well for a quick edit to a function or help parsing XML, the model provided thoughtful suggestions without the clunkiness of copy-pasting between tools.</p><p>I approached each task in smaller chunks — first retrieving data, then modelling, then building a simple interface. Working incrementally, with the LLM stepping in to fill in gaps, made it easier to navigate the inevitable complexities of data engineering. Debugging a function, writing the next logical step, and even getting creative with visualisations, it all became part of a smooth feedback loop.</p><h3>Next steps</h3><p>With the core functionality in place, I’m looking to take this project further. Hosting the app publicly is high on the list, which will enable more people to access and explore the FSA data themselves. I’d also like to automate the data refresh process to keep everything up to date. And maybe, down the road, I’ll add an LLM interface to make the app even easier to use, so it’s not just informative, but conversational too. There’s also the case of actually spending some time with this data set to explore the state of hygiene among UK’s food selling outlets! It’s hard to pick what to focus on next…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be97fb87dad2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atheon-analytics/leveraging-food-standards-agency-hygiene-ratings-data-be97fb87dad2">Leveraging Food Standards Agency hygiene ratings data</a> was originally published in <a href="https://medium.com/atheon-analytics">Atheon Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>