<?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 Juan Gesino on Medium]]></title>
        <description><![CDATA[Stories by Juan Gesino on Medium]]></description>
        <link>https://medium.com/@juangesino?source=rss-5a4d46a446e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b8jPd6awMpx0wMpwlPxZlg.jpeg</url>
            <title>Stories by Juan Gesino on Medium</title>
            <link>https://medium.com/@juangesino?source=rss-5a4d46a446e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:56:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juangesino/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[Running dbt using Gitlab CI/CD]]></title>
            <link>https://medium.com/data-science/running-dbt-using-gitlab-ci-cd-8a2ef0f05af0?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a2ef0f05af0</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[modern-data-stack]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Mon, 02 May 2022 06:31:15 GMT</pubDate>
            <atom:updated>2022-05-02T19:15:14.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>The easiest way to deploy, run and schedule dbt for free</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORaj_P2LDe7FldmL-4682A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@samthewam24?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Samuel Sianipar</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>My first implementation of <a href="https://www.getdbt.com/">dbt</a> was while running the Data Team at <a href="https://www.sirena.app/en-us/">Sirena</a> and I immediately became a huge fan of it. We used it for running all of our transformations and creating our models in our data warehouse (<a href="https://www.snowflake.com/">Snowflake</a>). It was literally a game-changer to be able to apply dimensional modelling to our data, especially having lots of sources with unstructured data. What’s better is that all of our models and business logic were version controlled, changes were fully visible and collaboration was extremely easy. Probably my favourite part though is the abstraction layer it creates between raw data and business entities. For example, we can create a dim_customers model and make that the Single Source of Truth for our company’s customers completely abstracted from the raw data that is generating the model. To our stakeholders, it doesn’t matter if that table they use in our BI tool is coming from our CRM, product DBs, our ERP, or our customer success software. All it matters is that in this table they can find all the information about our customers, it’s completely transparent to them. If things change upstream in our data sources, we as a data team can fix those through this abstraction layer. Even more surprising, and hopefully no one has to deal with this, it allows us to have dramatic changes in our data sources (such as a CRM migration or having multiple CRMs running at the same time) while minimising the impact on our BI layer (yes, I have a few battle scars). Oh, and also, all of this is powered by the simplicity of SQL. Just amazing!</p><p>As I mentioned, we version-controlled our dbt project, and for that we used Gitlab. Which made it super interesting when I came across <a href="https://www.youtube.com/watch?v=-XBIIY2pFpc&amp;t=1301s">this video</a> from the Gitlab data team explaining how they run dbt using Gitlab CI. At the same time, Gitlab being an open-source company makes all the code for their dbt project <a href="https://gitlab.com/gitlab-data">fully available</a>. I suggest you spend a bit of time over there, lots of useful things.</p><p>In this post, I will go into the details about how to “deploy” your dbt project using <a href="https://docs.gitlab.com/ee/ci/">Gitlab’s CI/CD</a>. Note that a similar workflow is possible using <a href="https://github.com/features/actions">Github Actions</a>.</p><h3>Getting Started</h3><p>The <a href="https://docs.gitlab.com/ee/ci/">CI/CD tool from Gitlab</a> is extremely easy to use, all you need to do is create a file in the root location of your repository called .gitlab-ci.yml. This <a href="https://docs.gitlab.com/ee/ci/yaml/index.html">file is basically a recipe</a> for how Gitlab should execute pipelines. In this post we’ll go over the simplest workflow we can implement, with a focus on running the dbt models in production. I’ll leave it up to later posts to discuss how to do actual CI/CD (including testing), generate docs, and store metadata. Right now, our goal is to be able to run dbt build every day so all of our models are up-to-date.</p><p>This is an example of a .gitlab-ci.yml file for one of the easiest setups to run dbt using Gitlab’s CI/CD:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cfb6ee4bb87a6269b101cfcabc919a1/href">https://medium.com/media/0cfb6ee4bb87a6269b101cfcabc919a1/href</a></iframe><p>We start by defining the stages that we want to run in our pipeline. In this case, we will only have one stage called deploy-production. If we ignore the middle part of the .gitlab-ci.yml file for now and jump straight to the bottom, we can see that we define what this stage actually does:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00417e8d62da558931b6d2d63454e0de/href">https://medium.com/media/00417e8d62da558931b6d2d63454e0de/href</a></iframe><p>Because we define the when parameter (<a href="https://docs.gitlab.com/ee/ci/yaml/index.html#when">docs</a>) to be only manual, this stage will only run after it’s triggered through Gitlab’s UI. Besides that, the stage defines a variable called TARGET_NAME whose value is postgres (more about this later). When it comes to what this stage actually does, it simply extends the definition in .deploy. At the same time, .deploy extends from the definition of dbt_jobs which is .dbt_run. This is specified by this line: &lt;&lt;: *dbt_jobs which essentially inserts the dbt_jobs definition.</p><p>Looking at .dbt_run we see that we define the image in which we will run everything which in this case is the python:3.8.1-slim-buster Docker image (<a href="https://docs.gitlab.com/ee/ci/yaml/index.html#image">docs</a>). After that, we run a few scripts to install dependencies and define a variable called CI_PROFILE_TARGET. For this, we use the TARGET_NAME variable we defined before. In this case, the CI_PROFILE_TARGET variable will look something like --profiles-dir . --target postgres. You can probably see where this is going. We can use this variable when running dbt commands to specify both the path to our profiles.yml and which target we want to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20daa64c01dd0d865703d915b4697be8/href">https://medium.com/media/20daa64c01dd0d865703d915b4697be8/href</a></iframe><p>In terms of the profiles.yml, we can use a similar setup to the one used for <a href="https://juangesino.medium.com/setup-dbt-using-docker-7b39df6c6af4">running dbt using docker</a>, getting our data warehouse credentials from env variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bbaa194ce6808d0812b408a8a28dff6/href">https://medium.com/media/8bbaa194ce6808d0812b408a8a28dff6/href</a></iframe><p>Setting up these variables is extremely easy using <a href="https://docs.gitlab.com/ee/ci/variables/">Gitlab’s CI/CD variables</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaOieXVEzb4Mvl1xx2wkkg.png" /><figcaption>Adding CI/CD variables in Gitlab (image by author)</figcaption></figure><p>After that, we can finally take a look at .deploy. Thanks to the addition of the dbt build <a href="https://docs.getdbt.com/reference/commands/build">command introduced in 0.21.0</a>, we can simply install dependencies and then run the dbt build command which will take care of running models, tests, snapshots and seeds in the order they should be run according to our dbt DAG.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b809b332dd651df54f69111adaa48844/href">https://medium.com/media/b809b332dd651df54f69111adaa48844/href</a></iframe><p>That’s it, if we push our code to Gitlab, we should see a new pipeline being created that we can manually trigger (remember, because of the when: manual config). Once we do, our dbt project will run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vERznOfIL1wzbe0d1oh1PQ.png" /><figcaption>Checking CI/CD pipelines in Gitlab (image by author)</figcaption></figure><h3>Scheduling dbt to run every day</h3><p>Using this setup, there are at least two ways that I came across to schedule dbt to run every day. The first method is using Gitlab’s built-in <a href="https://gitlab.com/help/ci/pipelines/schedules">pipeline schedules</a> and the second method is using <a href="https://docs.gitlab.com/ee/ci/triggers/">Gitlab’s API</a> to trigger the pipeline.</p><h4>Pipeline Scheduling</h4><p>This is probably the easiest and most straightforward way to do it. Under the CI/CD section in Gitlab, there is a section for creating pipeline schedules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1S_WiwecTVoF0-IUxmmBg.png" /></figure><p>You can follow the instructions to run the pipeline every day or however frequently your dbt models should be run.</p><h4>Trigger Pipeline via API</h4><p>Another way to schedule the pipeline is to use whichever orchestration tool you are currently using such as <a href="https://airflow.apache.org/">Airflow</a> or <a href="https://dagster.io/">Dagster</a>. This has the added advantage of being integrated with the rest of your data pipeline. Using this you could trigger your dbt build whenever your data has finished loading into your warehouse.</p><p>You can find the API documentation for triggering pipelines <a href="https://docs.gitlab.com/ee/ci/triggers/">here</a>, but essentially all that is required is for you to <a href="https://docs.gitlab.com/ee/ci/triggers/#create-a-trigger-token">create a trigger token</a> and use that in a POST request to the URL: https://gitlab.example.com/api/v4/projects/&lt;project_id&gt;/trigger/pipeline. An amazing feature of this approach is that you can pass variables to pipelines. This means that you could trigger a build of dbt when different parts of your data pipeline have loaded.</p><p>Here’s an example of how to trigger the pipeline using Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2133b2f06b04ca7dd45c5faad5b5687c/href">https://medium.com/media/2133b2f06b04ca7dd45c5faad5b5687c/href</a></iframe><p>Bear in mind that for this to work, you will need to remove the when: manual condition.</p><h3>Further improvements</h3><p>Hopefully, this post has shown you how Gitlab CI/CD (or Github Actions) can be used in combination with dbt. However, I hope that this serves as inspiration, as there are a great number of ways that this can be used. For example, at <a href="https://www.sirena.app/en-us/">Sirena</a> and <a href="https://www.zenvia.com/">Zenvia</a>, we used this workflow to do actual CI/CD taking advantage of Snowflake zero-copy clones. Whenever a merge request (or pull request) is created, it would trigger a pipeline that would clone our Snowflake databases and run the code changes and tests on it. This gave us a lot of confidence that our changes were not introducing any issues. Another thing we implemented using this workflow was storing metadata and generating dbt docs to document our data warehouse. If this all sounds interesting consider <a href="https://juangesino.medium.com/">following me</a> on Medium as I will be creating more content about this in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a2ef0f05af0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/running-dbt-using-gitlab-ci-cd-8a2ef0f05af0">Running dbt using Gitlab CI/CD</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[A Dockerized dbt Workflow]]></title>
            <link>https://juangesino.medium.com/setup-dbt-using-docker-7b39df6c6af4?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b39df6c6af4</guid>
            <category><![CDATA[modern-data-stack]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 16:55:47 GMT</pubDate>
            <atom:updated>2022-04-30T16:59:36.209Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to setup dbt using docker containers with an RPC server for Dagster</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCxtXemoLHPHTU2ZayKGig.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@toddcravens?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Todd Cravens</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Lately, I have been playing around quite a bit with <a href="https://dagster.io/">Dagster</a>, trying to understand how good of a replacement it would be for <a href="https://airflow.apache.org/">Airflow</a>. I might write a more comprehensive post about it, but one interesting thing I came across in my testing was the <a href="https://dagster.io/blog/dagster-dbt">integration</a> with <a href="https://www.getdbt.com/">dbt</a>. There are two ways to make Dagster work together with dbt: pointing to a dbt repository for running dbt commands or interacting with the dbt RPC server. I liked the idea of taking advantage of the RPC server as it meant I could decouple my implementation of dbt and Dagster. In this post, I will show you how you can dockerize a dbt RPC server while also maintaining a nice workflow for developing dbt models locally.</p><p>It should be noted, however, that the <a href="https://docs.getdbt.com/reference/commands/rpc">dbt RPC server will soon (end of 2022) be deprecated</a>. However, the replacement will be the new dbt server. I have huge expectations for the dbt server for much more than this implementation, but for taking dbt metrics to a whole new level. I still see some value in using the RPC server for the time being and migrating to the new server later on.</p><h3>Dockerized dbt RPC server</h3><p>When integrating dbt and Dagster, my first step was to dockerize the dbt RPC server. Searched for dbt docker images, but wasn’t satisfied with any so I decided to go with my own Dockerfile. Because dbt is such a simple (but powerful) piece of software this was extremely straightforward. I simply needed a Python environment to install the dbt package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/923989c36cb87c9491c146886e58dca4/href">https://medium.com/media/923989c36cb87c9491c146886e58dca4/href</a></iframe><p>The requirements.txt file contains the dependencies needed, including the dbt package. This will, of course, depend on the database adapter you are using, but for a PostgreSQL implementation, this would work:</p><pre>dbt-postgres==1.0.0<br>dbt-rpc==0.1.1</pre><p>For Snowflake you can use:</p><pre>dbt-snowflake==1.0.0<br>dbt-rpc==0.1.1</pre><p>Anyway, you get the idea!</p><p>Another thing to consider is the profiles.yml. As you can see from the Dockerfile, I’m copying a profiles.yml file from my dbt project into the container’s /root/.dbt/ directory. Now, there are a few ways to handle these credentials for the data warehouse.</p><p>The first option is to store the credentials inside the profiles.yml file itself but <strong>do not</strong> add them to version control. This means that when the repository is first cloned, contributors need to create their own profiles.yml. However, I prefer another method: using env variables in the profiles.yml. In dbt, you can use the env_var macro (<a href="https://docs.getdbt.com/reference/dbt-jinja-functions/env_var">reference</a>) to insert environment variables into the YAML. My profiles.yml the would look something like this for a PostgreSQL implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0543037342a38ac57b5f681d7ab9490d/href">https://medium.com/media/0543037342a38ac57b5f681d7ab9490d/href</a></iframe><p>For a Snowflake implementation it would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5b122a85cfc5db505fbc3e687d69a06/href">https://medium.com/media/e5b122a85cfc5db505fbc3e687d69a06/href</a></iframe><p>Now, this means that when we ran the Docker container we need to define these environment variables. We can either do this when starting up the container or do it through docker-compose. To give this a try, we can first build the image:</p><pre>docker build -t dbt .</pre><p>Now we can run a container from that image:</p><pre>docker run -p 8581:8580 --name dbt_rpc -v &quot;/$(pwd):/app&quot; --env-file ./.env -it dbt</pre><p>Note that using this command, we are specifying an .env file that has the credentials referenced above in the profiles.yml. As you can see we are also mapping port 8580 to port 8581. This means that our RPC server will be available at localhost:8581/jsonrpc.</p><p>Once this is running you can test it by either using the Dagster integration or by sending requests to the server. As an example, you can send the following status request:</p><pre>curl — location — request POST ‘localhost:8581/jsonrpc’ \<br> — header ‘Content-Type: application/json’ \<br> — data-raw ‘{<br> “jsonrpc”: “2.0”,<br> “method”: “status”,<br> “id”: “000000000”<br>}’</pre><p>If everything is working, you should receive back a 200 response with the status of ready.</p><h3>Improving the development workflow</h3><p>As a data manager and analytics engineer myself, developing an ergonomic development experience is extremely important to me. Developing new dbt models and modifying existing ones should be as straightforward as possible. One thing I noticed when implementing the dbt RPC server to work with Dagster is that it completely broke my developing workflow. Running and testing my models meant I had to run Dagster as an interface for dbt. So every time I need to develop dbt models, where I would just do a simple dbt run —-select my_model+, now I have to start Dagster. Don’t get me wrong, I love Dagster’s job parametrisation and it’s super powerful, but I need something better for simply running and testing my models.</p><p>The solution I came up with is another Docker container. This container is running exactly the same image as the RPC server, but instead of running the dbt-rpc serve command, it simply runs a bash console. We can then run this console interactively and run dbt commands on it.</p><p>To achieve this, we can keep the same image that we built before, but simply change the <a href="https://docs.docker.com/engine/reference/builder/#entrypoint">entrypoint</a> to execute a bash console:</p><pre>docker run --name dbt_console -v &quot;/$(pwd):/app&quot; --env-file ./.env --entrypoint /bin/bash -it dbt</pre><p>Notice that we are getting rid of the port mapping, changing the name to dbt_console and adding the --entrypoint flag to specify to run a bash console. Doing this will immediately open a bash console and we can test everything is working by running any dbt command such as dbt debug. We can use this console to run, test and iterate our models.</p><h3>Composing everything together</h3><p>This is nice, now we have 2 different docker containers, one for the RPC server to be used with Dagster and another one that provides a console we can use to run our dbt models. However, we can wrap this all together by using docker-compose. The resulting docker-compose is extremely simple, it includes 2 services, one for the RPC server and one for the console.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/455bdd8faf442d961f7576984acb9926/href">https://medium.com/media/455bdd8faf442d961f7576984acb9926/href</a></iframe><p>You can see that I also point to an env_file that helps me manage the credentials in the profiles.yml.</p><p>To enter the dbt console simply run:</p><pre>docker exec -it dbt_console /bin/bash</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b39df6c6af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstracting Data Loading with Airflow DAG Factories]]></title>
            <link>https://medium.com/data-science/abstracting-data-loading-with-airflow-dag-factories-12b6689f0aaa?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/12b6689f0aaa</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 17:15:29 GMT</pubDate>
            <atom:updated>2021-11-30T21:05:52.251Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating an abstraction layer for improved scalability and usability for loading Google Sheets data with Airflow</h4><p>This topic is not new. I’ve seen quite a few articles about generating different levels of abstractions for Airflow DAGs. For example, <a href="https://towardsdatascience.com/how-to-build-a-dag-factory-on-airflow-9a19ab84084c">this article</a> explains how to generate DAGs programmatically, and <a href="https://github.com/ajbosco/dag-factory">this library</a> allows you to generate DAGs using YAML. However, both of those abstractions are still for data practitioners to handle. I was looking for an abstraction that would remove the complexities and technicalities of creating Airflow DAGs and allow the author to concentrate on data-source specific configurations. To do this, the DAG factory needs to make a lot of assumptions and be highly opinionated, so that’s exactly what I did.</p><p>This post will show you how I generated Airflow factories to handle different data sources that allow me to create DAGs using explicit YAML files. My goal was to create an abstraction that could potentially enable stakeholders to generate Airflow DAGs to extract their data and load it into our data warehouse.</p><h3>Let’s talk about Google Sheets</h3><p>The concept I will show you applies to any data source, and if you implement it, you will ripe the benefits regardless of the data source. However, a niche example of this is Google Sheets. Whether you like it or not, most businesses run on either Excel or Google Sheets (or both!) and sooner rather than later, you will encounter stakeholders that will request to load data from a Google Sheets file into your data warehouse. Now, this is not a blog post about data philosophy, and I have no intention to discuss this (much sensitive) topic of Excels and Google Sheets. I will say, though, that if you opt to go for the route of allowing your stakeholders to load Google Sheets to your data warehouse, you’ll pretty soon see many requests coming in: for changing a column name, a column type, adding a column, removing a column, changing the sheet name and so on. Imagine an ideal world in which your stakeholders have the power of creating their pipelines themselves. In this world, you as a data practitioner would be free from all those requests and stop being a bottleneck for your stakeholders. At the same time, with great power comes great responsibility, and as your stakeholders get the power of managing their own Google Sheets pipelines, they become owners for that data. If changing a column breaks the ingestion, you are not accountable for that anymore (sort of), it is their responsibility, and they have the power to fix it. I know what you are thinking, and yes, this is, in fact, a double-edged sword. The ability to create their own Google Sheets pipeline could mean that your data warehouse becomes a black hole of endless Google Sheets’ data with poor structure, meaning and/or naming conventions. Again, I’m not arguing for or against here. <strong>If you implement this, I trust that you will maintain high governance over what gets pushed to production. Your critical thinking will ultimately set you free.</strong></p><p>Are you not buying onto the idea of letting stakeholders load their Google Sheets files? Fine. Abstract a bit from the specific use-case, and think about DAG factories as a way to help your team be more productive, be DRY and avoid mistakes. <strong>So it doesn’t matter if it’s loading Google Sheets or some other data from transactional APIs; your team could probably benefit from using Airflow DAG factories.</strong></p><p>With all of that rant out of the way, we can explore how to load Google Sheets data using Airflow DAG factories. Now, it’s also important to mention that this is definitely not the only way you can load data from a Google Sheets file. For example, Gitlab implemented their own tool they call <a href="https://gitlab.com/gitlab-data/analytics/tree/master/extract/sheetload">SheetLoad</a> (seriously, great name), and there are also tools like <a href="https://fivetran.com/docs/files/google-sheets">Fivetran</a> and <a href="https://www.stitchdata.com/docs/integrations/saas/google-sheets">Stitch</a>. However, if your team is already working with Airflow or if you want an extra dose of customization, this post will be helpful.</p><p>I digress. The real point about this is that it’s not about Google Sheets; it’s about ease of use. This is important, even if it’s just your team that’s using this tool. For example, I rather write YAML files for loading data from Salesforce than write Python scripts for every single object out there. Essentially, I’m just advocating for ease-of-use and DRY (don’t repeat yourself).</p><h3>What is a DAG factory anyway?</h3><p>So at this point, you might be wondering, what in the world is a DAG factory? In a more general way, a DAG factory is a script that generates Airflow DAGs programmatically. However, in this case, I add another condition. The factory generates DAGs programmatically from YAML configuration files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDQlpkEuwuuf12ii4hblyg.jpeg" /><figcaption>Image by author</figcaption></figure><p>More concretely, inside our /dags directory in Airflow, I would like to have a /dags/gsheets directory that will hold all of the YAML files. So we would have something like /dags/gsheets/invoices.yaml and /dags/gsheets/products.yaml and the goal is to have Airflow create corresponding DAGs for those configuration files. Using this structure, there should be a 1:1 relation between YAML configuration files and Airflow DAGs. However, nothing is stopping you from having a single YAML configuration file that generates many DAGs.</p><h3>What does a configuration file look like?</h3><p>Taking into account that ease-of-use is one of our main goals, this is a crucial question. The configuration file ends up being the interface with which analysts and other stakeholders will interact. In this case, the configuration file is the equivalent of the front-end in a web application. So we need to make sure it has a good “UX”. In this sense, simplicity is vital, and any complication you can hideaway is highly appreciated.</p><p>So here’s what a configuration file might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce5681aa063a28781b49eb6c98621475/href">https://medium.com/media/ce5681aa063a28781b49eb6c98621475/href</a></iframe><p>Is this the most straightforward configuration file we can have? Certainly not! We can simplify even more if we make certain assumptions. For example, does the creator of these config files need to decide where the data will be stored in the data warehouse, such as schema name, table, and database? This will all depend on your use case, of course.</p><p>However, let’s get straight to the point and address the elephant in the room. What is that mapper dictionary?</p><p>That’s a way we can deal with the renaming of columns and casting types. It will all become more evident when we look at the DAG factory, but its essence is that we can explicitly define the columns from the Google Sheets that we want to load and rename them to be SQL compliant (for example, rename them to snake_case). For instance, if in our Google Sheet file we have a column named Product Name, it would be annoying to have a column with that name in our data warehouse, and it could cause all sorts of problems. We want to change the name of that column to something like product_name. Using this mapper, we would do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/302ca7684aa40681126cf04ce3b2463e/href">https://medium.com/media/302ca7684aa40681126cf04ce3b2463e/href</a></iframe><h3>Let’s build a factory</h3><p>So it all starts with a good old fashion /dags/gsheets_factory.py script. This file will import all of the configuration files from /dags/gsheets, creating an Airflow DAG for each one of those.</p><p>That’s exactly how we start; we start by getting all of those YAML files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b510688ee1c78c8c48e68ae157d5ed22/href">https://medium.com/media/b510688ee1c78c8c48e68ae157d5ed22/href</a></iframe><p>Now we can iterate them and use them to create DAGs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c0c5a7a3bc5b1cc572073c0f233376/href">https://medium.com/media/32c0c5a7a3bc5b1cc572073c0f233376/href</a></iframe><p>All we are doing here is iterating those files and opening them with <a href="https://pyyaml.org/wiki/PyYAMLDocumentation">PyYAML</a>, which returns a dictionary version of the YAML file we discussed previously. We store that configuration dictionary in config. Finally, we pass that configuration dictionary to a function called create_gsheets_dag, and we add the DAG that function returns to the Airflow global scope.</p><p>As I said, create_ghseets_dag returns an Airflow DAG, so this is essentially where the magic actually happens. Let’s take a look at it.</p><p>Here is the entire function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d6f9ca92b63a188c105f1930a59c643/href">https://medium.com/media/5d6f9ca92b63a188c105f1930a59c643/href</a></iframe><p>But let’s break it down and understand what each part is doing.</p><p>The first part is simply defining the DAG’s properties, such as the ID, the schedule interval, etc. Notice that all of this is coming from the config which is a dictionary representation of the YAML configuration file we discussed before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc5f98a5c6e55ff44700a24dda991651/href">https://medium.com/media/fc5f98a5c6e55ff44700a24dda991651/href</a></iframe><p>For this task, we will use Airflow’s <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/operator/python.html">PythonOperator</a>. This operator will take a Python function as an argument (python_callable) and execute it. So we first need to define that function. In our case, we will call it _sync_data.</p><p>The first thing this function does is get the data from Google Sheets</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d69c2e617800b4b1464078505c9cddb/href">https://medium.com/media/7d69c2e617800b4b1464078505c9cddb/href</a></iframe><p>The next step is to clean the data we got:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e19ef18ac9c5af944271375f4e368e2d/href">https://medium.com/media/e19ef18ac9c5af944271375f4e368e2d/href</a></iframe><p>We are calling a helper function that we wrote clean_data, but this function’s details are not super relevant or exciting; it simply takes the mapper dictionary and renames the columns.</p><p>After that, we are ready to insert the data into our data warehouse. In our case, we use Snowflake, and we already have a function load_df that takes a Pandas DataFrame and writes it to Snowflake. This is based on the <a href="https://docs.snowflake.com/en/user-guide/python-connector.html">Snowflake Python library</a> that has a similar function. However, this part can be adapted to whatever destinations you are working with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87ff85dd4976d08b84e468ada23b71fb/href">https://medium.com/media/87ff85dd4976d08b84e468ada23b71fb/href</a></iframe><p>As described before, we then add a task to our DAG using the PythonOperator that will execute the function we just defined (_sync_data).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11abc33b4dfb38ee03a33e4a4c16d085/href">https://medium.com/media/11abc33b4dfb38ee03a33e4a4c16d085/href</a></iframe><h3>Conclusion</h3><p>Hopefully, I managed to show how we can drastically improve how we create Airflow DAGs by introducing a level of abstraction. It doesn’t matter if you are loading data from Google Sheets, Hubspot or Salesforce; these concepts still apply.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12b6689f0aaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/abstracting-data-loading-with-airflow-dag-factories-12b6689f0aaa">Abstracting Data Loading with Airflow DAG Factories</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[Data lake in S3 from MongoDB]]></title>
            <link>https://medium.com/data-science/data-lake-in-s3-from-mongodb-addd0b9f9606?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/addd0b9f9606</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 12:17:24 GMT</pubDate>
            <atom:updated>2021-10-18T18:17:30.356Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Python to upload MongoDB data to AWS S3 to build a data lake</h4><p>I was extremely lucky to be able to write my bachelor’s thesis combining the topics I am most passionate about; economics (in the form of auction theory), software development, and data analysis. Even though my thesis was an empirical research about auctions and bidding strategies, it involved gathering data using web crawling. However, that’s a whole other story for another post. The point is that a year after my thesis, I am still paying <a href="https://www.mongodb.com/cloud/atlas">MongoDB Atlas</a> a monthly fee to be able to store the data I collected, even though I am not using it. It’s time to archive the data.</p><p>In this post, I will not only show you how I moved the data from MongoDB to AWS S3 for cold storage archiving but also how you could use the same principle for a data pipeline to build a data lake. Depending on the type of Modern Data Stack that you are building, you might need to create a data lake. A common way to do this is by leveraging the cheap storage of AWS S3 and a common use-case is to stage data before ingesting it into a data warehouse for processing and transformation. For example, you might have a data warehouse running in Snowflake or Redshift and these warehouses have trivial ways of reading or copying data from AWS S3.</p><h3>Planning</h3><p>As always, I like over-engineering things, building abstractions and reusable code. Instead of writing a script that reads all records from MongoDB, creates a JSON file and uploads it to S3, I had the following premises in mind:</p><ul><li>Use YAML configuration files to determine extraction</li><li>Iterate through a timestamp field such as createdAt</li><li>Breakdown extraction by the time of day to avoid over-consuming RAM</li><li>Read from MongoDB using a cursor with pagination to avoid overhead in the server</li><li>Each collection should have its own config file to be able to customise it</li></ul><h4><strong>Configuration Files</strong></h4><p>I love configuration files in YAML. They are the ultimate abstraction. You can have an extremely complicated process running of a YAML file which anyone can modify to their liking without having to understand the logic behind it. They are decently user-friendly and easy to work with. The idea for using them here is that they can be used to extract different MongoDB collections in different ways. For example, the auctions collection in my MongoDB instance is not that big, it has around 16 thousand records. However, the bids collection contains more than 3.6 billion records. I can configure those differently to optimise the extraction process and avoid consuming too much RAM. This also saves me from hardcoding variables in the script, having to change them whenever I want to change the collection to extract and improves the reusability of the code.</p><p>The end result should be a script (main.py) that takes a command-line argument for the name of the config file, for example main.py auctions for running the auctions.yaml configuration file. This file will determine the name of the MongoDB collection, the start date, the end date and how we want to break up the extraction by hours of the day. Here&#39;s an example of a configuration file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73de3f32503a8d53fe5b277f5a40f61e/href">https://medium.com/media/73de3f32503a8d53fe5b277f5a40f61e/href</a></iframe><p>This will extract all the data in the collection catawiki_auctions with a createdAt field from 2020-03-01 to 2020-08-10 and will use 24-hour intervals for each day between those two dates.</p><p>Here’s an overview of the execution of the script and how it breaks up uploading the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1pwS_25_FTx8yHC7vkF3Q.png" /><figcaption>Script overview for loading data from MongoDB into AWS S3 data lake (Image by Author)</figcaption></figure><h3>Implementation</h3><h4><strong>AWS S3 bucket</strong></h4><p>The first step was to create an AWS S3 bucket to store the data and an IAM user to connect to AWS using <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3</a>. You can check <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html">this guide on creating an S3 bucket</a>, but it should be fairly straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtfLhd7PASGmiT8mV6hqpA.png" /><figcaption>Create an AWS S3 bucket to use as a data lake (Image by Author)</figcaption></figure><p>Now we’ll need some credentials to be able to connect with AWS S3 and upload our files. This is managed using AWS IAM. From there you can first create a policy to allow the user we will create to access the bucket we have created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a86b8a87c030092d5e6034695a29101/href">https://medium.com/media/6a86b8a87c030092d5e6034695a29101/href</a></iframe><p>Then you can create a user and when selecting permissions use the “Attach existing policies directly” option. This will allow you to attach the policy we created to the user. After that, you should be able to download the Access Key ID and the Secret Access Key. These are the credentials you need to call the AWS APIs using Boto3 to upload our files.</p><h4><strong>Looping to optimize RAM</strong></h4><p>Now it’s time to get to the code. I uploaded the final script to Github and you can access it <a href="https://github.com/juangesino/mongodb-s3-data-lake">here</a>. For didactical purposes, I left the script as a monolithic single file, but otherwise, I would break it up into several utility modules that I can import back into our main file. In any case, you can take a look at it and it should be pretty easy to follow, but I’ll go through the most important parts in this post while also explaining more about some definitions.</p><p>The most important aspect of this script is the looping and generators used. The goal of this is to optimise RAM, when running processes like this in production with MongoDB collections with many documents, you may encounter RAM problems. This is especially true when running the script on a small server in production. For that reason, we go through 3 loops that allow us to compartmentalize the data we get from MongoDB and avoid loading all of it in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHZ2Ew5hPcP3wdr5sy-Lig.png" /><figcaption>Loops to optimize RAM while loading data to the data lake (Image by Author)</figcaption></figure><p>Another extremely important part of these loops is to be able to recover from errors or connection problems. If there is a network error or a bug in our code, we can restart the process from where it left off, instead of having to purge and start all over again.</p><h4><strong>Iterate from start_date to end_date</strong></h4><p>We first iterate from the start_date to end_date parameters defined in the config file. This iteration is done one day at a time and, as usual in Python, the endpoint is not part of the generated sequence. The script defines a generator to implement this call date_range. The idea is that you can pass a start_date, an end_date and an increment in number of days. It works the same way as a range generator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46ce4103c1e10c31189208cd4730b608/href">https://medium.com/media/46ce4103c1e10c31189208cd4730b608/href</a></iframe><p>If this sounds interesting, you should definitely check out <a href="https://wiki.python.org/moin/Generators">Python generators</a>, they are quite handy.</p><h4><strong>Iterate from 00:00 to 23:59</strong></h4><p>Now that we are iterating each day, we can iterate different hours from that day. We can do this for example in batches of 6 hours (00:00 to 06:00, 06:00 to 12:00, 12:00 to 18:00, 18:00 to 00:00), batches of 12 hours (00:00 to 12:00, 12:00 to 00:00) or do the entire day at once using 24 hours intervals. For small collections this doesn’t make sense, we can just load the entire day at once using 24 hour-intervals. However, if we are loading massive amounts of data, this would make sense to be able to commit data extractions and be able to recover from possible errors. At the same time, this means we can parallelise our tasks. For example, if we are using this in Airflow to generate a DAG as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv-jLlIYGrhCM6Z4lepxAQ.png" /><figcaption>Example Airflow DAG to upload data to an S3 data lake (Image by Author)</figcaption></figure><h4><strong>Receive MongoDB data in batches of 5K documents</strong></h4><p>Finally, we don’t want to be asking for millions of documents all at once to the MongoDB server. This would also be true in production, otherwise, your engineering team might give you a call to see what you’re doing. At the same time, and as already mentioned, we can also optimise RAM usage by requesting fewer documents and paginating over the results. Lastly, if you are planning to later ingest these files into a warehouse such as Snowflake, it is actually useful to break down records into smaller files. This allows you to parallelise ingestion by reading over those files in parallel. For more information about file size and Snowflake ingestion, check the <a href="https://docs.snowflake.com/en/user-guide/data-load-considerations-prepare.html#general-file-sizing-recommendations">General File Sizing Recommendations</a> in their docs.</p><p>To accomplish this we again use Python generators and iterate over the MongoDB cursor. This allows us to get records 5K at a time without having to store them in memory or having to request all of them to the server. The 5K is completely customisable, in this case, I use 5K as a completely arbitrary number, but you can definitely increase that. In fact, the YAML files allow for a batch_size property that configures this exactly (the default is 5000).</p><h4><strong>File uploading to S3</strong></h4><p>After that, the process is trivial, we just get our records from MongoDB and store them in a JSON file. It’s important here to pay attention at all the loops we are executing, essentially, we want all the loops to be represented in one way or another in the file name. If we fail to do so, we might end up overwriting the same file over and over again. Furthermore, I include a timestamp for the date the data was extracted, this helps with reprocessing in case of errors and in case of overlaps during parallel/distributed runs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e412094dca61eb842ee261bb9657ba5b/href">https://medium.com/media/e412094dca61eb842ee261bb9657ba5b/href</a></iframe><p>One thing to notice is that MongoDB has some types that are a bit particular and not defined in JSON standard, so if you were to try to write a JSON string with them, you would get a serialisation error (“TypeError: Object of type ObjectId is not JSON serializable”).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b53d044a40bdd76667a4d8ad2513940/href">https://medium.com/media/2b53d044a40bdd76667a4d8ad2513940/href</a></iframe><p>You can solve this by using PyMongo dumper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/741aec4be77eba0791c083a69d4db1b5/href">https://medium.com/media/741aec4be77eba0791c083a69d4db1b5/href</a></iframe><p>Notice also that I used the .gz file extension, this is to store the JSON data compressed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56b0e97ac76a67aff8dc47d3833c0c55/href">https://medium.com/media/56b0e97ac76a67aff8dc47d3833c0c55/href</a></iframe><p>Finally, to upload the generated file, we simply initialise an S3 client using Boto3 and call the upload_file method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ededb27ff663ff6459eb8ac968efc1a8/href">https://medium.com/media/ededb27ff663ff6459eb8ac968efc1a8/href</a></iframe><h3>Conclusion</h3><p>Although the main objective for me was to archive data I had in MongoDB to AWS S3, I hope I have shown how this same script can be used to ingest data to build a data lake. This type of script can be easily extended to run on <a href="https://airflow.apache.org/">Airflow</a>, <a href="https://dagster.io/">Dagster</a> or <a href="https://airbyte.io/">Airbyte</a> as part of your data pipelines to extract data from production systems and load it into your data lake or data warehouse. In fact, this script is extremely similar to the Airflow DAGs we use at <a href="https://sirena.app/">Sirena</a> to extract and load data into <a href="http://snowflake.com/">Snowflake</a>. You can even use this script for one-time reprocessing of data or package everything as a CLI, dockerize it and run it in Kubernetes. The script is so simple that you can even run it using Celery in a distributed way to parallelise the extractions. The possibilities are endless.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=addd0b9f9606" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-lake-in-s3-from-mongodb-addd0b9f9606">Data lake in S3 from MongoDB</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[How we use Airflow for SQL alerts and Slack notifications]]></title>
            <link>https://medium.com/data-science/how-we-use-airflow-for-sql-alerts-and-slack-notifications-5becedfc03fd?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5becedfc03fd</guid>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[slack]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 07:41:43 GMT</pubDate>
            <atom:updated>2021-07-12T12:44:24.626Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Airflow to get notified over Slack when things don’t go as planned while loading data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16gVu90Ar7NwR1i8SdjjVw.png" /></figure><p>At <a href="https://sirena.app/">Sirena</a>, we use <a href="https://airflow.apache.org/">Apache Airflow</a> for running all of our data orchestration. Airflow is an open-source tool that was <a href="https://airbnb.io/projects/airflow/">created by Airbnb</a> to create and schedule data workflows. In essence, Airflow is an orchestrator that runs tasks on given frequencies while also handling backfilling, task dependencies and so much more. In Airflow, workflows are defined as Directed Acyclic Graphs (DAGs) that define the dependencies among different tasks.</p><p>At Sirena, we found another use for Airflow besides helping us move data from one place to another. We also use it to trigger alerts on certain data quality measures. The idea is quite simple, we define a SQL query and we define a condition for the result. The query should output a single number, and if that number does not match the condition, then we send a Slack alert. The beauty of it is how simple they are to create. We have parametrised the alerts in a way that allow us to create configuration files in <a href="https://yaml.org/">YAML</a> that will get materialised as DAGs in Airflow (more about this on a future post about Airflow factories…). These alerts are especially good for making sure nothing catastrophic has happened to the data pipelines.</p><p>In this post, I will guide you through the process of setting up a similar workflow for your Airflow implementation.</p><h3>Configuration Files</h3><p>Before we dig into Python code, let’s stop for a second to think about how we want our configuration file to look. Besides all of the “required” fields that are needed to create DAGs in Airflow, such as a name, interval, owner, etc. we are going to need a few other things.</p><p>Arguably the most important fields are those that we are going to use to actually define the alert. For that, we are going to need a field to write our SQL query and our condition, such as “<em>greater than 5</em>” or something. We’ll break our condition into two; the criteria (greater than, less than, etc) and our target value.</p><p>Besides that, we also need to define how we want to notify, who we want to notify and what the actual message will be. As I mentioned before, in Sirena we use Slack to send notifications, so our notification method is Slack. Our recipients come from a list of Slack channels or users, but we have a dedicated channel for all of the Data Team’s notifications. Lastly, we’ll use the description of the alert to send descriptive messages to let us know what happened.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a30758dcdba7c6b4de4c7e3f1318ed9/href">https://medium.com/media/5a30758dcdba7c6b4de4c7e3f1318ed9/href</a></iframe><p>Notice that we define a notifier. This allows us to configure what service we&#39;ll use to send out the notifications to our list of recipients.</p><p>We can create one of these configuration files for every alert we want to set up and store them all in /dags/alerts/, our DAG factory will pick up all of these config files from here and create the necessary DAGs. Our DAG factory will pick up all of the configuration files from this directory, that’s why that enabled property comes in handy. We can use it to enable/disable alerts without having to delete the entire file.</p><h3>Alert Factory</h3><p>Now we can jump to our alert factory. <strong>I suggest you </strong><a href="https://juangesino.medium.com/"><strong>follow my blog</strong></a><strong> for an upcoming post all about DAG factories in Airflow</strong>. For now, it’s important to know that a factory is essentially a Python script that will iterate through all the configuration files in /dags/alerts/ and create a DAG for each one of those. The code for it is pretty straightforward, but let&#39;s go through it together.</p><p>The first thing we’ll want to do is import all of the configuration files from /dags/alets/ and iterate them. For each one of them, we&#39;ll want to create a DAG and in order to do this, we implemented a function create_dag_alert that takes the configuration file (as a Python dictionary) and returns an Airflow DAG with one single task that uses the PythonOperator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2258151caef7d0fdf2021b30dd40cc41/href">https://medium.com/media/2258151caef7d0fdf2021b30dd40cc41/href</a></iframe><p>Let’s break this function into different parts so we can go over it part by part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6862f4fa252cbcacbacb112afe1cb4fc/href">https://medium.com/media/6862f4fa252cbcacbacb112afe1cb4fc/href</a></iframe><h4>Part 1: Define the DAG</h4><p>We start by defining some default arguments for our DAG based on the configuration file. You can see that for some of these values we actually use the config file (e.g. owner and schedule_interval) but for some others, we just hard-code the values we want to use (e.g. retries and catchup). This is up to you, we didn&#39;t see a lot of value in adding those to the configuration file at the moment, but we might do it at some point. The point is, don&#39;t stick to this way of doing it, do whatever works best for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/392bf5ea6fcf55079952523fe1364f05/href">https://medium.com/media/392bf5ea6fcf55079952523fe1364f05/href</a></iframe><h4>Part 2: Task function</h4><p>This is actually the bulk of the factory. What we want to do here is create a function that will be executed using the PythonOperator. Essentially, this is the function that should determine if the condition is met and if it&#39;s not, send out the notification.</p><p>We start by getting the query from the configuration file and running it against our data warehouse (in our case Snowflake, but this should work with any data warehouse). We then evaluate the result against the target value configured in the YAML file and compare it using the criteria we specified. After that, we check to see if we need to notify and if we do we call the appropriate function depending on the notifier we selected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e01028b6e606ad57a5d40e51b9957891/href">https://medium.com/media/e01028b6e606ad57a5d40e51b9957891/href</a></iframe><h4>Part 3: Setup the DAG and task</h4><p>Lastly, we just need to add a task to the DAG to execute the _run_alert function using the PythonOperator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc80a9ba4e338d04dfda427ea0455d22/href">https://medium.com/media/dc80a9ba4e338d04dfda427ea0455d22/href</a></iframe><p>Going back full circle, notice how we are returning the DAG (dag) we created so we can use it and add it to the global scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f479fafd0f82f9ed68b214ec8b9d847/href">https://medium.com/media/0f479fafd0f82f9ed68b214ec8b9d847/href</a></iframe><h3>Conclusion</h3><p>Now, there’s a lot to be said about this implementation. I think the most important point about it is the DAG factory approach to it and how simple it is to write new alerts. But more about that in a future post. About the alerts themselves, it’s good to bear in mind that this is not going to replace your data quality tool like <a href="https://greatexpectations.io/">great_expectations</a>, or even <a href="https://docs.getdbt.com/docs/building-a-dbt-project/tests">dbt tests</a>. Furthermore, in the same way, that great_expectations and dbt tests can live together in harmony, I see a place for these SQL alerts to be combined with these other tools. The way I think about it is that you can use these SQL alerts for data loading, dbt tests for testing out your transformations and great_expectations for your final products to make sure your data stakeholders are using reliable data.</p><p>Looking back at the implementation itself, as I was writing this post I noticed that this code is in need of a refactor, and there are some things that could be implemented in a cleaner way. But hey, I leave it as an exercise to the reader to find better ways to improve this script and maybe even extend it to more and better use-cases. In any case, hope this is useful as a base and sparks your creativity to improve your notifications regarding data loading into your data warehouse.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5becedfc03fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-we-use-airflow-for-sql-alerts-and-slack-notifications-5becedfc03fd">How we use Airflow for SQL alerts and Slack notifications</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[How to Build a Custom Estimator for scikit-learn]]></title>
            <link>https://medium.com/data-science/how-to-build-a-custom-estimator-for-scikit-learn-fddc0cb9e16e?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fddc0cb9e16e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 16:40:28 GMT</pubDate>
            <atom:updated>2021-03-03T20:48:55.150Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>Implementing a custom ensemble model with under-sampling for imbalanced data</h4><p>This post will show you how to implement your own model and make it compliant with scikit-learn’s API. The final result will be a model that can not only be fitted and used for predictions but also be used in combination with other scikit-learn tools like grid search and pipelines.</p><h3>Introduction</h3><p>This post traces back to a few months ago. In one of my machine learning courses, we were discussing the topic of imbalanced data and how algorithms have a hard time learning when data is not balanced. For our learning algorithms, the event we are trying to predict is so uncommon that in the process of improving evaluation scores, our model will rarely predict this category. As soon as I came into contact with this topic I knew it was super important. I had seen imbalanced data before and knew very well that real-life is not as easy as toy datasets. The case that resonated the most with me was predicting customer churn.</p><p>Anyway, in our class, we saw many ways we could avoid or try to mitigate the problem of imbalanced data, but one solution was particularly interesting to me: Ensemble Resampling. We were following <a href="https://amueller.github.io/ml-training-advanced/slides/04-imbalanced-data.html#27">Andreas Müller’s lectures</a>. In this section, he mentions a paper “<a href="https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/tsmcb09.pdf">Exploratory Undersampling for Class-Imbalance Learning</a>”. In this paper, the authors describe an interesting approach to improving classification in imbalanced datasets, they call it EasyEnsemble. The basic idea is to train an ensemble model using under-sampling, resampling every time, and combine the overall result of the ensemble. The benefit of this model is that it reduces the amount of data that gets discarded in the process of under-sampling.</p><h3>Building the Model</h3><p>The specific implementation of your custom model will depend a lot on the model you are trying to extend or build upon. If you are starting from scratch, a good start is the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html">BaseEstimator</a>. We can start by building the class for our model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb7a8d875763d96691ce0e7397233ef1/href">https://medium.com/media/bb7a8d875763d96691ce0e7397233ef1/href</a></iframe><p>There are a few methods we need to implement, but first and foremost, we can go ahead and create that __init__ method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95537615cf7a42780be3c7ac6ccb215d/href">https://medium.com/media/95537615cf7a42780be3c7ac6ccb215d/href</a></iframe><p>At this point, we are basically just passing on all the arguments and storing them as attributes. There is a couple of other things we need to do to implement the actual model. We need a way to generate the ensemble. To accomplish this, we’ll define a function to generate the estimators: _generate_estimators.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74891c634ab61245d2116d3f426b37d/href">https://medium.com/media/b74891c634ab61245d2116d3f426b37d/href</a></iframe><p>This method does not take any argument because all the data we need is already stored in the instance’s attributes. We start by creating a list of estimators. This will be our end result; a list of estimators. The number of estimators is determined by the attribute self.n_estimators, so we just create each estimator inside a for-loop. To build each estimator, we <a href="https://scikit-learn.org/stable/modules/generated/sklearn.base.clone.html">clone</a> the self.base_estimator, set it up using all the parameters and make a pipeline with it. Instead of using scikit-learn&#39;s pipeline, we need to use <a href="https://github.com/scikit-learn-contrib/imbalanced-learn">imbalanced-learn&#39;s</a> pipeline (<a href="https://imbalanced-learn.org/stable/references/generated/imblearn.pipeline.make_pipeline.html">docs</a>) so that we can do our under-sampling.</p><p>Now we can go back to the __init__ function and generate these estimators:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b086fd2be3c43fbe827d63c8d44c9ae/href">https://medium.com/media/9b086fd2be3c43fbe827d63c8d44c9ae/href</a></iframe><p>Perfect, now the last piece of the puzzle is to generate a single estimation that makes a decision about the result from the ensemble. We’ll use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.VotingClassifier.html">VotingClassifier</a> that will take the result of the estimators and reach a final conclusion using <a href="https://www.oreilly.com/library/view/machine-learning-for/9781783980284/47c32d8b-7b01-4696-8043-3f8472e3a447.xhtml">soft voting</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9db00c981310bb8d6665aef9c61306aa/href">https://medium.com/media/9db00c981310bb8d6665aef9c61306aa/href</a></iframe><p>Finally, there are a few other methods we need to implement for this to work but don’t worry, that was the hard part the rest is fairly straightforward.</p><p>We’ll implement fit, predict and classes_ methods that we&#39;ll simply delegate responsibility by calling the VotingClassifier methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b23c07d0734a283dd57a4c7f5ffe93a/href">https://medium.com/media/5b23c07d0734a283dd57a4c7f5ffe93a/href</a></iframe><p>Last but not least, we need to implement a set_params method. As mentioned in the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.base.clone.html">docs</a>, this functions is quite fundamental as it is used during grid searches to update the parameters of the models. In our case, this is fairly straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/639de99e2e12eb875b8e02bbaeb2dcec/href">https://medium.com/media/639de99e2e12eb875b8e02bbaeb2dcec/href</a></iframe><p>Putting it all together, we get our own model that we can use in combination with other scikit models and tools. We can use it in a pipeline, grid search and score it like any other model.</p><p>The only thing left to do is test it out!</p><h3>Using the Model</h3><p>If you store the class we just built in a resampled_ensemble.py file, importing your model is just as simple as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab95e2216c41e9fe2331d67415d71332/href">https://medium.com/media/ab95e2216c41e9fe2331d67415d71332/href</a></iframe><p>From now on, it’s basically just like a scikit-learn model, so we can proceed the usual way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1887a72b794ea77bbad952a6df0f0312/href">https://medium.com/media/1887a72b794ea77bbad952a6df0f0312/href</a></iframe><p>We’ll instantiate the model, fit it and check how it performed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/655342a2def2e7db1b6d855660aad514/href">https://medium.com/media/655342a2def2e7db1b6d855660aad514/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aO3228WtpN1tnUA6BzXawg.png" /><figcaption>Classification report for our fitted model</figcaption></figure><p>We can also plot the ROC curve and confusion matrices:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6e349889e385234ed53d09ebe714dff/href">https://medium.com/media/a6e349889e385234ed53d09ebe714dff/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TP8h_aRM025kqSZ-OFJapw.png" /><figcaption>ROC curve for our ResampledEnsemble model</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a62ba3fd0e11eadf626d8f50053e6898/href">https://medium.com/media/a62ba3fd0e11eadf626d8f50053e6898/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5KthyciKp7YM5X9Hf4UXw.png" /><figcaption>Normalized and absolute confusion matrix for our model</figcaption></figure><p>However, I think the best part is that we can now use it in pipelines and grid searches:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5954175918c7c1815bd5eec65e4a65be/href">https://medium.com/media/5954175918c7c1815bd5eec65e4a65be/href</a></iframe><h3>Conclusion</h3><p>As you can see, it’s extremely simple to build your own custom models for scikit-learn while also taking advantage of the other tools scikit-learn has to offer. You can build whichever model you want and still be able to use it with metrics, pipelines, and grid searches. In this post, I showed you one example of implementing a model for imbalanced data, but the possibilities are truly endless. For example, this same methodology could be used to implement <a href="https://www.youtube.com/watch?v=zGRnirbHWJ8">Bayesian models of probabilistic programming in scikit-learn</a>. I guess we’ll have to discuss it in a future post…</p><p>Liu, X. Y., Wu, J., &amp; Zhou, Z. H. (2008). Exploratory undersampling for class-imbalance learning. <em>IEEE Transactions on Systems, Man, and Cybernetics, Part B (Cybernetics)</em>, <em>39</em>(2), 539–550.</p><p>Müller, A. (2018). Advanced Scikit-learn, GitHub repository, <a href="https://github.com/amueller/ml-training-advanced">https://github.com/amueller/ml-training-advanced</a></p><p>Müller, A. C., &amp; Guido, S. (2016). <em>Introduction to Machine Learning with Python: A Guide for Data Scientists</em> (1st ed.). O’Reilly Media.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fddc0cb9e16e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-build-a-custom-estimator-for-scikit-learn-fddc0cb9e16e">How to Build a Custom Estimator for scikit-learn</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[Bayesian Weight Loss]]></title>
            <link>https://juangesino.medium.com/bayesian-weight-loss-6f80667bd876?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f80667bd876</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[weight-loss]]></category>
            <category><![CDATA[apple-health]]></category>
            <category><![CDATA[withings]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 07:58:26 GMT</pubDate>
            <atom:updated>2021-02-12T07:58:26.008Z</atom:updated>
            <content:encoded><![CDATA[<p>In a <a href="https://juangesino.medium.com/bayesian-capm-beta-estimation-9c25d95c5b44">previous post</a>, I discussed the concept of linear regressions in the realm of Bayesian statistics. I will do something similar in this post but we’ll change the topic a little bit. We’ll go from finance to weight loss.</p><h3>Introduction</h3><p>I have recently decided to start being more healthy in my life (about time). However, if I wanted to make a change in my life, it meant I was going to have to measure those changes to make sure I’m going in the right direction. In terms of my weight, I decided to purchase a <a href="https://www.withings.com/nl/en/scales">Withings Scale</a> to constantly track my weight and other important metrics.</p><p>As I started weighting myself, I did so twice a week, on Mondays and Thursdays. I started to realised there was quite a big variation in weight from those two data points and suspected there could be some weekly seasonality (I confess I might eat a bit more during the weekends that I do during the week). To properly understand this seasonality, I decided to weigh myself every single day, at the same time of the day (in the morning before my shower).</p><p>The problem was that it became harder to know if I was losing weight or not. Some days it would go up some other days it would go down, but it was hard to understand the pattern and the trends.</p><p>Being the data-loving person that I am, I decided to look at the data more carefully.</p><h3>Data</h3><p>My Withings scale is synced with my Apple Health, so it was incredibly easy to just download all of my data to start my analysis. I imported the XML data in Python selected the weight data from all the metrics collected from Apple and started to explore it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-uK5cw_-1R3nHh-KEjc3A.png" /><figcaption>Scatter plot of my weight recordings over time</figcaption></figure><p>I find the variations in my weight over time quite interesting, but at this point, it seems quite obvious that I am indeed losing weight. Let’s keep exploring.</p><p>The relation looks quite linear to me and I thing a lineal model would make a reasonable approximation. Besides, a linear model would offer an extremely simple interpretation. I would just look at the β coefficient. This coefficient determines the slope of the regression line, which translates into my change in weight over time. If the slope is negative (i.e. β is negative) then I am losing weight over time. If β ends up being positive it means I am actually gaining weight and if it’s zero then I am neither losing nor gaining weight.</p><p>A priori, it is quite likely that β will be negative, indicating a weight-losing trend.</p><h3>OLS</h3><p>I will start with an Ordinary Least Squares model, to have a benchmark and because it’s super easy to implement. All I have to do is regress my weight over time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25d7a53bf08ede0faa591af77e92775/href">https://medium.com/media/f25d7a53bf08ede0faa591af77e92775/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6KGqHGHJ77ANFYNB1NO2A.png" /><figcaption>Summary of results from OLS regression</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZdfNJcB69Gb60ONp-eMxw.png" /><figcaption>OLS regression line</figcaption></figure><p>From these results, it seems my hypothesis was correct. I seem to be losing weight. However, if you read any of my other posts, you’ll know that this is not enough for me. I want to understand how likely it actually is that I am losing weight. I also want to be able to estimate my current weight and understand the probability behind that estimation.</p><h3>Bayesian Regression</h3><p>To be able to answer these questions, we need to switch to a Bayesian model. If you want to read more about Bayesian linear regressions, check my previous post: <a href="https://juangesino.medium.com/bayesian-capm-beta-estimation-9c25d95c5b44">Bayesian CAPM Beta Estimation</a>.</p><p>In this case, I will use quite uninformative priors, but with (in my opinion) quite reasonable logic. For my alpha parameter which will be a sort of average weight parameter, I will use a normal distribution with quite a huge sigma to reflect my lack of knowledge about its actual value, but a mean to reflect a reasonable guess (70kg). I will also use a normal distribution for my beta and will centre it at 0 to be able to capture both weight loss or gains. Now I can build the model using <a href="https://docs.pymc.io/">PyMC3</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de2f81429a3a794befc79614c91501a7/href">https://medium.com/media/de2f81429a3a794befc79614c91501a7/href</a></iframe><p>After checking traces for convergence and diagnostics, I can start analysing the posterior distribution. We can start looking at the distribution of my beta parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gM6bS00GnMMl9zdlEyHLpw.png" /><figcaption>Posterior distribution of β</figcaption></figure><p>This looks good! It seems I am really losing weight and my posterior distribution assigns no probability to the possibility of me NOT having a weight-loss trend. Let’s look at the actual regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNVp5MjG3W_5UD4Ry7VTBQ.png" /><figcaption>Bayesian regression line</figcaption></figure><p>The regression also looks good, we can see that it’s starting to lose certainty as it becomes more unsure about the parameters closer to the current date, but it is pretty certain that I lost weight. Talking about my weight, we can use the estimates for beta and alpha to try to estimate my current weight. Or even better, generate a distribution for my current weight:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcKwjcFvs5jFyoS5mjabLw.png" /><figcaption>Posterior distribution of my weight</figcaption></figure><p>That’s interesting, we can see that uncertainty we saw in the regression line being reflected in this distribution. We are, in fact, quite unsure about my current weight. However, we can use Bayesian 95% credible intervals to understand this better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zby0-iLI1rUfJlUbWbPmbA.png" /><figcaption>Posterior distribution of my weight with 95% credible intervals</figcaption></figure><p>It seems my weight is most likely (95% probability) between 67.6kg and 68.1kg. We can even use this distribution to find some probabilities. For example, it seems I’m likely to weight less than 68kg, there’s only an 8.3% probability that I weight more than that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ca9e7862c9811beaa314fd3fe51fef6/href">https://medium.com/media/3ca9e7862c9811beaa314fd3fe51fef6/href</a></iframe><h3>Conclusion</h3><p>This post was yet another example of how to build linear regressions using Bayesian statistics. Hopefully, this serves as proof of how useful Bayesian statistics can be and reflects the power behind having an entire distribution of your parameters. In essence, we are able to quantify our uncertainty instead of just hiding it behind a single number estimation.</p><p>As far as my health goes, I’ll start keeping track of my beta from now on to make sure I am still keeping myself healthy even if I’m losing weight. This is hugely useful as losing weight too fast can have detrimental results (<a href="https://www.mayoclinic.org/healthy-lifestyle/weight-loss/expert-answers/fast-weight-loss/faq-20058289">source</a>). At the same time, my <a href="https://www.withings.com/nl/en/scales">Withings</a> scale records other really nice metrics which I’ll probably build some other Bayesian models to try to understand a little better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f80667bd876" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crazy Simple Anomaly Detection for Customer Success]]></title>
            <link>https://medium.com/data-science/crazy-simple-anomaly-detection-for-customer-success-458e94d4d516?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/458e94d4d516</guid>
            <category><![CDATA[customer-success]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[customer-health-score]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 16:53:49 GMT</pubDate>
            <atom:updated>2021-02-13T18:54:01.092Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to detect changes in usage, react in time and make your customers happy</h4><p>The topic of anomaly detection is fascinating. There is a vast number of methods that can be used, from simple statistics to more complex unsupervised learning methods. Additionally, the impact of anomaly detection is huge. The ability to detect when things are not going as planned is a fantastic tool and one that has the potential to save lives (for example in preventive maintenance).</p><p>In this article, we will explore an extremely easy approach to anomaly detection. Sometimes the simplest solutions can have the greatest impact. In this case, we’ll use the <a href="https://en.wikipedia.org/wiki/Median_absolute_deviation">median absolute deviation or MAD</a> to detect possible outliers in the number of WhatsApp messages transacted by businesses.</p><h3>Introduction</h3><p>In the area of Customer Success, and in particular, in SaaS B2B companies, measuring our customers&#39; product usage is paramount. In essence, SaaS businesses want to understand how their customers are using their product and how much they are using it. The reason behind it is that if customers are not using your product, it’s very likely they are having some kind of trouble. It could be that they just don’t understand how to use it, they are not getting value out of it or they are experiencing some sort of product bug. In any case, a drop in usage can result in customer churn. Among other things, the role of the Customer Success team is to identify cases where this could be happening and help those clients to ultimately lead them towards success.</p><p>Besides regular checks using, for example, MBRs or QBRs (monthly or quarterly business reviews), the Customer Success team can assume a proactive attitude by understanding when customers are using their product less than usual. This is a perfect example of implementing anomaly detection. The idea is to detect anomalies in the usage data from every customer and have the Customer Success team reach out to those customers that are dropping their usage.</p><h3>Data</h3><p>The kind of data to be used is very specific to the business. If you are an e-commerce platform like Shopify, you might be interested in tracking sales, if you are an email marketing platform like MailChimp, you will be interested in emails sent. As I work in <a href="https://www.sirena.app/">Sirena</a>, an app that lets businesses communicate with their customers through WhatsApp, I will use data on WhatsApp messages usage. For this article, I will use randomly generated data of WhatsApp messages coming from a very simple simulation. This dataset is publicly available in my Github: <a href="https://github.com/juangesino/FakeData/tree/master/WhatsAppMessages">FakeData/WhatsAppMessages</a></p><p>The dataset contains the number of messages transacted by 4 different customers through a period of 10 weeks. To keep things simple, we will focus on only one customer; Customer 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*E2LFPXTDi382oIapQK550w.png" /></figure><h3>Anomaly Detection</h3><h4><strong>MAD</strong></h4><p>The median absolute deviation or MAD, is a very simple measure of variation in a sample. In that sense, it is quite similar to the standard deviation in terms of measuring statistical dispersion. The MAD is defined as being the median of the absolute value of the residuals between each observation and the median:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roqPhHFocXDQyBZ54XTg3Q.png" /></figure><p>However, a great advantage of the MAD in comparison to the standard deviation is its robustness or insensitivity to outliers. Both the mean and the standard deviation are highly influenced by outliers and therefore are extremely bad for anomaly detection. In their paper, Leys et al. (2013) show that many researchers are still using standard deviation for representing dispersion and suggest a change towards MAD instead. They even show how to calculate it using SPSS and R. In this post, I will show you how to use it in Python to detect anomalies or outliers.</p><h4><strong>Implementation</strong></h4><p>We’ll start with looking at a single customer, Customer 3 in this case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56425f11f73832812ef964d7dd20d25a/href">https://medium.com/media/56425f11f73832812ef964d7dd20d25a/href</a></iframe><p>You’ll probably be quite surprised by how easy the implementation of this is. In fact, calculating the MAD is basically just one line of python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d1a09c1513bd1875a8e9c0c92d38e8d/href">https://medium.com/media/5d1a09c1513bd1875a8e9c0c92d38e8d/href</a></iframe><p>What that line is doing is defining a (lambda) function that takes a <a href="https://numpy.org/">numpy</a> array (x) and calculates the median for the element-wise absolute value of the difference between each x and the median of x. Which is exactly the definition of MAD. Simple.</p><p>The only (very tiny) complication we face when calculating the MAD is that we would actually like to calculate a rolling MAD. But that’s also quite straightforward using numpy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44a44d2b3b96d827e9a08df533ca354e/href">https://medium.com/media/44a44d2b3b96d827e9a08df533ca354e/href</a></iframe><p>As you can see, first we calculate the rolling median and then we add the rolling MAD. We can plot how that looks together with the data to get a sense of what we are doing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oETkiaM6NUkZgvmfDAL-Hg.png" /></figure><p>We can see that the MAD is highly lagged, and that’s OK. Remember we are not going for a hugely sophisticated anomaly detector or a predictive model. We just need to get a sense of what it would be “normal” usage changes for our clients.</p><p>Great, now that we have our MAD, we need to define criteria to understand if an observation is an actual anomaly or not. To do this we’ll add a threshold and create upper and lower bounds for our rolling MAD:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e80e694e282ce3aeacd9f9a58e52512/href">https://medium.com/media/8e80e694e282ce3aeacd9f9a58e52512/href</a></iframe><p>Great! Now we can add those boundaries to the graph and see what we are dealing with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAYV6vEYX_is41GO_3W7kw.png" /></figure><p>That’s looking good! Now we have our MAD and a boundary that can help us determine if an observation is an anomaly or not. This means that for every point in time if the observation is above the upper bound or below the lower bound of the rolling MAD, we’ll say that’s an anomaly.</p><p>In this specific case, it looks like that 50% threshold might be a little bit too tight. We can try changing that until we are comfortable with the number of false positives. We can try with 70%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEuI4pSWcdXIvvIgnkEE0Q.png" /></figure><p>Using this data we can very easily get a list of all the anomalies detected by our MAD implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1987ff0a434bc5646e4f06bebab25e0/href">https://medium.com/media/c1987ff0a434bc5646e4f06bebab25e0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnIpzHj38RZUigCM0qIZtw.png" /></figure><p>The result shows us what the usage was for each day (values), what we expected to see (MAD) and the interval (upper and lower MAD).</p><h3>Conclusion</h3><p>In this post, we have explored a very simple way of implementing anomaly detection for usage data using the median absolute deviation or MAD. Of course, there’s a lot of tinkering you can do to adjust this to your specific use-cases, such as the rolling window, the threshold, or the decision on when to notify your team. I’m sure you can imagine a Slack integration notifying Customer Success Executives when one of their accounts has dropped their usage. However, if your product usage has a relevant seasonality, consider adjusting the notification service. For example, in our case, it doesn’t make a lot of sense to notify CSEs if the drop in usage occurs during a weekend (usage is expected to drop during weekends). Another option is to have two MAD bounds, one for the weekend with a more permissive threshold and another one for weekdays with a more tight threshold. The possibilities are endless.</p><p><strong>References</strong></p><p>Leys, C., Ley, C., Klein, O., Bernard, P., &amp; Licata, L. (2013). Detecting outliers: Do not use standard deviation around the mean, use absolute deviation around the median. <em>Journal of experimental social psychology, 49</em>(4), 764–766.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=458e94d4d516" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/crazy-simple-anomaly-detection-for-customer-success-458e94d4d516">Crazy Simple Anomaly Detection for Customer Success</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[Bayesian CAPM Beta Estimation]]></title>
            <link>https://medium.com/swlh/bayesian-capm-beta-estimation-9c25d95c5b44?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c25d95c5b44</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 17:50:56 GMT</pubDate>
            <atom:updated>2021-02-16T07:01:52.013Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing with my (mostly) healthy obsession with Bayesian statistics (see <a href="https://medium.com/@juangesino/bayesian-a-b-testing-whatsapp-messages-fd03426e7e94">my previous article</a>), in this article, I’ll use a linear regression model from a Bayesian perspective.</p><p>To demonstrate how linear regressions in the context of Bayesian statistics work, I will use the CAPM to estimate stock’s Betas.</p><h3>Introduction</h3><p>It’s not fundamentally important that you are familiar with CAPM to understand the example of regressions using Bayesian statistics. However, for those out there who might be interested, CAPM stands for Capital Asset Pricing Model. The model defines a relationship between an asset’s (usually stocks) expected returns and the market risk premium. In essence, it describes how a stock’s expected return reacts to the market risk premium.</p><figure><img alt="The Capital Asset Pricing Model" src="https://cdn-images-1.medium.com/max/1024/1*4acn4eSfXOqS3TZtk93icg.png" /><figcaption>The Capital Asset Pricing Model</figcaption></figure><p>As can be seen in the model specification, this relationship is linear with a β coefficient describing the effect of a change in the market risk premium on the stock’s expected return. In finance, this coefficient is commonly known as (you guessed it) <em>Beta</em>.</p><figure><img alt="Yahoo! Finance showing the value of Beta for Amazon (AMZN)" src="https://cdn-images-1.medium.com/max/932/1*WC8T-tNFVHrhiNPC354XOg.png" /><figcaption>Yahoo! Finance showing the value of Beta for Amazon (AMZN)</figcaption></figure><p><strong>Beta</strong></p><p>The interpretation for this Beta coefficient is that it represents a measure of the volatility of the asset. In practice, the expected market returns used are the returns for investing in the S&amp;P 500. As a result, Beta ends up being a measure of the correlation between the S&amp;P 500’s expected returns and the stock’s expected returns.</p><p>I’m not going to go any deeper into the CAPM, or why it’s good and why it’s bad, but if you found it interesting, I encourage you to read more about it <a href="https://www.investopedia.com/terms/c/capm.asp">here</a>.</p><p>Measuring the Beta of a stock is nothing extraordinary or remarkable. In fact, if you go to Yahoo! Finance right now and search for any stock, you will find the Beta for that stock as part of the basic data that Yahoo! provides. However, as you can see, the number provided by Yahoo! Finance is a single point-estimate of the Beta for the stock. Whenever you are given a single number, always (seriously, always) ask yourself the following question: How certain are they?</p><p>This applies to almost any statical estimation, from stocks’ Betas to COVID-19 vaccine efficiency. If I tell you that a vaccine is 90% effective against COVID-19, you might be extremely impressed. But, how certain are you really that the vaccine has a 90% efficiency? What is the probability of the vaccine having a 90% efficiency? What is the probability of it being lower than 90%? These are all questions that should immediately come to your mind whenever someone gives you a point-value estimate.</p><p><strong>Remember</strong>: Always doubt point-estimates, ask yourself what is the probability of the estimate actually having that value.</p><p>We will see how we can use our Bayesian approach to solve this issue and give more information about our uncertainty.</p><h3>Model</h3><p>The model is quite straightforward, but we need to take care of how we operationalize it. We can re-arrange the model to find that the expected excess returns from the stock should be proportional to the excess return of the market, with β being the constant of proportionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLWvLoWJVrOaKr_UiW98ZA.png" /></figure><p>Furthermore, the returns for both the stock and the market, are basically the percentage change in closing prices at the stock market. The risk-free rate to use and subtract from the returns is an entire discussion on its own. We will avoid this discussion by assuming a risk-free rate of zero. This is obviously wrong, but the point of this post is not on perfect estimation of CAPM Betas, but Bayesian linear regression. In any case, you can do the entire procedure and simply subtract whichever risk-free rate you find appropriate (an exercise for the reader). Let’s call the excess returns for the stock Y and the excess returns for the market X. We can add an 𝛼 term to capture everything else that is not captured by the proportionality between X and Y, and get the following linear regression model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YmWOyPCUNzhFrYS9hA8Ig.png" /><figcaption>Linear regression model</figcaption></figure><h3>Data</h3><p>Now that we have defined our model, we can get some data to start fitting it and estimate the coefficients. In this case, all we need are the closing prices for the S&amp;P 500 (the market returns) and whichever stocks we want to use. In this case, let’s give it a try with Microsoft (<a href="https://finance.yahoo.com/quote/MSFT?p=MSFT">MSFT</a>), Amazon (<a href="https://finance.yahoo.com/quote/AMZN/">AMZN</a>), Facebook (<a href="https://finance.yahoo.com/quote/FB?p=FB">FB</a>) and Google (<a href="https://finance.yahoo.com/quote/GOOG?p=GOOG">GOOG</a>). As you can see from Yahoo! Finance, they use data from the last 5 years and on a monthly interval, so we’ll do the same.</p><p>To get all these data, we’ll use a Python package called <a href="https://pypi.org/project/yfinance/">yfinance</a>. This package lets us download data from Yahoo! Finance for any stock. We need to do a bit of data wrangling first to get all the data we need in a nice and convenient format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ce6513065807a5e5690ad2edbb8c29/href">https://medium.com/media/10ce6513065807a5e5690ad2edbb8c29/href</a></iframe><h4>Ordinary Least Squares</h4><p>To have a benchmark to compare our results, we will first fit and OLS model to our data before taking the Bayesian approach. This is fairly simple using the <a href="https://www.statsmodels.org/stable/index.html">statsmodels</a> Python package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda2fa96e6f74952786d60a2b771300f/href">https://medium.com/media/bda2fa96e6f74952786d60a2b771300f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzeVbq9THxAB96H1aV3UlA.png" /></figure><p>Great, now let’s run this for the four stocks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08b77114f4c40912b93f4b267d675be8/href">https://medium.com/media/08b77114f4c40912b93f4b267d675be8/href</a></iframe><pre>MSFT:  0.8079265809137846<br>GOOG:  0.9806040506006948<br>AMZN:  1.152025182533014<br>FB:    1.2664985151863173</pre><p>Now, if we compare with the values in Yahoo! Finance, we see that they are quite close to each other. These are the Betas for those 4 stocks at the time of writing:</p><pre>MSFT:  0.83<br>GOOG:  0.99<br>AMZN:  1.20<br>FB:    1.18</pre><p>By the way, did you see that R²? Do we really think this relationship is linear? Absolutely not! But let’s not get into that for now…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxLIS9GIVVmFXg8ChlXs6g.png" /></figure><h4>Bayesian Linear Regression</h4><p>Now that we have seen the results of this model using OLS, let’s try it out with a Bayesian approach. We will use the same model and we’ll even use the same assumptions as OLS. One of the great advantages of going Bayesian is the ability to choose our own assumptions and add domain knowledge into our model estimation through the use of priors. In this case, we’ll stick with the usual priors for a linear regression. We will assume all of our coefficients come from normal distributions and our error term is also normally distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8_Wi8yv9dUZo7e74lGDnA.png" /></figure><p>Having defined our model and our priors, we can start coding it using <a href="https://docs.pymc.io/">PyMC3</a>, an amazing Python library for probabilistic programming.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1076754c5411ec9c22433ada490f4318/href">https://medium.com/media/1076754c5411ec9c22433ada490f4318/href</a></iframe><p>After sampling from our model and checking we have convergence by looking at the trace plots, we can get our posterior distribution for our Beta. Remember, because we are going the Bayesian way, we are not getting a value as a result, but an entire distribution. This distribution will reflect the uncertainty we have on our prediction for Beta. But enough talking, let’s look at the distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmnEUHVpdAJGyfI-V0y-dA.png" /><figcaption>Posterior distribution for Amazon’s Beta</figcaption></figure><p>We can see that the Beta for Amazon is most likely between 0.9 and 1.3, in fact, there’s about a 70% chance of the Beta for Amazon being between 0.9 and 1.3. That’s the beauty of our Bayesian analysis, we can actually talk probabilities.</p><p>This result is also in line with the value from Yahoo! Finance. However, it’s when we take advantage of this distribution, that Bayesian analysis really shines. For example, we can now ask questions like “What is the probability that the Beta for Amazon is greater than 1.2?”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f200b697ca689198070fe8fa1cdc98/href">https://medium.com/media/a7f200b697ca689198070fe8fa1cdc98/href</a></iframe><p>There we have it, there’s around a 32% probability that the Beta for Amazon is actually greater than 1.2.</p><p>We can run the same process for all of our stocks and compare the result with Yahoo! Finance and OLS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVedlCa3zm-RzJjUCj1-pA.png" /><figcaption>Posterior distributions for Betas</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIJ1C6JHCWirCSkEEMrW5g.png" /></figure><p>We can see that results from our Bayesian linear regression are consistent with our OLS example and the value reported in Yahoo! Finance. However, the Bayesian approach has the advantage of letting us customise our assumptions for the model and quantify our uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPqKvKDiuV6OxLYh8AGmZw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c25d95c5b44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/bayesian-capm-beta-estimation-9c25d95c5b44">Bayesian CAPM Beta Estimation</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bayesian A/B Testing WhatsApp Messages]]></title>
            <link>https://medium.com/swlh/bayesian-a-b-testing-whatsapp-messages-fd03426e7e94?source=rss-5a4d46a446e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd03426e7e94</guid>
            <category><![CDATA[whatsapp]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[marketing]]></category>
            <dc:creator><![CDATA[Juan Gesino]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 15:47:15 GMT</pubDate>
            <atom:updated>2021-02-13T21:50:04.723Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will walk you through the process of performing an A/B testing analysis from the perspective of Bayesian statistics to determine the best WhatsApp message template to send to customers.</p><p>To be fair, there is no difference if this is about a website landing page, a product feature or WhatsApp messages. The logic of A/B testing can be applied to any experiment. However, because I work at <a href="https://www.sirena.app/">Sirena</a>, I find it appropriate to use the example of WhatsApp messages.</p><h3>Context about the problem</h3><p>Let’s set up the case for some context. You are an online retail business operating through WhatsApp in the modern era. For the purpose of this article, let’s say you get 10K messages per working week, most of them during the day and so your incoming WhatsApp traffic might look something like this:</p><figure><img alt="One week of WhatsApp incoming messages" src="https://cdn-images-1.medium.com/max/1024/1*vQZ7VbLl1sjpfOq8bUx8YA.png" /><figcaption>One week of WhatsApp incoming messages</figcaption></figure><p>Once your contacts reach out to you, a <a href="https://help.sirena.app/en/articles/4397418-sirena-bots">Sirena Bot</a> contacts them right away. After your bot talks to them, they get transferred to one of your sales reps and the sales process begins. The question is, <strong>which message should your sales representatives send first?</strong></p><p>Ideally, you already have a bunch of <a href="https://help.sirena.app/en/articles/3474991-whatsapp-and-facebook-message-templates">message templates</a> (highly-structured messages or HSMs) that your sales representatives can use. Probably they are currently alternating between a few options, but not really sure which one works best.</p><p>Let’s find out!</p><h3>Presenting the data</h3><p>Obviously answering this question will require us to dig into our data. For the purpose of this article, I have generated a random sample of data that simulates 10K incoming WhatsApp messages. The dataset is publicly available in my Github: <a href="https://github.com/juangesino/FakeData/tree/master/WhatsAppMessages">FakeData/WhatsAppMessages</a></p><p>In the data, we can also find the result of sending a given HSM (message template) to an incoming message. The result can be twofold; either the contact converts or they don’t. The meaning of conversion here is not extremely relevant, you can think of it as something extremely simple, such as getting a reply, or something more elaborate as getting a <em>positive</em> reply determined by a sentiment analysis model. In any case, the result boils down to a 1 (converted) or a 0 (not converted).</p><p>The flexibility of this dataset is that we can choose what message template to “send” to each incoming message and it will tell us what was the result. Pretty neat!</p><h3>Assigning templates to messages</h3><p>If you are not familiar with A/B testing, the basic idea is to randomly choose which treatment (A or B) to give to an individual. It’s a form of a controlled experiment where some fraction of the people get one treatment and another fraction gets another treatment. In the end, the objective is to determine which of the treatments is the “best”.</p><p>In our case, our treatments are different message templates (HSMs) and because we want to start simple, we will randomly assign each incoming message to one of the templates in a uniform manner. This means that at the end, we should have roughly 1/3 of the incoming messages being answered with HSM₁, another 1/3 with HSM₂ and finally, 1/3 using HSM₃. If you know anything about multi-armed bandits, you might recognize that this is not optimal. For now, bear with me and I’ll write about multi-armed bandits in another post.</p><p>Let’s assign those message templates:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ca010b1110f3444086f70bb910e9226/href">https://medium.com/media/7ca010b1110f3444086f70bb910e9226/href</a></iframe><p>If you recall, the dataset has data on how an incoming message would react to each message template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd210112009407b74f8009e8a5d54e56/href">https://medium.com/media/bd210112009407b74f8009e8a5d54e56/href</a></iframe><p>Now we are ready to explore our data.</p><h3>Exploratory data analysis</h3><p>Now that we have assigned HSMs to every message, we can take a look at the data and explore the results. I won’t focus too much on this part since the point of this article is the Bayesian analysis itself. However, it’s important to check what the empirical conversion rates are for our sample:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01fff5639dc78af80cc531459ae9543e/href">https://medium.com/media/01fff5639dc78af80cc531459ae9543e/href</a></iframe><pre>Total Conversions: 681</pre><pre>Overall conversion rate: 0.0681 </pre><pre>Conversion rate HSM 1: 0.0336<br>Conversion rate HSM 2: 0.101<br>Conversion rate HSM 3: 0.0774</pre><p>We can see that in our sample, the best template was HSM₂ with a conversion rate of about 10%. The worst conversion rate was for HSM₁ with a conversion rate of roughly 3.4%. The difference between these two templates is extreme, but if we take a look at HSM₃, with a conversion rate of 7.7%, one can wonder if there is really any difference between HSM₂ and HSM₃.</p><h3>Bayesian analysis</h3><p>Now let’s move to the fun part. We want to understand how different the conversion rates for our templates actually are. The question is: is HSM₂ <em>really</em> better than HSM₃? Or was this just by chance and an artefact of our sample?</p><p>To analyse this, I’ll take a <a href="https://en.wikipedia.org/wiki/Bayesian_probability">Bayesian</a> approach. I recognise most people will be familiar with the <a href="https://en.wikipedia.org/wiki/Frequentist_probability">Frequentists</a> approach (such as hypothesis testing) and I’ll probably write about it in another article. However, for the last couple of weeks, I’ve been obsessing about Bayesian statistics, so we’ll use that. Specifically, I will use <a href="https://docs.pymc.io/">PyMC3</a> to model the problem and obtain posterior distributions of our conversion rates for each HSM.</p><p>To start, we need to create a model for our conversion rates. The beautiful thing about Bayesian statistics is that it lets you incorporate prior knowledge or domain expertise into your analysis by using <a href="https://en.wikipedia.org/wiki/Prior_probability">priors</a>. In this case, let’s not make any bold claims about our conversion rates. We’ll use <a href="https://distribution-explorer.github.io/continuous/uniform.html">uniform distributions</a> for the two conversion rates to represent how we have no clue what those conversion rates are.</p><p>The next step is to define our delta, which we’ll define as the difference between the first conversion rate and the second one. This can be interpreted as the gain in conversion rate that HSM₂ gives us compared to HSM₃. Last but not least, we use the conversion rates from our uniform distributions to model the conversions we observed. To model these conversions, we’ll use a <a href="https://distribution-explorer.github.io/discrete/bernoulli.html">Bernoulli distribution</a> that takes values that are either 0 or 1 with a certain probability (our conversion rates).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a402dbd5e1d60c8e36b911055aa59ab2/href">https://medium.com/media/a402dbd5e1d60c8e36b911055aa59ab2/href</a></iframe><p>After sampling from our model, we can plot some diagnostics:</p><figure><img alt="Diagnostics trace plots" src="https://cdn-images-1.medium.com/max/1024/1*XJhRxMKyQclvVDDvsViviw.png" /><figcaption>Diagnostics trace plots</figcaption></figure><p>From these plots, we can see that <em>a priori</em>, HSM₂ has a conversion rate of about 9.6% and HSM₃ has a conversion rate of 7.7%. Additionally, we have the posterior distribution of deltas or the distribution of how much better HSM₂ is compared to HSM₃. All in all, it appears our model has converged and is looking good. Now, let’s explore those posterior distributions.</p><figure><img alt="Posterior distributions of the conversion rates" src="https://cdn-images-1.medium.com/max/1024/1*Mot-YGq-Eb6pite4_a55kA.png" /><figcaption>Posterior distributions of the conversion rates</figcaption></figure><p>Notice that our Bayesian analysis has yielded distributions as a result instead of point-estimates. This represents our uncertainty about our estimations and is a perfect way to communicate results with business stakeholders. For example, looking at the distribution, we can see that the conversion rate of HSM₂ is anywhere between 8.7% and 11.2% while the distribution of the conversion rate of HSM₃ is between 6.2% and 8.7%.</p><p>At the same time, we can analyse the distribution of delta (the difference in conversion rates). We see that the difference lies between 0% and 5%. This means that in the worst-case scenario, HSM₂ has no difference in conversion from HSM₃. However, there is a high probability (86%) that HSM₂ can increase our conversion rate by 1.25pp or more!</p><h3>Conclusion</h3><p>In this article, I’ve shown you how to perform A/B testing using a Bayesian approach to determine which WhatsApp message template is the best. The concepts I discussed in this article are equally applicable to any other A/B testing problem; landing pages, product features, CTAs, emails, and so much more! However, there are plenty of things I did not discuss in this article, such as my choice for the priors, conjugate priors, multi-armed bandits and more. I intend to get to discuss all these interesting topics in future articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd03426e7e94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/bayesian-a-b-testing-whatsapp-messages-fd03426e7e94">Bayesian A/B Testing WhatsApp Messages</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>