<?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 Mbaye SENE on Medium]]></title>
        <description><![CDATA[Stories by Mbaye SENE on Medium]]></description>
        <link>https://medium.com/@mbayemc2?source=rss-72cec60a6eb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gR_EDCj7isIQFXqCub3Ohw.jpeg</url>
            <title>Stories by Mbaye SENE on Medium</title>
            <link>https://medium.com/@mbayemc2?source=rss-72cec60a6eb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:26:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mbayemc2/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[End-to-End Data Engineering in Action : My Journey Building a Modern Stack with dbt, MotherDuck…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mbayemc2/end-to-end-data-engineering-in-action-my-journey-building-a-modern-stack-with-dbt-motherduck-51a7d66150eb?source=rss-72cec60a6eb5------2"><img src="https://cdn-images-1.medium.com/max/2600/1*aeqpvcirhkaHfzO2qV8OiQ.jpeg" width="3747"></a></p><p class="medium-feed-snippet">In this article, I&#x2019;ll walk through building a complete data engineering project that combines powerful open-source tools to create an&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@mbayemc2/end-to-end-data-engineering-in-action-my-journey-building-a-modern-stack-with-dbt-motherduck-51a7d66150eb?source=rss-72cec60a6eb5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mbayemc2/end-to-end-data-engineering-in-action-my-journey-building-a-modern-stack-with-dbt-motherduck-51a7d66150eb?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/51a7d66150eb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 20:40:23 GMT</pubDate>
            <atom:updated>2025-04-26T20:40:23.842Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Text to Meaning: Building a Semantic Search Engine with FastAPI, Hugging Face, and DuckDB…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mbayemc2/from-text-to-meaning-building-a-semantic-search-engine-with-fastapi-hugging-face-and-duckdb-a4cc8c5bdea0?source=rss-72cec60a6eb5------2"><img src="https://cdn-images-1.medium.com/max/2600/1*8tCqseIuSKUbi1YHMdk6bw.jpeg" width="2894"></a></p><p class="medium-feed-snippet">In today&#x2019;s data-driven world, the ability to search through large collections of text efficiently and meaningfully has become increasingly&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@mbayemc2/from-text-to-meaning-building-a-semantic-search-engine-with-fastapi-hugging-face-and-duckdb-a4cc8c5bdea0?source=rss-72cec60a6eb5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mbayemc2/from-text-to-meaning-building-a-semantic-search-engine-with-fastapi-hugging-face-and-duckdb-a4cc8c5bdea0?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4cc8c5bdea0</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[search-engine-optimizati]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 09:42:42 GMT</pubDate>
            <atom:updated>2025-03-30T09:42:42.025Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Hands-on : Building a Modern Data Platform with Airbyte, Snowflake and dbt orchestrated by Airflow]]></title>
            <link>https://medium.com/@mbayemc2/hands-on-building-a-modern-data-platform-with-airbyte-snowflake-and-dbt-orchestrated-by-airflow-289152c6e840?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/289152c6e840</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[airbyte]]></category>
            <category><![CDATA[modern-data-stack]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 11:07:53 GMT</pubDate>
            <atom:updated>2025-03-30T09:59:26.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-on : Building a Modern Data Platform with Airbyte, Snowflake and dbt orchestrated by Airflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*K5xHc0QQVJLfO_yt0QCtKQ.jpeg" /></figure><h3>Table of contents</h3><blockquote><strong><em>1. Overview of the Modern Data Stack<br>2. Data Warehousing with Snowflake<br>3. Data Ingestion with Airbyte<br>4. Data Transformation with dbt : the medallion architecture</em></strong><a href="https://medium.com/@mbayemc2/task-parallelization-in-airflow-end-to-end-data-engineering-project-f2ff95f0b186#8e7b"><strong><em><br></em></strong></a><strong><em>5. Orchestration with Apache Airflow<br>6. Data Visualization : Qlik Sense</em></strong></blockquote><p>I was introduced to the concept of the <strong>Modern Data Stack</strong> (MDS) a couple of months ago and was amazed by the progress in building data platforms. I mean the Data Engineering landscape is going crazy day after day. Nowadays, there are various tools that are extremely simple to use for ingesting, storing, and transforming data, and many of them are cloud-agnostic. With the right tools, even small teams can build robust, scalable data platforms.</p><p>This tutorial will guide you through building an end-to-end data platform using some of the most powerful tools available today: <strong>Airbyte</strong> for ingestion, <strong>Snowflake</strong> for storage, <strong>dbt</strong> for transformation, and <strong>Airflow</strong> for orchestration. Finally, we’ll create a reporting layer with popular BI tools like <strong>Qlik Sense</strong> ,<strong>Power BI, Tableau, or MicroStrategy</strong>.</p><p>We’ll walk through how I built this platform for my own data project, where the source data is stored as a CSV file in my GitHub repository. By the end of this guide, you’ll have a fully functional data pipeline that can be adapted to fit almost any use case — whether you’re working with small datasets or managing large-scale enterprise data flows. Check <a href="https://github.com/BlackRock2308/mds-dbt-airbyte-snowflake"><strong><em>here</em></strong></a> if you want to see the full github code.</p><h4>What You’ll Learn:</h4><ul><li>How to use <strong>Airbyte</strong> to ingest data from a CSV file into <strong>Snowflake</strong>.</li><li>How to transform and model data using <strong>dbt</strong>, following the <strong>medallion architecture</strong>.</li><li>How to orchestrate the entire process using <strong>Airflow</strong>, ensuring automated and repeatable workflows.</li><li>How to build insightful reports with <strong>Qlik Sense, </strong>pulling data directly from Snowflake.</li></ul><h3>1 . Overview of the Modern Data Stack</h3><p>Before we dive into the technical details of building our modern data platform, it’s crucial to understand the big picture. In this section, we’ll explore the objectives driving our project, examine the high-level architecture of our solution, and introduce the key components of the modern data stack. This overview will provide the context necessary to appreciate how each piece fits into the larger puzzle of our data platform. Let’s begin by clearly defining what we aim to achieve with this project.</p><h4>1.1 Goals of the Project</h4><p>The primary objective of this project is to construct a scalable, efficient, and modern data platform capable of handling the entire data lifecycle — from ingestion to analysis. Specifically, we aim to:</p><ol><li>Automate the ingestion of data from a CSV file hosted on GitHub.</li><li>Store and manage data efficiently in a cloud-based data warehouse.</li><li>Implement a robust data transformation process using the medallion architecture.</li><li>Orchestrate the entire data pipeline to ensure reliability and consistency.</li><li>Enable easy data visualization and analysis for business users.</li></ol><p>By achieving these goals, we’ll create a data platform that can serve as a foundation for data-driven decision-making in any organization.</p><h4>1.2 High-level Architecture</h4><p>Our modern data platform consists of several key components working in harmony. Here’s a high-level overview of the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rCw2DmkaOysVXgvUQPxAg.jpeg" /><figcaption>Modern Data Platform Architecture</figcaption></figure><h4>1.3 The Modern Data Stack</h4><p>Before diving into the hands-on steps, it’s important to understand the components of a modern data platform and why each of them plays a critical role in ensuring smooth and scalable data workflows.</p><p>- <strong>Ingestion (Airbyte)</strong></p><ul><li>Handles data extraction and loading (EL in ELT)</li><li>Connects to our GitHub source and Snowflake destination</li><li>Ensures efficient and reliable data ingestion</li><li>Makes it easy to connect to various data sources with minimal configuration</li></ul><p>- <strong>Storage (Snowflake)</strong></p><ul><li>Acts as our cloud-based data warehouse</li><li>Stores both raw and transformed data</li><li>Provides scalable compute and storage resources</li><li>Known for its ability to handle massive datasets with ease</li><li>Offers features like time travel and zero-copy cloning</li></ul><p>- <strong>Transformation (dbt)</strong></p><ul><li>Manages data transformations (T in ELT)</li><li>Implements the medallion architecture (Bronze, Silver, Gold layers)</li><li>Ensures data quality and consistency</li><li>Allows transformation of data directly in the warehouse using SQL</li><li>Follows a modular approach for data transformation</li></ul><p>- <strong>Orchestration (Apache Airflow)</strong></p><ul><li>Orchestrates the entire data pipeline</li><li>Schedules and monitors tasks</li><li>Manages dependencies between different stages of the pipeline</li><li>Allows programmatic authoring, scheduling, and monitoring of workflows</li><li>Automates the entire process to run on a schedule</li></ul><p>- <strong>Reporting (Power BI, Tableau, MicroStrategy)</strong></p><ul><li>Connects to Snowflake to access transformed data</li><li>Enables creation of reports and dashboards</li><li>Provides business users with intuitive data exploration capabilities</li><li>Offers rich, interactive data visualizations to drive insights and decision-making</li></ul><h4>1.4 Why This Architecture?</h4><p>This architecture follows modern data engineering principles, separating concerns and allowing for scalability and flexibility. By using best-in-class tools for each component, we create a robust platform that can adapt to changing data needs and grow with the organization.</p><p>The separation of ingestion, storage, transformation, and visualization layers allows for:</p><ol><li>Independent scaling of each component</li><li>Easier maintenance and troubleshooting</li><li>Flexibility to swap out components as technology evolves</li><li>Clear separation of responsibilities in the data team</li></ol><p>In the following sections, we’ll dive deep into each component, exploring how to set them up, configure them, and integrate them into our cohesive data platform. This hands-on approach will give you practical experience in building a modern data stack that can serve as a foundation for data-driven decision-making in any organization.</p><h3>2. <strong><em>Data Warehousing with Snowflake</em></strong></h3><p>The crucial step in building our modern data platform is storing and managing this data effectively. This is where Snowflake, our chosen cloud data warehouse, comes into play. Snowflake offers a powerful, flexible, and scalable solution for storing and analyzing large volumes of data.</p><h4>2.1 Introduction to Snowflake</h4><p>Snowflake is a cloud agnostics data warehousing platform that separates compute and storage, allowing for independent scaling of these resources. Some key features include:</p><ul><li>Automatic scaling and performance optimization</li><li>Support for structured and semi-structured data</li><li>Built-in security and data sharing capabilities</li></ul><p>You can find out why snowflake it a good choice as a warehouse by visiting their official page <a href="https://www.snowflake.com/en/why-snowflake/"><strong><em>here</em></strong></a><strong><em> .</em></strong></p><h4>2.2 Setting Up Snowflake</h4><p>In this subsection, we’ll walk through the process of setting up Snowflake for our project:</p><ol><li><strong>Creating a Snowflake Account</strong></li></ol><p>Setting up a Snowflake project is quite simple. All you have to do is to create a snowflake free trial account (no credit card information needed 😉). Just choose the right edition and cloud provider for your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKI3YmGkETfmkyvxFPN4Bw.png" /><figcaption>snowflake free trial page</figcaption></figure><p>After that, you will receive an email from snowflake ❄️ where you can find your activation link.</p><p>The following image shows the snowflake homepage after you log in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tN0s6jOpHE9p6S6uRscetg.png" /><figcaption>snowflake home page</figcaption></figure><p>The interface is easy to use and highly intuitive. You can try to explore the different features, you can run queries based on the sample data, so one and so forth.</p><p><strong>2. Configuring a Virtual Warehouse , create Databases and Schemas</strong>:</p><p>It’s all about SQL in this section. You need to create a worksheet and write your sql commands for setting up the different pieces : the warehouse, the db, the user, the role and the schema. You also need to grant permission for your created user (you can also use the admin user).</p><p>Here is a screenshot of the process :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bw3l1lsdn06ovRIyIzpCIg.png" /><figcaption>snowflake sql query for setting up</figcaption></figure><p>You can find out the full sql worksheet on the official Airbyte documentation for setting snowflake as a destination(<a href="https://docs.airbyte.com/integrations/destinations/snowflake"><strong><em>here</em></strong></a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Bg9o9WkmqY7mtsYUaqTHg.png" /></figure><p>We can notice on the sidebar on the left our AIRBYTE_DATABASE and all the required components for starting with our warehouse.</p><p>The next step is to load our data inside snowflake using our data ingestion tool.</p><h3><strong><em>3. Data Ingestion with Airbyte</em></strong></h3><p>As we embark on building our modern data platform, the first crucial step is setting up an efficient and reliable data ingestion process. This is where Airbyte comes into play, serving as the cornerstone of our data integration strategy.</p><h4>3.1 Overview of Airbyte</h4><p>Airbyte is an open-source data integration engine that helps consolidate data from various sources into your desired destinations. Its key features include:</p><ul><li>A wide array of pre-built connectors for different data sources and destinations</li><li>The ability to handle both batch and incremental data syncing</li><li>An intuitive UI for setting up and managing data pipelines</li><li>Extensibility through custom connectors</li></ul><h4>3.2 Step by Step with Airbyte</h4><p>Here is the different steps for setting up airbyte as an ingestion layer :</p><ol><li><strong>Installing and Setting Up Airbyte</strong>:</li></ol><p>The first step is to make airbyte up and running. We are going to use Docker for installing airbyte locally. You can follow the installation guide from the official Airbyte page <a href="https://docs.airbyte.com/using-airbyte/getting-started/oss-quickstart"><strong>here</strong></a><strong> .</strong></p><p>The first step for installing Airbyte is to install <strong>abctl</strong> (Airbyte command Line Tool) using the following command :</p><pre>curl -LsfS https://get.airbyte.com | bash -</pre><p>After that, you need to ensure that your docker Desktop is up and running before running the following command :</p><pre>abctl local install</pre><p>You can just visit the link <a href="http://localhost:8000/">http://localhost:8000</a> on your favorite browser.</p><p>Here is a screenshot of what I got after those steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37LIlHjVgm-rL5_fRq_03g.png" /><figcaption>Aibyte Login Page</figcaption></figure><p>You need to add your email and organization name (you can input any name). You will then receive an email to create your password</p><p>After being log in, thee following image shows the home page of Airbyte platform :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6yMzIqDGUrCgA7LlhGSKg.png" /><figcaption>Airbyte HomePage</figcaption></figure><p><strong>2. Configuring the Source Connector</strong></p><p>As we can see on the previous image, with Airbyte wee need to add a source connection and a Destination connection to build the ingestion pipeline. As we mention it earlier, our source system is a csv file publicly accessible on my GitHub repository.</p><p>Here are a list of source connectors we can choose from Airbyte to build our ingestion process :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qv68L75v-qnFDL5Jmz2KUA.png" /><figcaption>Airbyte data source’s connectors</figcaption></figure><p>We have to pick the File connector which can have different format(csv, json, parquet, …). The most important information here is the link of the csv file we need to ingest. The following image showcase the different information we need to fill here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPKmCYU5JFjcDah26XdqXw.png" /><figcaption>AIrbyte Connection Source</figcaption></figure><p>Just test the connection with your data source. If you got the message : “<em>All connections tests passed</em>”, you are good to go.</p><p><strong>3. Setting Up the Destination Connector</strong></p><p>After setting up our data source, we need to configure Airbyte to load our data into Snowflake. The steps are similar to the previous one. By clicking the button Destination in your sidebar menu, you’ll see a bunch of airbyte connectors for destination source. Most of them are used as warehouses.</p><p>The next image shows the different connectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPGMvOoeLGvdEHfdJj-RyA.png" /><figcaption>Airbyte Destination Connectors</figcaption></figure><p>In this case, we are using Snowflake. So just click on snowflake and fill the different information for configuration. You need to register the information of your warehouse (database name, databaser user, password …)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N24pBBhe_ycOKkIluz_JFA.png" /></figure><p>After that, just test the connection with the destination. If your information are correct , you’re ready to create your first airbyte ingestion pipeline.</p><p><strong>4. Creating and Running a Connection</strong></p><p>For establishing a connection between our source(csv file on github) and destination (snowflake) we first have to click on the option Connections. After that, we have to select one of our configured source and one of our destination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqhDXgN_SNBSCtWpuzeu7w.png" /><figcaption><strong>Airbyte Connexion between source and Destination</strong></figcaption></figure><p>After creating the connection between your source and your destination, you can initiate a synchronisation between both source. As you can see below, you have a scheduled option : every 24 hours(default option) for an automatic run or manual which is our option here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3fF5mDXal2JXPntDB6N6w.png" /><figcaption><strong>Airbyte sync between Source and Destination</strong></figcaption></figure><p>While establishing the connexion, you have to inform about the id of your data for allowing Airbyte to load it properly as you can notice it on the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-kL86AM5EdUbNORia4nWw.png" /></figure><p><strong>5. Checking the loaded data on Snowflake</strong></p><p>When the sync is successfully executed on Airbyte, you can check you snowflake warehouse. You’ll notice that a new table is created. After running the a SELECT query, the results are displayed in Snowflake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJo-F5uwt59sbPAL3DlB1w.png" /><figcaption>Running Select on snowflake ❄️</figcaption></figure><p>Note that on the created table, you can see additional data or additional columns. Airbyte adds some metadata when loading data from source to destination. Now, your data are loaded inside your warehouse and ready transformation. Remember , we’re building an ELT. That means that we have to load the data inside thee warehouse before performing the transformation logic.</p><h3><strong><em>4. Data Transformation with dbt : the medallion architecture</em></strong></h3><p>This is one of the most crucial steps in this type of project. Loading data inside our warehouse was quite an easy task. With dbt, we are going to move our data from a low level of data(Bronze) to a high quality of data(Gold) by applying a couple of data transformation. That kind of architecture is called a <strong><em>medallion architecture.</em></strong></p><h4>4.1 Medallion Architecture</h4><p>Let’s dive a little bit inside the medallion architecture. The following image shows the pattern of a medallion architecture from snowflake website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgK1o9Kg-E4IJJULkstVHQ.png" /><figcaption>Medallion architecture (<a href="https://www.databricks.com/glossary/medallion-architecture">image from Databricks wesbite</a>)</figcaption></figure><p>The primary aim of this architecture is to enhance the structure and quality of data gradually as it traverses through successive layers of the architecture, progressing from Bronze to Silver to Gold layers. In a nutshell , we got much more organised data from Bronze to Gold thanks to different level of transformations. You can learn more about this architecture by clicking <a href="https://www.databricks.com/glossary/medallion-architecture"><strong><em>here</em></strong></a><strong><em> .</em></strong></p><h4>4.2 Setting up dbt</h4><p>To begin our journey of building a medallion architecture on Snowflake using dbt, we first need to set up our dbt environment. This process involves installing dbt, configuring our Snowflake profile, and initializing our dbt project. Let’s walk through these steps:</p><p><strong>1. Installing dbt</strong></p><p>First, ensure you have Python installed on your system. I created a virtual environment for my case 😉. Then, install dbt using pip:</p><pre>pip install dbt-snowflake</pre><p>This command installs both dbt core and the Snowflake adapter. You can check more details by clicking <a href="https://docs.getdbt.com/docs/core/pip-install"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p><strong>2. Initializing the dbt Project</strong></p><p>Now, let’s create a new dbt project:</p><pre>dbt init data_pipeline</pre><p>This command does several things:</p><ol><li>Creates a new directory named data_pipeline with the basic dbt project structure.</li><li>Prompts you to set up your profile interactively.</li></ol><p>Follow the prompts in your command line to configure your Snowflake connection. You’ll be asked for details such as:</p><ul><li>Snowflake account</li><li>Username</li><li>Password</li><li>Role</li><li>Warehouse</li><li>Database</li><li>Schema</li></ul><p>This process will automatically create and populate your profiles.yml file in the ~/.dbt/ directory.</p><p><strong>3. Verifying the Profile Setup</strong></p><p>After the initialization, your profiles.yml file should look similar to this:</p><pre>data_pipeline:<br>  outputs:<br>    dev:<br>      account: ****** add your account link here****   # Remove https and .snowflakecomputing.com<br>      database: AIRBYTE_DATABASE<br>      password: BlackRock1234@#  # Ensure special characters are supported<br>      role: AIRBYTE_ROLE<br>      schema: AIRBYTE_SCHEMA<br>      threads: 10<br>      type: snowflake<br>      user: AIRBYTE_USER<br>      warehouse: AIRBYTE_WAREHOUSE<br>      client_session_keep_alive: False  # Optional, can help keep sessions alive<br>      retry_limit: 3  # Optional, adds retries<br>  target: dev</pre><p>You can always modify this file manually if you need to make changes or add additional environments.</p><p><strong>4. Configuring the dbt Project</strong></p><p>Navigate to your project directory and open the dbt_project.yml file. The following image shows the structure of my project. Of course you can create a better structure that reflects the medallion architecture by adding a different folder inside models for each layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65KMVH_HF3HiXwembGwiaQ.png" /></figure><p>Here I just create basic transformations with dbt for creating my different layers.</p><ul><li><strong>Silver layer</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPbCBUu2aEZ54D480A592g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBCryAHuMiwyQwaQtGUXvA.png" /><figcaption>dbt code for Silver layer</figcaption></figure><p>Here is the snowflake table for silver layer :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOJVErLZvmvxQKt9KrYHpg.png" /><figcaption>Silver layer on snowflake</figcaption></figure><p>You can notice the different tables (SILVER_, GOLD_, …) on the left sidebar.</p><ul><li>Gold layer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OOuoj8X-1tVNT34-CAAiw.png" /><figcaption>dbt code for building gold layer</figcaption></figure><p>Result on snowflake:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hC_DDTNWhL1dyxREgFWdVA.png" /><figcaption>Gold Layer : aggregation for analytics</figcaption></figure><h3>5. Orchestration with Apache Airflow</h3><p>While dbt handles our data transformations and Snowflake serves as our data warehouse, we need a robust orchestration tool to automate and manage our entire data pipeline. This is where Apache Airflow comes into play. Airflow allows us to programmatically author, schedule, and monitor workflows, making it an ideal choice for orchestrating our dbt transformations in Snowflake.</p><h4>5.1 Setting Up Airflow with Cosmos</h4><p>Nowadays , the easiest way to seet up airflow is by using cosmos. It completely simplifies your transformations with dbt in Apache Airflow. If you want to lean more about it you can check the official cosmos <a href="https://astronomer.github.io/astronomer-cosmos/"><strong><em>documentation</em></strong></a><strong><em> .</em></strong></p><p>First, you need to install Astro by typing the following command (if you’re using a Mac).</p><pre>brew install astro</pre><p>After that, you just have to create a new folder and initialise a new astro project with the command :</p><pre>astro dev init</pre><p>Make the following changes inside your Dockerfile and your requirements.txt file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O850PeVpoUGRx64fJstIZw.png" /></figure><p>You’re ready to go by running the next command. You have to ensure that your docker desktop is up and running.</p><pre>astro dev start</pre><p>If no error occurs , you can access you airflow on <em>localhost:8080. </em>If you encounter errors (about port usage for example), just refers to the official documentation<em> .</em></p><h4>5.2 Creating a DAG for dbt Transformations using Cosmos</h4><p>With Cosmos, we can create Airflow DAGs directly from our dbt project structure. You have to copy your dbt project file(data_pipeline for me) inside your airflow dags folder. The following image shows exactly what I did here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQqy30w_As-S42oOldPFQg.png" /></figure><p>As you can see, I created a folder named dbt where I just copied all my dbt project. It’s important to do that for allowing airflow to access your dbt project. The dag code is shown on the image to.</p><p>The last step is to add the connection between airflow and snowflake. Here is how to do so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-UXBubAYeNutUdfxKBRDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDDhJKUl87hinCYQw2UFAQ.png" /></figure><p>Just save your configuration and check your airflow dag graw. Here is mine :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtzxSoMAtNgBe7_SBBsOlQ.png" /><figcaption>Airflow dag graph</figcaption></figure><p>You can just notice my different layers. The staging area is my Bronze layer and help building the Silver layer. The pipeline is executed successfully (Green color 🍀).</p><p>By using Airflow with Cosmos to orchestrate our dbt transformations in Snowflake, we’ve created a fully automated, scalable data pipeline that closely aligns with our dbt project structure</p><h3><strong><em>6. Data Visualization : Qlik Sense</em></strong></h3><p>With our medallion architecture implemented in Snowflake using dbt, we now have a robust, well-organized data structure. The final step in our data analytics journey is to bring this data to life through visualization. For this purpose, we’ve chosen Qlik Sense, a powerful business intelligence tool known for its associative engine and interactive visualizations.</p><h4><strong>6.1 Connecting Qlik Sense to Snowflake</strong></h4><p>First, we established a connection between Qlik Sense and our Snowflake data warehouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_2KOBzQ7Nk0-6PXLGGG8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZxLtVrmUdXbBQ42u9ZSEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAYukj3qMy1p-YOWer5nzw.png" /></figure><p>Once connected, Qlik Sense can directly query our gold layer tables, leveraging the clean, aggregated data we prepared in our dbt models.</p><h4><strong>6.2 Building the Dashboard</strong></h4><p>Our Qlik Sense dashboard is designed to provide insights into energy consumption patterns across different dimensions. The following images show a visual representation of our data coming from snowflake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrVGkvBTgdU_66d3lbs0Eg.png" /><figcaption>Qlik Sense dashboard for energy consumption</figcaption></figure><p>You can also check the mobile version of that dashboard as shown in the following images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KQGKF-7ARAUJHDJQYE_GYQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XYFNC4ZYCVwArqN1romMmw.jpeg" /><figcaption>Mobile version of Qlik Sense Dashboard</figcaption></figure><p>Using <strong>Qlik Sense</strong>, I created a dashboard that visualizes key metrics from the <strong>GOLD</strong> layer of our data pipeline, offering a clear and concise overview of electricity consumption across different sectors and regions</p><h4>Key considerations</h4><p>By combining the power of dbt for data transformation, Snowflake for data storage and computation, Airflow for orchestration, and Qlik Sense for visualization, we’ve created a comprehensive and robust solution for analyzing energy consumption data. This approach allows for:</p><ul><li><strong>Data Integrity</strong>: Our medallion architecture ensures clean, well-structured data.</li><li><strong>Performance</strong>: Snowflake provides fast query performance for large datasets.</li><li><strong>Flexibility</strong>: dbt allows us to easily modify and extend our data models.</li><li><strong>Orchestration</strong>: Apache Airflow enables us to automate and schedule our entire data pipeline, ensuring timely and consistent data updates.</li><li><strong>Interactivity</strong>: Qlik Sense enables users to explore the data dynamically.</li><li><strong>Scalability</strong>: This architecture can easily accommodate growing data volumes and support additional data sources.</li></ul><p>We’ve created a fully automated, end-to-end data pipeline. Raw data is ingested into our bronze layer, transformed through our silver and gold layers using dbt, and finally visualized in Qlik Sense — all on a scheduled, automated basis.</p><p>As we continue to gather more data and refine our models, this comprehensive data stack — from ingestion through orchestration to visualization — will serve as a valuable tool for monitoring energy consumption trends and informing decision-making processes. The combination of these powerful tools provides us with a flexible, scalable, and maintainable solution that can evolve with our changing data needs.</p><p>Github Repo : <a href="https://github.com/BlackRock2308/mds-dbt-airbyte-snowflake">https://github.com/BlackRock2308/mds-dbt-airbyte-snowflake</a></p><h4>References</h4><ul><li><a href="https://docs.getdbt.com/docs/core/pip-install">https://docs.getdbt.com/docs/core/pip-install</a></li><li><a href="https://docs.airbyte.com/using-airbyte/getting-started/add-a-destination">https://docs.airbyte.com/using-airbyte/getting-started/add-a-destination</a></li><li><a href="https://docs.snowflake.com/en/user-guide/warehouses-overview">https://docs.snowflake.com/en/user-guide/warehouses-overview</a></li><li><a href="https://astronomer.github.io/astronomer-cosmos/index.html">https://astronomer.github.io/astronomer-cosmos/index.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=289152c6e840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Task Parallelization in Airflow : End-to-End Data Engineering Project]]></title>
            <link>https://medium.com/@mbayemc2/task-parallelization-in-airflow-end-to-end-data-engineering-project-f2ff95f0b186?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2ff95f0b186</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 20:42:02 GMT</pubDate>
            <atom:updated>2024-04-13T20:42:02.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>Task Parallelization in Airflow : End-to-End Data Engineering Project</h3><p><em>Explore the power of workflow parallelization 🔥</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Iv2vNsvbHn34-mk4RQxSQ.jpeg" /></figure><h4>Table of contents</h4><blockquote><strong>1. </strong><a href="#c32f"><strong>Introduction</strong></a><strong><br>2. </strong><a href="#1820"><strong>Project Goals and Requirements</strong></a><strong><br>3. </strong><a href="#80a9"><strong>Choosing the Right Tools</strong></a><strong><br>4. </strong><a href="#8e7b"><strong>Architecture Overview<br></strong></a><strong>5. </strong><a href="#cf9c"><strong>Deep Dive into the Workflow</strong></a><strong><br>6. </strong><a href="#00e5"><strong>Task Parallelization in Airflow</strong></a><strong><br>7. </strong><a href="#9b16"><strong>Visualisation and Data mining</strong></a><strong><br>8. </strong><a href="#dbd5"><strong>Conclusion</strong></a></blockquote><h3>Introduction</h3><p>In the ever-evolving landscape of data engineering, the ability to efficiently process and transform large volumes of data is paramount. With businesses generating data at an unprecedented rate, the need for robust and scalable data workflows has never been more critical.</p><p>This project was conceived out of the necessity to centralize disparate data sources into a coherent and accessible repository. By leveraging the strengths of Apache Airflow for orchestrating workflows, Amazon S3 for secure and scalable storage, Power BI for insightful analytics, and Weka for powerful data mining, we crafted a solution that stands as a testament to modern data engineering practices.</p><p>Whether you’re a seasoned data engineer or an enthusiast looking to understand the practicalities of data workflow optimization, this article aims to provide valuable insights and inspire your own endeavors in the field of data engineering.</p><h3>2 . <strong>Project Goals and Requirements ❄️</strong></h3><p>The primary objective of this data engineering initiative was to illuminate the trends and patterns in France’s energy consumption and production over a decade, spanning from 2011 to 2021. The data, meticulously collected as CSV files from government databases, serves as a historical ledger of the nation’s energy journey, capturing the nuances of sector-wise consumption and the diversity of production sources, including solar, green energy, and other types.</p><p>To achieve this, the project was designed with the following goals and requirements in mind:</p><p><strong>a. Data Centralization and Integrity:</strong></p><ul><li>Aggregate the disparate CSV files into a centralized data repository on Amazon S3, ensuring data integrity and consistency across the ten-year span.</li><li>Maintain a raw data directory for initial storage, followed by a transformation process to prepare the data for analysis.</li></ul><p><strong>b. Data Transformation and Enrichment:</strong></p><ul><li>Employ Apache Airflow to orchestrate the workflow of fetching raw data, performing necessary transformations, and organizing the data into a structured format suitable for analysis.</li><li>Enhance the data with additional context where needed, such as categorizing energy types and aligning sectoral information for comparative insights.</li></ul><p><strong>c. Efficient Data Processing:</strong></p><ul><li>Implement task parallelization within the Airflow pipeline to expedite the data processing, ensuring that the transformation of a decade’s worth of data is both swift and reliable.</li><li>Optimize the pipeline to handle large volumes of data without compromising on performance.</li></ul><p><strong>d. Insightful Visualization and Reporting:</strong></p><ul><li>Utilize Power BI to create dynamic and interactive visualizations that clearly depict the evolution of energy consumption and production across different sectors and energy types.</li></ul><p>By setting these goals and requirements, the project was poised to provide a clear and detailed view of France’s energy landscape, highlighting shifts towards renewable sources, the impact of policy changes, and the evolving demands of different sectors. The insights gleaned from this analysis are intended to inform future strategies and contribute to the broader discourse on sustainable energy practices.</p><h3><strong>3. Choosing the Right Tools 🔨</strong></h3><p>Selecting the appropriate technology stack is a pivotal decision in any data engineering project. It can mean the difference between a smooth, efficient workflow and a cumbersome, error-prone process. For this project, the tools were chosen with careful consideration of their functionality, compatibility, and ability to handle the specific demands of analyzing a decade’s worth of France’s energy consumption and production data.</p><p><strong>a. Apache Airflow</strong></p><ul><li>Chosen for its robust workflow orchestration capabilities, Apache Airflow allowed us to define, schedule, and monitor our data pipelines with precision. Its ability to handle task parallelization was particularly crucial, enabling us to process large datasets concurrently and significantly reduce the time to insight.</li></ul><p><strong>b. Amazon S3</strong></p><ul><li>Amazon S3 was the ideal choice for data storage due to its high durability, availability, and scalability. It provided a centralized repository for our CSV files, ensuring secure and easy access to both raw and transformed data. Its compatibility with various data processing tools further justified its selection.</li></ul><p><strong>c. Power BI</strong></p><ul><li>For visualization and reporting, Power BI stood out with its user-friendly interface and powerful data visualization capabilities. It allowed us to create compelling, interactive reports that could be easily understood by stakeholders, facilitating the communication of complex data trends in energy consumption and production.</li></ul><p><strong>d. Weka</strong></p><ul><li>Weka was incorporated for its comprehensive suite of machine learning algorithms and tools for data mining. It enabled us to analyze the dataset and uncover patterns or correlations that might not be immediately apparent, adding depth to our analysis.</li></ul><p>Each tool was not only chosen for its individual merits but also for how it integrates within the larger ecosystem of our project. The synergy between Airflow’s data pipeline management, S3’s reliable data storage, Power BI’s analytical visualizations, and Weka’s data mining capabilities created a cohesive and effective environment for tackling the project’s objectives.</p><h3><strong>4. Architecture Overview ☘️</strong></h3><p>The architecture of our data engineering project is a testament to thoughtful design, ensuring seamless communication between various components to facilitate a smooth data flow from collection to visualization. Below is an overview of the architecture, which illustrates the interconnected roles of Apache Airflow, Amazon S3, Power BI, and Weka in our data pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gV0iekIFvKW73NyQHh_vqA.jpeg" /></figure><ul><li>The process begins with the collection of CSV files containing energy consumption and production data from the French government’s databases. These files are then uploaded to Amazon S3, which serves as our centralized data lake. The raw data is stored in a dedicated ‘raw-data’ directory, preserving the original state of the datasets for reference and traceability.</li><li>Apache Airflow acts as the orchestrator, managing the workflow that transitions data from the raw state to a transformed and analysis-ready format. Airflow’s DAGs are configured to automate the extraction of data from the ‘raw-data’ directory, apply the necessary transformations, and subsequently load the processed data into the ‘transformed-data’ directory within S3.</li><li>Within the Airflow environment, task parallelization is implemented to handle multiple data transformation jobs concurrently. This not only accelerates the processing time but also optimizes resource utilization, ensuring that the system scales efficiently as the volume of data grows.</li><li>A set of transformed data (data mart) is then accessed by Power BI, which is responsible for crafting interactive and informative visualizations. These visualizations are designed to convey the evolution of energy consumption and production across different sectors and types of energy in a clear and impactful manner.</li><li>Another set of transformed data is accessed by Weka, where it undergoes a thorough analysis. Weka’s machine learning algorithms sift through the data to detect patterns, trends, and anomalies, providing a deeper understanding of the energy landscape over the past decade.</li></ul><h3><strong>5. Deep Dive into the Workflow 🧑🏿‍💻</strong></h3><p>Having established a high-level understanding of the project’s architecture, we now delve into the specifics of the workflow. This section will walk through the step-by-step process that data undergoes from initial collection to the final output, detailing the role of each component in the pipeline.</p><p><strong>a. Data Ingestion</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-g3l6MzY6FHROYMEIjpUyA.png" /></figure><p>The image below shows all the different files contains inside the raw-data directory in the S3 bucket. These files, which are periodically released, contain detailed records of energy consumption and production across various sectors and energy types. An Airflow DAG is scheduled to automatically download and store them in the ‘raw-data’ bucket on Amazon S3.</p><p><strong>b. Data Preprocessing / Transformation</strong></p><p>Once the raw data is in place, a series of preprocessing tasks are triggered. These tasks, managed by Airflow, include cleaning the data (e.g., handling missing values, correcting formats), validating its integrity, and standardizing the datasets to align with our analytical models. Following preprocessing, the data undergoes transformation. This involves restructuring the data into a format that is optimized for analysis.</p><p>The following image shows a function that load data from S3 , apply processing by dropping some columns and saving transformed data using Xcom mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBu9UVbjPAEI87EisHon7Q.png" /></figure><p>XComs (short for “cross-communications”) are a mechanism that let <a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/tasks.html">Tasks</a> talk to each other, as by default Tasks are entirely isolated and may be running on entirely different machines. Learn more about XComs <a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/xcoms.html"><strong>here</strong></a><strong> .</strong></p><h3><strong>6. Task Parallelization in Airflow ✍🏿</strong></h3><p>In our Airflow setup, task parallelization is achieved through the careful structuring of task dependencies within our Directed Acyclic Graphs (DAGs). This approach allows us to execute multiple tasks in parallel, optimizing our workflow’s efficiency. Below, we explain how this parallelization is implemented using the provided dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGTADdS2bivkhl38URinKQ.png" /></figure><p><strong>a. DAG Structure and Dependencies:</strong></p><p>Our DAG is structured to define clear dependencies between tasks. The start_pipeline task initiates the workflow, which then proceeds to the load_staging_dataset task. Once the staging dataset is loaded, the workflow branches out into several independent loading tasks, each responsible for a different dataset.</p><p><strong>b. Loading Tasks in Parallel:</strong></p><p>The load_staging_dataset task fans out to multiple loading tasks, such as load_conso_energy_region, load_conso_energy_dept, and others. These tasks are designed to run in parallel since they are independent of each other and do not share any input or output dependencies. This parallel execution allows for the simultaneous loading of various datasets, significantly speeding up this phase of the workflow.</p><p><strong>c. Data Quality Checks:</strong></p><p>After each loading task, a corresponding data quality check is performed. For example, load_conso_energy_region is followed by check_df_conso_energy_region, and similarly for other datasets. These checks ensure that the data loaded meets our quality standards before proceeding further in the pipeline.</p><p><strong>d. Dimension Table Creation:</strong></p><p>Once all loading tasks and their subsequent checks are complete, the workflow converges on the create_D_Table task. This task is responsible for creating dimension tables that are essential for our data model. Following its completion, the workflow again fans out to several tasks that create individual dimension tables such as create_dim_annee, create_dim_operateur, and so on. These tasks can also run in parallel, as each dimension table is created independently.</p><p><strong>e. Fact Table Creation:</strong></p><p>The dimension table checks, such as check_dim_annee and check_operateur_dim, lead to the create_Fact_Tables task. This task acts as a gateway to the creation of fact tables, which are the core of our data model, holding the metrics and measurements of our datasets. The creation of these fact tables is parallelized, with tasks like create_fact_table_energy_deptand create_fact_table_conso_energy_region running concurrently.</p><p><strong>f. Final Steps and Load to S3:</strong></p><p>The last set of checks on the fact tables ensures that our data model is accurate and reliable. Upon successful validation, the workflow concludes with the send_csv_s3 task, which uploads the final CSV files to S3. The finish_pipeline task marks the end of the workflow.</p><p>By structuring our DAG to take advantage of parallel task execution, we minimize the overall runtime and improve the efficiency of our data processing. This method of parallelization is a powerful feature of Airflow, allowing us to scale our data processing capabilities to meet the demands of large and complex datasets.</p><p>Here is the workflow shows in airflow&#39;s UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIEd1K3FmctuCc9S1mm2Cw.png" /></figure><p>Delving into particular sections of our pipeline reveals the detailed structure of our workflow.</p><ul><li>The diagram provided demonstrates how we load multiple CSV files from our S3 bucket in parallel, rather than one after the other as in our first version. It also shows that we create dimensional tables at the same time, using Airflow’s XComs to exchange data between tasks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnxGZekXoF8Uv1ZlZPILOw.png" /></figure><ul><li>The upcoming image displays the construction of fact tables, which are formed by merging select dimension tables with various specific tables. We employ a check function to confirm that the correct file has been outputted by the preceding task. Additionally, the send_csv_s3 step is used to upload the transformed data to our S3 bucket for future use.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GpikoE2F_FyGXm-84eA7g.png" /></figure><p>Following the completion of this pipeline, the final outputs are available for review in our S3 bucket, as depicted in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wa_fPMF8G2PKqnUaOv8dug.png" /></figure><h3><strong>7. Visualisation and Data mining 🌈</strong></h3><p>In this article, while our primary focus has been on the intricacies of task parallelization within Airflow, we have also touched upon the tools we use for data visualization and mining. This Section provides a brief overview of our utilization of Power BI and Weka for these purposes.</p><h4>a . Data analytics with Power BI</h4><p>For data visualization, we employ Power BI, which allows us to create interactive reports and dashboards that bring our data to life. The following images offer a snapshot of the kind of visual analytics we can achieve with Power BI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eL8EPdDzcWzM0haMIaaQ1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yVoF0YWr5uinf2cFBuy-w.png" /></figure><h4>b . Data mining using WEKA</h4><p>In the realm of data mining, Weka serves as our tool of choice. It enables us to apply complex algorithms and perform in-depth data analysis. Another image showcases Weka in action, giving a visual cue to the type of mining operations we conduct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJBD3TIAMWZHGAKBqNGMdw.png" /></figure><p>Although these images are present to illustrate our use of Power BI and Weka, we do not delve into detailed discussions of these aspects within the current article. Our intention is to provide a holistic view of our project’s scope while keeping the spotlight on Airflow’s task parallelization.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, this article has provided an overview of the task parallelization process within Airflow, highlighting the key strategies and insights gained from our experience. For those interested in delving deeper into the technical details and exploring the actual code, we invite you to visit our GitHub repository. The full code behind the Airflow parallelization discussed in this article is available for review and collaboration. You can access the repository at the following link: <a href="https://github.com/BlackRock2308/apache_airflow_pipeline_postgres_to_s3/tree/release">GitHub Repo Link</a>. We welcome any feedback or contributions to further enhance the project. 🤗</p><h4>References</h4><ul><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/xcoms.html">Apache airflow documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2ff95f0b186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S&P500 vs Stock picking : Building  a stock market portfolio using Data Mining ⛏️]]></title>
            <link>https://medium.com/@mbayemc2/s-p500-vs-stock-picking-building-a-stock-market-portfolio-using-data-mining-%EF%B8%8F-b367637a588c?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b367637a588c</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[stock-picking]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 19:01:59 GMT</pubDate>
            <atom:updated>2024-04-09T19:01:59.126Z</atom:updated>
            <content:encoded><![CDATA[<h3>S&amp;P500 vs Stock picking : Building a stock market portfolio using Data Mining ⛏️</h3><p>Uncover the Power of Data Mining in Crafting a Market-Beating Portfolio.</p><p>“ …However, we report majority underperformance in 11 out of 17 fixed income categories, topping out at <strong>95% </strong>for actively managed <strong>Government Intermediate </strong>funds. … ” <strong>SPIVA® U.S. Scorecard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hr-GM1cS0-xPWxAu5NLqcQ.jpeg" /><figcaption>S&amp;P500 vs Stock picking</figcaption></figure><blockquote><strong>Introduction<br>1. Understanding the S&amp;P 500<br>2. The Art of Stock Picking<br>3. Data Mining in Stock Market Analysis<br>4. Building a Portfolio Using Data Mining<br>5. Comparing Strategies<br>6. The Future of Investing with Data Mining<br>Conclusion</strong></blockquote><h3><strong>Introduction</strong></h3><p>In the ever-evolving landscape of investment strategies, two schools of thought have long vied for supremacy: the passive approach of tracking major indices like the S&amp;P 500 and the active pursuit of stock picking. The S&amp;P 500, a barometer of the U.S. stock market’s health, offers a straightforward path to investing by mirroring the performance of 500 leading companies. On the other hand, stock picking is an art form that requires a blend of intuition, research, and sometimes, a bit of luck. It’s a method favored by those who seek to beat the market by selecting individual stocks they believe are poised for success.</p><p>But as we stand on the cusp of a data-driven era, a new contender has entered the arena: data mining. This technique, which involves extracting patterns and insights from large datasets, is revolutionizing the way we approach stock market analysis. With the wealth of financial data available on platforms like Yahoo Finance, investors now have the tools to sift through the noise and uncover investment opportunities that might otherwise go unnoticed.</p><p>This article aims to demystify the process of building a stock market portfolio using data mining and compare it with the traditional approach of investing in the S&amp;P 500. We will delve into the historical performance data from Yahoo Finance, explore the methodologies behind data mining, and examine whether a synergy of technology and analysis can truly give investors an edge. Whether you’re a seasoned investor or taking your first steps into the world of finance, understanding these strategies is crucial in making informed decisions that align with your financial goals.</p><h3><strong>1. Understanding the S&amp;P 500</strong></h3><p>The S&amp;P 500, or Standard &amp; Poor’s 500, is a stock market index that serves as a barometer for the overall health of the United States economy. Comprising 500 of the largest publicly traded companies in the U.S., it represents approximately 80% of the total market capitalization, making it a key indicator of the market’s overall performance.</p><p><strong>Composition of the S&amp;P 500</strong></p><p>The S&amp;P 500 is a market-capitalization-weighted index, meaning that companies with larger market values have a greater impact on the index’s movements. This weighting method reflects the actual economic footprint of the companies and ensures that the index movements are representative of shifts in the broader economy.</p><p><strong>Advantages of Index Investing</strong></p><p>Investing in the S&amp;P 500 offers several advantages. Firstly, it provides instant diversification, as purchasing an S&amp;P 500 index fund or exchange-traded fund (ETF) is similar to holding a small piece of 500 different companies. This diversification helps to mitigate company-specific risk.</p><p><em>Moreover, index investing is often associated with lower management fees compared to active management</em>. Funds that track the S&amp;P 500 simply aim to replicate the performance of the index, which requires less intervention and analysis by fund managers, thus resulting in lower costs for the investor.</p><p><strong>Historical Performance</strong></p><p>Historically, the S&amp;P 500 has provided solid returns over the long term. According to data from Yahoo Finance, the index has experienced an average annual return of around 10% before inflation over the last 90 years. While past performance is not indicative of future results, the S&amp;P 500’s track record has made it a popular choice for investors seeking to build wealth over time.</p><p><strong>S&amp;P 500 as a Benchmark</strong></p><p>The S&amp;P 500 is also widely used as a benchmark against which the performance of stocks, mutual funds, and investment strategies are measured. Professional money managers often compare their returns to the S&amp;P 500 to demonstrate their value in terms of beating the market. For individual investors, it serves as a reference point to gauge the success of their investment choices.</p><h3><strong>2. The Art of Stock Picking</strong></h3><p>Stock picking is the practice of selecting individual stocks to invest in, with the aim of outperforming the market or a benchmark index like the S&amp;P 500. It’s a strategy that requires a blend of analytical skills, market knowledge, and often, a bit of intuition.</p><p><strong>Fundamental Analysis</strong></p><p>At the core of stock picking is fundamental analysis, which involves delving into a company’s financial statements to evaluate its viability and growth potential. Investors scrutinize earnings reports, balance sheets, and cash flow statements to assess factors such as profitability, debt levels, and operational efficiency. Ratios like price-to-earnings (P/E), debt-to-equity, and return on equity (ROE) are key metrics that can help determine whether a stock is undervalued or overvalued.</p><p><strong>Technical Analysis</strong></p><p>Some investors also employ technical analysis, which is the study of statistical trends gathered from trading activity, such as price movement and volume. Unlike fundamental analysts, technical traders are more concerned with patterns and signals on charts that suggest future activity, rather than a company’s financials.</p><p><strong>Qualitative Analysis</strong></p><p>Qualitative factors also play a significant role in stock selection. This includes evaluating the company’s business model, competitive advantage, management quality, and market share. Factors such as industry growth, brand loyalty, and regulatory environment can also influence a stock’s potential.</p><p><strong>Risk and Reward</strong></p><p>The allure of stock picking lies in the potential for significant returns if one can identify undervalued stocks or predict industry trends. However, it comes with higher risks, as individual stocks can be subject to volatile swings due to market sentiment, earnings reports, and other factors.</p><p><strong>Diversification and Portfolio Management</strong></p><p>While stock picking can lead to high rewards, it’s also important to manage risk through diversification. A well-rounded portfolio typically includes a mix of stocks across different sectors and industries, reducing the impact of any single stock’s poor performance.</p><p><strong>Behavioral Aspects</strong></p><p>Investor psychology is another critical aspect of stock picking. Emotional biases and market sentiment can heavily influence investment decisions. Successful stock pickers often have the discipline to stick to their strategies and avoid the pitfalls of emotional trading.</p><p>In essence, the art of stock picking is about finding the hidden gems in the market that can provide substantial returns. It requires diligence, patience, and a deep understanding of market dynamics. For those with the time and inclination to research and analyze individual stocks, stock picking can be a rewarding strategy that offers the potential for above-average returns.</p><h3><strong>3. Data Mining in Stock Market Analysis</strong></h3><p>Data mining in stock market analysis is the process of using algorithms and statistical methods to uncover patterns and insights from large datasets. This approach has gained popularity with the advent of big data and advanced computing power, allowing investors to make more informed decisions.</p><p><strong>Understanding Data Mining</strong></p><p>Data mining involves the extraction of hidden predictive information from vast amounts of data. In the context of the stock market, it can help identify stock trends, forecast market movements, and develop trading strategies. Techniques such as machine learning, artificial intelligence, and neural networks are commonly used to analyze historical data and predict future stock performance.</p><p><strong>Machine Learning and Predictive Analytics</strong></p><p>Machine learning algorithms can learn from and make predictions on data by building models from sample inputs. In stock market analysis, these models can be trained on historical price data, financial ratios, and other relevant metrics to forecast future stock prices or market trends.</p><p><strong>Quantitative Analysis</strong></p><p>Quantitative analysis is a data-driven approach that relies on mathematical and statistical models. It’s used to evaluate investments and identify trading opportunities by processing large datasets to find patterns that are not easily visible to the human eye.</p><p><strong>Big Data in Finance</strong></p><p>The financial sector generates a massive amount of data daily, including stock prices, trading volumes, and economic indicators. Big data technologies enable the processing and analysis of this data in real time, providing a significant advantage in market analysis and decision-making.</p><p><strong>Challenges and Considerations</strong></p><p>While data mining can provide valuable insights, it also comes with challenges. Overfitting, where a model is too closely tailored to past data, may not perform well in real-world trading. Additionally, the stock market is influenced by unpredictable factors such as political events and investor sentiment, which can be difficult to quantify and incorporate into models.</p><h3><strong>4. Building a Portfolio Using Data Mining</strong></h3><p>Building a portfolio using data mining involves leveraging advanced analytics to make informed investment decisions. By extracting patterns and insights from historical and real-time data, investors can construct a portfolio that aligns with their risk tolerance and investment goals.</p><p>In this section, I am going to show step by step the entire process of creating a portfolio using S&amp;P500 data from yahoo finance by displaying the code used. Here, we are working with jupyter notebook to write our python code. For some part, I am going to insert the code but for others I have to insert an image to illustrate the work.</p><p><strong><em>a . Install and import all the dependancies</em></strong></p><pre>!pip install pandas-ta</pre><p>pandas-ta is a Technical Analysis library useful to do feature engineering from financial time series datasets (Open, Close, High, Low, Volume). It is built on Pandas and Numpy. Here is the documentation for more details : <a href="https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html">Technical analysis in Python</a></p><pre>from statsmodels.regression.rolling import RollingOLS<br>import pandas_datareader.data as web<br>import matplotlib.pyplot as plt<br>import statsmodels.api as sm<br>import pandas as pd<br>import numpy as np<br>import datetime as dt<br>import yfinance as yf<br>import pandas_ta<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br><br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><p>The different dependancies are just basics for data analysis in python. We are using pandas, numpy and ploting tools.</p><p><strong><em>b . Download/Load SP500 stocks prices data</em></strong></p><p>The code begins by fetching the list of S&amp;P 500 companies from Wikipedia, which is a common reference for investors looking to analyze large-cap U.S. equities. The pd.read_html function is used to scrape the table containing the S&amp;P 500 companies directly into a pandas DataFrame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shejGkNhxo39RnBzbhmQ7w.png" /></figure><p>We can see a couple of rows in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XS-V46gRGTfM7kdKpKDi3w.png" /></figure><p>We observe that the dataset comprises 994,448 rows and 6 columns, encompassing market data from the years 2025 to 2023. This ensures that our analysis incorporates the most up-to-date information available.</p><p>We can check display the price variation from 2015 to 2023 of Apple stock as example.</p><pre># Sélectionner uniquement les données pour AAPL<br>aapl_data = df.loc[df.index.get_level_values(&#39;ticker&#39;) == &#39;AAPL&#39;]<br><br># Tendances temporelles pour AAPL<br>plt.figure(figsize=(12, 6))<br>aapl_data[&#39;adj close&#39;].plot(label=&#39;AAPL&#39;, color=&#39;blue&#39;)<br>plt.title(&#39;Tendances Temporelles pour AAPL&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Prix des Actions (Adj Close)&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMR56vbGD3Pygk1IhFV9Tg.png" /></figure><p>It’s evident that Apple’s stock has been on an upward trajectory since 2015. An initial investment made at the beginning of this period could have yielded substantial profits. Considering a stock picking strategy and examining the returns, if one had purchased Apple stock in 2015 at a price of $25 and it has now reached nearly $200 in 2023, the investment would have seen a significant appreciation in value.</p><p><strong><em>c . Calculate features and technical indicators for each stock.</em></strong></p><p>Following the data acquisition phase, the next step in building a data-driven portfolio is to calculate features and technical indicators for each stock. These indicators are crucial for analyzing market trends and making informed investment decisions. Here are some of the key technical indicators that you might calculate:</p><ul><li><strong>Garman-Klass Volatility</strong>: This measure provides an estimate of a stock’s volatility based on high, low, opening, and closing prices. It’s particularly useful for capturing the price movement within a trading day.</li></ul><pre>df[&#39;garman_klass_vol&#39;] = ((np.log(df[&#39;high&#39;])-np.log(df[&#39;low&#39;]))**2)/2 - <br>(2*np.log(2)-1)*((np.log(df[&#39;adj close&#39;])-np.log(df[&#39;open&#39;]))**2)</pre><p>This line calculates the Garman-Klass volatility for each stock, which is a measure of volatility that takes into account the high, low, opening, and closing prices.</p><ul><li><strong>RSI (Relative Strength Index)</strong>: The RSI is a momentum oscillator that measures the speed and change of price movements. It can help identify overbought or oversold conditions in a stock.</li></ul><pre>df[&#39;rsi&#39;] = df.groupby(level=1)[&#39;adj close&#39;].transform(lambda x: <br>pandas_ta.rsi(close=x, length=20))</pre><p>The RSI is calculated using the pandas_ta library, which is applied to the adjusted closing price of each stock over a window of 20 periods.</p><ul><li><strong>Bollinger Bands</strong>: These are volatility bands placed above and below a moving average. The bands widen or contract based on the volatility of prices, helping to identify potential overbought or oversold levels.</li></ul><pre>df[&#39;bb_low&#39;], df[&#39;bb_mid&#39;], df[&#39;bb_high&#39;] = zip(*df.groupby(level=1)[&#39;adj close&#39;]<br>.transform(lambda x: pandas_ta.bbands(close=np.log1p(x), length=20).iloc[:, [0, 1, 2]]))</pre><p>Bollinger Bands are calculated for the lower, middle, and upper bands using the pandas_ta library. The np.log1p function is used to apply a log transformation to the adjusted close prices before calculating the bands.</p><ul><li><strong>ATR (Average True Range)</strong>: The ATR is an indicator that measures market volatility by decomposing the entire range of an asset price for that period.</li></ul><pre>def compute_atr(stock_data):<br>    atr = pandas_ta.atr(high=stock_data[&#39;high&#39;],<br>                        low=stock_data[&#39;low&#39;],<br>                        close=stock_data[&#39;close&#39;],<br>                        length=14)<br>    return atr.sub(atr.mean()).div(atr.std())<br><br>df[&#39;atr&#39;] = df.groupby(level=1, group_keys=False).apply(compute_atr)</pre><p>The ATR is calculated using a custom function that applies the pandas_ta.atr function to each group of stock data. The result is standardized by subtracting the mean and dividing by the standard deviation.</p><ul><li><strong>MACD (Moving Average Convergence Divergence)</strong>: This trend-following momentum indicator shows the relationship between two moving averages of a stock’s price. It can signal changes in the strength, direction, momentum, and duration of a trend in a stock’s price.</li></ul><pre>def compute_macd(close):<br>    macd = pandas_ta.macd(close=close, length=20).iloc[:,0]<br>    return macd.sub(macd.mean()).div(macd.std())<br><br>df[&#39;macd&#39;] = df.groupby(level=1, group_keys=False)[&#39;adj close&#39;].apply(compute_macd)</pre><p>The MACD is calculated using a custom function that applies the pandas_ta.macd function to the adjusted close price of each stock. The result is standardized in a similar manner to the ATR.</p><ul><li><strong>Dollar Volume</strong>: This is a measure of the total amount of money traded in a particular stock over a given period. It’s calculated by multiplying the volume of shares traded by the price of the shares.</li></ul><pre>df[&#39;dollar_volume&#39;] = (df[&#39;adj close&#39;]*df[&#39;volume&#39;])/1e6</pre><p>The dollar volume is calculated by multiplying the adjusted close price by the volume of shares traded, then dividing by 1 million to scale the values.</p><p>You can see the full code in the following image :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upVXMNWM7oQGA909A6idRg.png" /></figure><p>After running this code, the DataFrame df will have new columns for each of the calculated technical indicators, which can be used for further analysis and to inform investment decisions.</p><p>Here is the output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqZ3-9cDO-FthLP8yO35kA.png" /></figure><p><strong><em>d . Filtering the 150 most liquid Stocks</em></strong></p><p>This part is crucial for a bunch of reasons. In fact, focusing on the 150 most liquid stocks is useful for several reasons, particularly when implementing a stock picking strategy:</p><ul><li><strong>Ease of Entry and Exit</strong>: Liquid stocks have higher trading volumes, which means that large quantities of shares can be bought or sold without significantly affecting the stock price. This is crucial for investors who may need to enter or exit positions quickly without incurring substantial slippage costs.</li><li><strong>Price Discovery</strong>: Liquid stocks tend to have tighter bid-ask spreads, which means the buying price and selling price are closer together. This leads to better price discovery and ensures that the stock price more accurately reflects the underlying value and market sentiment.</li><li><strong>Reduced Transaction Costs</strong>: Trading in liquid stocks often results in lower transaction costs because the tight bid-ask spread means less money is lost when crossing the spread. This is particularly important for strategies that involve frequent trading.</li><li><strong>Market Representation</strong>: The most liquid stocks are often large-cap stocks that have a significant impact on the market and are usually part of major indices like the S&amp;P 500. By focusing on these stocks, your portfolio is more aligned with the broader market trends.</li><li><strong>Financial Stability</strong>: Highly liquid stocks are typically associated with well-established companies that have a stable financial background. This can reduce the risk of investing in companies with uncertain futures.</li><li><strong>Information Efficiency</strong>: Liquid stocks are closely followed by many investors and analysts, which means information is quickly incorporated into the stock price. This leads to a more efficient market and allows investors to make decisions based on the most current information available.</li></ul><p>First of all, we created a different data-frame that only contains the indicators calculated below. Those indicators help a lot for checking volatility of an asset in the market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GN6smdQr7sV4pduXqti-g.png" /></figure><p>Typically, liquidity is measured by the volume of shares traded and the dollar volume. Since we have already calculated the dollar volume, we can use this as a primary measure of liquidity.</p><p>Here’s a step-by-step approach to select the 150 most liquid stocks:</p><ul><li><strong>Calculate Average Dollar Volume</strong>: Compute the average dollar volume for each stock over the period you’re analyzing to get a sense of its typical liquidity.</li><li><strong>Rank Stocks by Liquidity</strong>: Rank the stocks based on their average dollar volume, with the highest values representing the most liquid stocks.</li><li><strong>Select Top Stocks</strong>: Select the top 150 stocks from this ranking to focus on for your portfolio.</li></ul><p>Here’s how we implemented this in code:</p><pre>data[&#39;dollar_volume&#39;] = (data.loc[:, &#39;dollar_volume&#39;].unstack(&#39;ticker&#39;).rolling(5*12, min_periods=12).mean().stack())<br><br>data[&#39;dollar_vol_rank&#39;] = (data.groupby(&#39;date&#39;)[&#39;dollar_volume&#39;].rank(ascending=False))<br><br>data = data[data[&#39;dollar_vol_rank&#39;]&lt;150].drop([&#39;dollar_volume&#39;, &#39;dollar_vol_rank&#39;], axis=1)<br><br>data</pre><p>We can see the output below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qQyl-v_bjIx9_zMqgKD4A.png" /></figure><p>Here are out 150 most liquid stocks based on the previous calculations.</p><p><strong><em>e . Calculate stocks returns for different periods</em></strong></p><p>The function calculate_returns is designed to calculate the investment returns for each stock over different time periods, specified as lags in months.</p><pre>def calculate_returns(df):<br><br>    outlier_cutoff = 0.005<br><br>    lags = [1, 2, 3, 6, 9, 12]<br><br>    for lag in lags:<br><br>        df[f&#39;return_{lag}m&#39;] = (df[&#39;adj close&#39;]<br>                              .pct_change(lag)<br>                              .pipe(lambda x: x.clip(lower=x.quantile(outlier_cutoff),<br>                                                     upper=x.quantile(1-outlier_cutoff)))<br>                              .add(1)<br>                              .pow(1/lag)<br>                              .sub(1))<br>    return df<br><br><br>data = data.groupby(level=1, group_keys=False).apply(calculate_returns).dropna()<br><br>data</pre><p>After running this code, the data DataFrame will have new columns for each lag period, named return_1m, return_2m, return_3m, return_6m, return_9m, and return_12m, representing the investment returns over 1, 2, 3, 6, 9 and 12 months, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rh5NHjw63Jaepw8_1fng0Q.png" /></figure><p><strong><em>f . Fama-French Factors et Rolling Factor Betas</em></strong></p><p>After calculating the investment returns for each stock, the next step in your analysis is to incorporate the Fama-French factors and calculate rolling factor betas for each stock. The Fama-French three-factor model is an asset pricing model that expands on the capital asset pricing model (CAPM) by adding size risk (SMB, Small Minus Big) and value risk (HML, High Minus Low) to the market risk factor.</p><p>Here’s an outline of what you would typically do in this step:</p><ul><li><strong>Obtain Fama-French Factors</strong>: You need to acquire the historical factor data for the market risk premium, SMB, and HML. This data is often available from research databases or directly from the websites of researchers like Kenneth French.</li><li><strong>Merge Factor Data with Stock Returns</strong>: Combine the Fama-French factor data with your stock returns data, ensuring that the dates align correctly.</li><li><strong>Calculate Rolling Betas</strong>: For each stock, calculate the rolling betas with respect to each Fama-French factor. Rolling betas are calculated using a rolling window (e.g., 36 months) to estimate how sensitive a stock is to each factor over time.</li><li><strong>Regression Analysis</strong>: Perform a regression analysis for each stock over the rolling window, with the stock’s excess returns as the dependent variable and the Fama-French factors as independent variables. The coefficients from these regressions are the rolling betas.</li><li><strong>Store the Results</strong>: Save the rolling beta coefficients for each stock and each factor. These betas can be used to understand the stock’s exposure to different risk factors and to build a diversified portfolio.</li></ul><p>Here is the implementation on how we calculated the rolling factor bettas</p><pre>factor_data = web.DataReader(&#39;F-F_Research_Data_5_Factors_2x3&#39;, &#39;famafrench&#39;,<br>                               start=&#39;2010&#39;)[0].drop(&#39;RF&#39;, axis=1)<br><br>factor_data.index = factor_data.index.to_timestamp()<br><br>factor_data = factor_data.resample(&#39;M&#39;).last().div(100)<br><br>factor_data.index.name = &#39;date&#39;<br><br>factor_data = factor_data.join(data[&#39;return_1m&#39;]).sort_index() <br><br>factor_data</pre><p>Here, we deleted the stock with less than 10 months of data.</p><pre>observations = factor_data.groupby(level=1).size()<br><br>valid_stocks = observations[observations &gt;= 10]<br><br>factor_data = factor_data[factor_data.index.get_level_values(&#39;ticker&#39;).isin(valid_stocks.index)]<br><br>factor_data</pre><ul><li>The rolling factor</li></ul><pre>betas = (factor_data.groupby(level=1,<br>                            group_keys=False)<br>         .apply(lambda x: RollingOLS(endog=x[&#39;return_1m&#39;],<br>                                     exog=sm.add_constant(x.drop(&#39;return_1m&#39;, axis=1)),<br>                                     window=min(24, x.shape[0]),<br>                                     min_nobs=len(x.columns)+1)<br>         .fit(params_only=True)<br>         .params<br>         .drop(&#39;const&#39;, axis=1)))<br><br>betas</pre><p>After that, we join the rolling factors data to the principal dataframe.</p><pre>factors = [&#39;Mkt-RF&#39;, &#39;SMB&#39;, &#39;HML&#39;, &#39;RMW&#39;, &#39;CMA&#39;]<br><br>data = (data.join(betas.groupby(&#39;ticker&#39;).shift()))<br><br>data.loc[:, factors] = data.groupby(&#39;ticker&#39;, group_keys=False)[factors].apply(lambda x: x.fillna(x.mean()))<br><br>data = data.drop(&#39;adj close&#39;, axis=1)<br><br>data = data.dropna()<br><br>data.info()</pre><p><strong><em>g . Applying K-means clustering to group similar stocks</em></strong></p><p>Applying K-means clustering to group similar stocks based on their characteristics is a common technique in portfolio management to create clusters of stocks with similar features, which can help in diversification and risk management. Here’s how we can apply K-means clustering to your stock data:</p><pre># Code permettant de faire le clustering sur chaque mois en fixant un nombre de cluster de 4<br># avec une initialisation random des centroides<br><br>from sklearn.cluster import KMeans<br><br># data = data.drop(&#39;cluster&#39;, axis=1)<br><br>def get_clusters(df):<br>    df[&#39;cluster&#39;] = KMeans(n_clusters=4,<br>                           random_state=0,<br>                           init=&#39;random&#39;).fit(df).labels_<br>    return df<br><br>data = data.dropna().groupby(&#39;date&#39;, group_keys=False).apply(get_clusters)<br><br>data</pre><p>The image below displays the results generated by the aforementioned function, illustrating the assigned cluster for each stock on a monthly basis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2diXhG9OP4EQj6M2oYhzQ.png" /></figure><p>We have four distinct groups of stocks, each categorized based on their unique characteristics. Our stock selection strategy will utilize these diverse groups as a foundation for constructing our investment portfolio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m3oflaKc9-4buitfH0_tg.png" /></figure><p><strong><em>g . Select stocks based on cluster for building a portfolio, for each month</em></strong></p><p>To select stocks for building your portfolio based on their cluster assignments each month, you can create a function that iterates through each cluster and selects stocks according to your predefined criteria.</p><pre>def select_stocks_by_cluster(data, selection_criteria):<br>    portfolio_selection = {}<br>    clusters = data[&#39;cluster&#39;].unique()<br>    <br>    for cluster in clusters:<br>        # Filter data for the current cluster<br>        filtered_df = data[data[&#39;cluster&#39;] == cluster].copy()<br>        filtered_df = filtered_df.reset_index(level=1)<br>        filtered_df.index = filtered_df.index + pd.DateOffset(1)<br>        filtered_df = filtered_df.reset_index().set_index([&#39;date&#39;, &#39;ticker&#39;])<br>        <br>        # Get unique dates<br>        dates = filtered_df.index.get_level_values(&#39;date&#39;).unique().tolist()<br>        <br>        # Apply selection criteria for each date<br>        for d in dates:<br>            tickers = filtered_df.xs(d, level=0).index.tolist()<br>            selected_tickers = selection_criteria(tickers)<br>            portfolio_selection[d.strftime(&#39;%Y-%m-%d&#39;)] = selected_tickers<br>    <br>    return portfolio_selection<br><br># Define your selection criteria function<br>def selection_criteria(tickers):<br>    # Implement your selection logic here<br>    # For example, select a subset of tickers based on your criteria<br>    return tickers[:5]  # Placeholder: select the first 5 tickers<br><br># Apply the function to your data<br>portfolio = select_stocks_by_cluster(data, selection_criteria)</pre><p>In this extended function, selection_criteria is a placeholder for the actual logic we used to select stocks. We can replace this with our specific criteria, such as selecting the top-performing stocks based on past returns, lowest volatility, or any other metric that suits your investment strategy. The portfolio dictionary will then contain the selected stocks for each date, organized by cluster.</p><p>The image below presents the output, where a set of 5 chosen stocks for each month is displayed, representing our stock selection process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFrrzH2nDrkl62F_8QIWkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gr1kxJXZPbGAgGyeJAZHKg.png" /></figure><p><strong><em>h. Define a portfolio optimization function</em></strong></p><p>The importance of the portfolio optimization step lies in its ability to systematically allocate capital across the selected stocks in a way that aims to maximize returns for a given level of risk, or alternatively, to minimize risk for a given level of expected return. Here are the key reasons why this step is crucial:</p><ul><li><strong>Maximizing the Sharpe Ratio</strong>: By optimizing for the Sharpe ratio, you are effectively seeking the highest possible expected return per unit of volatility (risk). A higher Sharpe ratio indicates a more efficient portfolio with better risk-adjusted returns.</li><li><strong>Risk Management</strong>: Portfolio optimization takes into account the covariance between the returns of the assets, which helps in diversifying the portfolio. Diversification can reduce the portfolio’s overall risk because the poor performance of some investments may be balanced by the better performance of others.</li><li><strong>Constraint Satisfaction</strong>: Applying constraints on the weights of individual stocks ensures that the portfolio is not overly concentrated in a few assets, which can expose you to idiosyncratic risks. Setting a minimum and maximum weight for each stock helps maintain a balanced and diversified portfolio.</li><li><strong>Systematic Approach</strong>: Using a mathematical and systematic approach to determine the optimal weights of the stocks in the portfolio removes emotional biases and subjective judgment from the investment process.</li><li><strong>Adaptability</strong>: The optimization process can be repeated periodically to adjust the portfolio weights in response to changing market conditions or changes in the investor’s risk appetite, investment horizon, or financial goals.</li></ul><p>Here is an implementation of the optimization function :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wdSrykiltEKYBJ3PjOgtw.png" /></figure><p>This process is important because it uses the latest available data to ensure that the portfolio is optimized based on the most recent market conditions. By regularly updating the portfolio weights using fresh data and the optimization function, we can maintain a portfolio that is aligned with our investment goals and risk tolerance.</p><p>The next step involves iterating over a set of rebalancing dates, optimizing the stock weights for each period to maximize the Sharpe ratio, calculating the weighted log returns for the portfolio, and compiling these into a single DataFrame that tracks the portfolio’s strategy returns over time. If the optimization fails, equal weights are used. The final DataFrame is cleaned to remove any duplicate entries, ensuring an accurate representation of the portfolio’s performance. Here is the code :</p><pre>returns_dataframe = np.log(new_df[&#39;Adj Close&#39;]).diff()<br><br>portfolio_df = pd.DataFrame()<br><br>for start_date in fixed_dates.keys():<br><br>    try:<br><br>        end_date = (pd.to_datetime(start_date)+pd.offsets.MonthEnd(0)).strftime(&#39;%Y-%m-%d&#39;)<br><br>        cols = fixed_dates[start_date]<br><br>        optimization_start_date = (pd.to_datetime(start_date)-pd.DateOffset(months=12)).strftime(&#39;%Y-%m-%d&#39;)<br><br>        optimization_end_date = (pd.to_datetime(start_date)-pd.DateOffset(days=1)).strftime(&#39;%Y-%m-%d&#39;)<br><br>        optimization_df = new_df[optimization_start_date:optimization_end_date][&#39;Adj Close&#39;][cols]<br><br>        success = False<br>        try:<br>            weights = optimize_weights(prices=optimization_df,<br>                                   lower_bound=round(1/(len(optimization_df.columns)*2),3))<br><br>            weights = pd.DataFrame(weights, index=pd.Series(0))<br><br>            success = True<br>        except:<br>            print(f&#39;Max Sharpe Optimization failed for {start_date}, Continuing with Equal-Weights&#39;)<br><br>        if success==False:<br>            weights = pd.DataFrame([1/len(optimization_df.columns) for i in range(len(optimization_df.columns))],<br>                                     index=optimization_df.columns.tolist(),<br>                                     columns=pd.Series(0)).T<br><br>        temp_df = returns_dataframe[start_date:end_date]<br><br>        temp_df = temp_df.stack().to_frame(&#39;return&#39;).reset_index(level=0)\<br>                   .merge(weights.stack().to_frame(&#39;weight&#39;).reset_index(level=0, drop=True),<br>                          left_index=True,<br>                          right_index=True)\<br>                   .reset_index().set_index([&#39;Date&#39;, &#39;index&#39;]).unstack().stack()<br><br>        temp_df.index.names = [&#39;date&#39;, &#39;ticker&#39;]<br><br>        temp_df[&#39;weighted_return&#39;] = temp_df[&#39;return&#39;]*temp_df[&#39;weight&#39;]<br><br>        temp_df = temp_df.groupby(level=0)[&#39;weighted_return&#39;].sum().to_frame(&#39;Strategy Return&#39;)<br><br>        portfolio_df = pd.concat([portfolio_df, temp_df], axis=0)<br><br>    except Exception as e:<br>        print(e)<br><br>portfolio_df = portfolio_df.drop_duplicates()<br><br>portfolio_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHouCSNpip1GpQSX3IpRFw.png" /></figure><h3><strong>5. Comparing Strategies</strong></h3><p>In this Section , we delve into a critical analysis where the performance of our custom stock picking strategy is meticulously evaluated against a well-established market benchmark, the S&amp;P 500 index. This comparison is pivotal as it provides a clear perspective on the efficacy of the stock selection and portfolio optimization techniques employed in our strategy. By juxtaposing the returns of our tailored portfolio with the SPY ETF — a proxy for the S&amp;P 500’s performance — we can discern whether our approach has succeeded in generating excess returns or if it has fallen short of the broad market’s performance. This benchmarking exercise not only highlights the relative success of our investment decisions but also informs potential adjustments to enhance future strategy outcomes. It is a testament to the importance of rigorous performance evaluation in the realm of investment strategy development.</p><p>Here is the code for juxtaposing the S&amp;P500 returns with our strategy ‘s performance.</p><pre>spy = yf.download(tickers=&#39;SPY&#39;,<br>                  start=&#39;2015-01-01&#39;,<br>                  end=dt.date.today())<br><br>spy_ret = np.log(spy[[&#39;Adj Close&#39;]]).diff().dropna().rename({&#39;Adj Close&#39;:&#39;SPY Buy&amp;Hold&#39;}, axis=1)<br><br>portfolio_df = portfolio_df.merge(spy_ret,<br>                                  left_index=True,<br>                                  right_index=True)<br><br>portfolio_df</pre><p>The output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opNRhCyckdLueSGYZn8-HQ.png" /></figure><p>To visualize the comparative performance of our custom stock picking strategy alongside the S&amp;P 500 index, we’ll employ matplotlib to create a cohesive graph that plots the returns of both strategies on the same chart. This graphical representation will allow us to easily compare the trajectories of the returns and gain immediate insights into how our strategy stacks up against the market benchmark over time. The implementation in matplotlib will enable us to produce a clear and informative visual aid for our analysis.</p><pre>import matplotlib.ticker as mtick<br><br>plt.style.use(&#39;ggplot&#39;)<br><br>portfolio_cumulative_return = np.exp(np.log1p(portfolio_df).cumsum())-1<br><br>portfolio_cumulative_return[:&#39;2023-09-29&#39;].plot(figsize=(16,6))<br><br>plt.title(&#39;Unsupervised Learning Trading Strategy Returns Over Time&#39;)<br><br>plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(1))<br><br>plt.ylabel(&#39;Return&#39;)<br><br>plt.show()</pre><p>Presented below is the output graph that illustrates the comparison between the returns of our custom stock picking strategy and the S&amp;P 500 index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jtl4zypjVe35-6hpDNSw-Q.png" /></figure><p>The output graph reveals that following the 2020 COVID-19 market crash, the S&amp;P 500’s buy-and-hold approach has consistently outperformed our custom stock picking strategy. Despite this, there have been instances where our strategy nearly matched the benchmark’s performance, indicating moments of close competition. This observation underscores the resilience and potential of our strategy, even in the face of significant market upheavals, and suggests areas for further refinement to enhance its competitiveness.</p><h3><strong>6. The Future of Investing with Data Mining</strong></h3><p>As we stand on the cusp of a new era in finance, the role of data mining in investing is becoming increasingly pivotal. The vast amounts of data generated daily hold untapped potential that, when harnessed correctly, can lead to significant competitive advantages. In this section, we explore the transformative impact that data mining and advanced analytics are expected to have on the future of investing.</p><p>The advent of sophisticated machine learning algorithms and artificial intelligence has opened up new frontiers for identifying patterns, trends, and correlations within complex datasets that were previously inaccessible or too intricate to analyze. These technologies enable investors to predict market movements with greater accuracy, optimize portfolio allocations, and manage risks in ways that were not possible before.</p><p>Moreover, the rise of alternative data sources, such as social media sentiment, satellite imagery, and transactional data, provides a richer, more granular view of market dynamics. Investors who can effectively integrate and interpret these diverse data streams are likely to gain an edge in identifying undervalued assets and anticipating shifts in consumer behavior.</p><p>However, the proliferation of data mining in investing also raises important questions about privacy, data security, and ethical use of information. As regulations struggle to keep pace with technological advancements, the industry must navigate these challenges with care to maintain trust and integrity in the markets.</p><p>Furthermore, the democratization of data and analytics tools has leveled the playing field, allowing retail investors to access resources that were once the exclusive domain of institutional players. This shift is likely to spur innovation and competition, leading to more inclusive and efficient markets.</p><h3>Conclusion</h3><p>In conclusion, our journey through the development and evaluation of a custom stock picking strategy has provided valuable insights into the complexities of portfolio management. By comparing our strategy’s performance with the S&amp;P 500 benchmark, we have highlighted the importance of benchmarking and the need for continuous improvement. The practical considerations discussed serve as a reminder of the myriad factors that can influence investment outcomes. Looking ahead, the integration of data mining and advanced analytics into investing practices holds the promise of more informed and dynamic strategies. As the financial industry continues to embrace technological innovation, investors who adapt and learn to harness the power of data will be well-positioned to thrive in the markets of tomorrow.</p><p><strong>References</strong> :</p><ul><li><a href="https://www.spglobal.com/spdji/en/documents/spiva/spiva-us-year-end-2022.pdf"><strong>SPIVA® U.S. Scorecard</strong></a></li><li><a href="https://app.corcel.io/chat/">corcel.io</a></li><li><a href="https://youtu.be/9Y3yaoi9rUQ?si=Br1u669GAHf_WanQ">Algorithmic Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b367637a588c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Cloud-Native Architecture Service Mesh, a Game-Changing Approach]]></title>
            <link>https://medium.com/@mbayemc2/leveraging-cloud-native-architecture-service-mesh-a-game-changing-approach-c492e71083fd?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c492e71083fd</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[sidecar-pattern]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[cloud-native]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 18:05:37 GMT</pubDate>
            <atom:updated>2024-01-12T09:34:12.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leveraging Cloud-Native Architecture: Service Mesh, a Game-Changing Approach</h3><blockquote><em>A comprehensive guide that walks through cloud native architecture with a service mesh layer.</em></blockquote><p>· <a href="#db13">Introduction</a><br>· <a href="#25fa">What is Service mesh </a>?<br>· <a href="#9b23">Advantages of Service mesh</a><br>∘ <a href="#8f8a">Demystifying service mesh : The sidecar pattern</a><br>∘ <a href="#741c">An implementation of service mesh : Istio service mesh</a><br>∘ <a href="#45a4">Cloud-Native architecture with Istio</a><br>∘ <a href="#271d">Implementations</a> <br>∘ <a href="#51db">Results</a> <br>· <a href="#e2e3">References</a></p><h3>Introduction</h3><p>In the ever-evolving landscape of contemporary application development, the integration of microservices architectures signifies a paradigm shift, bringing forth a heightened era of adaptability and scalability. As software ecosystems transition towards modular and distributed frameworks, the advantages of microservices become evident. However, this architectural shift introduces a host of challenges, particularly concerning the intricate management, seamless connectivity, and robust security required in complex infrastructures.</p><p>Amidst these challenges, the emergence of service meshes has become a cornerstone in reshaping the landscape of microservices. Positioned as a sophisticated network architecture model, a service mesh acts as a strategic mediator in orchestrating the interactions among microservices. This layer of abstraction provides meticulous control over critical aspects such as communication patterns, service discovery, and resilience strategies. As we embark on this exploration, we navigate the role of service meshes in empowering developers, enhancing operational visibility, and fortifying security mechanisms.</p><h3>What is Service mesh ?</h3><p>Modern applications are typically designed as distributed collections of microservices, with each grouping of microservices executing a distinct business function. A service mesh is a dedicated infrastructure layer that controls service-to-service communication across a network. It allows you to seamlessly add features such as observability, traffic management, and security without integrating them into your own code. The term “service mesh” describes both the type of software used to implement this model and the realm of security or networking created when using this software.</p><p>As the deployment of distributed services, as seen in a Kubernetes-based system, scales and becomes more complex, it can become challenging to comprehend and manage. Its requirements may include service discovery, load balancing, failover recovery, metrics, and monitoring. A service mesh also addresses more intricate operational demands such as A/B testing, canary deployments, rate limiting, access control, end-to-end encryption, and authentication.</p><p>The communication between microservices is what makes a distributed application possible. Routing this communication, both within and between application clusters, becomes increasingly complex as the number of services grows. Istio contributes to reducing this complexity while easing the burden on development teams.</p><h3>Advantages of Service mesh</h3><h4>Before Service mesh : Netflix OSS</h4><p>In the implementation of a cloud-native architecture, the integration of essential features becomes imperative to ensure the success and performance of the system. Among these crucial functionalities, we find:</p><p><strong>Service Discovery</strong>: This capability enables microservices to dynamically locate other services they need to communicate with, facilitating smooth interaction among the various components of the system.</p><p><strong>Distributed Tracing</strong>: This feature allows tracking the path of requests across multiple microservices, providing better visibility into performance and interactions.</p><p><strong>Resilience</strong>: Resilience is fundamental to ensuring that the system remains stable and operational, even in the presence of failures. Error recovery mechanisms and fault management are therefore essential.</p><p><strong>Distributed Logging</strong>: Distributed logging ensures centralized collection of logs generated by microservices, facilitating troubleshooting and analysis of potential issues.</p><p><strong>Monitoring</strong>: Real-time monitoring of the health and performance of microservices is essential to ensure continuous availability and optimal responsiveness.</p><p>One popular solution for integrating these features is <strong>Netflix OSS (Open Source Services).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Gwytff1Miff2sX_-ZL6jTA.jpeg" /><figcaption><strong>Figure : Embedded dependencies in a microservices architecture with Netflix OSS</strong></figcaption></figure><p>However, a notable limitation of this solution is that it is <strong>exclusively oriented towards Java</strong>.</p><h4>The rise of Service mesh</h4><p>One of the major challenges in microservices integration lies in the <strong>communication</strong> between them. When all microservices rely on a single technological stack, such as Spring Boot, managing this communication is relatively smooth. However, as soon as a microservice developed in another language or framework is added, complexity increases. <strong><em>Service meshes offer an elegant solution to this problem by providing a uniform mechanism for inter-microservices communication, independent of the underlying technologies.</em></strong></p><p>Indeed, service meshes play a crucial role in shifting <strong>cross-cutting concerns</strong>, such as security, traffic management, and observability, to an <strong>infrastructure layer in the form of a proxy</strong>. This allows developers to focus on the essential business logic of their microservices, while service meshes seamlessly handle critical aspects such as service-to-service communication, routing rules, retry attempts, circuit breakers, performance monitoring, and traceability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*C9lfjJVhuV1azeIybaF-OQ.jpeg" /><figcaption><strong>Figure 2 : embedding components with service mesh approach</strong></figcaption></figure><p>— <strong>Polyglot</strong>: Service meshes support multiple programming languages, allowing for flexibility in choosing languages for microservices development.</p><p>— <strong>Easier Diagnosis of Communication Errors</strong>: With dedicated infrastructure, diagnosing communication errors becomes more straightforward.</p><p>— <strong>Faster Development and Deployment</strong>: Service meshes contribute to accelerated development and deployment cycles.</p><p>— <strong>Secure Update Deployment (Blue/Green, Canary, etc.)</strong>: The service mesh facilitates secure updates with deployment strategies like Blue/Green and Canary.</p><p>— <strong>Discovery</strong>: The service mesh provides an automatic service discovery mechanism. When a microservice needs to communicate with another, it relies on the service mesh to dynamically locate the target microservice, eliminating the need for manual configuration of IP addresses or endpoints.</p><p>— <strong>Traffic Management</strong>: The service mesh enables the definition of precise routing rules to direct traffic between microservices. This includes load balancing strategies, failover rules, retry attempts, and error management mechanisms.</p><p>— <strong>Security</strong>: A service mesh ensures secure communication between microservices using Transport Layer Security (TLS) encryption. It also provides identity-based authentication and allows the implementation of access control policies to authorize or deny interactions between services.</p><p>— <strong>Observability</strong>: The service mesh offers comprehensive visibility into communications between microservices. It automatically generates metrics, logs, and traces to monitor the performance, throughput, and latency of requests. This facilitates troubleshooting, performance analysis, and continuous optimization.</p><p>— <strong>Policies and Controls</strong>: The service mesh allows the definition of centralized control policies for quota management, rate limits, security, and other operational aspects. These policies can be consistently and uniformly implemented across the entire infrastructure.</p><h3>Demystifying service mesh : The sidecar pattern</h3><p>The architecture of a service mesh relies on one or more proxies known as “sidecars.” This term is inspired by their placement in relation to the application. Just as a sidecar is attached to a motorcycle to add additional functionalities, the sidecar proxy is attached to a parent component to extend its capabilities.</p><p>In the context of the service mesh, sidecar proxies are deployed within the Data Plane and Control Plane of our service mesh.</p><p>— <strong>Data Plane</strong>: This includes proxies deployed as sidecars. These sidecars control all inter-service communications between microservices.</p><p>— <strong>Control Plane</strong>: The control plane consists of components that contribute to service discovery, management of proxies and certificates, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AS8cLL-htUXPVHPJvrbRLw.png" /><figcaption><strong>Figure 3 — Simplified architecture of a service mesh</strong></figcaption></figure><h4>Traffic Flow</h4><p>— External incoming traffic flows through the Ingress Controller to a specific Pod, for example, Service A.</p><p>— The sidecar container of the Service A Pod intercepts the request. For a valid request, it forwards the request to the application container, and so on.</p><p>— Invalid requests are rejected by the sidecar, without being processed by the running application.</p><p>— Inter-service traffic between Service A and Service B is solely served using the sidecar proxy layer following the service discovery model.</p><p>— Similarly, external outgoing traffic exits through the Egress Controller from any given Service Pod.</p><h3>An implementation of service mesh : Istio service mesh</h3><p>When operating in a Kubernetes environment and aiming to establish a robust service mesh, the most compelling and widely recommended choice is Istio. This open-source service mesh represents a cutting-edge solution for orchestrating, securing, and monitoring interactions between microservices within your Kubernetes cluster. Istio particularly excels in the Kubernetes context for several reasons:</p><ul><li>Native Integration with Kubernetes Istio is specifically designed to seamlessly operate with Kubernetes, making its deployment and management within your clusters more straightforward.</li><li>Advanced Traffic Management Istio allows the definition of granular traffic rules, the implementation of load balancing strategies, failovers, and A/B experiments, all while ensuring sophisticated error management.</li><li>Enhanced Security Istio offers advanced security features such as certificate-based authentication, security policy management, and traffic monitoring to detect potential threats.</li><li>Data Persistence Management Istio facilitates the management of connections to databases and external services, ensuring security and resilience policies.</li><li>Observability Istio provides comprehensive visibility into interactions between microservices through the collection of metrics, logs, and traces, facilitating troubleshooting and performance optimization.</li><li>Extensibility and Ecosystem Istio is extensible and offers the ability to customize its features. Moreover, it is supported by a broad community and benefits from a constantly expanding ecosystem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6xU9cRrBWDM2ZOoY80Btw.png" /><figcaption><strong>Figure 4 — Istio Service mesh architecture</strong></figcaption></figure><p>— <strong><em>Pilot</em></strong>: Provides service discovery for Envoy sidecars, traffic management capabilities for intelligent routing (e.g., A/B testing, progressive canary deployments, etc.), and resilience (timeouts, retries, circuit breakers, etc.).</p><p>— <strong><em>Mixer</em></strong>: An independent component of the platform, Mixer applies access controls and usage policies across the service mesh and collects telemetry data from the Envoy proxy and other services.</p><p>— <strong><em>Citadel</em></strong>: Enables robust service-to-service and end-user authentication with integrated identity and credential management.</p><p>— <strong><em>Galley</em></strong>: The component for Istio’s configuration validation, ingestion, processing, and distribution.</p><p>However, there is a variety of options for service meshes, offering diverse solutions to meet the specific needs of your cloud-native architecture. Among notable alternatives, we can mention:</p><blockquote><strong>Anthos</strong>: This Google-managed service mesh solution allows simplified deployment, management, and monitoring of your microservices, leveraging Google Cloud expertise.</blockquote><blockquote><strong>Linkerd</strong>: Recognized for its lightweight nature and user-friendly configuration, Linkerd, a CNCF project, is often chosen for deployments requiring less complex setup while providing essential service mesh features.</blockquote><blockquote><strong>Consul Connect</strong>: Offered by HashiCorp, Consul Connect provides a service mesh solution that seamlessly integrates with Consul for service management and service discovery. It is appreciated for its extensibility and flexibility.</blockquote><p>Each of these options has its specific advantages and can be tailored based on your needs, technological environment, and preferences.</p><h3>Cloud-Native architecture with Istio</h3><p>The introduction of a <strong>cloud-native</strong> architecture holds crucial significance in ensuring the resilience, scalability, and flexibility of your applications. A service mesh like Istio has significantly simplified our architecture while paving the way for more sophisticated orchestration and seamless management of our microservices.</p><p>Our starting point was an architecture based on fundamental microservices developed with Spring Boot. While this approach facilitated better management of individual services, it also introduced complexities in the communication between these microservices. This is where the integration of Istio brought about a profound and positive change. The following figure illustrates our architecture with the introduction of the Istio service mesh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iaedpZNz7zg7lwDab0cs9g.jpeg" /><figcaption><strong>Figure 5 — Cloud-Native architecture with istio service mesh</strong></figcaption></figure><h3>Implementation</h3><p>The implementation of the Istio service mesh requires some adjustments at the level of our microservices. <strong><em>As discussed in the service mesh introduction section, the dependencies and libraries embedded by each service are no longer required</em></strong>. Therefore, they will be removed, leading to a significant reduction in the size of our Docker images.</p><p>Our new architecture clearly highlights the need to inject an <strong>Envoy proxy</strong> into each pod. However, this injection will not be done manually, as the Istio service mesh will handle this task for us. Our only responsibility will be to configure Istio within our cluster.</p><p>In the interest of resource optimization, we will move away from using Google Kubernetes Engine. Instead, we will deploy a local K8s cluster with Minikube, upgrade it, and proceed with the integration of our service mesh.</p><h4>Installing Requirements</h4><p>To begin, we need to set up our cluster. The link below will guide you through the installation and configuration of Istio using Minikube: <a href="https://kubernetes.io/fr/docs/tasks/tools/install-minikube/">install minikube</a>.</p><p>We have installed Minikube with Docker as the driver using the following command:</p><pre>minikube start −−cpu 4 −−memory 7000 −−driver=docker</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXUeOQ3Jh6oOOOqRn4pulw.png" /><figcaption><strong>Figure 6 — Minikube node</strong></figcaption></figure><p>Once our cluster is operational, we can proceed with the installation of the Istio service mesh. There are several methods to do this, depending on our specific environment. However, a simple approach is to use the curl command to get the installation file directly into our cluster.</p><pre>curl -L https://istio.io/downloadIstio | sh -</pre><p>Now, let’s activate the Istio CLI (istioctl), which will allow us to install all components of the Istio architecture, including the control plane components. To do this, simply enter the following command:</p><pre>istioctl install</pre><p>The CLI will proceed with the installation of all default components. However, it’s always possible to add an installation profile (“prod,” “dev,” “profile” or “demo”). In our case, we are working with the default profile.</p><h4>Injecting Istio service mesh</h4><p>Installing the service mesh in our cluster is not enough to inject Envoy proxies into our different pods. An additional step is required for this purpose. However, before addressing this step, let’s deploy our application into the Minikube cluster to observe its initial state.</p><p>By executing the command:</p><pre>kubectl apply -f .</pre><p>with our manifests, we obtain the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIMcPdDV6YFqD44pgfB4vA.png" /><figcaption><strong>Figure — Node description before injecting Istio service mesh</strong></figcaption></figure><p>The key element to note here is the number of containers present in each pod. Currently, there is one container per pod (READY 1/1). This practice is recommended unless multiple containers per pod are essential in certain scenarios. In our case, we find ourselves in one of these usage scenarios.</p><p>Now we are ready to inject the Istio service mesh. To do this, simply add a label to the namespace where we have deployed our microservices. This action will allow Istio to inject its proxies into each pod running in the same namespace.</p><p>In our case, we are using the default namespace. The command to add the label istio-injection=enabled is as follows:</p><pre>kubectl label namespace default istio −injection=enabled</pre><p>Après injection, on peut regarder l’état de nos pods sur l’image suivante :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqz-pRrtDD-mIGr3m5Dk9w.png" /><figcaption><strong>Figure — Node description after injecting Istio</strong></figcaption></figure><p>This time, you’ll notice that in the READY indicator, we now have 2/2. This means that each pod now contains two containers. One of these containers belongs to our application, while the second container is the Envoy proxy injected by Istio into our pod. The latter is now responsible for managing traffic within the pod.</p><p>For more details on one of the pods, you can execute the describe command for that pod, which will provide more specific information about its state and characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOsMMolP1lHThDoDLLs9zg.png" /><figcaption><strong>Figure — Pod details after injecting Istio service mesh</strong></figcaption></figure><h4>Traffic Configuration</h4><p>As we are using Istio as our service mesh, it’s important to note that Istio does not allow incoming and outgoing traffic by default. Istio uses gateways to manage incoming and outgoing traffic. Istio comes with preconfigured gateway (proxy) deployments, namely istio-ingressgateway and istio-egressgateway. To allow traffic to enter our various microservices, we need to create our own Gateway and Virtual Service. These are just YAML files that need to be configured according to our application. This can be seen in the following images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CY0Uijazu5ZUPvYIfok-eg.png" /><figcaption><strong>Figure — Istio gateway : Ingress controller</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cm7P2yvnv_e0yhxrZ7gyPA.png" /><figcaption><strong>Figure — Virtual Service for requests routing</strong></figcaption></figure><p>By executing this YAML manifest with kubectl apply, we will observe that a LoadBalancer-type service is created in our cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydJ1ObVxd8HjcxtEu4FLdw.png" /><figcaption><strong>Figure — Istio service inside istio-system namespace</strong></figcaption></figure><p>In a cloud environment, the cloud provider would have allocated a public IP address to allow access to the application from the outside. However, since we are working with a local cluster, we will use the “port-forwarding” technique to access our ingress gateway, which, in turn, will route traffic to our various services.</p><pre>kubectl port-forward service/istio-ingressgateway 8002:80 -n istio-system</pre><p>Our ingress controller is now accessible at the address <a href="http://localhost:8002.">http://localhost:8002.</a> Now, we can access our various microservices through the ingress controller using predefined urls address:</p><h3>Results Evaluation</h3><p>One of the most significant advantages of <strong>service meshes</strong> lies in the integration of a tracing and logging system within their proxy network. Proxy interceptors capture the entire traffic within our cluster. Istio greatly facilitates monitoring through its integrated monitoring stack. It simply requires applying the YAML manifest containing the various resources. Among the tools included with Istio, the following additional modules stand out:</p><ol><li><strong>Kiali</strong> : a graphical user interface that allows for visualizing and monitoring the services mesh managed by Istio. It provides real-time views of traffic flows, service topologies, metrics, and traffic rules, making debugging and service management more accessible.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VWqdtmgl5wlMRGgozKq6Q.png" /><figcaption><strong>Figure — Kiali’s Dashboard</strong></figcaption></figure><p><strong>2. Jaeger</strong> : It is an open-source distributed tracing system. It allows tracking and analyzing the flow of traffic across microservices, which is crucial for diagnosing performance and latency issues in a service mesh environment. It serves as an alternative to Zipkin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2LPSW_I5zoDkrX-9Sj12w.png" /><figcaption><strong>Figure — Distributed tracing with Jaeger</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7eQ5mdeMTsbhw_LhnWo2Pw.png" /><figcaption><strong>FIgure — Trace details with Jaeger</strong></figcaption></figure><p><strong>3. Grafana :</strong> an open-source platform for metric visualization and monitoring. With Istio, Grafana can be used to create customized dashboards to monitor and display performance metrics, trends, and key performance indicators (KPIs) for your microservices.s</p><p>By introducing a declarative model for traffic management and leveraging the sidecar pattern, Istio enables developers to focus on feature development while ensuring granular control over communication, resilience, and discovery.</p><p>The benefits extend to enhanced visibility, monitoring, and security. Istio’s architecture facilitates the adoption of robust security measures, including encryption and authentication, ensuring secure communication between microservices. This article explores Istio’s role in reshaping cloud-native architectures, offering a live demonstration to illustrate its transformative impact. In navigating microservices challenges, service meshes emerge as pivotal tools, with Istio leading the way in streamlining complex communication patterns within modern applications.</p><h3>References</h3><ul><li><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjy0Iih4NWDAxWjU6QEHUXZBvgQtwJ6BAgcEAI&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7cINRP0BFY8&amp;usg=AOvVaw1DldqwrXUdvpM6Cn3EBHKp&amp;opi=89978449">Google Cloud Tech. Istio in production : Day 2 traffic routing (cloud next ’19)</a></li><li><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjC_7CF4dWDAxU7cKQEHbNIB-cQFnoECBEQAQ&amp;url=https%3A%2F%2Fistio.io%2Flatest%2Fdocs%2F&amp;usg=AOvVaw2k9QHeGZsTnPI5aPKvYOvz&amp;opi=89978449">Istio documentation</a></li><li><a href="https://www.talend.com/fr/resources/cloud-native/">Introduction to cloud-native applications</a></li><li><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwj0wYyp4dWDAxWQaqQEHT0jDU8QFnoECBgQAQ&amp;url=https%3A%2F%2Fwww.baeldung.com%2Fops%2Fistio-service-mesh&amp;usg=AOvVaw10rlvq33Oft8h6GPYWp23V&amp;opi=89978449">Service mesh architecture with istio</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c492e71083fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Kubernetes Continuous Deployment : ArgoCD and the App-of-apps patterns ‍]]></title>
            <link>https://medium.com/@mbayemc2/continuous-deployment-with-kubernetes-argocd-and-the-app-of-apps-patterns-37188fdbfb3a?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/37188fdbfb3a</guid>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 09:31:34 GMT</pubDate>
            <atom:updated>2023-10-03T11:15:21.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing deployments in a Kubernetes environment can be a complex and challenging endeavor. As the world of software development continues to evolve at a rapid pace, the importance of efficient deployment and management practices cannot be overstated. In today’s landscape, where agility and reliability are paramount, organizations are constantly seeking ways to streamline their deployment processes and ensure the smooth delivery of applications.</p><p>In response to these challenges, the world of DevOps and container orchestration has seen the rise of innovative solutions designed to simplify deployment in Kubernetes. Among these solutions, ArgoCD has emerged as a powerful tool for managing continuous deployment in Kubernetes clusters. But that’s just the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wjpejewh4EgxEUUMNiFMg.png" /><figcaption><strong>argoCD logo</strong></figcaption></figure><p>This article delves deep into the world of Continuous Deployment with Kubernetes, with a specific focus on ArgoCD and the App-of-apps pattern. I’ve had several experiences using ArgoCD across different projects. Whether you’re a seasoned Kubernetes expert or just getting started with container orchestration, this article will provide you with a comprehensive understanding of how ArgoCD and the <strong>App-of-apps </strong>pattern can revolutionize your deployment workflow.</p><p>For instance, I will demonstrate the deployment of a <strong>microservices-based </strong>application utilizing ArgoCD. Below, you’ll find the architectural layout of the application that we’ll be deploying using ArgoCD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4g9N3oMZew8wGgQF7G8YOw.jpeg" /><figcaption><strong>Microservice architecture for argoCD deployment</strong></figcaption></figure><p>So, let’s embark on this exploration of Continuous Deployment with Kubernetes, ArgoCD, and the <strong>App-of-apps</strong> Pattern, and unlock new possibilities for your deployment workflows.</p><h3>Understanding Kubernetes Deployment Challenges</h3><p>Deploying applications in a Kubernetes environment presents a unique set of challenges that require careful consideration. As we explore ArgoCD and the App-of-apps pattern, it’s essential to first grasp these challenges:</p><ul><li><strong>Complexities in Kubernetes Deployments:</strong> Kubernetes, with its intricate architecture for container orchestration, can be daunting. Coordinating the deployment of multiple containers and microservices, managing configuration, scaling resources, and ensuring high availability can quickly become overwhelming.</li><li><strong>Need for Automation:</strong> Manual deployments in Kubernetes are error-prone and time-consuming. To meet the demands of modern software development, automation is key. We must aim for deployments that are not only efficient but also repeatable and reliable.</li><li><strong>Consistency Matters:</strong> Inconsistent deployment practices can lead to issues such as configuration drift, where the actual state of deployed applications diverges from the desired state. Ensuring consistency across environments is crucial for predictable and stable deployments.</li></ul><h3>A Brief Introduction to ArgoCD</h3><p>ArgoCD is a Kubernetes-native continuous delivery tool that simplifies application deployment and management. It’s built with a <strong><em>GitOps approach</em></strong>, which means that <strong><em>your application configurations and deployment definitions are stored in Git repositories</em></strong>, ensuring version control, auditability, and collaboration. In a nutshell , <strong><em>Git is your single source of truth</em></strong>.</p><p>The following shows the architecture of argoCD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6HN4YKDQvR1TNxtSLWvkw.png" /><figcaption><strong>ArgoCD Architecture</strong></figcaption></figure><p>Here’s an overview of ArgoCD’s key features and how it contributes to more effective Kubernetes deployments:</p><ul><li><strong>Kubernetes-Native:</strong> ArgoCD is designed specifically for Kubernetes, making it a natural fit for your container orchestration environment. It understands Kubernetes resources, making it easier to manage and deploy applications in a Kubernetes cluster.</li><li><strong>GitOps-Driven Deployment:</strong> With ArgoCD, your Kubernetes configurations are stored in Git repositories. This GitOps approach brings many benefits, including version control, automated rollback, and the ability to define your desired state clearly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhBbkhFNFUtXm5EzbY8A7g.png" /><figcaption><strong>How GitOps methodology works</strong></figcaption></figure><ul><li><strong>Application Synchronization:</strong> ArgoCD continually synchronizes your declared desired state (from Git) with the actual state in your Kubernetes cluster. If any deviations are detected, ArgoCD automatically corrects them, ensuring your applications are always in the desired state.</li><li><strong>Declarative Configuration:</strong> You declare the desired state of your applications and resources using Kubernetes manifests in YAML files. ArgoCD takes care of the imperative steps required to reach that state, simplifying your deployment process.</li><li><strong>Multi-Tenancy and RBAC:</strong> ArgoCD supports multi-tenancy, allowing teams to manage their applications independently while adhering to Role-Based Access Control (RBAC) policies. This enhances security and separation of concerns in your Kubernetes environment.</li></ul><p>In the following sections, we’ll dive deeper into how to set up and use ArgoCD effectively to streamline your continuous deployment workflows in Kubernetes. You’ll learn how to install and configure ArgoCD in your cluster, and we’ll walk through the process of deploying applications using this powerful tool.</p><h3>Setting Up ArgoCD</h3><p>Now that we have a foundational understanding of the challenges in Kubernetes deployments and an overview of ArgoCD’s capabilities, it’s time to roll up our sleeves and get hands-on with ArgoCD. In this section, we’ll guide you through the steps of setting up ArgoCD in your Kubernetes cluster.</p><h4><strong>Step 1: Prerequisites</strong></h4><p>Before you can start using ArgoCD, ensure that you have the following prerequisites in place:</p><ul><li>A Kubernetes cluster: You should have a working Kubernetes cluster up and running. You can use managed Kubernetes services like GKE, EKS, or AKS, or set up your own using tools like Minikube or k3s.</li><li><strong>kubectl</strong> CLI: Install the <strong>kubectl</strong> command-line tool and configure it to connect to your Kubernetes cluster.</li><li>Git repository: You’ll need a Git repository to store your application manifests and configurations. Make sure you have one set up, and you have the necessary permissions to access it.</li></ul><p>In this article, I’ve employed a Google Kubernetes Engine (GKE) cluster operating in autopilot mode. However, you have the flexibility to utilize any type of Kubernetes (k8s) cluster of your choice.</p><h4><strong>Step 2 : Installing ArgoCD</strong></h4><p>ArgoCD can be installed as a Kubernetes application. Here’s a simplified guide to getting ArgoCD up and running. Note that depending on your specific environment and requirements, you may need to adjust the installation process accordingly.</p><ol><li><strong>Create a namespace for ArgoCD</strong></li></ol><pre>kubectl create namespace argocd</pre><p><strong>2. Deploy ArgoCD using the provided manifest</strong></p><pre>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</pre><p><strong>3. Once the installation is complete, check the status of the ArgoCD components</strong></p><pre>kubectl get pods -n argocd</pre><p>you can write the command above on your terminal or use you GKE UI interface by selecting argoCD namespace to fetch specific components that belongs to that namespace</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5iaQPGSN3m5DexvutRRkw.png" /><figcaption><strong>Install ArgoCD components within my GKE cluster</strong></figcaption></figure><p>Ensure that all pods are in a Running state before proceeding.</p><h4><strong>Step 3 : Accessing the ArgoCD Web UI</strong></h4><p>ArgoCD comes with a user-friendly web-based interface that allows you to manage your applications visually. You can access the argoCD UI using port-forwarding while working on a local Kubernetes cluster. In my case, I created a LoadBalancer service that exposed my argoCD server by providing an external IP address (hats off to the managed K8s cluster 🤭)</p><p>You can use the following command to expose a LoadBalancer for your argoCD server :</p><pre>kubectl patch svc argocd−server −n argocd −p ’{&quot;spec&quot;:{&quot;type&quot;:&quot;LoadBalancer&quot;}}’</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ex1vBPpwTKQdHWZkuubbcQ.png" /><figcaption><strong>ArgoCD login interface</strong></figcaption></figure><p>The initial username is “admin,” and the password is stored in a Kubernetes Secret object encoded in base64. You will need to decode it later using the following command (echo password | base64). You can obtain it with the following command:</p><pre>argocd admin initial-password -n argocd</pre><p>or with kubectl with the following command :</p><pre>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d</pre><blockquote><strong><em>Note</em></strong> : You can install the ArgoCD CLI by using the official documentation <a href="https://argo-cd.readthedocs.io/en/stable/cli_installation/">here</a> .</blockquote><blockquote>It’s essential to change the password after the initial login for security reasons.</blockquote><p>After login to ArgoCD, here is the image of the home page :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RzAZwFHjwxnlOyH1ZPGag.png" /></figure><p>Congratulations! 🥳 👏</p><p>You now have ArgoCD installed and ready for use in your Kubernetes cluster. In the following sections of this article, we’ll dive deeper into deploying applications using ArgoCD’s GitOps-driven approach and explore how it simplifies the continuous deployment process while maintaining consistency and automation.</p><h3>Introduction to the App-of-apps Pattern</h3><p>In the world of Kubernetes and cloud-native application development, managing a single application is challenging enough. However, as your ecosystem grows, you may find yourself dealing with multiple microservices, and interdependencies between various applications. This is where the “App-of-apps” pattern comes to the rescue.</p><p><strong>What Is the App-of-apps Pattern?</strong></p><p>The App-of-apps pattern, often referred to as the “umbrella chart” pattern, is an architectural approach that enables you to manage and deploy multiple related applications as a single cohesive unit. It acts as a higher-level abstraction, providing a unified control point for orchestrating complex deployments.</p><p>Since we’re using ArgoCD, we need to create an Application definition for each microservice being deployed. But, since they’re part of a set of services, it would be nice if we had a way to ArgoCD know that.</p><p>The Argo community has provided a solution to our questions with the “App of Apps” model. Essentially, this model allows us to define a root Argo CD application that will itself define and synchronize multiple child applications. Instead of pointing to an application manifest, as we did before, the root application points to a folder in Git where we store the application manifests that define each application we want to create and deploy. This way, you can declare all your applications in a single YAML manifest. Click <a href="https://argo-cd.readthedocs.io/en/stable/operator-manual/cluster-bootstrapping/#app-of-apps-pattern">here</a> for more details about that pattern.</p><p>We have a bunch of microservices located in separate directories. A basic deployment with ArgoCD will create an Application resource for each microservice. This means that ArgoCD will manage them as if they belong to different applications.</p><p>Here’s why App-of-apps pattern is valuable:</p><ul><li><strong>Simplified Management</strong>: Instead of managing each microservice or application individually, you group them under a single parent chart. This simplifies management tasks, such as deployment, configuration, and versioning.</li><li><strong>Consistency</strong>: With the App-of-apps pattern, you ensure consistent deployment and configuration across multiple applications. This is especially critical in complex environments where consistency can be challenging to maintain.</li><li><strong>Dependency Resolution</strong>: Managing dependencies between applications becomes more manageable. You can specify version constraints and ensure that interdependent components are deployed together in a coordinated manner.</li><li><strong>Scalability</strong>: As your ecosystem grows, the App-of-apps pattern scales with it. Adding new applications or microservices is a matter of extending the umbrella chart, rather than reconfiguring the entire environment.</li><li><strong>Simplified Rollbacks</strong>: When issues arise or you need to roll back changes, the App-of-apps pattern allows you to roll back the entire set of applications to a previous state, ensuring consistency.</li></ul><h3>Implementing the App-of-apps Pattern with ArgoCD</h3><p>Now that we understand the value of the App-of-apps pattern and how it aligns with ArgoCD’s GitOps-driven approach, let’s delve into the practical implementation of this powerful pattern.</p><p><strong>Step 1: Organizing Your Git Repositories</strong></p><p>The first step in implementing the App-of-apps pattern is to organize your Git repositories effectively. Here, we have separate repositories for each of group of applications. You can group your microservices based on certain aspects. Personally, I chose to create a separate directory for my edge microservices since they handle communication aspects in my architecture and also for each service that contributes to the functional requirement of the application. Here’s a suggested structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFcaBhoU6I1m344uxeCYfQ.png" /><figcaption><strong>k8s manifest for argoCD deployment with apps-of-App pattern</strong></figcaption></figure><p><strong>Step 2 : Define Application Dependencies</strong></p><p>By implementing the App-of-Apps model, we define our root application as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3NAL-f_Fq-bvCBmiHq_VQ.png" /><figcaption><strong>root application for App-of-apps</strong></figcaption></figure><p><strong>Step 3 : ArgoCD Application Configuration</strong></p><p>The structure of a child application simply points to the directory containing the manifests of the microservice to be deployed in ArgoCD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVUSoIw1hfc4wcedKm2Uyw.png" /><figcaption><strong>Definition of child App-of-apps</strong></figcaption></figure><p>You can find the entire code on my <a href="https://github.com/going-cloud-native-2023/argo-cd-manifest/blob/master/application.yaml"><strong>GITHUB</strong></a> repository.</p><blockquote>Once this is done, you can fetch the repository using the GKE console or your terminal if you work locally and apply the manifest using <strong>kubectl apply.</strong></blockquote><p>We can now visualize the results by accessing the ArgoCD UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDeJdNBNomhJjKLsNAKWXQ.png" /><figcaption><strong>fleet of microservices applications with app-of-apps</strong></figcaption></figure><p>Similarly, we can inspect the contents of a specific application, such as “adhesions-apps,” to understand how ArgoCD establishes connections between the various objects we have created with Kubernetes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYh1HeWZUXoYhbBIiWeYfg.png" /><figcaption><strong>adhesion-microservice with app-of-apps pattern</strong></figcaption></figure><p>It is also possible to examine the various pods of our deployment in detail through the ArgoCD interface. Furthermore, logs can be reviewed to ensure the proper execution of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dLafnYiwctZfJzleW2Jvg.png" /><figcaption><strong>adhesion service pod details</strong></figcaption></figure><p>You can also see the logs of each pod. In this example, we have a spring boot application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwJxgPkPWtIaK9KshEZrpA.png" /><figcaption><strong>adhesion service pod logs</strong></figcaption></figure><p>The following image shows the links between my edge microservices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_As1PGZkcyOsIRUtJ1CkVA.png" /><figcaption><strong>edge microservices running on argoCD</strong></figcaption></figure><p>By implementing the App-of-apps pattern with ArgoCD, you can efficiently manage complex Kubernetes deployments and orchestrate multiple applications. This approach simplifies your deployment workflows and ensures consistency across your Kubernetes environment. In the next section, we’ll explore advanced features and use cases of ArgoCD, including RBAC, webhook integrations, and automation, to further enhance your continuous deployment processes.</p><h3><strong>Advanced Features and Use Cases</strong></h3><p>ArgoCD offers a range of advanced features and use cases that elevate your continuous deployment workflow in Kubernetes. In this section, we’ll explore some of these capabilities and highlight scenarios where ArgoCD truly shines.</p><ul><li><strong>Role-Based Access Control (RBAC)</strong></li></ul><p>ArgoCD supports Role-Based Access Control (RBAC), allowing you to define fine-grained access policies for different users and teams. RBAC ensures that only authorized personnel can make changes to applications or access sensitive configurations within ArgoCD. This is particularly valuable in large organizations with complex access requirements.</p><ul><li><strong>Web-hook Integrations</strong></li></ul><p>Webhook integrations enable you to trigger ArgoCD deployments automatically in response to events from your Git repository or other sources. For example, you can set up webhooks to initiate deployments whenever changes are pushed to a specific branch in your repository. This real-time synchronization simplifies the deployment process and ensures that your applications stay up to date.</p><ul><li><strong>Automation with GitOps Workflows</strong></li></ul><p>ArgoCD allows you to define GitOps workflows to automate various aspects of your deployment pipeline. You can automate testing, integration, and deployment processes, reducing manual intervention and ensuring consistent deployments across environments. GitOps workflows are especially beneficial in Continuous Integration/Continuous Deployment (CI/CD) pipelines, where automation is crucial for efficiency.</p><ul><li><strong>Canary Deployments and Blue-Green Deployments</strong></li></ul><p>ArgoCD can be used in conjunction with other Kubernetes tools to implement advanced deployment strategies like Canary Deployments and Blue-Green Deployments. These strategies involve rolling out new versions of your applications gradually, reducing the risk of deploying faulty updates to all users simultaneously. By leveraging ArgoCD’s capabilities, you can orchestrate these deployment strategies effectively.</p><p><strong>Use Cases :</strong></p><ul><li><strong>Microservices-Based Applications</strong>: ArgoCD is well-suited for managing microservices-based applications where multiple services need to be deployed, scaled, and coordinated. It ensures that changes to one service do not disrupt the entire application.</li><li><strong>Compliance and Audit Requirements</strong>: ArgoCD’s version-controlled and auditable deployment process is invaluable for organizations with strict compliance and audit requirements. It provides a clear history of changes and who made them.</li><li><strong>GitOps in DevOps Pipelines</strong>: Integrating ArgoCD into your DevOps pipelines allows for automated testing, deployment, and validation of applications. It streamlines the development cycle and helps teams deliver updates faster and more reliably.</li></ul><p>By leveraging these advanced features and use cases, ArgoCD becomes a versatile tool in your Kubernetes toolbox. Whether you’re managing microservices, complex infrastructure, or multiple clusters, ArgoCD empowers you to streamline deployments and maintain consistency, making it a valuable asset in modern software development practices.</p><p>Kudos 🔥🔥, Everything is in place for you to strengthen your DevOps skills with GitOps methodology 😉</p><p>References :</p><ul><li><a href="https://argo-cd.readthedocs.io/en/stable/getting_started/#7-sync-deploy-the-application">https://argo-cd.readthedocs.io/en/stable/getting_started/#7-sync-deploy-the-application</a></li><li><a href="https://medium.com/dzerolabs/turbocharge-argocd-with-app-of-apps-pattern-and-kustomized-helm-ea4993190e7c">https://medium.com/dzerolabs/turbocharge-argocd-with-app-of-apps-pattern-and-kustomized-helm-ea4993190e7c</a></li><li><a href="https://argo-cd.readthedocs.io/en/stable/operator-manual/cluster-bootstrapping/#app-of-apps-pattern">https://argo-cd.readthedocs.io/en/stable/operator-manual/cluster-bootstrapping/#app-of-apps-pattern</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37188fdbfb3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End to End Data Engineering project using apache airflow and AWS (AWS Crawler, AWS Glue , Amazon…]]></title>
            <link>https://medium.com/@mbayemc2/end-to-end-data-engineering-project-using-apache-airflow-and-aws-aws-crawler-aws-glue-amazon-9f61100efbe0?source=rss-72cec60a6eb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f61100efbe0</guid>
            <category><![CDATA[aws-athena]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Mbaye SENE]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 19:41:28 GMT</pubDate>
            <atom:updated>2024-01-11T14:22:27.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>End to End Data Engineering project using apache airflow and AWS (AWS Crawler, AWS Glue , Amazon Athena)</h3><p>Here is my first article on Medium and I enjoyed working on this end to end project about data engineering. It’s all about learning by doing. In this project, you will use apache airflow to build an ETL pipeline , store the result on a PostgreSQL running on docker. After that, we are going to upload the data on AWS s3 and use Amazon Athena to run queries on top of my CSV file there by adding a Crawler. There are two DAGs. The first one is used to fetch data from API and send it to postgreSQL. After the data is sent to PostgreSQL a trigger mechanism is run and trigger dag 2. Dag 2 gets data from PostgreSQL and send it to S3 bucket as csv file.</p><p>The full architecture of the project is below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISIyu4pNI_ywt66G2rFGrg.jpeg" /></figure><p>The project’s architecture involves multiple components and follows an end-to-end data engineering process. In my first article on Medium, I had the opportunity to work on this project and explore various aspects of data engineering. It was a great learning experience, emphasizing the principle of learning by doing.</p><p>The project utilizes Apache Airflow, a powerful workflow management platform, to build an ETL (Extract, Transform, Load) pipeline. The data extracted is stored in a PostgreSQL database running on Docker. To enable further analysis and querying, the data is uploaded to an AWS S3 bucket. Amazon Athena, a serverless query service, is leveraged to perform queries on the CSV files stored in the S3 bucket. Additionally, a Crawler is employed to facilitate the organization and discovery of the data.</p><p>The project comprises two separate DAGs (Directed Acyclic Graphs). The first DAG focuses on fetching data from an API and sending it to PostgreSQL. Once the data is successfully loaded into PostgreSQL, a trigger mechanism is activated, which in turn triggers the second DAG. The second DAG retrieves the data from PostgreSQL and sends it to the designated S3 bucket as a CSV file.</p><p>This project’s architecture demonstrates a comprehensive data pipeline encompassing various technologies and steps, enabling efficient data extraction, storage, and analysis.</p><p>The following image shows my different directory. you can create your own of just clone the repos to get hand on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKqqVqRCG8n3OxIsl_lveQ.png" /></figure><p>You can fid the docker-compose.yaml file on the official website of apache airflow here [link] but you can check the one I used (it’s quite the same)</p><pre><br>---<br>version: &#39;3.8&#39;<br>x-airflow-common:<br>  &amp;airflow-common<br>  # In order to add custom dependencies or upgrade provider packages you can use your extended image.<br>  # Comment the image line, place your Dockerfile in the directory where you placed the docker-compose.yaml<br>  # and uncomment the &quot;build&quot; line below, Then run `docker-compose build` to build the images.<br>  image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.6.1}<br>  # build: .<br>  environment:<br>    &amp;airflow-common-env<br>    AIRFLOW__CORE__EXECUTOR: CeleryExecutor<br>    AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow<br>    # For backward compatibility, with Airflow &lt;2.3<br>    AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow<br>    AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow@postgres/airflow<br>    AIRFLOW__CELERY__BROKER_URL: redis://:@redis:6379/0<br>    AIRFLOW__CORE__FERNET_KEY: &#39;&#39;<br>    AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: &#39;true&#39;<br>    AIRFLOW__CORE__LOAD_EXAMPLES: &#39;False&#39;<br>    AIRFLOW__API__AUTH_BACKENDS: &#39;airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session&#39;<br>    # yamllint disable rule:line-length<br>    # Use simple http server on scheduler for health checks<br>    # See https://airflow.apache.org/docs/apache-airflow/stable/administration-and-deployment/logging-monitoring/check-health.html#scheduler-health-check-server<br>    # yamllint enable rule:line-length<br>    AIRFLOW__SCHEDULER__ENABLE_HEALTH_CHECK: &#39;true&#39;<br>    # WARNING: Use _PIP_ADDITIONAL_REQUIREMENTS option ONLY for a quick checks<br>    # for other purpose (development, test and especially production usage) build/extend Airflow image.<br>    _PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-}<br>  volumes:<br>    - ${AIRFLOW_PROJ_DIR:-.}/dags:/opt/airflow/dags<br>    - ${AIRFLOW_PROJ_DIR:-.}/logs:/opt/airflow/logs<br>    - ${AIRFLOW_PROJ_DIR:-.}/config:/opt/airflow/config<br>    - ${AIRFLOW_PROJ_DIR:-.}/plugins:/opt/airflow/plugins<br>  user: &quot;${AIRFLOW_UID:-50000}:0&quot;<br>  depends_on:<br>    &amp;airflow-common-depends-on<br>    redis:<br>      condition: service_healthy<br>    postgres:<br>      condition: service_healthy<br><br>services:<br>  postgres:<br>    image: postgres:13<br>    environment:<br>      POSTGRES_USER: airflow<br>      POSTGRES_PASSWORD: airflow<br>      POSTGRES_DB: airflow<br>    volumes:<br>      - postgres-db-volume:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;pg_isready&quot;, &quot;-U&quot;, &quot;airflow&quot;]<br>      interval: 10s<br>      retries: 5<br>      start_period: 5s<br>    restart: always<br><br>  redis:<br>    image: redis:latest<br>    expose:<br>      - 6379<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;redis-cli&quot;, &quot;ping&quot;]<br>      interval: 10s<br>      timeout: 30s<br>      retries: 50<br>      start_period: 30s<br>    restart: always<br><br>  airflow-webserver:<br>    &lt;&lt;: *airflow-common<br>    command: webserver<br>    ports:<br>      - &quot;8080:8080&quot;<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8080/health&quot;]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 5<br>      start_period: 30s<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-scheduler:<br>    &lt;&lt;: *airflow-common<br>    command: scheduler<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8974/health&quot;]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 5<br>      start_period: 30s<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-worker:<br>    &lt;&lt;: *airflow-common<br>    command: celery worker<br>    healthcheck:<br>      test:<br>        - &quot;CMD-SHELL&quot;<br>        - &#39;celery --app airflow.executors.celery_executor.app inspect ping -d &quot;celery@$${HOSTNAME}&quot;&#39;<br>      interval: 30s<br>      timeout: 10s<br>      retries: 5<br>      start_period: 30s<br>    environment:<br>      &lt;&lt;: *airflow-common-env<br>      # Required to handle warm shutdown of the celery workers properly<br>      # See https://airflow.apache.org/docs/docker-stack/entrypoint.html#signal-propagation<br>      DUMB_INIT_SETSID: &quot;0&quot;<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-triggerer:<br>    &lt;&lt;: *airflow-common<br>    command: triggerer<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &#39;airflow jobs check --job-type TriggererJob --hostname &quot;$${HOSTNAME}&quot;&#39;]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 5<br>      start_period: 30s<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-init:<br>    &lt;&lt;: *airflow-common<br>    entrypoint: /bin/bash<br>    # yamllint disable rule:line-length<br>    command:<br>      - -c<br>      - |<br>        function ver() {<br>          printf &quot;%04d%04d%04d%04d&quot; $${1//./ }<br>        }<br>        airflow_version=$$(AIRFLOW__LOGGING__LOGGING_LEVEL=INFO &amp;&amp; gosu airflow airflow version)<br>        airflow_version_comparable=$$(ver $${airflow_version})<br>        min_airflow_version=2.2.0<br>        min_airflow_version_comparable=$$(ver $${min_airflow_version})<br>        if (( airflow_version_comparable &lt; min_airflow_version_comparable )); then<br>          echo<br>          echo -e &quot;\033[1;31mERROR!!!: Too old Airflow version $${airflow_version}!\e[0m&quot;<br>          echo &quot;The minimum Airflow version supported: $${min_airflow_version}. Only use this or higher!&quot;<br>          echo<br>          exit 1<br>        fi<br>        if [[ -z &quot;${AIRFLOW_UID}&quot; ]]; then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: AIRFLOW_UID not set!\e[0m&quot;<br>          echo &quot;If you are on Linux, you SHOULD follow the instructions below to set &quot;<br>          echo &quot;AIRFLOW_UID environment variable, otherwise files will be owned by root.&quot;<br>          echo &quot;For other operating systems you can get rid of the warning with manually created .env file:&quot;<br>          echo &quot;    See: https://airflow.apache.org/docs/apache-airflow/stable/howto/docker-compose/index.html#setting-the-right-airflow-user&quot;<br>          echo<br>        fi<br>        one_meg=1048576<br>        mem_available=$$(($$(getconf _PHYS_PAGES) * $$(getconf PAGE_SIZE) / one_meg))<br>        cpus_available=$$(grep -cE &#39;cpu[0-9]+&#39; /proc/stat)<br>        disk_available=$$(df / | tail -1 | awk &#39;{print $$4}&#39;)<br>        warning_resources=&quot;false&quot;<br>        if (( mem_available &lt; 4000 )) ; then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: Not enough memory available for Docker.\e[0m&quot;<br>          echo &quot;At least 4GB of memory required. You have $$(numfmt --to iec $$((mem_available * one_meg)))&quot;<br>          echo<br>          warning_resources=&quot;true&quot;<br>        fi<br>        if (( cpus_available &lt; 2 )); then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: Not enough CPUS available for Docker.\e[0m&quot;<br>          echo &quot;At least 2 CPUs recommended. You have $${cpus_available}&quot;<br>          echo<br>          warning_resources=&quot;true&quot;<br>        fi<br>        if (( disk_available &lt; one_meg * 10 )); then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: Not enough Disk space available for Docker.\e[0m&quot;<br>          echo &quot;At least 10 GBs recommended. You have $$(numfmt --to iec $$((disk_available * 1024 )))&quot;<br>          echo<br>          warning_resources=&quot;true&quot;<br>        fi<br>        if [[ $${warning_resources} == &quot;true&quot; ]]; then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: You have not enough resources to run Airflow (see above)!\e[0m&quot;<br>          echo &quot;Please follow the instructions to increase amount of resources available:&quot;<br>          echo &quot;   https://airflow.apache.org/docs/apache-airflow/stable/howto/docker-compose/index.html#before-you-begin&quot;<br>          echo<br>        fi<br>        mkdir -p /sources/logs /sources/dags /sources/plugins<br>        chown -R &quot;${AIRFLOW_UID}:0&quot; /sources/{logs,dags,plugins}<br>        exec /entrypoint airflow version<br>    # yamllint enable rule:line-length<br>    environment:<br>      &lt;&lt;: *airflow-common-env<br>      _AIRFLOW_DB_UPGRADE: &#39;true&#39;<br>      _AIRFLOW_WWW_USER_CREATE: &#39;true&#39;<br>      _AIRFLOW_WWW_USER_USERNAME: ${_AIRFLOW_WWW_USER_USERNAME:-airflow}<br>      _AIRFLOW_WWW_USER_PASSWORD: ${_AIRFLOW_WWW_USER_PASSWORD:-airflow}<br>      _PIP_ADDITIONAL_REQUIREMENTS: &#39;&#39;<br>    user: &quot;0:0&quot;<br>    volumes:<br>      - ${AIRFLOW_PROJ_DIR:-.}:/sources<br><br>  airflow-cli:<br>    &lt;&lt;: *airflow-common<br>    profiles:<br>      - debug<br>    environment:<br>      &lt;&lt;: *airflow-common-env<br>      CONNECTION_CHECK_MAX_COUNT: &quot;0&quot;<br>    # Workaround for entrypoint issue. See: https://github.com/apache/airflow/issues/16252<br>    command:<br>      - bash<br>      - -c<br>      - airflow<br><br>  # You can enable flower by adding &quot;--profile flower&quot; option e.g. docker-compose --profile flower up<br>  # or by explicitly targeted on the command line e.g. docker-compose up flower.<br>  # See: https://docs.docker.com/compose/profiles/<br>  flower:<br>    &lt;&lt;: *airflow-common<br>    command: celery flower<br>    profiles:<br>      - flower<br>    ports:<br>      - &quot;5555:5555&quot;<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:5555/&quot;]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 5<br>      start_period: 30s<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>volumes:<br>  postgres-db-volume:</pre><p>In this setup, the project utilizes four containers to achieve its functionality. The first container is dedicated to the initialization process. The PostgreSQL container is responsible for hosting the PostgreSQL database. The scheduler container handles the scheduling and execution of tasks and jobs within Airflow. Finally, the webserver container is used to access and interact with the Airflow user interface.</p><p>To start the project, ensure that you are in the same directory as the docker-compose file, and then run the command “docker-compose up -d” in your command line interface (CLI). This command will initiate the container setup and start the services. Before running the command, it’s important to create an S3 bucket and populate the configuration.json file with the necessary configuration details.</p><p>By following these steps, you will be able to build and deploy the project using Docker Compose, allowing you to leverage the functionalities of PostgreSQL, Airflow, and the S3 bucket for your data engineering tasks.</p><p>Here is my configuration file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lzcuejxm4vsXrgvwv26cZQ.png" /></figure><p>Feel free to replace the access_key and secret_key by your own.</p><p>Required packages</p><pre>import os, json, boto3, pathlib, psycopg2, requests<br>import pandas as pd<br>from airflow import DAG<br>from pathlib import Path<br>import airflow.utils.dates<br>from airflow.sensors.python import PythonSensor<br>from airflow.operators.python import PythonOperator<br>from airflow.operators.trigger_dagrun import TriggerDagRunOperator<br>import csv , json</pre><p>My DAGS</p><pre>dag1 = DAG(<br>    dag_id=&quot;get_university_api_send_psql&quot;,<br>    start_date=airflow.utils.dates.days_ago(1),<br>    schedule_interval=None)<br><br>dag2 = DAG(<br>    dag_id=&quot;get_psql_data_send_s3&quot;,<br>    start_date=airflow.utils.dates.days_ago(1),<br>    schedule_interval=None)</pre><p>Tasks</p><p>It’s important to understand that each task in Apache Airflow must be assigned to a particular DAG. Tasks in Airflow can be thought of as individual methods that serve a specific purpose and contribute to the overall workflow.</p><pre>def _fetch_and_save():<br>    # Fetch data from API<br>    response = requests.get(&#39;http://universities.hipolabs.com/search?country=&#39;)<br>    data_json = response.json()<br><br>     # Check if path is exists or create<br>    main_path = &quot;/tmp/json_file&quot;<br>    pathlib.Path(main_path).mkdir(parents=True, exist_ok=True)<br><br>    # Prepare CSV file path<br>    csv_file = main_path + &quot;/data_university.csv&quot;<br><br>    # Open CSV file in write mode <br>    with open(csv_file, &#39;w&#39;, newline=&#39;&#39;) as file:<br>        writer = csv.writer(file)<br>        <br>        # Write header<br>        writer.writerow([&#39;country&#39;, &#39;alpha_two_code&#39;, &#39;name&#39;, &#39;state-province&#39;, &#39;domains&#39;, &#39;web_pages&#39;])<br>        <br>        # Iterate over each JSON object and extract required fields<br>        for item in data_json:<br>            country = item.get(&#39;country&#39;, &#39;&#39;)<br>            alpha_two_code = item.get(&#39;alpha_two_code&#39;, &#39;&#39;)<br>            name = item.get(&#39;name&#39;, &#39;&#39;)<br>            state_province = item.get(&#39;state-province&#39;, &#39;&#39;)<br>            domains = &#39;, &#39;.join(item.get(&#39;domains&#39;, []))<br>            web_pages = &#39;, &#39;.join(item.get(&#39;web_pages&#39;, []))<br>            <br>            # Write row to CSV<br>            writer.writerow([country, alpha_two_code, name, state_province, domains, web_pages])<br><br>    # Print success message<br>    print(&#39;Data has been loaded into CSV:&#39;, csv_file)</pre><p>The task “fetch_and_save” fetches data from an API and saves it as a CSV file named “data_university.csv”. The task’s ID is set to the same name as the task itself. The function specified in the “python_callable” parameter is responsible for performing the actual fetching and saving of the data. The task is associated with a DAG using the “dag” parameter. This creates a task named “fetch_and_save”, as shown in the second image above.</p><pre>def _read_json_file():<br>    main_path = &quot;/tmp/json_file&quot;<br><br>    csv_file_path = main_path + &quot;/data_university.csv&quot;<br>    json_file_path = main_path +  &quot;/data_university.json&quot;<br>    # Open the CSV file for reading<br>    with open(csv_file_path, &#39;r&#39;) as csv_file:<br>        # Create a CSV reader object<br>        csv_reader = csv.DictReader(csv_file)<br><br>        # Initialize an empty list to store the rows<br>        rows = []<br><br>        # Iterate over each row in the CSV file<br>        for row in csv_reader:<br>            # Create a dictionary with the desired fields<br>            data = {<br>                &#39;country&#39;: row[&#39;country&#39;],<br>                &#39;alpha_two_code&#39;: row[&#39;alpha_two_code&#39;],<br>                &#39;name&#39;: row[&#39;name&#39;],<br>                &#39;state-province&#39;: row[&#39;state-province&#39;],<br>                &#39;domains&#39;: row[&#39;domains&#39;],<br>                &#39;web_pages&#39;: row[&#39;web_pages&#39;]<br>            }<br><br>            # Append the dictionary to the list<br>            rows.append(data)<br><br>    # Open the JSON file for writing<br>    with open(json_file_path, &#39;w&#39;) as json_file:<br>        # Write the list of dictionaries to the JSON file<br>        json.dump(rows, json_file)</pre><p>This method enables us to load data from a CSV source and convert it into a JSON file. Alternatively, we could have directly created the JSON file during the API data fetching process, but the approach chosen depends on various factors. We can discuss optimization decisions regarding this matter when the time comes.</p><pre>def _wait_for_json(filepath):<br>    return Path(filepath).exists()<br><br><br>wait_for_json = PythonSensor(<br>    task_id=&quot;wait_for_json&quot;,<br>    python_callable=_wait_for_json,<br>    poke_interval=30,<br>    timeout=24*60*60,<br>    mode=&quot;reschedule&quot;,<br>    op_kwargs={<br>        &quot;filepath&quot;:&quot;/tmp/json_file/data_university.json&quot;},<br>    dag=dag1)</pre><p>Here we utilize the PythonSensor. However, we can also use the FileSensor instead of the PythonSensor. The primary objective is to verify whether the file exists or not.</p><pre>def _send_to_postgresql():<br><br>    json_file_path = &#39;/tmp/json_file/data_university.json&#39;<br><br>    # Connect to the PostgreSQL database<br>    conn = psycopg2.connect(<br>        database=&quot;postgres_db&quot;, <br>        user=&quot;postgres&quot;, <br>        password=&quot;postgres&quot;, <br>        host=&quot;host.docker.internal&quot;,<br>        port=&quot;5433&quot;<br>    )<br><br>    # Create a cursor object to interact with the database<br>    cursor = conn.cursor()<br><br><br>    cursor.execute(&quot;&quot;&quot;CREATE TABLE IF NOT EXISTS university_table(<br>                        id SERIAL PRIMARY KEY NOT NULL, <br>                        country VARCHAR(255), <br>                        alpha_two_code VARCHAR(2),<br>                        name VARCHAR(255), <br>                        state_province VARCHAR(255),<br>                        domains TEXT[],<br>                        web_pages TEXT[]<br>                    )&quot;&quot;&quot;)<br><br>    # Read the JSON data from the file<br>    with open(json_file_path, &#39;r&#39;) as json_file:<br>        json_data = json.load(json_file)<br><br>    # Insert each JSON record into the database table<br>    for record in json_data:<br>        country = record[&#39;country&#39;]<br>        alpha_two_code = record[&#39;alpha_two_code&#39;]<br>        name = record[&#39;name&#39;]<br>        state_province = record[&#39;state-province&#39;]<br>        domains = record[&#39;domains&#39;]<br>        web_pages = record[&#39;web_pages&#39;]<br><br>        # Execute the INSERT query<br>        cursor.execute(&quot;&quot;&quot;<br>            INSERT INTO university_table (country, alpha_two_code, name, state_province, domains, web_pages)<br>            VALUES (%s, %s, %s, %s, ARRAY[%s], ARRAY[%s])<br>        &quot;&quot;&quot;, (country, alpha_two_code, name, state_province, domains, web_pages))<br><br>    # Commit the changes to the database<br>    conn.commit()<br><br>    # Close the cursor and database connection<br>    cursor.close()<br>    conn.close()<br>    os.remove(&quot;/tmp/json_file/data_university.json&quot;)</pre><p>Here is the method I use to insert data into my PostgreSQL database using the records we created in our JSON file. First, we create a query to create the table with the specific columns. Then, we use a for loop on our json_data to insert each record into the table and we remove the json file.</p><pre>def _fetch_psql_save_csv(file_path, csv_path):<br>    conn = psycopg2.connect(<br>        database=&quot;postgres_db&quot;,<br>        user=&quot;postgres&quot;,<br>        password=&quot;postgres&quot;,<br>        host=&quot;host.docker.internal&quot;,<br>        port=&quot;5433&quot;<br>    )<br><br>    cursor = conn.cursor()<br><br>    cursor.execute(&quot;&quot;&quot;SELECT country, alpha_two_code, name, state_province, domains, web_pages <br>                        FROM university_table&quot;&quot;&quot;)<br>    all_data = cursor.fetchall()<br><br>    countries = []<br>    alpha_two_codes = []<br>    names = []<br>    state_provinces = []<br>    domains = []<br>    web_pages = []<br><br>    for data in all_data:<br>        countries.append(data[0])<br>        alpha_two_codes.append(data[1])<br>        names.append(data[2])<br>        state_provinces.append(data[3])<br>        domains.append(data[4])<br>        web_pages.append(data[5])<br><br>    dataframe = pd.DataFrame({<br>        &quot;country&quot;: countries,<br>        &quot;alpha_two_code&quot;: alpha_two_codes,<br>        &quot;name&quot;: names,<br>        &quot;state_province&quot;: state_provinces,<br>        &quot;domains&quot;: domains,<br>        &quot;web_pages&quot;: web_pages<br>    })<br><br>    pathlib.Path(file_path).mkdir(parents=True, exist_ok=True)<br><br>    dataframe.to_csv(csv_path, index=False)<br>    print(&quot;Dataframe saved!&quot;)<br><br>    cursor.close()<br>    conn.close()</pre><p>Before executing the function to upload data to an AWS S3 bucket, we must first retrieve the data from our PostgreSQL database and save it into a CSV file.</p><pre>def _wait_for_csv(filepath):<br>    return Path(filepath).exists()<br><br>wait_for_csv = PythonSensor(<br>    task_id=&quot;wait_for_csv&quot;,<br>    python_callable=_wait_for_csv,<br>    poke_interval=30,<br>    timeout=24*60*60,<br>    mode=&quot;reschedule&quot;,<br>    op_kwargs={&quot;filepath&quot;:&quot;/tmp/csv/data_university.csv&quot;},<br>    dag=dag2)</pre><p>In order to ensure that the specific CSV file exists before proceeding to the next task, we incorporate a timeout interval. This allows us to periodically check for the existence of the file within the given time limit.</p><pre>def _send_csv_s3():<br>    with open(CUR_DIR + &quot;/configurations.json&quot;,&quot;r&quot;) as output:<br>        configurations = json.load(output)<br><br>    s3_client = boto3.client(<br>        service_name=configurations[&quot;service_name&quot;],<br>        region_name=configurations[&quot;region_name&quot;],<br>        aws_access_key_id=configurations[&quot;aws_access_key_id&quot;],<br>        aws_secret_access_key=configurations[&quot;aws_secret_access_key&quot;])<br><br>    s3_client.upload_file(<br>        &quot;/tmp/csv/data_university.csv&quot;,<br>        configurations[&quot;bucket_name&quot;],<br>        configurations[&quot;file_name&quot;])<br><br>    os.remove(&quot;/tmp/csv/data_university.csv&quot;)</pre><p>This method sed the file to our S3 bucket and removes the file.</p><p>Pipeline on airfow</p><ul><li>Dag1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hnMv6KxoSOTK6ApkvdqDw.png" /></figure><ul><li>Dag2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIC7cONsejwkevLo9Mp3eQ.png" /></figure><p>The Green color means that the tasks were perfectly executed.</p><p>Kudos ….</p><p>Results on Bucket</p><p>As you can see, my file is successfully added there.Now, we have to jump on the second part of this article.We have to add a crawler and allows Amazon Athena to ru on top of my csv file.Before that, let’s make a little explanation of the services we are going to use.</p><p>According to chatGPT, we have the following :</p><ul><li>AWS Crawler</li></ul><p>AWS Crawler is a service provided by Amazon Web Services (AWS) that helps automate the process of discovering and cataloging data in various sources, such as databases, data lakes, and data warehouses. It is part of the AWS Glue service, which is a fully managed extract, transform, and load (ETL) service.</p><p>AWS Crawler simplifies the task of creating and maintaining a data catalog by automatically crawling the specified data sources and extracting metadata about the data. It analyzes the data schema, detects changes in the schema over time, and updates the catalog accordingly.</p><p>By using AWS Crawler, you can automate the process of data discovery, cataloging, and schema updates, saving time and effort in managing your data catalog and making it easier to work with and analyze your data.</p><ul><li>AWS Glue Data Catalog</li></ul><p>The Glue Data Catalog is a fully managed metadata repository provided by AWS. It acts as a central catalog for storing and managing metadata information about various data sources. It provides a unified view of metadata from multiple data stores, making it easier to discover, understand, and analyze data. The Glue Data Catalog allows users to define and maintain table schemas, column names, data types, and other metadata attributes. It also supports features like metadata search, data lineage, and data governance. The Glue Data Catalog integrates with other AWS services and can be accessed by various tools and applications for data processing and analysis.</p><ul><li>AWS Athena</li></ul><p>AWS Athena is a serverless query service provided by Amazon Web Services (AWS) that allows you to analyze and query large amounts of data stored in Amazon S3 using standard SQL syntax. It enables you to perform ad hoc queries on structured, semi-structured, and unstructured data without the need for setting up and managing complex infrastructure.</p><p>Here’s a simple explanation of how AWS Athena works:</p><ol><li>Data Storage: AWS Athena works directly with data stored in Amazon S3. You can store your data in S3 in various formats such as CSV, JSON, Parquet, or ORC.</li><li>Schema Definition: Before querying the data in Athena, you need to define a schema for the data. The schema defines the structure of your data, including column names, data types, and partitions (if applicable). Athena supports automatic schema detection for certain file formats, or you can provide a schema manually.</li><li>Query Execution: With the data stored in S3 and the schema defined, you can start executing SQL queries on your data using the Athena query editor or any SQL client that supports JDBC/ODBC connections. You can run SELECT, INSERT, UPDATE, DELETE, and other SQL statements to retrieve, modify, or analyze your data.</li></ol><p><strong>To configure the integration between your Glue crawler and S3 bucket, follow these steps:</strong></p><ol><li>Create a Glue crawler: Use the AWS Glue console or API to create a crawler. Specify the data source as your S3 bucket and provide the necessary details such as the path, file format, and crawler name.</li><li>Configure the crawler: Set up the crawler’s properties, including the IAM role that the crawler will assume. The IAM role should have appropriate permissions to access your S3 bucket and perform necessary operations.</li><li>Specify the S3 bucket and subfolder: In the crawler configuration, specify the S3 bucket you want to crawl. You can also specify a subfolder within the bucket if you only want to crawl a specific portion of the data.</li><li>Set up IAM role permissions: Create an IAM role with the necessary permissions to allow the Glue service to access your S3 bucket. The role should have permissions for reading data from the S3 bucket and performing necessary operations like listing objects and reading object metadata.</li><li>Attach the IAM role to the crawler: Associate the IAM role you created with the Glue crawler. This allows the crawler to assume the role and access the S3 bucket using the specified permissions.</li><li>Run the crawler: Start the crawler to begin the scanning and cataloging process. The crawler will analyze the data in the specified S3 bucket and subfolder, infer the schema, and populate the Glue Data Catalog with the metadata.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*HSCMl_VPXKPd2dUdcct1dA.png" /></figure><p>Open your AWS Athena service and select the appropriate database. When creating your crawler, you will also have the option to create a database if one does not already exist.</p><p>Here is my final result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*e7lWSM6q2k8X6y4444gdIQ.png" /><figcaption>amazon Athena query editor</figcaption></figure><p>Now, it’s done. All you have to do is write sql queries ad run.</p><ul><li>my query</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*aPWxAp3nmpPj4UjhF851gg.png" /></figure><ul><li>The result</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*M1fgu0-48vTsrujdu5W_6g.png" /><figcaption>select query result on aws Athena</figcaption></figure><p>Kudos ….</p><p>You can find the Github link <a href="https://github.com/BlackRock2308/apache_airflow_pipeline_postgres_to_s3.git"><strong>here</strong></a></p><p>Thank you for reading my first articles. As a beginner, I may have made some mistakes, so please feel free to leave comments and suggestions. I would appreciate your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f61100efbe0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>