<?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 George Owino on Medium]]></title>
        <description><![CDATA[Stories by George Owino on Medium]]></description>
        <link>https://medium.com/@george_owino?source=rss-354bcb132fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Mm415LFO9buXEGWdSNMXng.jpeg</url>
            <title>Stories by George Owino on Medium</title>
            <link>https://medium.com/@george_owino?source=rss-354bcb132fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:11:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@george_owino/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[Sending Microsoft Exchange Email using Python (and Terraform)]]></title>
            <link>https://medium.com/@george_owino/sending-microsoft-exchange-email-using-python-and-terraform-dadaa5c3e72c?source=rss-354bcb132fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/dadaa5c3e72c</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[azure-app-registration]]></category>
            <category><![CDATA[microsoft-graph-api]]></category>
            <dc:creator><![CDATA[George Owino]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 10:33:05 GMT</pubDate>
            <atom:updated>2025-03-10T13:15:10.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*QOMQv_IDLbavQb_S9fcEQA.png" /><figcaption>Sending MS Exchange Emails from Python</figcaption></figure><p>The title of this post is deliberate in the sense that there are hundreds of posts out there about sending emails using Python. In fact, this is something you can achieve with just 5 lines of code and no extra library installed since the smtp library is a default python package. However, I ran into a scenario where I needed to automate emails from my corporate account after the execution of a scheduled job. The problem is, my Azure AD admin has enforced 2FA on our emails so that it’s not enough to just provide the email username and password to the smtp library. In other cases your admin might have disabled the SMTP AUTH protocol in your Exchange Online Organization. These two scenarios will raise an insufficient authentication error making it impossible to use the smtp library.</p><h4>App Registration and Microsoft Graph API</h4><p>In order to give a third party tool access to your Exchange account, you need to use the Microsoft Graph API. Simply put, MS Graph is a REST API with endpoints that give you access to data in Microsoft 365. Think about all the MS 365 tools and services that you interact with daily (Exchange Mail, AAD, SharePoint, Excel, Teams etc.) and the different ways you might want to programmatically model this interaction.</p><p>Before you can grant your app access to your Exchange account using Graph API, you have to set up App Registration. Essentially, you want to establish trust between your Python app and Microsoft identity platform which is what will perform identity and access management. To create app registration, you need to have an azure portal account in which you have write access. Search for app registration to create a new registration. Once you have created one, go to certificates and secrets submenu of the App to create a new client secret. Copy the client secret before existing that screen because that is the only time it will be shown to you in plain text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*ESCFfDxJouUBdc8oxNvmHw.png" /><figcaption>app registration client secret</figcaption></figure><p>For the app we are building to have access to a protected resource like email, the resource owner (you, in this case) needs to authorize it. There are two types of access scenarios you can opt for: delegated and app-only access.</p><ol><li>Delegated Access — With this type of access, you’re letting the application act on behalf of the user. The user, therefore, needs to login and grant the application delegated permissions, also referred to as scopes of access that the application has on the user’s account. This is the access type we will use for this app. For Azure AD admins, it’s worth noting that the application cannot access any resource or perform any activity that the signed in user has no access to.</li><li>App-only Access — In this case, the app can perform certain operations with no user signed in. This access is mostly meaningful when the data required cannot be limited to a single user.</li></ol><p>To set the delegated access scopes that the app will have on Graph API, go to API permissions submenu and add the following Delegated Permissions for Graph:</p><ul><li>IMAP.AccessAsUser.All</li><li>Mail.Send</li><li>POP.AccessAsUser.All</li><li>SMTP.Send</li><li>User.Read</li><li>offline_access — this will save the refresh token in the file 0365_tokent.txt (discussed later) so that you or people using your app don’t have to manually refresh the access token every hour.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Rt0-rONnsg230q1WqA-yeQ.png" /><figcaption>Microsoft Graph permission scopes required to send email</figcaption></figure><p>Now you need to get the access token that your app uses to identify itself to Microsoft identity platform. First add a redirect url by going to the Authentication submenu &gt; Add A Platform &gt; Web &gt; Redirect URIs and enter <a href="https://login.microsoftonline.com/common/oauth2/nativeclient">https://login.microsoftonline.com/common/oauth2/nativeclient</a> as the redirect uri.</p><p>We will not interact with MS Graph directly but instead use python’s o365 library which is a wrapper around the API. Install this library using your favourite package manager pip install o365. Then create a file with the following script and run it to obtain the access token. Replace the credentials with your app’s client id and the client secret you copied earlier. Follow the instructions by clicking on the link returned on your terminal.</p><pre>from O365 import Account<br><br>scopes =  [&quot;IMAP.AccessAsUser.All&quot;, &quot;POP.AccessAsUser.All&quot;, &quot;SMTP.Send&quot;, &quot;Mail.Send&quot;, &quot;offline_access&quot;]<br><br>account = Account(credentials=(&#39;client_id_of_azureapp&#39;, &#39;client_secret_of_azureapp&#39;))<br>result = account.authenticate(scopes=scopes)  # request a token for this scopes</pre><p>The script above will add a file called o365_token.txt to your project directory. This file contains the access token granted to the app by App Registration and the refresh token needed to refresh the access token. Now that we have granted our app access to Microsoft Identity platform, let’s actually send an email.</p><p>The script below is all you need to send an email from your Exchange account. For client_id you need to key in your app registration’s <em>client_id</em> which you will find in the app’s overview page. As you may have noticed, the intricacy of this process is not in the code itself (it’s barely 10 lines) but understanding how to use Microsoft Graph API and App Registration.</p><pre>from O365 import Account<br>from O365.utils.token import FileSystemTokenBackend<br><br><br>def send_email():<br>    tk = FileSystemTokenBackend(token_path=&quot;.&quot;, token_filename=&#39;o365_token.txt&#39;)<br>    credentials = (&#39;client_id&#39;))<br>    account = Account(credentials=credentials, auth_flow_type=&#39;public&#39;, token_backend=tk)<br>    m = account.new_message()<br>    m.to.add([&#39;someone@somewhere.com&#39;, &#39;another@somewhere.com&#39;])<br>    m.subject = &#39;Email Subject&#39;<br>    m.body = &quot;Insert email text here&quot;<br>    m.send()<br><br>send_email()<br></pre><h4>Automating Azure App Registration creation using Terraform</h4><p>If this post ended at this point it would succinctly cover the objective we set out to achieve, i.e. sending Exchange emails using Python. However, the process of creating app registration can be made even easier using Infrastructure as Code (IaC) concepts. Since this is a service created on Azure, the process can be automated using an IaC technology like Terraform.</p><p>If you’re not familiar with IaC or Terraform, you can think of it as a tool used to provision infrastructure components on the cloud. Terraform takes a declarative approach in that you only need to define the desired state of your infrastructure and it will figure out the steps needed to get to that state. This post is not about the fundamentals of Terraform so I will not delve deeper into it and instead focus on the process of provisioning an app registration service.</p><p>For this we need to use Terraform’s less known Azure Active Directory (azuread) provider as opposed to the popular azurerm provider. According to its official documentation, azuread is used to configure infrastructure in Azure AD using Microsoft Graph API.</p><p>First, we will create the App Registration. In a file called main.tf add the following piece of code.</p><pre>terraform {<br>  required_providers {<br>    azuread = {<br>      source  = &quot;hashicorp/azuread&quot;<br>      version = &quot;2.43.0&quot;<br>    }<br>  }<br>}<br><br># Define a data block to fetch the object_id from the currently signed Azure AD account<br>data &quot;azuread_client_config&quot; &quot;current&quot; {}<br><br><br>resource &quot;azuread_application&quot; &quot;app&quot; {<br>  display_name     = &quot;tf-app&quot;<br>  sign_in_audience = &quot;AzureADMultipleOrgs&quot;<br>  owners           = [data.azuread_client_config.current.object_id]<br><br>}<br><br>resource &quot;azuread_service_principal&quot; &quot;sp&quot; {<br>  application_id = azuread_application.app.application_id<br>}<br><br>output &quot;client_id&quot; {<br>  value = azuread_application.app.application_id<br>}</pre><p>In the code above, the required provider is set to azuread with version 2.4.3. We then define a data block which contains data for other resources that are already available on the Azure account. In this case, we are saving the object_id for the currently logged in user.</p><p>We need to define our first resource which is azuread application (App Registration). We give it a name and set the supported account types to multitenant (AzureADMultipleOrgs). The owner is set to the current signed user as previously defined in the data block. Add the second resource (service principal) which will be used to manage the App registration.</p><p>We define an output block which will return the generated client_id to the command line. Running terraform plan will give display the steps that terraform intends to take to achieve the desired stated defined in your infra file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*tr-QjsdSb87gon94EhpLNw.png" /><figcaption>Terraform plan output</figcaption></figure><p>Run terraform apply -auto-approve to create your resources. The auto-approve flag bypasses the need to confirm the changes. Below is the result of applying our configurations. Notice that that client_secret is displayed on the terminal. Copy this value since you need it in your python code that actually sends the email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*SkwB2yecABMOKzoPtZZ6mg.png" /></figure><p>Next, generate a client_secret by adding the following lines. Terraform knows, inherently, that client_secret is sensitive information so it will not, allow you to include it in output without marking it as sensitive. If you do not set sensitive to true, terraform plan and apply will fail.</p><pre>#Generate client secret<br>resource &quot;azuread_application_password&quot; &quot;secret&quot; {<br>  application_object_id = azuread_application.app.object_id<br>}<br><br>output &quot;client_id&quot; {<br>  value = azuread_application.app.application_id<br>}<br><br>output &quot;client_secret&quot; {<br>  value     = azuread_application_password.secret.value<br>  sensitive = true<br>}</pre><p>With this addition, terraform will read your current infrastructure’s state and know that the other resources are already in place so there is only one more addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mx_ozduD2I06d6eJhQDGzA.png" /></figure><p>Once you apply these changes, the client_secret will be generated but it will not be displayed on the terminal the same way that the client_id was. You have to explicitly run terraform output client_secret to have it displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*L8_OlvICBPODiGPIqbyKWw.png" /></figure><p>Finally, we need to add API permissions to App Registration. There is little documentation on how to go about this especially when retrieving permission ids. Yes, each permission has a uuid and that is the only way you can set it from terraform. Go to <a href="https://learn.microsoft.com/en-us/graph/permissions-reference">this link</a> that has Graph API permissions references. On that page, there is a curl command that you can run from within the browser, click on the ‘Try It’ prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*LLPDumpawoN9o1r3f6nFHg.png" /></figure><p>This will return a JSON with all the possible permission scopes for Graph. You can save this as a file for reference. For each permission that you need to set, search for it within this file and grab its id property. The JSON object defines three different permission types: appRoles, oauth2PermissionScopes, and resourceSpecificApplicationPermissions. All permissions within appRoles are of the resource_access ‘Role’ type and they require admin consent. Some of these permissions are also available under oauth2PermissionScopes and these do not require admin consent — if they are of User type. These scopes have resource_access ‘Scope’ type. Items in the final section are of resource_access ‘Resource type.</p><p>Let’s bring it all together. Within the azuread_application resource block, add the following property.</p><pre>resource azuread_application &quot;app&quot; {<br>  display_name     = &quot;tf-app&quot;<br>  sign_in_audience = &quot;AzureADMultipleOrgs&quot;<br>  owners           = [data.azuread_client_config.current.object_id]<br><br>  required_resource_access {<br>      resource_app_id = &quot;00000003-0000-0000-c000-000000000000&quot; # Microsoft Graph<br>  <br>      resource_access {<br>        id   = &quot;e1fe6dd8-ba31-4d61-89e7-88639da4683d&quot; # User.Read<br>        type = &quot;Scope&quot;<br>      }<br>  <br>      resource_access {<br>        id   = &quot;652390e4-393a-48de-9484-05f9b1212954&quot; # IMAP.AccessAsUser<br>        type = &quot;Scope&quot;<br>      }<br>  <br>      resource_access {<br>        id   = &quot;e383f46e-2787-4529-855e-0e479a3ffac0&quot; # Mail.Send<br>        type = &quot;Scope&quot;<br>      }<br>  <br>      resource_access {<br>        id   = &quot;d7b7f2d9-0f45-4ea1-9d42-e50810c06991&quot; # POP.AccessAsUser.All<br>        type = &quot;Scope&quot;<br>      }<br><br>      resource_access {<br>        id   = &quot;258f6531-6087-4cc4-bb90-092c5fb3ed3f&quot; # SMTP.Send<br>        type = &quot;Scope&quot;<br>      }<br>  <br>      resource_access {<br>        id   = &quot;7427e0e9-2fba-42fe-b0c0-848c9e6a8182&quot; # offline_access<br>        type = &quot;Scope&quot;<br>      }<br>  }<br>}<br></pre><p>We define the resource access required within the required_resource_access block and specify the API that we are granting these access. Each API has its unique app_id and in this case we’ve set the app_id for Graph API. For each access scope, we specify a resource_access block in which we define the permission id and the type of resource_access.</p><p>When you run terraform plan, you’ll notice that since we did not add any new resource, none will be added. We are only modifying an existing resource. Applying these changes will give you an Azure App with all the configurations that we had in the previous app that we created manually in the portal. More importantly, you can do this in one step by defining all your desired configurations then calling terraform apply. If you are no longer interested in using this App, you can simply delete it by running terraform destroy.</p><p>That covers the entire process of sending emails using Python from your Microsoft Exchange email account. The gist of it was learning how Microsoft Graph API and App Registration work then interacting with the API using Python’s o365 library. We also went over how to automate the process of provisioning the Azure App which comes in handy if this is something you need to do regularly.</p><p>Links</p><ol><li><a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/permissions-consent-overview?WT.mc_id=Portal-Microsoft_AAD_RegisteredApps">Overview of permissions and consent in the Microsoft identity platform — Microsoft Entra | Microsoft Learn</a></li></ol><p>2. <a href="https://learn.microsoft.com/en-us/graph/overview">https://learn.microsoft.com/en-us/graph/overview</a></p><p>3. <a href="https://pypi.org/project/O365/#account">https://pypi.org/project/O365/#account</a></p><p>3. <a href="https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application">https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dadaa5c3e72c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Airflow Architecture]]></title>
            <link>https://medium.com/@george_owino/airflows-architecture-and-concepts-68943fdb1f5e?source=rss-354bcb132fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/68943fdb1f5e</guid>
            <category><![CDATA[airflow-architecture]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[workflow-orchestration]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[George Owino]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 12:46:40 GMT</pubDate>
            <atom:updated>2023-09-01T14:04:52.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*lZr96VjAotJKoDJ5AE3Etg.png" /><figcaption>ELT orchestration using Airflow</figcaption></figure><p>As a data or machine learning engineer, you often need to automate complex data workflows that involve ETL/ELT tasks or ML model training pipelines. Before the advent of tools such as Airflow, NiFi, Dagster, and others in this space, workflows were previously scheduled using cronjobs. However, cronjobs lack the mechanisms for managing complex dependencies and fault tolerance; which is where Airflow comes in. Airflow was developed at Airbnb as a workflow orchestration tool primarily intended for scheduling tasks. It was then adopted by the Apache Foundation to make it an open-source project.<br>With Airflow, tasks are scheduled and executed by leveraging the concept of Directed Acyclic Graphs (DAG). When jobs are deployed this way, one can define dependencies between tasks, handle failures, and automate retries. This article goes over Airflow’s architecture which is essential to understand if you want to write efficient DAGs.</p><h3>Airflow Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*7rzIsSDKO3x9ZUZq.png" /><figcaption>Fig 1. Relationship between scheduler and executor in Airflow</figcaption></figure><p>1. <strong>Scheduler</strong><br>The scheduler is one of the three key components of Airflow and its role is to parse your Dag definitions and determine which tasks need to run and in what order.</p><p>2. <strong>Executor</strong><br>Even though it is the scheduler’s job to determine the tasks to be run and the conditions under which they should run, it is the Executor’s job to run the task. There are different types of executors that you can use including LocalExecutor, Celery, and Kubernetes. These all depend on the environment in which your Airflow project is deployed.</p><p><strong><em>a) LocalExecutor </em></strong>— should only be used for testing purposes in your environment and even then you will experience some challenges. For instance, when you have tasks with the same priority level, this executor will only process one task at a go whereas Celery and Kubernetes executors will know to parallelize the execution of multiple tasks with equal priorities.</p><p>b) <strong><em>CeleryExecutor</em></strong> — This executor is based on the celery project which is a distributed system used to run python processes. It works with a pool of independent workers and uses messages to delegate tasks. Here tasks are sent to a queue from which workers pull and run them. It is a quick low latency system where the workers live on continuously and do one task after another meaning there is no restart between tasks.</p><p>c) <strong><em>KubernetesExecutor</em></strong> — As the name suggests, this executor leverages the power of kubernetes to optimize resource consumption. It relies on a single pod which delegates tasks and resources dynamically. For each task that needs to run, the executor calls to the Kubernetes API to launch a pod which will then terminate after the task completes. It thus takes a while to inject a pod into Kubernetes, allocation a pod to a node, spin up the pod and run the task inside it.</p><blockquote>Whereas one gets low latency with celery, they do not get isolation or security. On the other hand, kubernetes guarantees these two while sacrificing latency since pods have to restart between tasks.</blockquote><p>While the above diagram depicts the relationship between the scheduler and executor, it does not accurately capture the actual Airflow architecture. In real sense, the Executor is found inside the scheduler as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*m7C8XtmDputPH9sX.png" /><figcaption>Fig 2. Expanded architecture with all airflow components</figcaption></figure><p><strong>3. Workers</strong></p><p>In the expanded diagram, you notice that Celery takes a task and hands it over to a queue data store (think Redis, rabbitmq). Worker processes actively monitor the task queue and pull tasks from there which they execute depending on the priority and dependency definition. Workers perform the actual task execution by running the operator that defined the task. They then update the task status e.g. scheduled, running, succeeded, failed, up for retry et cetera.c</p><p>Since KubernetesExecutor does not queue tasks, the queue data store is not present in an architecture that uses it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*__UjyUc8jHk-2t-n.png" /><figcaption>Fig 3. Airflow architecture with k8s executor</figcaption></figure><p><strong>4. Metadata Database</strong></p><p>The metadata database is the single point of cordination in airflow as it plays a central role in the management and orchestration of workflows. Usually a relational database (think postgres, mysql, or sqlite), it stores all the metadata related to Airflow, including DAG definitions, task status, task logs, execution history, and configuration settings.</p><p>Notice how all the three components (data stores are in the light shade of green and components are in blue) i.e webserver, worker, and scheduler communicate with the metadata database. This design pattern uses row locking (i.e cannot read data that is being changed) to ensure that all the three components have a consistent view of the application.</p><h3>Airflow Concepts</h3><ol><li><strong>Directed Acyclic Graph</strong></li></ol><p>A DAG is a computational structure that depicts nodes connected by directed edges. The edges have a specific direction and there is no looping between nodes, hence acyclic. This means that if you start at a specific node and follow a directed edge, you can never land back at that node again. Airflow uses this concept to represent all the tasks in a workflow by defining the order in which they should be run. A DAG is, therefore, a container for tasks and the relationships between the tasks. DAGs are particularly useful for modeling workflows because they provide a clear visual representation of the sequence in which tasks need to be executed. This makes it easier to understand the order of operations and manage complex dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*cemsTPAdZppnwfeZ.png" /><figcaption>Fig 4. Directed Acyclic Graph</figcaption></figure><p>In Airflow, a Dag can be defined using the dag decorator or as a context manager with DAG class from airflow models.</p><pre># Creating a dag using the DAG context manager<br>from airflow import DAG<br>with DAG(<br>    dag_id = &quot;first_dag&quot;,<br>      default_args = default_args = {<br>      &#39;owner&#39;:&#39;dag_owner&#39;,<br>      &#39;retries&#39;:1,<br>      &#39;retry_delay&#39;: timedelta(seconds=30)<br>},<br>    description = &quot;the very first dag&quot;,<br>    start_date = datetime(2023, 8, 14, 2),<br>    schedule_interval = &#39;@daily&#39;<br>) as dag:<br> pass</pre><pre># Creating a dag using the taskflow API<br>from airflow.decorators import  dag<br>@dag(<br>    dag_id = &#39;dag_id&#39;,<br>    start_date=datetime(2023, 8, 17),<br>    schedule_interval = &#39;0 0 * * thu&#39;,<br>    default_args=default_args<br>)<br>def first_dag():<br> pass<br><br>first_dag()</pre><p><strong>2. Tasks</strong></p><p>A task is the most basic unit of work in Airflow. It defines an individual operation that needs to be performed in a DAG. Tasks are usually instantiated as instances of operators (these are defined later). Each task is associated with a unique task ID and belongs to a particular DAG, forming a part of the overall workflow. Tasks also define their execution dependencies, specifying which other tasks must successfully complete before they can be executed. This dependency management ensures that tasks are executed in the correct order, allowing for complex workflows with branching and parallelism.</p><pre># creating a task by instantiating an operator<br>from airflow import DAG<br>with DAG(<br>    dag_id = &quot;first_dag&quot;,<br>    default_args = default_args,<br>    description = &quot;the very first dag&quot;,<br>    start_date = datetime(2023, 8, 14, 2),<br>    schedule_interval = &#39;@daily&#39;<br>) as dag:<br>    task1 = BashOperator(<br>        task_id = &quot;first_task&quot;,<br>        bash_command = &quot;echo Hello world&quot;<br>    )</pre><p><strong>3. Operators and Sensors</strong></p><p>Operators are classes which are instantiated to create a task. They encapsulate the logic of how a unit of work should be processed such as running a Python script, executing a SQL query, moving files, or interacting with external systems. Examples of operators in airflow include BashOperator (used in the above task example), PostgresOperator, and PythonOperator. There are dozens of operators specific to different vendors and you can even build your own operators.</p><p>Sensors, on the other hand, are a special kind of operators that wait for an event. They particularly come in handy when building an event-driven system. Sensors check for a condition (e.g. file landing in file system data store) before the downstream tasks can execute. Sensors can be written in two modes:</p><p>a) <em>Poke</em> — the sensors occupies a worker slot for the entire execution time and sleeps in between pokes. This is the default mode and it’s only advisable to use if you expect that the condition you are checking for will be met within a short period of time.</p><p>b) <em>Reschedule</em> — if a condition has not been met, the sensor releases its worker slot and reschedules to check at a later time.</p><p><strong>4. Hooks</strong></p><p>When I started working with Airflow, I had a hard time understanding how hooks differed from operators. For me, the simplest way to separate these two concepts is that whereas operators encapsulate a specific activity we need to perform on or using a system, hooks simply provide a way to interact with them. That is, with hooks, it is not enough to connect to a system, you have to specify what it is you want to do on that environment.</p><p>More accurately, operators describe a logic unit of work while hooks abstract your interaction with external systems. To use a hook, you only to specify a connection id to the system (often set in airflow’s web UI).</p><p><strong>Conclusion</strong></p><p>There are other concepts that I have not covered in this article such as plugins, triggers, XCOM, and templates and macros. You can refer to the official airflow documentation or astronomer for these.<br>I wanted this article to be more about the architectural components of airflow and the concepts you need to understand to get going and less about code. Which is why I have also not provided code snippets for hooks and creating your operators. I will follow this up with an article in which we setup airflow in docker and develop an ETL pipeline for reading data from AWS s3 to postgres.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68943fdb1f5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting in Excel]]></title>
            <link>https://medium.com/@george_owino/time-series-forecasting-in-excel-dec8af210e9c?source=rss-354bcb132fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/dec8af210e9c</guid>
            <category><![CDATA[stock-forecasting]]></category>
            <category><![CDATA[scom]]></category>
            <category><![CDATA[excel-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[safaricom]]></category>
            <dc:creator><![CDATA[George Owino]]></dc:creator>
            <pubDate>Thu, 12 Aug 2021 16:57:18 GMT</pubDate>
            <atom:updated>2021-08-12T16:57:18.090Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most popular applications of data analytics is in financial markets. In this series of posts, we will be going through the different applications of data analysis (and data science) in financial forecasting. While there are several tools for this kind of work, we will work with Excel and Python. Part 1 of this series focuses on data collection and exploratory data analysis using Excel. It then concludes with a primer on financial indicators and forecasting.</p><h3>Data Collection and Preparation</h3><p>This post does not delve deep into the entire scope of data collection as that would require an entire series on its own. Instead, it will only focus on collecting financial data — specifically for Kenyan companies. The task at hand will be to forecast the share price of Safaricom for the last two quarters of 2021. Usually, getting the kind of data we need here (ohlcv data) is a painless process because there are nearly hundreds of data portals including Nasdaq, Yahoo Finance, Google Finance API, WSJ, and MarketWatch. But for local markets, this is not the case. You have to pay some amount to get this kind of information from the Nairobi Securities Exchange website (<a href="http://www.nse.co.ke/">http://www.nse.co.ke/</a>). On the other hand, only a few of the data aggregation portals mentioned above have data for other markets, especially in developing economies. WSJ has the most complete data where you can customize your start and end dates. You can download the dataset from WSJ by following <a href="https://www.wsj.com/market-data/quotes/KE/XNAI/SCOM/historical-prices"><em>this link</em></a> and setting the start date as 01/01/2019 and end date as <strong>30/06/2021</strong> (if you want to have the exact results in this post) or any other date (if you are reading this far past the date of posting). Below is an overview of what you would expect from the downloaded dataset.</p><p>OHLCV refers to:</p><p>1. Open — the price at which the share open that day</p><p>2. High — the highest price it sold for on that day</p><p>3. Low — its lowest price</p><p>4. Close — the closing price</p><p>5. Volume — the amount of shares that were traded on that day.</p><p>These are the columns (or attributes) for our data. In addition to the date on which the stock trade at that particular price, we will only use the closing price for our analysis and forecast. Therefore, the first thing we need to do is get rid of the other columns.</p><p>You’ll only have two columns left: The Date column and Close which gets shifted to Column B. WSJ provides the data with the most recent stock price going back. We need to sort it the other way. To do so, you need to select column A (click right above the column) and go to Sort and Filter. Select Sort Oldest to Newest. It will give you a prompt like below. This prompt is essentially asking whether the sort should also affect the next column. The default value is yes so press Enter. Ignore the chart you see to the right.</p><p><strong>Time Series Analysis.</strong></p><p>What we are doing here is known as a time series analysis. We have a variable that is observed over a certain successive period and is recorded nearly daily, except for weekends and public holidays when trading is closed. The end goal is to identify any long-term and seasonal trends with Safaricom’s share price. We have data from the beginning of 2019 to June 2021 (30 months or ten quarters) and we are trying to predict what it will look like 6 months from now.</p><p>First, we will group our periods into years, quarters, and months. In Cell C1, enter a new column title and name it Year. On cell C2, enter a new formula, <strong>=YEAR(A2).</strong> We are extracting the year from the date in the corresponding cell in column A. On Column D, input the new column header as Quarter. Then insert the formula, <strong><em>=</em> “Q”&amp;ROUNDUP(MONTH(A2)/3,0), </strong>in cell D2 and once again flash fill. This formula does two things: date and text manipulation. First, we are extracting the month number from the date in cell A2 then dividing that number by 3 because a quarter is 3 months. After that, we’re rounding that quotient to zero decimal place. Finally, we concatenate the result of that operation to the letter Q which stands for quarter. For instance, the date on cell A2 is 2nd January, 2019. The MONTH function returns 1 which divided by 3 is 0.333. When we round that up to no decimal place we get 1 which is then appended to Q to give Q1. With that done, move to column E where we will extract the month name using the formula <strong>TEXT(A2, “mmmm”)</strong>. Flash fill these formulas in their corresponding columns to the end of the dataset on row 627. If any of these formulas seem strange or complicated to you, we have a course that covers some of the basic to intermediate excel utilities (including the date and text manipulation functions used here) for just $20. Click here to go to the course page.</p><p>With the years, quarters and months extracted, the data is not visually appealing since there is a lot of repetition. More importantly, there is a programming necessity for having these cells merged. While we can use merge and center to do this, it would take long to achieve this since we have three columns each with hundreds of data. We will merge and center these cells using VBA code. Hit the <strong>ALT + F11 </strong>key combinations to open the MS Visual Basic for Applications window. Then select Insert &gt; Module as in the screenshot below.</p><p>In the new console window, insert the following code:</p><blockquote>Sub MergeSameCell()</blockquote><blockquote>‘Updateby Extendoffice</blockquote><blockquote>Dim Rng As Range, xCell As Range</blockquote><blockquote>Dim xRows As Integer</blockquote><blockquote>xTitleId = “KutoolsforExcel”</blockquote><blockquote>Set WorkRng = Application.Selection</blockquote><blockquote>Set WorkRng = Application.InputBox(“Range”, xTitleId, WorkRng.Address, Type:=8)</blockquote><blockquote>Application.ScreenUpdating = False</blockquote><blockquote>Application.DisplayAlerts = False</blockquote><blockquote>xRows = WorkRng.Rows.Count</blockquote><blockquote>For Each Rng In WorkRng.Columns</blockquote><blockquote>For i = 1 To xRows — 1</blockquote><blockquote>For j = i + 1 To xRows</blockquote><blockquote>If Rng.Cells(i, 1).Value &lt;&gt; Rng.Cells(j, 1).Value Then</blockquote><blockquote>Exit For</blockquote><blockquote>End If</blockquote><blockquote>Next</blockquote><blockquote>WorkRng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j — 1, 1)).Merge</blockquote><blockquote>i = j — 1</blockquote><blockquote>Next</blockquote><blockquote>Next</blockquote><blockquote>Application.DisplayAlerts = True</blockquote><blockquote>Application.ScreenUpdating = True</blockquote><blockquote>End Sub</blockquote><p>This article is not about VBA programming so I will not delve into what the above code does. All you need to know is that it merges all the cells with similar data given a range. To run it, hit F5; it will prompt you for a range. Select all the three columns that we just added: Year, Quarter, and Month. Once you hit Enter, your excel should look like below.</p><p><strong>Moving Averages</strong></p><p>A moving average (MA) is one of the basic stock indicators commonly used by financial analysts and traders for technical analysis. In its simplest form, a moving average subdivides a data points into subsets and calculates the averages of these subsets. The point of obtaining these averages is to smoothen out the data and make it less responsive to temporary price fluctuations. The price of a stock often experiences random variations (some of which might end up being outliers). When correctly utilized, MAs reduce the noise in the variations and reveal underlying seasonal and annual trends. Although the commonly used number of days for calculating the mean is 200 and 50, this is very much an arbitrary choice that depends on what you want to achieve. In our case, we have data spanning 30 months recorded every trading day (626 data points in total). This is a rather small dataset for illustrative purposes only and we will thus use 15 days to get the moving averages.</p><p>There are two types of moving averages: Exponential (EMA) moving averages and Simple MA (SMA), which is what is used in this article. I have attached an article in the reference page where you can read further on how MA is used for technical analysis.</p><p>In our dataset, the first 15 days begin from 2nd January and end on 22nd January, 2019 (or rows 2 to 16). The next 15 days data point start on 3rd and end on the 23rd. Fundamentally, to get our subsequent datapoints, we remove the first day from the current subset and add the next day after the subset. So the first three datapoints are as follows:</p><p>Rows 2 to 16,</p><p>Rows 3 to 17, and</p><p>Rows 4 to 18.</p><p>On a new column, enter the title as SMA (15) to mean simple moving average over 15 days. When we’re calculating the moving average, we want to put the result on the last day of the subset, which is row 16 for the first subset. We could calculate the averages manually by using the excel average function or use the data analysis toolpak’s moving average. The Data Analysis Toolpak must be enable for you to use it. Once you’ve selected the moving average option, you need to select the range, interval, and output. The range is our entire <strong><em>close</em></strong> column, interval is 15, and for output select the first cell of the SMA column, F2. Do not select chart output or standard errors. There will be NAs for the first 14 values because there are not enough previous data points. Delete the cells with N/As to have a clean sheet. If you select any of the cells in the SMA column, you’ll find they are also using the AVERAGE function.</p><p><strong>Data Analysis.</strong></p><p>The first thing we want to do is have an overall view of the closing price over the duration. For this, we need to use a line chart. First, shift the close column to be the second last so that our period columns or independent variables (Date, Year, Quarter, Month) are stacked together and our dependent values (Close and SMA) are on the other side. You can do this by cutting the whole column B and pasting it before column F. Your columns now look like this:</p><p>Go to Insert menu and in the Charts group select line. If excel has automatically populated your chart with some values clear those out by using the Chart Design tab group (towards the end of the menu bar) and clicking Select Data. In the pop up, remove every value from both horizontal axis and legend entry tabs. Then click add on the left tab (Legend Entries Series) and select the close price values, i.e, cells E2 to E627. For the horizontal axis, we need to visualize the yearly, quarterly and monthly trends so select these tabs, i.e. cells B2 to D626. Once done, your data source needs to look like the screenshot below. The chart data range selects all the values for both horizontal and vertical axes.</p><p>Once you have a chart output, right click on the vertical axis and change the minimum value from 0.0 to 15.0 to enhance the trend output.</p><p>Some optional modifications that I have made to my chart are as follows:</p><p>i) I have copied it into a new sheet so as to scale it out.</p><p>ii) The chart style is set to 7. I like this style because it also enhances the trends we are trying to visualize. Here is the final output.</p><p>Using data that includes 2020 performance was a risky choice, particularly for an illustrative work. That was an abnormal year for most companies and abnormalities lead to outliers. However, as a data analyst or scientist, you will never have perfect data. We all wish we do but that is never the case. There’s a long running joke that 90% of data science work is data cleaning and preprocessing. It is not a joke.</p><p>There are some subtle observations to be made from just the times series plot of the close price but I will choose to do this with the MA plot. Once again click on Select Data and add the MA column to the Legend series as we did Closing Price. Your data source should now look like this:</p><p>Whereas the chart output looks like this:</p><p><em>(part 2 of this article continues </em><strong><em>here)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dec8af210e9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>