<?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 Oluwatobi Ojo on Medium]]></title>
        <description><![CDATA[Stories by Oluwatobi Ojo on Medium]]></description>
        <link>https://medium.com/@oluwatobi_ojo?source=rss-78729eb91c2d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vA-vpeqWQ7MceALP9xhGvQ.jpeg</url>
            <title>Stories by Oluwatobi Ojo on Medium</title>
            <link>https://medium.com/@oluwatobi_ojo?source=rss-78729eb91c2d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:17:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oluwatobi_ojo/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[Building a Crypto Market ELT Pipeline Using Docker, Python, PostgreSQL, dbt, and Looker Studio]]></title>
            <link>https://medium.com/@oluwatobi_ojo/building-a-crypto-market-elt-pipeline-using-docker-python-postgresql-dbt-and-looker-studio-8d7281dea8d2?source=rss-78729eb91c2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7281dea8d2</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[elt-pipeline]]></category>
            <dc:creator><![CDATA[Oluwatobi Ojo]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 22:43:28 GMT</pubDate>
            <atom:updated>2025-10-13T22:43:28.152Z</atom:updated>
            <content:encoded><![CDATA[<p>This project demonstrates how to design and deploy an end-to-end <strong>ELT (Extract, Load, Transform)</strong> pipeline for cryptocurrency market data using modern data tools like <strong>Python</strong>, <strong>PostgreSQL</strong>, <strong>dbt</strong>, <strong>Docker</strong>, and <strong>Looker Studio</strong>.</p><p>The goal is to create a reproducible data pipeline that automatically collects daily cryptocurrency data from the CoinGecko API, stores it in a warehouse, transforms it into analytical datasets, and visualizes key insights through dashboards.</p><h3>Project Overview</h3><h4>Objective</h4><p>To build a reliable, automated data pipeline that tracks daily price and market movements of major cryptocurrencies, enabling analysis of trends such as volatility and rankings over time.</p><h4>Architecture Summary</h4><p>The solution is structured around three main stages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c33e6a6fff5f0fbca65d19eca876c55/href">https://medium.com/media/5c33e6a6fff5f0fbca65d19eca876c55/href</a></iframe><h3>Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgeypNKzlwsjbyA37bK8vw.png" /></figure><h3>Components</h3><h4>a. Python (Extract &amp; Load)</h4><p>A Python script retrieves data from the <strong>CoinGecko API</strong> and loads it into PostgreSQL.<br> The script is responsible for:</p><ul><li>Fetching live data for major cryptocurrencies (top 750)</li><li>Structuring it into a consistent schema</li><li>Loading it into the warehouse (source_crypto_market_data table)</li></ul><p>Acts as both the <strong>data warehouse</strong> and the <strong>staging area</strong>.</p><ul><li>Raw API data is stored in dedicated tables.</li><li>dbt then builds transformed models on top.</li></ul><h4>c. dbt (Transform)</h4><p>dbt manages the transformation process, generating analytical datasets such as:</p><ul><li><strong>latest_snapshot</strong>: Most recent coin data</li><li><strong>top_20_coins</strong>: Top coins by market cap</li><li><strong>volatility_analysis</strong>: Daily price movement metrics</li></ul><h4>d. Looker Studio (Visualization)</h4><p>The transformed tables are connected to Looker Studio for analysis and reporting. Dashboards display:</p><ul><li>Top coin rankings</li><li>Historical price change trends</li><li>Volatility comparisons across assets</li></ul><h3>Repository Structure</h3><pre>ELT_Pipeline_with_Docker/<br>│<br>├── python_app/<br>│   ├── main.py               # Extract &amp; Load script<br>│   ├── requirements.txt      # Python dependencies<br>│<br>├── dbt_project/<br>│   ├── models/               # dbt models and transformations<br>│   ├── profiles.yml          # dbt profile configuration<br>│<br>├── docker-compose.yml        # Container definitions<br>├── .env                      # Environment variables (e.g., DB credentials)<br>└── README.md</pre><h3>Running the Project</h3><h4>Prerequisites</h4><ul><li>Docker and Docker Compose installed</li><li>A valid CoinGecko API endpoint (no API key required)</li></ul><h4>Steps</h4><ul><li><strong>Clone the repository</strong></li></ul><pre>git clone https://github.com/Ojosticka/ELT_Pipeline_with_Docker.git<br>cd ELT_Pipeline_with_Docker</pre><ul><li><strong>Configure environment variables</strong><br> Update the .env file with PostgreSQL credentials, database name, and any other parameters like below</li></ul><pre># Database credentials<br><br>POSTGRES_USER=******<br>POSTGRES_PASSWORD=******<br>POSTGRES_DB=*****<br><br># Database connection details for Python and dbt<br>DB_HOST=******<br>DB_PORT=5432<br>DB_NAME=*****<br>DB_USER=*******<br>DB_PASSWORD=******</pre><ul><li><strong>Build and run the containers</strong></li></ul><pre>docker compose up --build</pre><p>This will spin up the following services:</p><p>python_app: Extracts and loads data into Postgres</p><p>postgres: Stores all data</p><p>dbt: Transforms data into final models</p><ul><li><strong>Access the database</strong><br> Once running, connect to Postgres using any client (e.g., DBeaver or pgAdmin):</li></ul><pre>host: localhost  <br>port: 5433 <br>user: your_username<br>password: your_password  <br>database: your_db_name</pre><ul><li><strong>Connect Looker Studio</strong><br> Add PostgreSQL as a data source, and explore the transformed tables to create dashboards.</li><li><strong>Scheduling the Pipeline</strong></li></ul><p>To automate daily runs, you can schedule the Docker command via <strong>cron</strong> or any scheduler:</p><pre>0 9 * * * cd /path/to/ELT_Pipeline_with_Docker &amp;&amp; docker compose up --build</pre><ul><li><strong>Key Outcomes</strong></li></ul><p>At the end of each run, the pipeline generates:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f15161036cdf1aec7f47f64632319cea/href">https://medium.com/media/f15161036cdf1aec7f47f64632319cea/href</a></iframe><p>These can be directly visualized or integrated into downstream analytical tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7281dea8d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker to a 5 year old]]></title>
            <link>https://medium.com/@oluwatobi_ojo/docker-to-a-5-year-old-f458055312d3?source=rss-78729eb91c2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f458055312d3</guid>
            <category><![CDATA[docker-basic]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Oluwatobi Ojo]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 22:57:45 GMT</pubDate>
            <atom:updated>2025-09-19T22:57:45.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Docker: Lagos-to-Abuja Jollof Problem</h3><p>Imagine you run a small restaurant in Lagos, and your jollof rice is so good that everyone in town loves it. Now, someone in Abuja orders the same jollof. You send your recipe, but when they cook it there, it doesn’t taste the same.</p><p>Why?</p><ul><li>The Abuja chef added extra pepper “based on vibes.”</li><li>The type of rice used was different.</li><li>The cooking gas was on lower heat than in Lagos.</li></ul><p>Result: your Abuja customers complain, saying <strong>“this is not the same jollof we used to have in Lagos!”</strong></p><p>This is a very common problem in tech — an app works fine on one developer’s laptop but fails on someone else’s laptop or on the company’s server because their setup (software versions, libraries, configurations) is different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*qSYu_QkwrxgyVhO7X-omQQ.png" /></figure><h3>How Docker Solves This</h3><p>Docker says:</p><p><em>“Instead of just sharing the recipe and hoping Abuja cooks it the same way, let’s package </em><strong><em>everything</em></strong><em> — the rice, tomatoes, seasoning, gas cooker, pot, even the cooking temperature — into a sealed box. Anyone who opens the box anywhere in the world will get the </em><strong><em>exact same jollof rice</em></strong><em> every time.”</em></p><blockquote>That’s exactly what Docker does for apps — it makes sure they run the same way everywhere.</blockquote><p><strong>Key Concepts Made Simple</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc4277d31950b64bfc6728d420a630d/href">https://medium.com/media/3fc4277d31950b64bfc6728d420a630d/href</a></iframe><h3>Why It’s a Game-Changer</h3><ul><li><strong>No Surprises:</strong> The app works the same everywhere, no more “it worked on my laptop!” excuses.</li><li><strong>Time-Saving:</strong> You don’t need to set up the environment from scratch each time.</li><li><strong>Portable:</strong> You can ship your app anywhere even to the cloud and it will behave exactly the same.</li></ul><p>For better understanding of Docker basics, I’d advice you go through this youtube video from Tech with Nana.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fpg19Z8LL06w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dpg19Z8LL06w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fpg19Z8LL06w%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/db087b0b4fbcd8cfa2891d520303771e/href">https://medium.com/media/db087b0b4fbcd8cfa2891d520303771e/href</a></iframe><p>Hope this helps, and see you on the next article, cheers 🥂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f458055312d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Article — Uncovering Negative Balance Patterns in SQL]]></title>
            <link>https://medium.com/@oluwatobi_ojo/my-first-article-uncovering-negative-balance-patterns-in-sql-5df1f1bc0d45?source=rss-78729eb91c2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5df1f1bc0d45</guid>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Oluwatobi Ojo]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 00:16:39 GMT</pubDate>
            <atom:updated>2025-04-02T07:26:46.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>My First Article — Uncovering Negative Balance Patterns in SQL</h3><p>Hey there, first off, thanks for making it this far into my first Medium article, you are the real MVP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wiNBpQFEr-EpY_kN" /><figcaption>Photo by <a href="https://unsplash.com/@wesleyphotography?utm_source=medium&amp;utm_medium=referral">Wesley Tingey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re wondering why I sound so excited, well, it’s because this marks the beginning of what I hope will be an exciting journey, one where I share challenges I face as a data professional, how I solve them, how I collaborate, my thought process, and, more importantly, a deep dive into analytics in the fintech space (Fun fact: I recently realized that many people have no idea what analytics does in Fintech. I used to be one of them, I’m probably still one😑)</p><p>So, if you work with data, like problem-solving, or just curious about how data makes the world of finance go round, you’re in the right place. Stick around because I plan to make this space insightful, engaging, and try to leave you learning a thing or two by the end of every article.</p><p>Now, let’s jump in! I’ll be breaking things down using a simple approach, the “what”, “why” and the “how”</p><ul><li><strong>What</strong> was the problem that needed solving?</li><li><strong>Why</strong> was it important? (Basically, what decisions did stakeholders need to make using this information?)</li><li><strong>How</strong> did I go about finding the solution?</li></ul><p>Let’s get into it! (In Fabrizio’s voice — here we go 🚀)</p><h3>What</h3><p>A stakeholder reached out, looking for visibility into accounts with a negative ledger balance. Specifically, they wanted to know:</p><ul><li>Which accounts currently have a negative balance?</li><li>How long have they remained in the negative?</li><li>When did they first go negative?</li></ul><p>To make this relatable, think back to when telcos introduced the “borrow airtime” feature. If you borrowed ₦500, your balance would show <strong>-500</strong> until you recharged. Now, imagine you didn’t recharge for weeks — that gap represents how long you’ve been in the negative. The day you first borrowed marks when you initially went negative. This same logic applies to account balances, to easily track transaction trends over time.</p><h3>Why</h3><p>Accounts with negative balances typically fall into two categories:</p><p><strong>Recently negative accounts</strong> — These accounts might recover if engaged proactively.</p><p><strong>Long-term negative accounts</strong> — These accounts may have churned, stopped using our services, or even pose a financial risk.</p><p>Why does this matter from a business standpoint? Here are key reasons:</p><ul><li><strong>Assessing Credit Risk</strong><br> If an account remains negative for an extended period, should we allow it to continue transacting at high volumes? Or should it be flagged for closer monitoring? Understanding this helps mitigate financial exposure.</li><li><strong>Detecting Fraud &amp; Chargebacks</strong><br> Accounts frequently going negative often have a history of chargebacks, potentially indicating fraudulent activity. Identifying these patterns early helps prevent losses.</li><li><strong>Understanding Customer Churn</strong><br> If an account was previously active but stopped transacting after going negative, there’s a chance they took their business elsewhere to avoid settling their balance. Recognizing this pattern enables the team to intervene before losing high-value customers.</li><li><strong>Identifying Linked Accounts</strong><br> Sometimes, users avoid paying off a negative balance by creating a new account. If we can link accounts belonging to the same owner, we might recover funds from another active account. Similar to the telco scenario , if MTN identified that I had multiple numbers, they could ensure my debt followed me across accounts.</li><li><strong>Spotting Patterns in Negative Balances</strong><br> Are accounts from specific industries — such as sports betting, loan sharks, buy now pay later, or gaming — more prone to negative balances? If so, should we revise onboarding criteria or renegotiate terms like rolling reserves based on risk exposure?</li></ul><h3>How</h3><p>Now, for the fun part — solving this with data.</p><p>The process starts with <strong>aligning with stakeholders</strong> to clarify what insights they need and the business decisions they want to drive, as earlier mentioned in the “what” and “why”. Once the requirements are clear, the next step is diving into the data:</p><ul><li>Identifying relevant tables and fields</li><li>Structuring the approach to track negative balances over time</li><li>Writing the query.</li></ul><h3>Focusing on the “How”</h3><h3>Identifying Relevant Tables</h3><ul><li><strong>Ledger Wallet Balance Table</strong></li></ul><p>To understand the structure, imagine a financial institution that allows customers to maintain multiple wallets for receiving payments. Each wallet can hold a different currency depending on the nature of the transactions.</p><p>For example, if I were a customer, I might have <strong>five wallets</strong> for different currencies — USD, GBP, EUR, NGN, and KES. However, in practice, I might only actively use my <strong>NGN wallet</strong> for day-to-day business transactions. While my transaction history would likely be concentrated in my NGN wallet, it’s also possible that I’d see activity across multiple wallets if I transacted in different currencies. I hope this context helps clarify the table structure below.</p><p>The <strong>Ledger Wallet Balance Table</strong> follows a standardized format, storing key financial details of each wallet. Below are the essential fields relevant to our analysis:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16735183e36a773aecf8c74674c8c8ba/href">https://medium.com/media/16735183e36a773aecf8c74674c8c8ba/href</a></iframe><ul><li><strong>Exchange Rate Table</strong></li></ul><p>This table stores a daily conversion rate from one currency to the other, basically helps in unifying reporting in the desired currency an organization wants to report in. See structure below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aff188ff3de5ef461675eae5cbaaa841/href">https://medium.com/media/aff188ff3de5ef461675eae5cbaaa841/href</a></iframe><ul><li><strong>Customer Table</strong></li></ul><p>The Customer Table serves as a centralized location for storing unique customer records, capturing essential details ranging from basic information to demographic attributes. Below is the table structure;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e836332a521650ffda44e0328e61ac1/href">https://medium.com/media/5e836332a521650ffda44e0328e61ac1/href</a></iframe><h3>Approach to Implementation</h3><p>Now that we have identified the tables required to solve this, I’ll walk through my thought process behind the solution before diving into the SQL code.</p><ul><li><strong>Identify the Last Transaction Per Wallet Daily</strong></li></ul><p>Since each customer can have multiple wallets, and transactions occur at different times, we need to determine the last transaction for every wallet daily, this helps us track the wallet balance at end of each day.</p><ul><li><strong>Aggregating the Customer’s Balance daily in USD</strong></li></ul><p>Since customers may hold wallets in different currencies, we need to convert all balances into a single currency (USD). Once this is done, we aggregate the balances daily on a customer level since this is the focus.</p><ul><li><strong>Identifying the Most Recent Balance and Its Status</strong></li></ul><p>Once we have the daily balances for each customer, we determine the most recent balance entry (i.e., the last day they had a transaction). A flag is also created to check whether the customer is currently negative.</p><ul><li><strong>Tracking the History of Negative Balances</strong></li></ul><p>If a customer has a negative balance, we check how long they have been in this state by calculate how many consecutive days they have remained negative.</p><ul><li><strong>Determining When a Customer First Turned Negative</strong></li></ul><p>We also add the first date the customer first fell into a negative balance.</p><ul><li><strong>Enriching the final output for stakeholders</strong></li></ul><p>To ensure the stakeholder has all necessary details to make informed decisions, we add some basic customer details as well and the final output looks like; customer id, customer name, compliance status, signed up date, last transaction date, day customer turned negative, last balance, recurring negative days.</p><h3><strong>SQL Code </strong>Implementation</h3><pre>-- Problem Statement<br>-- Kindly help figure out which customers currently have a negative ledger balance, how long have they been on it in days and the day they turned negative<br><br>-- wallet_cte helps identify the last activity done on a wallet each day which helps in getting current balance down the line<br>with wallet_cte as<br>(select customer_id, wallet_id, currency, balance, transaction_date, date(b.transaction_date) as date_reported,<br>     row_number() over (partition by customer_id, wallet_id, date(transaction_date) order by transaction_date desc) as recent_wallet_activity<br> from ledger_balances b<br> qualify recent_wallet_activity = 1<br> )<br><br>-- bal_cte calculates the ledger balance of a customer as at the last day a transaction occured on account<br>bal_cte as<br>(select b.customer_id, b.date_reported, <br>     sum(b.balance::float * r.rate) as balance_usd,<br>     max(b.date_reported) as cur_bal_date<br> from wallet_cte b<br> join (select * <br>       from exchange_rate<br>       where to_currency = &#39;USD&#39;) r on b.currency = r.from_currency and b.date_reported = r.date<br> group by b.customer_id, b.date_reported<br>),<br><br>-- cur_bal_cte identifies the record for the current balance of a customer and if that balance is negative or not<br>cur_bal_cte as<br>(select customer_id, date_reported, balance_usd,<br>    case when date_reported = cur_bal_date then &#39;Yes&#39; else &#39;No&#39; end as current_bal_check,<br>      case when (date_reported = cur_bal_date and balance_usd &lt; 0) then &#39;Yes&#39; else &#39;No&#39; end as neg_current_bal_check<br>from bal_cte<br> ),<br> <br>-- bal_check_cte helps identify all balances that are negative, and creates an index for each customer in decending order<br>bal_check_cte as<br>(select *, row_number() over (partition by customer_id order by report_date desc) as index_desc,<br>        case when balance_usd &lt; 0 then 1 else 0 end as negatives<br> from cur_bal_cte<br>)<br><br>-- recurring_bal_cte looks into if a customer has been having recurring negative balance and the difference in days to know how long<br>recurring_bal_cte as<br>(select *, sum(negatives) over (partition by customer_id order by index_desc rows between unbounded preceding and current row) as cum_sum_check,<br>     datediff(day, date_reported, lead(date_reported, 1, getdate()) over (partition by customer_id order by date_reported)) as days_between_customer_activity<br>from bal_check_cte <br>),<br><br>-- final_bal_cte identifies total recurring days of a customer being on negative balance and when a customer turned negative<br>final_bal_cte as<br>(select *, min(case when index_desc = cum_sum_check then date_reported else null end) over (partition by customer_id) as  day_customer_turned_negative,<br>     sum(case when index_desc = cum_sum_check then days_between_customer_activity else 0 end) over (partition by customer_code) as totalsum<br>from recurring_bal_cte<br> )<br><br>-- Share the necessary records for stakeholders<br>select f.customer_id, c.customer_name, c.compliance_status, c.signed_up_date, c.industry,<br>    date_reported as last_transacted_date, day_customer_turned_negative, balance_usd as last_balance,<br>    totalsum as recurring_negative_days<br>from finalcte f<br>join customers c on f.customer_id = c.id<br>where neg_current_bal_check = &#39;Yes&#39;</pre><p><strong>Walking through the code;</strong></p><p>Some pre-requisites to understanding this implementation would be basic to intermediate SQL, understanding CTEs, Subqueries and Window Functions (one of my best brief tutorials for window functions can be seen here by Alice Zhao — <a href="https://www.youtube.com/watch?v=rIcB4zMYMas">link</a>).</p><p>Going cte by cte;</p><pre>-- wallet_cte helps identify the last activity done on a wallet each day which helps in getting current balance down the line<br>with wallet_cte as<br>(select customer_id, wallet_id, currency, balance, transaction_date, date(b.transaction_date) as date_reported,<br>     row_number() over (partition by customer_id, wallet_id, date(transaction_date) order by transaction_date desc) as recent_wallet_activity<br> from ledger_balances b<br> qualify recent_wallet_activity = 1<br> )</pre><p>wallet_cte uses the row_number window function to capture the last transaction recorded on a customer&#39;s wallet each day. This ensures that for every day a transaction occurs, we retain the most recent balance for that wallet. The qualify function works similarly to having in group by queries, allowing one to filter results after applying a window function.</p><pre>-- bal_cte calculates the ledger balance of a customer as at the last day a transaction occured on account<br>bal_cte as<br>(select b.customer_id, b.date_reported, <br>     sum(b.balance::float * r.rate) as balance_usd,<br>     max(b.date_reported) as cur_bal_date<br> from wallet_cte b<br> join (select * <br>       from exchange_rate<br>       where to_currency = &#39;USD&#39;) r on b.currency = r.from_currency and b.date_reported = r.date<br> group by b.customer_id, b.date_reported<br>)</pre><p>bal_cte performs 3 key functions: it aggregates data at the customer level by transaction date, allowing us to determine the end-of-day balance for each customer. It standardizes reporting in USD by joining to the rates from the exchange rate table. It also identifies for each customer the most recent day the customer made a transaction.</p><pre>-- cur_bal_cte identifies the record for the current balance of a customer and if that balance is negative or not<br>cur_bal_cte as<br>(select customer_id, date_reported, balance_usd,<br>    case when date_reported = cur_bal_date then &#39;Yes&#39; else &#39;No&#39; end as current_bal_check,<br>      case when (date_reported = cur_bal_date and balance_usd &lt; 0) then &#39;Yes&#39; else &#39;No&#39; end as neg_current_bal_check<br>from bal_cte<br> )</pre><p>cur_bal_cte determines the most recent balance record for each customer, marking it as current_bal_check. If this recent balance is negative, it is flagged under neg_current_bal_check.</p><pre>-- bal_check_cte helps identify all balances that are negative, and creates an index for each customer in decending order<br>bal_check_cte as<br>(select *, row_number() over (partition by customer_id order by report_date desc) as index_desc,<br>        case when balance_usd &lt; 0 then 1 else 0 end as negatives<br> from cur_bal_cte<br>)</pre><p>bal_check_cte performs two key functions: it identifies all records with a negative balance, regardless of whether they represent the most recent balance. Additionally, it assigns an index to each record per customer in descending order of transaction dates using the index_desc window function. This indexing will be useful later in determining periods of consecutive negative balances for each customer.</p><pre>-- recurring_bal_cte looks into if a customer has been having recurring negative balance and the difference in days to know how long<br>recurring_bal_cte as<br>(select *, sum(negatives) over (partition by customer_id order by index_desc rows between unbounded preceding and current row) as cum_sum_check,<br>     datediff(day, date_reported, lead(date_reported, 1, getdate()) over (partition by customer_id order by date_reported)) as days_between_customer_activity<br>from bal_check_cte <br>)</pre><p>recurring_bal_cte performs some of the critical window functions tricks used in this code and I’ll try to break it down. First cum_sum_check</p><pre>sum(negatives) over (partition by customer_id order by index_desc rows between unbounded preceding and current row) as cum_sum_check</pre><p>sum(negatives) calculates the total count of negative balance occurrences, where negatives flags whether a balance is negative. partition by customer_id ensures the sum resets for each customer. order by index_desc rows between unbounded preceding and current row means the sum accumulates sequentially, capturing all previous values up to the current row. The final total is only reflected on the earliest recorded negative balance date for each customer. Recall the goal here is to determine concurrent negative balances for a customer. A sample table to bring home what this result would look like is seen below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aaae5ce47b0c74123d0220ca70248de/href">https://medium.com/media/1aaae5ce47b0c74123d0220ca70248de/href</a></iframe><p>Here you can see that if I would like to get total period a customer had their balance on negative, I can focus on only records where index_desc equals cum_sum_check.</p><pre>datediff(day, date_reported, lead(date_reported, 1, getdate()) over (partition by customer_id order by date_reported)) as days_between_customer_activity</pre><p>The goal here was to calculate the difference in days between each date_reported and the next one, which is why I used the LEAD function. I used GETDATE() as “next” for the latest record because a customer&#39;s last transaction day may not be on the current day. Our objective is to determine how long the balance has remained negative up to today, not just until the last transaction date.</p><pre>-- final_bal_cte identifies total recurring days of a customer being on negative balance and when a customer turned negative<br>final_bal_cte as<br>(select *, min(case when index_desc = cum_sum_check then date_reported else null end) over (partition by customer_id) as  day_customer_turned_negative,<br>     sum(case when index_desc = cum_sum_check then days_between_customer_activity else 0 end) over (partition by customer_code) as totalsum<br>from recurring_bal_cte<br> )</pre><p>final_bal_cte ties everything together, making sense of the previous steps. It does two key things:</p><ol><li>It identifies the first day a customer’s balance turned negative during a continuous negative period and populates that date across all related records using the day_customer_turned_negative window function.</li><li>It calculates the total number of days the customer remained in a negative balance, helping determine the duration of their negative status.</li></ol><pre>-- Share the necessary records for stakeholders<br>select f.customer_id, c.customer_name, c.compliance_status, c.signed_up_date, c.industry,<br>    date_reported as last_transacted_date, day_customer_turned_negative, balance_usd as last_balance,<br>    totalsum as recurring_negative_days<br>from finalcte f<br>join customers c on f.customer_id = c.id<br>where neg_current_bal_check = &#39;Yes&#39;</pre><p>This selects all relevant columns, including customer details that stakeholders might need. It filters the results to include only customers whose most recent balance is negative and ensures that only one record per customer is retained by applying the neg_current_bal_check = &#39;Yes&#39; filter.</p><p>We made it to the finish line, I’d love to say huge shoutout to you for sticking with me to the end. This is just the beginning of me sharing what I do, and there’s a lot more to come! As I mentioned earlier, I’ll be writing more, especially on analytics in the fintech space. So if you’re interested in learning more about this space, kindly follow me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6AE37nz-kgVn2hxjzIB2A.png" /></figure><p>Before we wrap up, here’s a quick one:</p><p>🔹 Got a different approach to solving this with SQL? I’d love to hear it, I’m always learning<br> 🔹 Think you’d prefer to do this on a different tool, maybe Python or Excel? share your solution, let’s review together<br> 🔹 Need clarity on any part of the code? Don’t hesitate to reach out — I’m happy to help.<br> 🔹 Found this useful and want to implement it but need guidance? feel free to reach out.<br> 🔹 Enjoyed this as much as I did writing it? please show some love with a like, clap, or comment — I’d really appreciate it!</p><p>Until next time, keep learning🫡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5df1f1bc0d45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>