<?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 Jihan Kamilah on Medium]]></title>
        <description><![CDATA[Stories by Jihan Kamilah on Medium]]></description>
        <link>https://medium.com/@jihankamilah?source=rss-cd3dfd31e5e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0f3E-qXZ9HjW5Fb6UL1EUw.jpeg</url>
            <title>Stories by Jihan Kamilah on Medium</title>
            <link>https://medium.com/@jihankamilah?source=rss-cd3dfd31e5e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:34:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jihankamilah/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[Beyond Dashboards: Testing Business Hypotheses Through KPI Trees & Diagnostic Analytics]]></title>
            <link>https://code.likeagirl.io/beyond-dashboards-testing-business-hypotheses-through-kpi-trees-diagnostic-analytics-c15b64897966?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c15b64897966</guid>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[growth-mindset]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 17:25:35 GMT</pubDate>
            <atom:updated>2026-06-25T17:25:35.698Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step investigation of customer experience using KPI decomposition, diagnostic analytics, and root cause thinking</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A26BcJUWEaQmLWx7RbHkeA.png" /><figcaption>Image Generated by Gemini AI</figcaption></figure><p>When I first started learning data analysis using Python, I thought the process was pretty simple, just download a dataset, open a Python IDE or notebook, run the df.head(), create a few charts, identify some insights, and summarize the findings. That workflow appeared in nearly every practice project I worked on, so I naturally assumed that’s what data analysts did.</p><p>As I’ve completed more projects, and most importantly, since I started working as a data analyst. I’ve found that companies aren’t actually asking for dashboards. Instead, they ask questions like:</p><blockquote>&quot;Why are customers complaining more often?&quot;</blockquote><blockquote>&quot;Why are delivery issues increasing?&quot;</blockquote><blockquote>&quot;Why are customer ratings getting worse?&quot;</blockquote><blockquote>&quot;What exactly is going wrong?&quot;</blockquote><p>To answer these questions, simply creating charts isn’t enough. It requires a deeper analysis of the data, identifying patterns, testing assumptions, and connecting those findings to real-world business problems.</p><p>That’s the mindset I want to adopt this time… hehehe..</p><h3>Starting with the Problem, Not the Data</h3><p>Right now, I’m working with the <a href="https://www.kaggle.com/datasets/prachi13/customer-analytics"><strong>Customer Analytics</strong></a> dataset from Kaggle. Like always, my first instinct was to open the dataset and start exploring it. This time, instead of writing a line of SQL queries or Python code, I decided to try something different.</p><p>I asked myself, <em>“If I were actually working as a data analyst at this company, what kind of problems would management ask me to solve?”</em></p><p>Not, Show me the distribution of customer ratings, Create five visualizations, or Build a dashboard.</p><p>More realistic would be…, <em>“Customers seem dissatisfied with their shopping experience. Could you look into what’s going on?”</em></p><h3>Dashboards Describe. Investigations Explain.</h3><p>Actually.. there’s nothing wrong with dashboards. They’re incredibly useful. Dashboards often just tell us what’s happening, but they don’t always explain why. And that’s exactly what I want to focus on in this project. Instead of compiling a collection of unrelated charts, I want each analysis to help answer a specific business question.</p><h3>So… Where Does My Investigation Begin?</h3><p>Yeahh here.. I was facing a business challenge. Management wasn’t asking me for a new dashboard. Nor were they asking for five Power BI visualizations or reports. Instead, they made a much more specific question:</p><blockquote><strong>“We’ve noticed that a surprisingly large proportion of orders are not being delivered on time. Could this operational issue be affecting our customers’ overall experience?”</strong></blockquote><p>Rather than making assumptions, these concerns can actually be verified with data. Before diving into explanations or visualizations, I want to verify the KPI itself.</p><p>This quick calculation gives us the percentage of late deliveries.</p><pre>late_rate = (<br>    df[&quot;Reached.on.Time_Y.N&quot;] == 1<br>).mean()<br><br>print(f&quot;Late Delivery Rate: {late_rate:.2%}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*chNQ5kijtLBG5FvL5pDANA.png" /></figure><p>I am now facing a real business problem, not just a feeling or an assumption, but measurable KPIs. This immediately shifts the perspective of my investigation. Instead of saying, <em>“Customers seem dissatisfied with their shopping experience.”</em></p><p>Now we can say:</p><blockquote><strong><em>“</em></strong>Early assessment of the KPIs indicates that approximately <strong>59.67% of orders were not delivered on time</strong>, causing concern about the potential continued impact on customer satisfaction and the overall customer experience.<strong><em>”</em></strong></blockquote><p>And that raises the next question,<em> “Is this operational issue actually affecting customer experience?”</em></p><p>Looking through the dataset, there isn’t a single column titled “Customer Experience Score.” Instead, customer experience must be inferred based on multiple indicators, such as Customer Rating, Customer Care Calls, Reached on Time, or Discount Offered.</p><p>These variables became the main focus of my investigation. But measuring these factors wasn’t enough to explain the issue. The next step was to understand <strong><em>whyy</em></strong><em> </em>this might be happening.</p><h3>From KPI to Hypothesis</h3><p>After calculating KPIs, I’m often tempted to jump straight into creating charts and calling the results <em>“insights”</em>. But this time, I want every analysis to start with a hypothesis.</p><p>Rather than trying to prove a single explanation, I want to explore various possibilities and let the data guide the investigation. Here’s what the research I have in mind looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCNJfcY_pQxrxZtTTkbrYQ.png" /><figcaption>Image Generated by Gemini AI</figcaption></figure><h3>Hypothesis 1. Delivery Performance May Affect Customer Experience</h3><p>My first hypothesis is probably the most intuitive one, hehehe. If customers receive their orders late, there is a reasonable expectation that they may have a poorer shopping experience, which could eventually be reflected in lower their ratings. But rather than assuming that’s the case, I want to let the data answer that question. So, the first diagnostic question is:</p><blockquote><strong>Do customers experiencing delayed deliveries tend to report lower customer ratings?</strong></blockquote><pre>rating_delivery = (<br>    df.groupby(&quot;Reached.on.Time_Y.N&quot;)<br>      .agg(<br>          avg_rating=(&quot;Customer_rating&quot;, &quot;mean&quot;),<br>          total_orders=(&quot;Customer_rating&quot;, &quot;count&quot;)<br>      )<br>)<br><br>rating_delivery</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*zJ5BLvHkBto186Geemr9Jg.png" /></figure><blockquote><em>I’m not trying to prove causality here. I just want to know if late deliveries are associated with worse customer ratings.</em></blockquote><p>Surprisingly, the results didn’t support my initial hypothesis at all! Customers with delayed deliveries reported an average rating of 3.01, while on-time customers reported 2.97. This “teeny-weeny” difference suggests no meaningful relationship between delivery timeliness and customer ratings. It completely challenges one of the most obvious business assumptions. Even tho roughly 59.67% of orders were delivered late, customers just don’t rate their experience differently based on delivery status alone. At this stage, delivery performance is definitely not the main driver of customer ratings.</p><p>Of course, that doesn’t mean my investigation is over. It actually makes me wonder, if delays are so common, <em>“why are they even happening in the first place?”</em></p><h4>H1.1 If Delivery Performance Matters… Why Are Deliveries Delayed?</h4><p>The previous analysis suggests that delayed deliveries may not directly explain customer ratings. But, the late delivery rate remains unusually high. So the next diagnostic question is, <em>“</em><strong><em>Which shipment mode experiences the highest proportion of delayed deliveries?”</em></strong></p><pre>shipment_delay.rename(<br>    columns={<br>        0: &quot;On Time&quot;,<br>        1: &quot;Late&quot;<br>    },<br>    inplace=True<br>)<br><br>shipment_delay</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*wV9BKSTa4u3sBCtgefmS-A.png" /></figure><p>Using proportions instead of raw counts makes it much easier to compare performance. Interestingly, the delay rates are almost identical across the board with Flight (60.16%), Ship (59.76%), and Road (58.81%). Since Flight is only slightly higher, the variation is way too small to blame a specific transportation mode. But honestly, ruling this out is still a huge clue for me. If one method had been a total disaster, it would be an obvious target to fix. Instead, this tells me the issue is much broader than the shipment mode itself, helping me eliminate one big suspect and shifting my focus to new questions.</p><h4>H1.2 Is Shipment Mode Really the Problem?</h4><p>Or is shipment mode simply reflecting operational inefficiencies occurring elsewhere in the fulfillment process?</p><p>One possible explanation is warehouse performance. To investigate this possibility, the next question is<em>, “</em><strong><em>Which warehouse contributes most to delayed deliveries?”</em></strong></p><pre>warehouse_delay = pd.crosstab(<br>    df[&quot;Warehouse_block&quot;],<br>    df[&quot;Reached.on.Time_Y.N&quot;],<br>    normalize=&quot;index&quot;<br>)<br><br>warehouse_delay</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*k9hKwcrSHJVTowV3sZGmmQ.png" /></figure><p>Once again, the same pattern shows up. Warehouse delay rates are almost identical, and even though Warehouse B has the highest late rate, the variation is too tiny to mean anything. So, I definitely can’t blame a specific warehouse for these late deliveries.</p><p>So, instead of pointing fingers at one bad warehouse, it clearly shows me that delays are distributed evenly throughout our whole fulfillment network.</p><p>At this point, I’ve officially scratched off two major suspects:</p><ul><li>Shipment mode isn’t driving the delays.</li><li>Warehouse location isn’t the culprit either.</li></ul><p>Even tho I haven’t found the root cause yet, eliminating these obvious operational guesses has successfully narrowed down my search space!</p><h3>Hypothesis 2. Customer Support May Reflects Service Quality</h3><p>Hmm yaa.. Shipping performance isn’t the only possible explanation. Another possibility is that customers who repeatedly contact customer service are experiencing unresolved issues during their shopping experience. If that assumption is true, customers with more customer care interactions should report lower ratings. This raises another diagnostic question, <strong><em>“Do customers making more customer care calls tend to report lower customer ratings?”</em></strong></p><pre>care_rating = (<br>    df.groupby(&quot;Customer_care_calls&quot;)<br>      .agg(<br>          avg_rating=(&quot;Customer_rating&quot;, &quot;mean&quot;),<br>          customers=(&quot;Customer_rating&quot;, &quot;count&quot;)<br>      )<br>)<br><br>care_rating</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*r5I2dgpeZpv7hxcn2ohbPA.png" /></figure><p>The results show that customer ratings remain remarkably flat, no matter how many times a customer calls support. Instead of a consistent decline, the scores just bounce around a tiny, narrow range between <strong>2.96</strong> and <strong>3.08</strong>.</p><p>This tells me that the number of customer care calls alone isn’t a red flag for customer dissatisfaction here. In other words, the spam-callers aren’t necessarily giving us terrible ratings. Of course, that doesn’t mean customer support is completely irrelevant. It just means the relationship isn’t as obvious as my initial thought.</p><h3>Hypothesis 3. Pricing Strategy May Be Masking Deeper Problems</h3><p>Finally, I also wanted to challenge another common business assumption.</p><p>Promotions are often used to stimulate purchases and improve customer engagement. However, discounts do not automatically improve customer experience. So.. another diagnostic question is, <strong><em>“Do customers receiving larger discounts still report poor customer ratings?”</em></strong></p><p>To make the analysis easier to interpret, discounts were grouped into three categories.</p><pre>df[&quot;discount_group&quot;] = pd.cut(<br>    df[&quot;Discount_offered&quot;],<br>    bins=[0,10,30,100],<br>    labels=[<br>        &quot;Low&quot;,<br>        &quot;Medium&quot;,<br>        &quot;High&quot;<br>    ]<br>)<br><br>discount_rating = (<br>    df.groupby(&quot;discount_group&quot;)<br>      .agg(<br>          avg_rating=(&quot;Customer_rating&quot;,&quot;mean&quot;),<br>          customers=(&quot;Customer_rating&quot;,&quot;count&quot;)<br>      )<br>)<br><br>discount_rating</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*eNwSHBwQ296Ac4W_NNpPfg.png" /></figure><p>The results show basically zero variation between the discount groups. Customer ratings remain almost identical no matter how big the discount is.</p><p>Surprisingly, the customer group getting massive discounts doesn’t look any happier than the others. This tells me that a discount strategy alone isn’t going to fix or explain the customer experience here.</p><h3>Hypothesis 4: Customer Loyalty May Influence Customer Experience</h3><p>After running all those operational hypotheses, I noticed something kinda frustrating but interesting. Delivery performance? Flat. Customer support calls? No pattern. Discounts? Identical ratings.</p><p>At that point, I started wondering… Hmm, what if this isn’t an operational issue at all? What if customer experience is driven by something purely behavioral? Like, customer loyalty?</p><p>My logic here is pretty simple here, customers who buy from us repeatedly are probably more used to our shopping process, shipping timelines, and overall quirks. So, my next question is, <em>“Do customers with more prior purchases actually give higher ratings?”</em></p><pre>df[&quot;loyalty_group&quot;] = pd.cut(<br>    df[&quot;Prior_purchases&quot;],<br>    bins=[0, 3, 6, 10],<br>    labels=[<br>        &quot;New&quot;,<br>        &quot;Returning&quot;,<br>        &quot;Loyal&quot;<br>    ]<br>)<br><br>loyalty_rating = (<br>    df.groupby(&quot;loyalty_group&quot;)<br>      .agg(<br>          avg_rating=(&quot;Customer_rating&quot;, &quot;mean&quot;),<br>          customers=(&quot;Customer_rating&quot;, &quot;count&quot;)<br>      )<br>)<br><br>loyalty_rating</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*DsBlTjsMEMzyg-7L2WfwuA.png" /></figure><p>At first glance, the numbers aren’t exactly mind-blowing. Me is definitely not expecting a scenario where loyal customers rate for a whole point higher than new ones.</p><p>But, hmm wait… a subtle pattern does crawl up! The average ratings gradually increase the more prior purchases a customer has. While the gaps are small, returning and loyal customers consistently report slightly better scores than first-time buyers.</p><p>Now, does this prove that loyalty <em>causes</em> satisfaction? Yeahh… Not really. This is possibly customer keep buying because they already liked us in the past, or maybe familiarity just sets more realistic expectations, so they don’t get disappointed as easily. Either way, this was one of the few hypotheses that actually showed a consistent directional trend across my whole analysis.</p><h3>Reality Check: Connecting the Dots (and Embracing the Flat Lines)</h3><p>After testing all those hypotheses, I sat back and looked at the bigger picture. To be honest, the results were a bit of a reality check. Delivery performance, customer support calls, and discount strategies all turned out to be completely flat lines that barely made a diff on customer ratings. The only real runner in this analysis was customer loyalty, which showed a small but positive trend.</p><p>In a textbook or a classroom project, I (maybe youu also hehehe) expect to find that one perfect, glaring root cause. But in the real world of data, sometimes the most valuable insight is realizing that the answer simply isn’t in the data you are currently tracking.</p><p>These flat relationships are telling me that we might be measuring our logistics and warehouse operations perfectly, but we are completely missing how customers actually feel. Customer experience isn’t just a byproduct of isolated operational metrics. Instead, it’s heavily shaped by behavioral and psychological context that lives outside this dataset, like product quality consistency, brand trust, or the frustrating gap between what marketing promised versus what reality delivered. At the end of the day, you can’t fix customer perception purely with faster trucks or bigger discounts.</p><h3>Business Recommendations</h3><ol><li><strong>Time to rethink how we measure customer experience.</strong> Current operational KPIs like delivery timeliness or support calls don’t capture the whole story. I highly recommend tracking the gap between expectation versus actual delivery perception, along with post-purchase satisfaction scores instead.</li><li><strong>Stop obsessing over logistics alone.</strong> Improving logistics or warehouse efficiency in isolation won’t automatically fix customer ratings. Operational tweaks should be treated as a bare minimum, not a magic fix for satisfaction.</li><li><strong>Investigate the missing drivers.</strong> For future analysis, we need to explore unobserved variables outside this dataset, such as product quality consistency, text-based review sentiment, and marketing-driven expectations.</li><li><strong>Strengthen customer lifecycle analysis.</strong> Since customer loyalty was the only metric showing a mild positive trend, it would be super useful to shift toward comparing first-time vs returning customer experiences and tracking satisfaction across repeat purchases.</li></ol><h3>Donee — (!!!)</h3><p>To explore my other projects, feel free to check out my <a href="https://medium.com/@jihankamilah"><strong>Medium</strong></a><strong> </strong>or <strong>GitHub</strong>. Stay tuned for more challenging projects~~</p><p><a href="https://github.com/jihanKamilah">jihanKamilah - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c15b64897966" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/beyond-dashboards-testing-business-hypotheses-through-kpi-trees-diagnostic-analytics-c15b64897966">Beyond Dashboards: Testing Business Hypotheses Through KPI Trees &amp; Diagnostic Analytics</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Is More Than Just Queries: How to Think Like a Data Analyst]]></title>
            <link>https://code.likeagirl.io/sql-is-more-than-just-queries-how-to-think-like-a-data-analyst-33c5c2d7baa8?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/33c5c2d7baa8</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 13:15:16 GMT</pubDate>
            <atom:updated>2026-06-04T13:15:16.835Z</atom:updated>
            <content:encoded><![CDATA[<h4>A beginner-friendly SQL journey through real problems. It covers JOIN, GROUP BY, window functions, and how we actually think with data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPEUmi0BFdahkYI1AZNLAw.png" /></figure><p>Early on, my learning as a data analyst was limited to Excel.</p><p>You know… just the basics like filtering rows, dragging formulas, and quickly creating pivot tables.</p><p>As the volume of data grew, everything started to slow down. Things got weirder and weirder. What used to be simple questions turned into complicated workarounds. Then suddenly, Excel just wasn’t enough anymore.</p><p>That’s when I started learning SQL for data analysis.</p><p>It felt simple. Just a single query… just at the beginning ;&gt;</p><pre>SELECT * FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4swBNKyX3dZ5MX-5F8Kuw.png" /></figure><p>And.. Boommm, a lot of data showed.</p><blockquote>But isn’t that just too much data to look at all at once?</blockquote><p>It became difficult for me to understand patterns and relations between variables, or even just to see what was wrong with the data.</p><h3>Where Did the Data Come From?</h3><p>Before jumping into the queries, fyi, I worked with a public <a href="https://www.kaggle.com/datasets/laibaanwer/superstore-sales-dataset"><strong>Superstore sales dataset</strong></a>. This contains transactional data like orders, customers, products, and sales performance. This dataset is ideal for practicing SQL in data analysis because it reflects real-world business questions. But here, I converted the original flat table into three relational tables named customers (add new variables customer_id, orders, and products). For this project, I’m using PostgreSQL for the querying.</p><p>When you follow along with my learning process, you don’t need to use the same dataset as I did. More important is how we approach the business problems here that need to be solved.</p><h3>It Started with a “SELECT”</h3><p>My first task actually seemed easy.</p><blockquote><strong>Can you get all orders from January?</strong></blockquote><pre>SELECT *<br>FROM order<br>WHERE order_date &gt;= &#39;2013-01-01&#39;<br> AND order_date &lt; &#39;2013-02-01&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLCv7Fs1BS8fWCzjtaMojQ.png" /></figure><p>As data analysts, we’re often asked to provide monthly sales details. In this case, our store has 709 sales records for January 2013.</p><p>When there is a lot of data, it can take a long time, so your boss might ask questions like<em>“Why is this query taking so long?”.</em></p><p>I found out something new, SELECT * isn’t always a solution. And, avoid using unnecessary columns, so the database doesn’t have to read and send as much data, which can make queries run quicker.</p><p>So I changed it:</p><pre>SELECT order_id, order_date, sales<br>FROM orders<br>WHERE order_date &gt;= &#39;2013-01-01&#39;<br> AND order_date &lt; &#39;2013-02-01&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*L-sz1KVHGjqlbNuEi4-8JA.png" /></figure><p>Same data, less load, and faster. As you can see, the query time went from 0.218 seconds to 0.166 seconds. It might not seem like a huge difference here, but imagine if we started with millions of records and needed to display thousands of them.</p><p>Because now, the database reads fewer columns (less disk I/O). And i felt like <em>“Owhhh… I get it now, it makes my work more efficient.”</em></p><h3>Then They Asked for “Just a Summary.”</h3><blockquote><strong>“Can you total the sales per month in 2014?”</strong></blockquote><p>Sounds normal, doesn’t it?</p><pre>SELECT <br>    DATE_TRUNC(&#39;month&#39;, order_date) AS month,<br>    SUM(sales) AS total_sales<br>FROM orders<br>WHERE year = 2014<br>GROUP BY 1<br>ORDER BY 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*Vflt0OINBuQmvT0PmRG9QQ.png" /></figure><p>When I first started learning SQL, I and maybe you too (right now hehe) might be a little confuse about <strong>what exactly </strong><strong>DATE_TRUNCdoes?</strong></p><p>It turns out it’s quite simple. Instead of storing the full date (like 2023-01-15), the DATE_TRUNC(&#39;month&#39;, order_date) function will truncate it to just the month, like for example, if a sale was made on <strong><em>2014-01-15 </em></strong>it will be converted to the start of the month<strong><em>2014-01-01 </em></strong>to keep things clear and the format easy to read.</p><p>So now, all dates in January become the same value. Which means… SQL can group them together. And that’s exactly why GROUP BY works here and then adds them up by using SUM(sales) . Instead of raw transactions, we now receive <strong><em>total sales per month for 2014</em></strong><em>.</em></p><h3>Then the Data Started Looks Weird</h3><p>Next request.</p><blockquote><strong>“Can you include customer names?”</strong></blockquote><pre>SELECT <br>    o.order_id,<br>    o.order_date,<br>    o.sales,<br>    c.customer_name,<br>    c.segment,<br> c.country<br>FROM orders o<br>JOIN customers c<br>ON o.customer_id = c.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_2QdoBBgMp3wml0hMj42g.png" /></figure><p>We’re just combining two tables:</p><ul><li>orders → transactional data</li><li>customers → customer details</li></ul><p>And the JOIN condition o.customer_id = c.customer_id. Basically tells SQL <em>“Match each order with its customer id”.</em></p><p>But <em>“Why are the numbers duplicated?”</em></p><p>Because <strong>JOIN in SQL</strong><em>, it doesn’t just “add columns to” but </em><strong><em>combines rows</em></strong><em>. </em>So if the join condition isn’t perfectly aligned, you might accidentally multiply rows.</p><p>And that means duplicate data, inflated totals, and… completely misleading insights. However, since our context here is only displaying orders by customer name, it’s safe because we need the details regardless of how many transactions that customer has. It would be a different story if we had to display total sales (because if we’re not careful, the data will just keep getting added over and over).</p><h3>Then Came the Hard Question</h3><blockquote><strong>“What’s the top-selling product each month?”</strong></blockquote><p>Okay… this one will be tricky. My first instinct is</p><pre>SELECT <br>    DATE_TRUNC(&#39;month&#39;, order_date) AS month,<br>    product_id,<br>    MAX(sales)<br>FROM orders<br>GROUP BY 1, product_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*8iIXobkhEJzhsvjl5Ikatg.png" /></figure><p>It <em>looks</em> right. But it’s actually not. Let’s break it down:</p><ul><li>GROUP BY month, product_id→ groups data per product per month</li><li>MAX(sales)→ gives the highest transaction value for each product</li></ul><p>So what we actually get is <strong><em>the max sale per product</em></strong><em>. </em>Not <em>the top product per month.</em></p><p>And honestly, this is one of those moments where I go like <em>“Hmmm wait… why is this wrong?”</em></p><h3>This time for “Window Functions”</h3><p>This is where I discovered that one of the most powerful tools in SQL for data analysis is <strong>window functions</strong>.</p><pre>SELECT *<br>FROM (<br>    SELECT <br>        DATE_TRUNC(&#39;month&#39;, order_date) AS month,<br>        product_id,<br>        SUM(sales) AS total_sales,<br>        ROW_NUMBER() OVER (<br>            PARTITION BY DATE_TRUNC(&#39;month&#39;, order_date)<br>            ORDER BY SUM(sales) DESC<br>        ) AS rank<br>    FROM orders<br>    GROUP BY 1, product_id<br>) t<br>WHERE rank = 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*nNO4B9InrEs0eSXeAwoEDg.png" /></figure><p>Let’s discuss them one by one together.</p><h4>Step 1. Aggregate first</h4><pre>SUM(sales)<br>GROUP BY month, product_id</pre><p>Total sales per product each month.</p><h4>Step 2. Rank within each month</h4><pre>ROW_NUMBER() OVER (<br>    PARTITION BY month<br>    ORDER BY total_sales DESC<br>)</pre><p>Here’s the main point of our query before.</p><ul><li>PARTITION BY month → reset ranking every month.</li><li>ORDER BY total_sales DESC → highest sales = rank 1.</li><li>ROW_NUMBER() → assigns ranking (1, 2, 3, etc).</li></ul><h4>Step 3 . Pick the top one</h4><pre>WHERE rank = 1</pre><p>We got the Top-selling product for each month.</p><h3>Then They Wanted Trends</h3><blockquote><strong>“Is this month better than last month?”</strong></blockquote><pre>SELECT <br>    month,<br>    total_sales,<br>    LAG(total_sales) OVER (ORDER BY month) AS prev_month_sales,<br>    total_sales - LAG(total_sales) OVER (ORDER BY month) AS growth<br>FROM (<br>    SELECT <br>        DATE_TRUNC(&#39;month&#39;, order_date) AS month,<br>        SUM(sales) AS total_sales<br>    FROM orders<br>    GROUP BY 1<br>) t;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*p9wiLsH8TwwEUFvq9lwNwQ.png" /></figure><p>Let’s break this down too.</p><h4>Step 1 . Monthly totals</h4><pre>SUM(sales) GROUP BY month</pre><p>This is where we will sum up the sales and group them monthly.</p><h4>Step 2. Look at the previous row</h4><pre>LAG(total_sales) OVER (ORDER BY month)</pre><p>The LAG() in SQL is a window function that allows you to access data from the previous row in a dataset without using a self-join. It is commonly used in time-series analysis and trend calculations. This expression tells the database to look at the value total_sales from the previous row, based on the order of month.</p><h4>Step 3 . Calculate growth</h4><pre>total_sales - prev_month_sales</pre><p>In this step calculates growth by subtracting previous month sales from the current total sales (total_sales - prev_month_sales) to measure month-over-month sales change.</p><h3>Then My Queries Became a Mess</h3><p>At some point, I felt like my queries started to look like nested everywhere, hard to read, or slightly terrifying.</p><p>They worked… but next time it’s barely understandable.</p><p>That’s when I found <strong>CTEs (Common Table Expressions), </strong>a temporary result set that you can name and reuse inside our query.</p><pre>WITH monthly_sales AS (<br>    SELECT <br>        DATE_TRUNC(&#39;month&#39;, order_date) AS month,<br>        SUM(sales) AS total_sales<br>    FROM orders<br>    GROUP BY 1<br>)<br>SELECT <br>    month,<br>    total_sales,<br>    LAG(total_sales) OVER (ORDER BY month) AS prev_month<br>FROM monthly_sales;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*OYhoNjz-e4EHyGSaok8w1Q.png" /></figure><p>Let’s see what changed. Instead of nesting everything inside one giant query, we split it into steps.</p><h4>Step 1. The CTE part</h4><pre>WITH monthly_sales AS (...)</pre><p>This is the CTE. We’re basically saying, <em>“Hey SQL, create a temporary table called </em><em>monthly_sales using this query”.</em></p><p>For this part.</p><pre>SELECT <br>    DATE_TRUNC(&#39;month&#39;, order_date) AS month,<br>    SUM(sales) AS total_sales<br>FROM orders<br>GROUP BY 1</pre><p>So it becomes a cleaner and reusable query.</p><h4>Step 2. Use it like a table</h4><pre>FROM monthly_sales</pre><p>Instead of rewriting the same logic again (or nesting it deeply), we just use monthly_sales like a normal table.</p><p>With CTE we get same result, but with much better structure.</p><h3>Woahh Done—?</h3><p>I used to think SQL was about writing queries. But now, I see it differently. Every step taught me something.</p><ul><li>Slow query → think about efficiency</li><li>Wrong numbers → question your logic</li><li>Hard questions → rethink your approach</li><li>Messy queries → structure your thinking</li></ul><p>From me,</p><blockquote><strong>SQL is just not about queries. But, it’s about how we think when solving problems with data in a more efficient and structured.</strong></blockquote><p>To explore my other projects, feel free to check out my <a href="https://medium.com/@jihankamilah"><strong>Medium</strong></a><strong> </strong>or <strong>GitHub</strong>. Stay tuned for more challenging projects~~</p><p><a href="https://github.com/jihanKamilah">jihanKamilah - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33c5c2d7baa8" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/sql-is-more-than-just-queries-how-to-think-like-a-data-analyst-33c5c2d7baa8">SQL Is More Than Just Queries: How to Think Like a Data Analyst</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Lie in Customer Averages]]></title>
            <link>https://medium.com/learning-data/the-hidden-lie-in-customer-averages-28d0106829c0?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d0106829c0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 16:11:53 GMT</pubDate>
            <atom:updated>2026-06-02T16:11:53.981Z</atom:updated>
            <content:encoded><![CDATA[<h4>What a retail dataset revealed about misleading summary statistics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMNJfhRXItfiS5ePozV7Lw.png" /></figure><p>Businesses love averages.</p><p>Open almost any dashboard, and you’ll find them everywhere: average order value, average customer lifetime value, average purchase frequency.</p><p>The logic feels obvious.</p><p>If we understand the average customer, then surely we understand the business. It’s such a common assumption that most teams rarely question it.</p><p>I didn’t question it either, until I decided to test whether this “average customer” actually exists.</p><p>What began as a simple statistical exercise turned into something far more curious. That “the average customer wasn’t real. Not because the math was wrong, but because the assumption was.”</p><h3>Starting With Real Customer Behavior</h3><p>To test this idea, I used a <a href="https://www.kaggle.com/datasets/vijayuv/onlineretail"><strong><em>retail transaction dataset</em></strong></a> and transformed raw purchases into customer-level behavioral profiles.</p><p>Each customer was summarized using just two signals.</p><ul><li><strong>Total lifetime spending,</strong></li><li><strong>Total number of completed orders.</strong></li></ul><p>The aggregation was simple:</p><pre>customer = df.groupby(&quot;CustomerID&quot;).agg(<br>    total_spent=(&quot;total&quot;, &quot;sum&quot;),<br>    number_of_orders=(&quot;InvoiceNo&quot;, &quot;nunique&quot;)<br>).reset_index()</pre><p>At this point, each row represented a real customer and their actual purchasing behavior.</p><p>This is exactly how many companies model customer value internally.</p><p>The next step seemed obvious is <strong><em>find the average customer.</em></strong></p><h3>Constructing the Statistical Center</h3><p>To locate this “typical” customer, I calculated three standard measures of central tendency.</p><pre>mean_spent = customer[&quot;total_spent&quot;].mean()<br>median_spent = customer[&quot;total_spent&quot;].median()<br>mode_spent = customer[&quot;total_spent&quot;].mode().iloc[0]</pre><p><strong>Mean spending:</strong> <strong>$2,054</strong><br><strong>Median spending:</strong> <strong>$674</strong><br><strong>Mode spending:</strong> <strong>$76</strong></p><p>The gap was impossible to ignore. The average customer appeared to spend <strong>3X more than the median customer</strong> and nearly <strong>27X more than the most common spending behavior</strong>.</p><p>That immediately raised a question, <strong><em>Who exactly is this “average” customer?</em></strong></p><p>Could I point to a real person in the dataset and say:</p><blockquote>Yes. This customer perfectly represents the average.</blockquote><p>So I searched for the customers closest to this statistical center.</p><h3>Looking for the Average Customer</h3><p>To measure proximity to the average, I calculated each customer’s distance from the mean profile:</p><pre>customer[&quot;distance_to_mean&quot;] = (<br>    abs(customer[&quot;total_spent&quot;] - mean_spent)<br>    + abs(customer[&quot;number_of_orders&quot;] - mean_orders)<br>)</pre><p>I expected at least a few customers to land almost exactly on this point.</p><p>Instead, I found only rough approximations. Even the closest customers were merely near the statistical center — not exact representations of it.</p><p>That was strange.</p><p>So I visualized the distribution. And that’s when the illusion became obvious.</p><h3>Where the Average Supposedly Lives</h3><p>The first thing I plotted was the distribution of customer spending.</p><pre>sns.histplot(customer[&quot;log_spent&quot;], bins=80)<br>plt.axvline(mean_log)<br>plt.axvline(median_log)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChdvIaHKLLnXdpbSqq0emA.png" /></figure><p>The shape tells the whole story.</p><p>The distribution is heavily right-skewed.</p><p>Most customers cluster toward low spending levels, while a small number of extreme high-value customers stretch the tail far to the right. That’s why the mean sits noticeably above the median.</p><p>A few large spenders are pulling the average upward.</p><p>The average is mathematically valid. But behaviorally, it’s misleading. It describes balance, not reality.</p><h3>The Scatter Plot Made It Worse</h3><p>Next, I mapped purchase frequency against total spending and highlighted both the statistical mean and the behavioral median.</p><pre>sns.scatterplot(<br>    data=customer,<br>    x=&quot;number_of_orders&quot;,<br>    y=&quot;total_spent&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcXUwNFQ-TAgH8tOUGdKqg.png" /></figure><p>The result was weird. The “mean customer” floats awkwardly in open space. Real customers cluster into natural regions.</p><p>Very few customers actually exist at the exact statistical center.</p><p>The average customer exists numerically. But behaviorally, it’s almost fictional.</p><h3>Real Customers Form Segments, Not Averages</h3><blockquote>If averages weren’t describing reality, what was?</blockquote><p>The answer turned out to be segmentation.</p><p>Instead of forcing every customer into a single synthetic profile, I used K-Means clustering to identify natural behavioral groups.</p><pre>kmeans = KMeans(n_clusters=3)<br>customer[&quot;cluster&quot;] = kmeans.fit_predict(X_scaled)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxMafGl1yPy3JZnpUhGaFQ.png" /></figure><p>The dataset revealed three very different customer types.</p><p><strong>4,107 low-value customers</strong><br> Average spend: <strong>$1,114</strong><br> Average orders: <strong>3</strong></p><p><strong>218 mid-value loyal customers</strong><br> Average spend: <strong>$12,295</strong><br> Average orders: <strong>22</strong></p><p><strong>13 extreme high-value customers</strong><br> Average spend: <strong>$127,338</strong><br> Average orders: <strong>83</strong></p><p>These are real behavioral patterns. Unlike the average customer, these groups actually exist.</p><p>And that changes everything.</p><h3>The Revenue Concentration Effect</h3><p>To quantify how uneven this distribution really was, I measured revenue concentration among the top spenders.</p><p>The result was striking. <strong>Just 5% of customers generated 50.31% of total revenue.</strong></p><p>That’s an extreme concentration effect. And it explains exactly why averages become deceptive.</p><p>When a small minority contributes disproportionately large value, the mean gets pulled upward and stops describing normal customer behavior. It becomes less of a customer profile and more of a mathematical compromise between fundamentally different groups.</p><h3>Why Businesses Get This Wrong</h3><p>This matters because many business decisions are still built around averages.</p><p>Products get designed for the “average user.”</p><p>Pricing gets optimized for the “average customer.”</p><p>Marketing gets targeted toward “average behavior.”</p><p>But if that customer doesn’t actually exist, then those decisions are being optimized for fiction. The result is usually a product that feels.</p><ul><li>Too generic for power users, too demanding for casual users. and perfectly tuned for nobody.</li></ul><p>Businesses often assume averages simplify reality. Sometimes they erase it.</p><h3>What We Should Look At Instead</h3><p>The real insight rarely lives inside a single summary statistic. It lives in:</p><ul><li>Behavioral segments</li><li>Distribution shape</li><li>Outlier concentration</li><li>Customer-level variation</li></ul><p>These are the patterns that describe how real customers actually behave.</p><p>The next time a dashboard tells you what your “average customer” looks like, ask a better question:</p><blockquote><strong>Can I point to a real person who actually matches this profile?</strong></blockquote><p>If the answer is no, then you’re probably not looking at customer insight.</p><p>You’re just looking at arithmetic, and sometimes arithmetic tells a very convincing lie.</p><p>For more data science, machine learning, and real-world analytics projects are coming soon. So stay tuned for my next journey on <a href="https://medium.com/@jihankamilah">Medium</a> or GitHub^^~</p><p><a href="https://github.com/jihanKamilah">jihanKamilah - Overview</a></p><p><em>The contents of external submissions are not necessarily reflective of the opinions or work of </em><a href="http://mavenanalytics.io/"><em>Maven Analytics</em></a><em> or any of its team members.</em></p><p><em>We believe in fostering lifelong learning and our intent is to provide a platform for the data community to share their work and seek feedback from the Maven Analytics data fam.</em></p><p><a href="https://medium.com/learning-data/how-to-get-your-work-published-by-learning-data-with-maven-analytics-7df21e466a3e?source=friends_link&amp;sk=020dfac485597d602e218968d9ffb395"><em>Submit your own writing here</em></a><em> if you’d like to become a contributor.</em></p><p><em>Happy learning!</em></p><p><em>-Team Maven</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d0106829c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-data/the-hidden-lie-in-customer-averages-28d0106829c0">The Hidden Lie in Customer Averages</a> was originally published in <a href="https://medium.com/learning-data">Learning Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Spotify-Style Music Recommendation System with R]]></title>
            <link>https://medium.com/data-and-beyond/building-a-spotify-style-music-recommendation-system-with-r-2c563510ff08?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c563510ff08</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spotify]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Tue, 12 May 2026 05:23:42 GMT</pubDate>
            <atom:updated>2026-05-12T05:23:42.553Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making an Algorithm That Knows I’m Sad Before I Do</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAaivgmNURGI8gI3PCv86g.png" /></figure><p>If Part 1 was about understanding what makes a song popular, then Part 2 is where things get more exciting.</p><p>What if we could actually recommend songs based on their audio characteristics?</p><p>Not random recommendations , but something that feels closer to how Spotify works.</p><p>Using features like danceability, energy, valence, tempo, and acousticness, we can build a mini recommendation engine that searches songs, handles typos, applies mood &amp; genre filters, and ranks similar tracks automatically.</p><p>And honestly, this project started from one simple thought — <em>“If songs can be mathematically described… can we mathematically find similar songs too?”</em></p><p>And, it’s turns out — we absolutely can HEHEHE😎</p><h3>Background</h3><p>In my previous project, we explored:</p><ul><li>What makes songs popular?</li><li>Which Spotify audio features influence popularity?</li><li>How machine learning can analyze music patterns?</li></ul><p>But while working on that project, I realized something interesting. If audio features can explain popularity, they should also explain similarity between songs.</p><p>That idea became the starting point for this project.</p><p>Instead of predicting popularity, this time I wanted to simulate a simplified version of how modern music platforms recommend songs. Because recommendation systems are everywhere, like Spotify, YouTube Music, Apple Music, or TikTok algorithms.</p><p>And behind all of those systems, there’s one important concept — that songs can be converted into numerical patterns. Once songs become data, machine learning can compare them.</p><h3>Project Goal</h3><p>This project aims to build a lightweight Spotify-style recommendation system using R by combining.</p><ul><li>Search suggestion &amp; Typo-friendly song search</li><li>Content-based similarity</li><li>Mood filtering &amp; Genre filtering</li><li>Hybrid ranking system</li></ul><h3>About the Dataset</h3><p>This project uses the Spotify Tracks Dataset, containing thousands of songs and their audio characteristics. The dataset includes information such as:</p><ul><li>track_name → Song title</li><li>artists → Artist name</li><li>popularity → Spotify popularity score</li><li>danceability → How dance-friendly a song is</li><li>energy → Intensity &amp; activity level</li><li>valence → Musical positivity/ happiness</li><li>tempo → Song speed</li><li>loudness → Perceived intensity</li><li>acousticness → Acoustic vs electronic feel</li><li>speechiness → Spoken-word presence</li><li>track_genre → Music genre</li></ul><h3>Import Libraries &amp; Dataset</h3><pre>library(tidyverse)<br><br>df &lt;- read.csv(&quot;/kaggle/input/datasets/maharshipandya/-spotify-tracks-dataset/dataset.csv&quot;)</pre><p>We first import the dataset and required libraries for data manipulation and recommendation modeling.</p><h3>Data Preparation</h3><pre>df &lt;- df %&gt;%<br>  select(<br>    track_name,<br>    artists,<br>    track_genre,<br>    popularity,<br>    danceability,<br>    energy,<br>    valence,<br>    tempo,<br>    loudness,<br>    acousticness,<br>    speechiness<br>  ) %&gt;%<br>  na.omit() %&gt;%<br>  distinct(track_name, artists, .keep_all = TRUE)</pre><p>Here, I only keep columns relevant to recommendation modeling. Why these variables?</p><ul><li>danceability → Measures how dance-friendly a song is</li><li>energy → Measures intensity &amp; activity</li><li>valence → Represents musical positivity</li><li>tempo → Represents song speed</li><li>loudness → Indicates perceived intensity</li><li>acousticness → Detects acoustic feel</li><li>speechiness → Detects spoken-word characteristics</li></ul><p>These features become the <em>“</em><strong><em>personality</em></strong><em>”</em> of each song.</p><h3>Performance Optimization</h3><pre>set.seed(123)<br><br>df &lt;- df %&gt;%<br>  arrange(desc(popularity)) %&gt;%<br>  slice(1:12000)</pre><p>Instead of using the entire dataset, I limit the data to the top 12,000 songs for faster computation. This is especially helpful when running the notebook in Kaggle or Google Colab.</p><h3>Creating Mood Labels</h3><pre>df &lt;- df %&gt;%<br>  mutate(<br>    mood = case_when(<br>      valence &gt;= 0.6 &amp; energy &gt;= 0.6 ~ &quot;Happy&quot;,<br>      valence &lt; 0.4 &amp; energy &lt; 0.4 ~ &quot;Sad&quot;,<br>      energy &gt;= 0.75 ~ &quot;Workout&quot;,<br>      TRUE ~ &quot;Chill&quot;<br>    )<br>  )</pre><p>This creates a simple rule-based mood classification system. For example:</p><ul><li>high energy + high valence → Happy</li><li>low energy + low valence → Sad</li><li>extremely energetic songs → Workout</li></ul><p>This allows users to receive recommendations based on emotional vibes.</p><h3>Cleaning Song Titles</h3><pre>df$track_clean  &lt;- tolower(trimws(df$track_name))<br>df$artist_clean &lt;- tolower(trimws(df$artists))</pre><p>This step helps make the search engine case-insensitive, cleaner, and ofc — typo tolerant. So users can type:</p><pre>recommend_music(&quot;shape&quot;)<br>recommend_music(&quot;Shape of You&quot;)<br>recommend_music(&quot;shap of you&quot;)</pre><h3>Building the Feature Matrix</h3><pre>features &lt;- df %&gt;%<br>  select(<br>    danceability,<br>    energy,<br>    valence,<br>    tempo,<br>    loudness,<br>    acousticness,<br>    speechiness<br>  )<br><br>scaled_df &lt;- as.data.frame(scale(features))</pre><p>This is the heart of the recommendation engine.</p><p>I scale the features because variables like tempo have much larger values compared to danceability or valence. Without scaling, larger-number variables would dominate the similarity calculations.</p><h3>Search Suggestion System</h3><p>One thing I realized while building this project is that users rarely type song titles perfectly. Sometimes they only remember part of the title, type in lowercase, or even make typos.</p><p>That is why I added a <strong>Search Suggestion System</strong> similar to Spotify’s search dropdown.</p><pre>search_suggestion &lt;- function(query, n = 5){<br>  query &lt;- tolower(trimws(query))<br><br>  df %&gt;%<br>    filter(grepl(query, track_clean)) %&gt;%<br>    arrange(desc(popularity)) %&gt;%<br>    select(track_name, artists, popularity) %&gt;%<br>    head(n)<br>}</pre><p>Let’s break this down.</p><pre>query &lt;- tolower(trimws(query))</pre><p>This line cleans the user input by converting everything to lowercase, or removing unnecessary spaces. So:</p><ul><li>&quot; Shape Of You &quot;</li><li>&quot;shape of you&quot;</li><li>&quot;SHAPE OF YOU&quot;</li></ul><p>will all be treated the same.</p><p>Next,grepl() checks whether the keyword exists inside the song title. For example:</p><pre>search_suggestion(&quot;shape&quot;)</pre><p>The system searches all song titles containing the word &quot;shape&quot;.</p><p>Then:</p><pre>arrange(desc(popularity))</pre><p>Sorts the results from the most popular songs to the least popular ones. This is important because users usually expect famous songs to appear first.</p><h3>Intelligent Song Matching</h3><p>After creating the search suggestion system, the next challenge was — <em>“How do we make the system understand what song the user actually means?”</em></p><p>Real users often type:</p><pre>recommend_music(&quot;shap of you&quot;)</pre><p>instead of “Shape of You”.</p><p>To solve this, I built an intelligent matching function using exact matching, partial matching, and fuzzy matching.</p><pre>find_song &lt;- function(song_name, artist_name = NULL){<br>  query &lt;- tolower(trimws(song_name))<br>  exact &lt;- which(df$track_clean == query)<br><br>  partial &lt;- grep(<br>    query,<br>    df$track_clean,<br>    ignore.case = TRUE<br>  )<br><br>  fuzzy &lt;- agrep(<br>    query,<br>    df$track_clean,<br>    max.distance = 0.1<br>  )</pre><p>Here is how it works:</p><pre>exact &lt;- which(df$track_clean == query)</pre><p>This searches for songs with titles that are exactly the same as the user input. Example: &quot;Shape of You&quot; → exact match found.</p><p>Then:</p><pre>partial &lt;- grep(query, df$track_clean)</pre><p>This allows partial searches. So users can simply type &quot;shape&quot;. and the system can still detect related songs.</p><p>Next comes the coolest part:</p><pre>fuzzy &lt;- agrep(<br>  query,<br>  df$track_clean,<br>  max.distance = 0.1<br>)</pre><p>agrep() performs fuzzy matching. This means the system tolerates typos. For example: &quot;shap of you&quot;, &quot;shape fo you&quot; can still match to &quot;Shape of You&quot;.</p><p>Then I added an extra filter:</p><pre>fuzzy &lt;- fuzzy[<br>  abs(nchar(df$track_clean[fuzzy]) - nchar(query)) &lt;= 5<br>]</pre><p>This prevents completely unrelated songs from appearing due to typo matching. Without this filter, fuzzy search can sometimes become too aggressive. Finally, the system prioritizes matches in this order:</p><ol><li>Exact match</li><li>Partial match</li><li>Fuzzy match</li></ol><p>This layered, matching approach enables the recommendation engine to behave more naturally like a real music platform.</p><h3>Similarity Calculation &amp; Hybrid Recommendation Scoring</h3><p>Now comes the core recommendation engine. After identifying the target song, the system compares it with every other song using Spotify audio features. The similarity calculation uses Euclidean Distance:</p><pre>similarity &lt;- sqrt(sum((x - target)^2))</pre><p>This formula calculates the distance between two songs. Where:</p><ul><li>x = another song</li><li>target = selected song</li></ul><p>The process works by calculating the squared difference for every audio feature. Then, adds all feature differences together and finally calculates the Euclidean distance with &quot;sqrt(...)&quot;.</p><p>The smaller the distance, the more similar the songs are.</p><p>The comparison is based on Spotify audio features such as:</p><ul><li>danceability</li><li>energy</li><li>valence</li><li>tempo</li><li>loudness</li><li>acousticness</li><li>speechiness</li></ul><p>But similarity alone is not enough. If we only rely on similarity, the system might recommend very obscure songs that technically match mathematically but feel irrelevant to users. That is why I added a hybrid scoring mechanism.</p><pre>pop_boost &lt;- (100 - df$popularity) / 100<br><br>final_score &lt;- 0.7 * similarity + 0.3 * pop_boost</pre><p>Let’s break this down.</p><pre>(100 - df$popularity) / 100</pre><p>converts popularity into a normalized score. More popular songs get smaller values, making them rank higher in recommendations.</p><p>Then gives higher importance to audio similarity.</p><pre>0.7 * similarity</pre><p>while:</p><pre>0.3 * pop_boost</pre><p>adds popularity influence.</p><p>This means:</p><ul><li>70% recommendation quality comes from similarity</li><li>30% comes from popularity</li></ul><p>This hybrid approach makes the recommendation system feel much more realistic and platform-like.</p><p>Because in real-world recommendation systems. Similarity matters, but popularity and engagement matter too.</p><h3>Main Recommendation Pipeline</h3><p>After building the search system, matching logic, and similarity scoring, the final step was combining everything into one complete recommendation pipeline. This function acts as the “brain” of the music recommendation system.</p><pre>recommend_music &lt;- function(<br>  song_name,<br>  artist_name = NULL,<br>  mood_filter = NULL,<br>  genre_filter = NULL,<br>  n = 5<br>)</pre><p>The function accepts several user inputs:</p><ul><li>song_name → the song the user searches for</li><li>artist_name → optional artist filter</li><li>mood_filter → optional mood personalization</li><li>genre_filter → optional genre personalization</li><li>n → number of recommendations</li></ul><p>This structure makes the recommendation system feel more flexible and interactive, similar to real streaming platforms.</p><ul><li>The pipeline starts with song matching.</li></ul><pre>matches &lt;- find_song(song_name, artist_name)</pre><p>This calls the intelligent matching system built earlier. The function automatically handles exact matches, partial matches, and typo-friendly fuzzy matching. If no songs are found:</p><pre>if(is.null(matches)){<br>  cat(&quot;❌ Song not found.\n\n&quot;)<br>  cat(&quot;💡 Suggestions:\n&quot;)<br>  print(search_suggestion(song_name))<br>  return(NULL)<br>}</pre><p>The system does not immediately fail. Instead, it provides search suggestions to help users find the intended song.</p><p>Once a match is found:</p><pre>idx &lt;- matches[1]</pre><p>The system selects the best-matching song.</p><p>Then:</p><pre>cat(&quot;🎵 Matched:&quot;, df$track_name[idx], &quot;-&quot;, df$artists[idx])</pre><p>displays the detected song and artist to confirm the selection. Example:</p><pre>🎵 Matched: Shape of You - Ed Sheeran</pre><ul><li>Next comes the recommendation scoring process.</li></ul><pre>scores &lt;- calculate_score(idx)</pre><p>This calculates similarity scores between the selected song and all other songs in the dataset using Spotify audio features, Euclidean Distance, and hybrid popularity scoring. The generated scores are then attached to the dataset:</p><pre>temp_df$score &lt;- scores</pre><p>Songs with lower scores are considered more relevant recommendations. To avoid recommending the exact same song again:</p><pre>result &lt;- temp_df %&gt;%<br>  filter(row_number() != idx)</pre><p>The matched song is removed from the recommendation list.</p><ul><li>The next stage adds personalization filters — for mood filtering:</li></ul><pre>if(!is.null(mood_filter)){<br>  temp &lt;- result %&gt;%<br>    filter(mood == mood_filter)<br>}</pre><p>The system only keeps songs matching the selected mood. For example:</p><pre>recommend_music(<br>  &quot;Shape of You&quot;,<br>  mood_filter = &quot;Happy&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ER5ZDDZ0SXocwmL8wd2z4w.png" /></figure><p>Returns songs with similar characteristics but specifically labeled as &quot;Happy&quot;.</p><p>The same logic is applied to genre filtering. This allows recommendations such as only pop songs, dance songs, or only acoustic songs — depending on user preference.</p><ul><li>One important design decision here is the use of “safe filters”.</li></ul><pre>if(nrow(temp) &gt; 0){<br>  result &lt;- temp<br>} else {<br>  cat(&quot;⚠️ Genre not found → fallback&quot;)<br>}</pre><p>If the filter becomes too restrictive and produces zero results, the system automatically falls back to general recommendations. This prevents the recommendation engine from returning empty outputs.</p><ul><li>Finally, the recommendation ranking process happens here:</li></ul><pre>result %&gt;%<br>  arrange(score) %&gt;%<br>  distinct(track_name, .keep_all = TRUE) %&gt;%<br>  select(<br>    track_name,<br>    artists,<br>    track_genre,<br>    mood,<br>    popularity<br>  ) %&gt;%<br>  head(n)</pre><p>The system:</p><ol><li>Sorts songs by recommendation score</li><li>Removes duplicates</li><li>Selects relevant output columns</li><li>Returns the top recommendations</li></ol><p>This creates a recommendation flow that feels much closer to a real-world music platform.</p><p>Here is an example of the output of the model we created:</p><ul><li>Typos in the titles of the tracks being searched for</li></ul><pre>recommend_music(&quot;shap of you&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*jp65Jy_GoN7xBQ0JO7HWKw.png" /></figure><p>We know that, typo-friendly feature successfully found “Shape of You” by Ed Sheeran.</p><ul><li>Inclusion of track titles, artist names, mood filters, and genre filters</li></ul><pre>recommend_music(<br>  &quot;Shape of You&quot;,<br>  artist_name = &quot;ed sheeran&quot;,<br>  mood_filter = &quot;Happy&quot;,<br>  genre_filter = &quot;pop&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*rnpytc2goAWrjJNfewaSSw.png" /></figure><p>These recommendations are specifically for the “Happy” mood filter, and the genre is pop.</p><h3>Conclusion</h3><p>Building this project made me realize that recommendation systems are much more than simply “finding similar songs”. Behind every recommendation, there are layers of:</p><ul><li>search logic</li><li>similarity calculations</li><li>ranking systems</li><li>personalization filters</li><li>user experience considerations</li></ul><p>Using Spotify audio features, this project successfully demonstrates how machine learning concepts can be transformed into an interactive recommendation engine. The system can:</p><ul><li>detect songs even with typos</li><li>suggest alternative matches</li><li>compare songs mathematically</li><li>personalize recommendations using mood and genre</li><li>rank songs using hybrid scoring</li></ul><h4>Types of Recommendation Used</h4><p>This project combines several recommendation approaches into one integrated system.</p><ol><li><strong>Content-Based Filtering —</strong>compares songs using Spotify audio features such as danceability, energy, valence, tempo, loudness, acousticness, speechiness.</li><li><strong>Mood-Based Recommendation — </strong>based on valence &amp; energy. The system groups songs into Happy, Sad, Workout, Chill.</li><li><strong>Genre-Based Recommendation — </strong>pop, dance, acoustic, hip-hop.</li><li><strong>Hybrid Ranking — </strong>similarity score &amp; popularity score.</li></ol><p>Combining these approaches makes the recommendation system more flexible, dynamic, and closer to how modern music streaming platforms operate. The recommendation pipeline created here resembles simplified versions of systems commonly used in platforms like Spotify, YouTube Music, or Netflix — where personalization and engagement become key priorities.</p><h3>Business &amp; Platform Recommendations</h3><p>From a business perspective, systems like this can help music platforms:</p><ol><li><strong>Improve User Retention, </strong>better recommendations increase listening time and platform engagement.</li><li><strong>Enhance Personalization</strong>, mood-based and genre-based filtering allows platforms to create more personalized listening experiences.</li><li><strong>Support Playlist Automation,</strong> Recommendation systems can automatically generate playlists based on user mood, listening patterns, favorite genres, similar tracks.</li><li><strong>Increase Music Discoverability, </strong>hybrid recommendation approaches help smaller or lesser-known songs become discoverable while still maintaining recommendation quality.</li><li><strong>Strengthen User Experience,</strong> features such as typo-tolerant search and intelligent suggestions reduce friction and improve overall usability.</li></ol><p>Even though this project is still a simplified version of a real production recommendation system, it demonstrates how machine learning, data processing, and personalization strategies can work together to create meaningful digital experiences.</p><p>So, <strong>for another interesting upgrade</strong>, would be implementing:</p><ul><li>listening-time analysis</li><li>skip behavior prediction</li><li>favorite genre tracking</li><li>user session analytics</li></ul><h3>The End — Seriously Hehe</h3><p>And that wraps up Part 2 of this Spotify Machine Learning journey~~</p><p>To better understand the dataset used and how the analysis was conducted, check out Part 1 - <a href="https://medium.com/data-and-beyond/what-makes-a-song-popular-694dbb54f378">What Makes a Song Popular?</a> first.</p><p>And if you want to explore the full notebook, complete code, or try this project by yourself, you can click the GitHub Embed Link hereee~~</p><p><a href="https://github.com/jihanKamilah/Spotify-Music-Recommender-with-R">GitHub - jihanKamilah/Spotify-Music-Recommender-with-R: Part 2 of Spotify ML project: A Spotify-inspired recommendation engine built with R using content-based filtering, mood matching, and hybrid recommendation scoring.</a></p><p>For more data science, machine learning, and real-world analytics projects are coming soon. So stay tuned for the my next journeyy~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c563510ff08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/building-a-spotify-style-music-recommendation-system-with-r-2c563510ff08">Building a Spotify-Style Music Recommendation System with R</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Clicks to Revenue: What A/B Testing Taught Me About Marketing Performance]]></title>
            <link>https://medium.com/learning-data/from-clicks-to-revenue-what-a-b-testing-taught-me-about-marketing-performance-97c9ff5078e4?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/97c9ff5078e4</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ab-testing]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Wed, 06 May 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-05-06T13:31:01.729Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical breakdown of campaign A vs B — going beyond CTR to uncover what actually drives profit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_QLiDzFpmdXYz3vrskoxw.png" /></figure><p>At first, everything looked great.</p><p>The new campaign was getting more clicks, more engagement, and honestly… everyone on the marketing team felt optimistic.</p><p>But then a simple question came up:</p><blockquote>“Are we actually making more money… or just getting better vanity metrics?”</blockquote><p>And that’s where this analysis started. Because the truth is, situations like this happen all the time.</p><p>You launch a new campaign.<br>The numbers look promising.<br>CTR goes up, traffic increases, engagement improves.</p><p>But when it comes to making decisions, especially something like scaling budget or replacing an existing campaign. There’s always that hesitation:</p><blockquote>Is this actually better… or does it just look better?</blockquote><p>Instead of guessing, one of the most reliable ways to answer that question is simple — <strong><em>Compare it directly with what you already have.</em></strong></p><h3>Business Understanding</h3><p>In this project, I’m stepping into the role of a data analyst in an e-commerce company.</p><p>We’re running two campaigns:</p><ul><li><strong>Control Campaign</strong> → the old, stable version</li><li><strong>Test Campaign</strong> → a new version with improved creatives and targeting</li></ul><p>The core question:</p><blockquote><strong>Does the Test Campaign actually generate higher revenue and profit — not just clicks?</strong></blockquote><p>Because in the end, better marketing isn’t about getting more attention. It’s about generating better outcomes.</p><h3>Data Understanding &amp; Cleaning</h3><p>Before jumping into insights, I made sure the data was clean and usable.</p><pre>import pandas as pd<br>import numpy as np<br><br>control = pd.read_csv(&quot;control_group.csv&quot;, sep=&#39;;&#39;)<br>test = pd.read_csv(&quot;test_group.csv&quot;, sep=&#39;;&#39;)<br><br># Add label<br>control[&#39;campaign&#39;] = &#39;Control&#39;<br>test[&#39;campaign&#39;] = &#39;Test&#39;<br><br># Combine<br>df = pd.concat([control, test], ignore_index=True)<br><br># Standardize columns<br>df.columns = df.columns.str.lower().str.strip()<br><br># Remove duplicate columns (cek aja)<br>df = df.loc[:, ~df.columns.duplicated()]</pre><p>Also, make sure the date column is usable.</p><pre>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;], dayfirst=True)</pre><p>To make the analysis easier, I standardized column names. And, still a little cleaning (or just for check).</p><pre># Rename columns<br>df = df.rename(columns={<br>    &#39;campaign name&#39;: &#39;campaign_name&#39;,<br>    &#39;spend [usd]&#39;: &#39;spend&#39;,<br>    &#39;# of impressions&#39;: &#39;impressions&#39;,<br>    &#39;reach&#39;: &#39;reach&#39;,<br>    &#39;# of website clicks&#39;: &#39;clicks&#39;,<br>    &#39;# of searches&#39;: &#39;searches&#39;,<br>    &#39;# of view content&#39;: &#39;view_content&#39;,<br>    &#39;# of add to cart&#39;: &#39;add_to_cart&#39;,<br>    &#39;# of purchase&#39;: &#39;purchase&#39;<br>})<br><br># Handle missing<br>df = df.dropna()<br><br># Final check<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*fEM0gx2fM1cZ3NxfAJO-Pw.png" /><figcaption>info</figcaption></figure><p>So, the data cleaning steps performed here include combining, standardizing, removing duplicates, adjusting the ‘date’ data format, renaming columns, and removing missing values.</p><h3>Feature Engineering (The Real Foundation)</h3><p>This is where raw data turns into something meaningful.</p><h4>Funnel Metrics</h4><pre>df[&#39;ctr&#39;] = df[&#39;clicks&#39;] / df[&#39;impressions&#39;]<br>df[&#39;view_rate&#39;] = df[&#39;view_content&#39;] / df[&#39;clicks&#39;]<br>df[&#39;cart_rate&#39;] = df[&#39;add_to_cart&#39;] / df[&#39;view_content&#39;]<br>df[&#39;purchase_rate&#39;] = df[&#39;purchase&#39;] / df[&#39;add_to_cart&#39;]</pre><h4>Financial Metrics</h4><p>Since the dataset doesn’t include order value, I used a simple assumption.</p><pre>AOV = 50<br><br>df[&#39;revenue&#39;] = df[&#39;purchase&#39;] * AOV<br>df[&#39;profit&#39;] = df[&#39;revenue&#39;] - df[&#39;spend&#39;]<br>df[&#39;cac&#39;] = df[&#39;spend&#39;] / df[&#39;purchase&#39;]<br>df[&#39;roi&#39;] = (df[&#39;revenue&#39;] - df[&#39;spend&#39;]) / df[&#39;spend&#39;]</pre><h4>Funnel Analysis</h4><p>Instead of looking at conversion directly, I wanted to see the <strong>entire journey</strong>.</p><pre>funnel = df.groupby(&#39;campaign&#39;)[[<br>    &#39;impressions&#39;,<br>    &#39;clicks&#39;,<br>    &#39;view_content&#39;,<br>    &#39;add_to_cart&#39;,<br>    &#39;purchase&#39;<br>]].sum()<br><br>funnel</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*V9BAr1BgO8y8IeIcPOmr_g.png" /></figure><p>The Test Campaign generates more clicks despite fewer impressions, reflected in a higher click-through rate (CTR), indicating stronger top-of-funnel performance. However, it underperforms in the mid-funnel — especially from <strong>view content to add to cart</strong>, where conversion rates are noticeably lower, suggesting possible friction in the user journey.</p><p>Interestingly, this doesn’t reduce final outcomes, as the Test Campaign still results in slightly more purchases.</p><blockquote>In short, the campaign attracts more qualified users, but improving the mid-funnel experience could drive even better results.</blockquote><p>For further visualization, I used this code, and here are the results.</p><pre>funnel = df.groupby(&#39;campaign&#39;)[[<br>    &#39;impressions&#39;,<br>    &#39;clicks&#39;,<br>    &#39;view_content&#39;,<br>    &#39;add_to_cart&#39;,<br>    &#39;purchase&#39;<br>]].sum()<br><br>funnel.T.plot(kind=&#39;bar&#39;, color=colors)<br>plt.title(&quot;Funnel Comparison: Control vs Test&quot;)<br>plt.ylabel(&quot;Users&quot;)<br>plt.xticks(rotation=15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*-6o7TglO5Ln5C5AiBxScEQ.png" /></figure><h4>Conversion Rate Comparison</h4><p>Let’s compare key metrics.</p><pre>conversion = df.groupby(&#39;campaign&#39;)[[<br>    &#39;ctr&#39;,&#39;view_rate&#39;,&#39;cart_rate&#39;,&#39;purchase_rate&#39;<br>]].mean()<br><br>conversion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*-5OV0XdS4Mvlcp_bzmsK6A.png" /></figure><p>The Test Campaign significantly improves CTR (10.2% vs 5.1%), confirming stronger performance at the top of the funnel. However, it shows weaker mid-funnel efficiency, with lower <strong>view rate</strong> and <strong>cart rate</strong>, meaning fewer users continue their journey after clicking.</p><p>Interestingly, the Test Campaign compensates for this with a much higher <strong>purchase rate (61.8% vs 45.7%)</strong>, indicating stronger conversion at the final stage.</p><blockquote><em>In short, the Test Campaign attracts more users, loses more in the middle, but converts better at the bottom — suggesting higher intent from those who reach the final stage.</em></blockquote><p>For further visualization, I used this code, and here are the results.</p><pre>conversion = df.groupby(&#39;campaign&#39;)[[<br>    &#39;ctr&#39;,&#39;view_rate&#39;,&#39;cart_rate&#39;,&#39;purchase_rate&#39;<br>]].mean()<br><br>conversion.plot(kind=&#39;bar&#39;, color=colors)<br>plt.title(&quot;Conversion Rate Comparison&quot;)<br>plt.ylabel(&quot;Rate&quot;)<br>plt.xticks(rotation=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*GAMqITICkXbr_eP7sals0w.png" /></figure><h4>Testing (Statistical Validation)</h4><p>To validate whether the difference in performance is statistically significant, a proportion z-test was conducted on purchase conversion.</p><pre>from statsmodels.stats.proportion import proportions_ztest<br><br>group = df.groupby(&#39;campaign name&#39;)[&#39;purchase&#39;].agg([&#39;sum&#39;,&#39;count&#39;])<br>success = group[&#39;sum&#39;].values<br>nobs = group[&#39;count&#39;].values<br><br>zstat, pval = proportions_ztest(success, nobs)<br>print(zstat, pval)group = df.groupby(&#39;campaign&#39;).agg({<br>    &#39;purchase&#39;: &#39;sum&#39;,<br>    &#39;clicks&#39;: &#39;sum&#39;<br>})<br><br>success = group[&#39;purchase&#39;].values<br>nobs = group[&#39;clicks&#39;].values<br><br>from statsmodels.stats.proportion import proportions_ztest<br><br>zstat, pval = proportions_ztest(success, nobs)<br><br>print(&quot;Z-stat:&quot;, zstat)<br>print(&quot;P-value:&quot;, pval)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*NeD05LjakU4vEnWYgmnkdw.png" /></figure><p>Interpretation:</p><ul><li>p &lt; 0.05 → statistically significant</li><li>p &gt; 0.05 → could be random</li></ul><p>The result shows:</p><ul><li><strong>Z-stat: 11.84</strong></li><li><strong>P-value: ~0.0000000000000000000000000000000246</strong></li></ul><p>Since the p-value is far below 0.05, the difference between the Control and Test Campaign is <strong>statistically significant</strong>.</p><blockquote>This means the improvement in conversion is very unlikely to be caused by random chance — the Test Campaign is genuinely performing better.</blockquote><h4>Revenue &amp; Profit Analysis</h4><p>Now the real question: <strong><em>money</em></strong>.</p><pre>df.groupby(&#39;campaign&#39;)[[&#39;revenue&#39;,&#39;spend&#39;,&#39;profit&#39;]].sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*jva91-Z1TH3Bgn1A78YS_w.png" /></figure><p>The Test Campaign generates higher total revenue (<strong>$781,850 vs $758,050</strong>) despite having a higher spend. More importantly, it also delivers higher profit (<strong>$704,958 vs $691,232</strong>), indicating that the additional cost is effectively converted into returns.</p><blockquote>In short, even though the Test Campaign is more expensive, it produces more value — making it a stronger revenue driver overall.</blockquote><p>For further visualization, I used this code, and here are the results.</p><pre>df.groupby(&#39;campaign&#39;)[[&#39;revenue&#39;,&#39;spend&#39;,&#39;profit&#39;]].sum().plot(<br>    kind=&#39;bar&#39;,<br>    color=[&quot;#6BAED6&quot;, &quot;#9ECAE1&quot;, &quot;#FD8D3C&quot;]<br>)<br><br>plt.title(&quot;Revenue vs Spend vs Profit&quot;)<br>plt.xticks(rotation=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*ifr4EyqF6i_Inhdt6ypwLg.png" /></figure><h4>ROI Summary</h4><pre>roi_summary = df.groupby(&#39;campaign&#39;).agg({<br>    &#39;roi&#39;: &#39;mean&#39;,<br>    &#39;revenue&#39;: &#39;sum&#39;,<br>    &#39;spend&#39;: &#39;sum&#39;,<br>    &#39;profit&#39;: &#39;sum&#39;<br>})<br><br>roi_summary</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*kW3KipToFzRE4SLgAc3JeQ.png" /></figure><p>While the Test Campaign generates higher revenue and profit, the Control Campaign actually delivers a higher average ROI (<strong>10.6 vs 9.3</strong>).</p><p>This indicates that, relative to the amount spent, the Control Campaign is more cost-efficient in generating returns.</p><blockquote>In short, the Test Campaign wins in total profit, but the Control Campaign is more efficient per dollar spent.</blockquote><p>For further visualization, I used this code, and here are the results.</p><pre>df.groupby(&#39;campaign&#39;)[&#39;roi&#39;].mean().plot(<br>    kind=&#39;bar&#39;,<br>    color=colors<br>)<br><br>plt.title(&quot;ROI Comparison&quot;)<br>plt.ylabel(&quot;ROI&quot;)<br>plt.xticks(rotation=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*p_7YwoRKLejGgf5q4m0Q7w.png" /></figure><h4>CAC Analysis</h4><pre>cac = df.groupby(&#39;campaign&#39;).apply(<br>    lambda x: x[&#39;spend&#39;].sum() / x[&#39;purchase&#39;].sum()<br>)<br><br>cac</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*P-6B1yODJV7__fxbHwIkMQ.png" /></figure><p>The Test Campaign has a higher Customer Acquisition Cost (<strong>$4.92 vs $4.41</strong>), meaning it is more expensive to acquire each customer. This aligns with the earlier ROI finding, where the Control Campaign is more cost-efficient overall.</p><blockquote>In short, the Test Campaign spends more to acquire customers — but as seen earlier, it compensates with higher total revenue and profit.</blockquote><p>For further visualization, I used this code, and here are the results.</p><pre>cac = df.groupby(&#39;campaign&#39;).apply(<br>    lambda x: x[&#39;spend&#39;].sum() / x[&#39;purchase&#39;].sum()<br>)<br><br>cac</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*L_0xs27ojBLONNBhKuL86Q.png" /></figure><h4>Time Trend</h4><pre># Revenue per date &amp; campaign<br>time_trend = df.groupby([&#39;date&#39;, &#39;campaign&#39;])[&#39;revenue&#39;].sum().unstack()<br><br>time_trend.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*odjErwH1dD0USVg79zim-Q.png" /></figure><p>From the daily revenue trend, performance between the two campaigns fluctuates over time, with the Test Campaign occasionally outperforming the Control Campaign on specific days. There are also gaps in the data (e.g., missing values for certain dates), which suggests that performance is not entirely consistent across the entire period.</p><blockquote>In short, the Test Campaign shows strong potential on certain days, but its performance is not consistently dominant over time.</blockquote><p>For further visualization, I used this code, and here are the results.</p><pre>df.groupby([&#39;date&#39;,&#39;campaign&#39;])[&#39;revenue&#39;].sum().unstack().plot(<br>    color=colors,<br>    linewidth=2<br>)<br><br>plt.title(&quot;Revenue Over Time by Campaign&quot;)<br>plt.xlabel(&quot;Date&quot;)<br>plt.ylabel(&quot;Revenue&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*LkVmRVDDORC8sFmox2NZvg.png" /></figure><h4>Break-even Analysis</h4><pre>profit_per_customer = df.groupby(&#39;campaign&#39;)[&#39;profit&#39;].mean()<br>total_spend = df.groupby(&#39;campaign&#39;)[&#39;spend&#39;].sum()<br><br>break_even = total_spend / profit_per_customer<br><br>break_even</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*l4-CBF2q2uIPn9yhQApW1g.png" /></figure><p>The Control Campaign requires fewer customers to break even (<strong>~2.8 vs ~3.3</strong>), indicating a more efficient path to recovering its initial spend. This aligns with earlier findings where the Control Campaign shows better cost efficiency (lower CAC and higher ROI).</p><blockquote>In short, the Control Campaign reaches break-even faster, while the Test Campaign requires more customers to cover its higher cost.</blockquote><h4>What-if Analysis</h4><p><em>What happens if we increase the budget?</em></p><pre>df[&#39;spend_whatif&#39;] = df[&#39;spend&#39;] * 1.2<br>df[&#39;revenue_whatif&#39;] = df[&#39;revenue&#39;] * 1.1<br>df[&#39;profit_whatif&#39;] = df[&#39;revenue_whatif&#39;] - df[&#39;spend_whatif&#39;]<br><br>df.groupby(&#39;campaign&#39;)[[&#39;profit&#39;,&#39;profit_whatif&#39;]].sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*z41tx5YgQtwlPSfs_X5tCA.png" /></figure><p>When simulating a 20% increase in spend with a modest 10% increase in revenue, both campaigns show higher total profit. However, the Test Campaign continues to outperform, generating the highest projected profit (<strong>~767K vs ~753K</strong>).</p><blockquote>In short, both campaigns benefit from scaling, but the Test Campaign remains the stronger driver of profit even under increased budget.</blockquote><h4>Scenario Analysis</h4><pre>scenarios = [0.95, 1.0, 1.1]<br><br>results = []<br><br>for s in scenarios:<br>    temp = df.copy()<br>    temp[&#39;rev_scenario&#39;] = temp[&#39;purchase&#39;] * AOV * s<br>    temp[&#39;profit_scenario&#39;] = temp[&#39;rev_scenario&#39;] - temp[&#39;spend&#39;]<br>    <br>    results.append(temp.groupby(&#39;campaign&#39;)[&#39;profit_scenario&#39;].sum())<br><br>pd.DataFrame(results, index=[&#39;pessimistic&#39;,&#39;realistic&#39;,&#39;optimistic&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*9vxwf83Y97tUbVLAAdiKaw.png" /></figure><p>Across all scenarios — pessimistic, realistic, and optimistic — both campaigns remain profitable. However, the Test Campaign consistently outperforms the Control Campaign in every condition, generating higher profit regardless of changes in conversion assumptions.</p><blockquote>In short, the Test Campaign is not only more profitable, but also more resilient under different performance scenarios.</blockquote><p>For further visualization, I used this code, and here are the results.</p><pre>scenario_profit = pd.DataFrame(results, index=[&#39;pessimistic&#39;,&#39;realistic&#39;,&#39;optimistic&#39;])<br><br>scenario_profit.plot(<br>    kind=&#39;bar&#39;,<br>    color=colors<br>)<br><br>plt.title(&quot;Profit Under Different Scenarios&quot;)<br>plt.xticks(rotation=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*eBwOXDm-BnAlA45D8xsyng.png" /></figure><h4>Segment Analysis (Adapted)</h4><p>Since we don’t have demographics, I used alternative segmentation:</p><p><strong>Time-based</strong></p><pre># Time-based<br>df[&#39;day_type&#39;] = df[&#39;date&#39;].dt.weekday &lt; 5<br><br>df.groupby([&#39;day_type&#39;,&#39;campaign&#39;])[&#39;purchase_rate&#39;].mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*aLjQOprwjyFSmN5F5dbUkg.png" /></figure><p>The Test Campaign consistently outperforms the Control Campaign on both weekdays and weekends.</p><p>However, the gap is <strong>much larger on weekends</strong>:</p><ul><li>Control drops significantly (<strong>33%</strong>)</li><li>Test remains relatively strong (<strong>60%</strong>)</li></ul><blockquote>This suggests that the Test Campaign is more resilient during lower-intent periods like weekends, while the Control Campaign is more sensitive to traffic quality.</blockquote><p><strong>Performance-based</strong></p><pre># Reach-based<br>df[&#39;reach_segment&#39;] = pd.qcut(df[&#39;reach&#39;], q=2, labels=[&#39;low&#39;,&#39;high&#39;])<br><br>df.groupby([&#39;reach_segment&#39;,&#39;campaign&#39;])[&#39;purchase_rate&#39;].mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*hEvSj9R-4gBVUCRXDN0RAA.png" /></figure><p>The Test Campaign outperforms the Control Campaign across both segments, but the difference becomes even stronger in the <strong>high-reach segment.</strong></p><ul><li>Test reaches ~<strong>67.8% purchase rate</strong></li><li>Control only ~<strong>48.3%</strong></li></ul><blockquote>This indicates that the Test Campaign benefits more from higher exposure, making it more effective when scaled.</blockquote><h4>Funnel Bottleneck Analysis</h4><p><em>Where are we losing users the most?</em></p><pre>drop = pd.DataFrame({<br>    &#39;click_rate&#39;: funnel[&#39;clicks&#39;] / funnel[&#39;impressions&#39;],<br>    &#39;view_rate&#39;: funnel[&#39;view_content&#39;] / funnel[&#39;clicks&#39;],<br>    &#39;cart_rate&#39;: funnel[&#39;add_to_cart&#39;] / funnel[&#39;view_content&#39;],<br>    &#39;purchase_rate&#39;: funnel[&#39;purchase&#39;] / funnel[&#39;add_to_cart&#39;]<br>})<br><br>drop</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*Qdgp41nwmE8rFfNUu3lASw.png" /></figure><p>By breaking down each step of the funnel into conversion rates, we can clearly see where the biggest drop-offs occur.</p><p>For the Test Campaign:</p><ul><li>Strong performance at the top (<strong>click rate: 8.1% vs 4.9%</strong>)</li><li>But significant drop in the mid-funnel with <strong>view rate is lower (30.8% vs 36.5%), and cart rate drops sharply (47.4% vs 66.9%).</strong></li></ul><p>Interestingly, the Test Campaign recovers at the final stage with a higher <strong>purchase rate (59.1% vs 40.2%)</strong>.</p><blockquote>In short, the biggest bottleneck lies in the <strong>view → add to cart stage</strong>, where a large portion of users drop off.</blockquote><h3>Executive Summary — One Look, One Decision</h3><p>After going through funnel performance, conversion rates, and financial metrics, I wanted a single view that answers the core business question:</p><blockquote><strong>Should we scale the Test Campaign?</strong></blockquote><p>Instead of showing multiple charts again, I summarized the most important metrics:</p><ul><li>ROI</li><li>Profit</li><li>CAC</li></ul><pre>summary = df.groupby(&#39;campaign&#39;).agg({<br>    &#39;roi&#39;: &#39;mean&#39;,<br>    &#39;profit&#39;: &#39;sum&#39;,<br>    &#39;spend&#39;: &#39;sum&#39;,<br>    &#39;purchase&#39;: &#39;sum&#39;<br>})<br><br>summary[&#39;cac&#39;] = summary[&#39;spend&#39;] / summary[&#39;purchase&#39;]<br><br>summary[[&#39;roi&#39;,&#39;profit&#39;,&#39;cac&#39;]].plot(<br>    kind=&#39;bar&#39;,<br>    subplots=True,<br>    layout=(1,3),<br>    figsize=(12,4),<br>    sharex=True,<br>    color=colors<br>)<br><br>plt.suptitle(&quot;Executive Summary: Campaign Performance&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuvIBoBULB9MBR751WkzOQ.png" /></figure><p>Insight — <em>The Test Campaign consistently outperforms the Control Campaign in terms of profit and ROI, while maintaining a higher — but justified — CAC.</em></p><h3>Conclusion</h3><p>We thought we had a winning campaign.<br> More clicks. Higher CTR. Stronger engagement.</p><p>But performance at the top doesn’t always translate into business impact.</p><p>When we look across the full funnel, the picture changes.</p><p>The Test Campaign clearly drives stronger outcomes where it matters most — generating higher revenue and total profit, and consistently outperforming across different scenarios. It also shows stronger conversion at the final stage, indicating higher purchase intent.</p><p>But that growth comes with a cost. Higher CAC, lower ROI, and a clear drop-off in the mid-funnel reveal inefficiencies that can’t be ignored.</p><p>Meanwhile, the Control Campaign tells a different story — more efficient, more stable, and faster to break even.</p><p><em>This is the real trade-off:<br></em><strong><em>Are we optimizing for efficiency — or for total value?</em></strong></p><p>So this is not just a simple “better vs worse” situation. It’s a trade-off between <strong>scale (Test)</strong> and <strong>efficiency (Control)</strong>.</p><h3>Final Recommendation</h3><p>The right move isn’t choosing one campaign over the other — it’s using both strategically.</p><p><strong>1. Scale the Test Campaign — as the primary growth driver</strong><br>The Test Campaign has proven its ability to generate higher profit and maintain strong performance across scenarios. This makes it the best candidate for scaling.</p><p>But scaling without fixing inefficiencies means leaving significant value on the table.</p><p><strong>2. Fix the mid-funnel bottleneck (highest impact opportunity)</strong><br>The largest drop occurs between <em>view content → add to cart</em>.</p><p>This signals a disconnect between user interest and purchase intent — likely driven by factors such as landing page experience, pricing perception, or mismatch between ad messaging and product reality.</p><p>Improving this stage will directly unlock additional revenue without increasing acquisition cost.</p><p><strong>3. Scale with guardrails, not assumptions</strong><br>As spend increases, CAC will likely rise and ROI may decline.</p><p>Define clear limits:</p><ul><li>Maximum acceptable CAC</li><li>Minimum ROI threshold</li></ul><p>Growth should be controlled and measurable — not aggressive and blind.</p><p><strong>4. Double down on high-performing segments</strong><br>The Test Campaign performs especially well in high-reach segments and remains strong during lower-intent periods like weekends.</p><p>Budget allocation should prioritize segments that consistently convert better.</p><p><strong>5. Keep the Control Campaign as a benchmark (or hybrid strategy)</strong><br>The Control Campaign still plays an important role — providing cost efficiency, stability, and a reliable baseline.</p><p>Instead of turning it off, it can be used to balance risk or support a hybrid budget strategy.</p><h3>The End — ?</h3><p>So, here’s what I can say if the goal is:</p><ul><li><strong>Maximize profit → Choose Test Campaign</strong></li><li><strong>Maximize efficiency → Keep Control Campaign</strong></li><li><strong>Maximize long-term growth → Scale Test + optimize funnel</strong></li></ul><p>So the real answer is <strong><em>Scale the Test Campaign — but fix the funnel and control the cost.</em></strong></p><p>That’s it for this one. If you want to see more of my journey in building data projects, come along — you can find me on <a href="https://medium.com/@jihankamilah"><strong>Medium</strong></a> and GitHub.</p><p><a href="https://github.com/jihanKamilah">jihanKamilah - Overview</a></p><p><em>The contents of external submissions are not necessarily reflective of the opinions or work of </em><a href="http://mavenanalytics.io/"><em>Maven Analytics</em></a><em> or any of its team members.</em></p><p><em>We believe in fostering lifelong learning and our intent is to provide a platform for the data community to share their work and seek feedback from the Maven Analytics data fam.</em></p><p><a href="https://medium.com/learning-data/how-to-get-your-work-published-by-learning-data-with-maven-analytics-7df21e466a3e?source=friends_link&amp;sk=020dfac485597d602e218968d9ffb395"><em>Submit your own writing here</em></a><em> if you’d like to become a contributor.</em></p><p><em>Happy learning!</em></p><p><em>-Team Maven</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97c9ff5078e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-data/from-clicks-to-revenue-what-a-b-testing-taught-me-about-marketing-performance-97c9ff5078e4">From Clicks to Revenue: What A/B Testing Taught Me About Marketing Performance</a> was originally published in <a href="https://medium.com/learning-data">Learning Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Is What Real Data Looks Like (And How I Turned It Into Insights)]]></title>
            <link>https://medium.com/learning-data/this-is-what-real-data-looks-like-and-how-i-turned-it-into-insights-3d520e7da561?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d520e7da561</guid>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 17:03:36 GMT</pubDate>
            <atom:updated>2026-04-29T17:03:36.232Z</atom:updated>
            <content:encoded><![CDATA[<h4>A hands-on ETL project transforming messy HR data into clean, structured, and analysis-ready datasets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8fn--Rf9ETVJkmD-JQ4CA.png" /></figure><p>Let me be honest.</p><p>At first, I thought working with data was just Load → analyze → done.</p><p>But the moment I opened a real dataset… It was messy, inconsistent, and confusing.</p><p>That’s when I realized<em> </em><strong><em>Data is not ready. You have to make it ready.</em></strong></p><p>So in this project, I decided to go beyond analysis.<br>I built a <strong>complete ETL pipeline</strong>, transformed raw HR data into structured tables, and answered real business questions — including predicting employee attrition.</p><p>And I’ll walk you through everything — step by step.</p><h3><strong>Business Background</strong></h3><p>Imagine you are part of a Human Resources analytics team in a growing company.</p><p>Over the years, the company has accumulated a large amount of employee data — from hiring records to performance evaluations. However, the data is scattered, inconsistent, and not structured for analysis.</p><p>Despite having all this data, the HR team struggles to answer critical questions such as:</p><ul><li>Why do some employees leave while others stay?</li><li>Are certain managers associated with better performance outcomes?</li><li>Is the company truly diverse, or just appears to be?</li><li>Which hiring channels actually bring in diverse talent?</li></ul><p>Without a proper data pipeline, these questions remain unanswered.</p><p>This is where data engineering and analytics come into play.</p><h3>What is ETL (and why should you care?)</h3><p>ETL stands for:</p><ul><li><strong>Extract</strong> → Get the data</li><li><strong>Transform</strong> → Clean + reshape it</li><li><strong>Load</strong> → Store it in a usable format</li></ul><p>Think of it like cooking 🍳:</p><ul><li>Extract = buying ingredients</li><li>Transform = cooking</li><li>Load = plating the dish</li></ul><p>Without ETL, your data is just… raw ingredients.</p><h4>The Dataset</h4><p>For this project, I used a publicly available HR dataset from Kaggle, <a href="https://www.kaggle.com/datasets/rhuebner/human-resources-data-set"><strong><em>Human Resources Data Set</em></strong></a>.</p><p>It contains a variety of information, including:</p><ul><li>Employee info (name, age, gender)</li><li>Job details (department, position, salary)</li><li>Performance &amp; absences</li><li>Hiring &amp; termination dates</li></ul><h4>Step 1 — Extract (Getting the Data)</h4><pre>def extract_data(path):<br>    print(&quot;📥 Extracting data...&quot;)<br>    return pd.read_csv(path)</pre><ul><li>pd.read_csv() loads the dataset</li><li>We wrap it in a function to make it reusable</li></ul><p>This is matters, because in real projects, your data might come from:</p><ul><li>APIs</li><li>databases</li><li>cloud storage</li></ul><p>So having a modular <strong>extract step = scalable pipeline.</strong></p><p>In other words, instead of working with one large, complex table, we now have a system that is easier to maintain and better suited for analytical workloads.</p><h3>Step 2 — Transform (The Real Work Happens Here)</h3><p>At this point, I started thinking beyond just cleaning the data.</p><p>The dataset initially came as a single flat table — one file with many columns containing employee details, job information, performance metrics, and more. While this structure works for quick analysis, it becomes inefficient as the data grows.</p><p>As the number of records increases, a wide table like this can:</p><ul><li>slow down queries</li><li>make analysis more complex</li><li>and create redundancy across repeated values</li></ul><p>This led me to think about a more scalable approach.</p><blockquote>Instead of keeping everything in one table, why not restructure the data into a more organized model?</blockquote><p>This is where the idea of a <strong>star schema</strong> comes in.</p><p>In a star schema design:</p><ul><li>a central <strong>fact table</strong> stores core transactional data</li><li>multiple <strong>dimension tables</strong> store descriptive attributes</li></ul><p>So I transformed the original dataset into:</p><ul><li>a <strong>fact table</strong> for employee records</li><li>separate dimension tables such as department, position, and salary</li></ul><p>By doing this, the data becomes more structured, redundancy is reduced, and analysis becomes more efficient and scalable.</p><p>In other words, instead of working with a large, complex table, we now have a system that is easier to maintain and better suited for analytical workloads.</p><p>This is where things get interesting.</p><p><strong>Cleaning the Data</strong></p><pre>df.columns = df.columns.str.strip()</pre><p>Here, we remove hidden spaces in column names (yupsiie~, this breaks code more often than you think).</p><p><strong>Fixing Dates</strong></p><pre>df[&#39;DateofHire&#39;] = pd.to_datetime(df[&#39;DateofHire&#39;], errors=&#39;coerce&#39;)<br>df[&#39;DateofTermination&#39;] = pd.to_datetime(df[&#39;DateofTermination&#39;], errors=&#39;coerce&#39;)<br>df[&#39;DOB&#39;] = pd.to_datetime(df[&#39;DOB&#39;], format=&#39;%m/%d/%y&#39;, errors=&#39;coerce&#39;)</pre><ul><li>Converts strings → actual datetime</li><li>errors=&#39;coerce&#39; turns bad values into NaT instead of crashing</li></ul><p><strong>Feature Engineering → Age</strong></p><pre>today = pd.Timestamp.today()<br>df[&#39;Age&#39;] = ((today - df[&#39;DOB&#39;]).dt.days // 365)</pre><p>Why don’t we use Age directly? Because..</p><ul><li>The dataset didn’t have it properly</li><li>We calculate it from DOB (more reliable)</li></ul><p>This is a key data engineering skill. Don’t trust the data — derive what you can.</p><p><strong>More Features</strong></p><pre>df[&#39;tenure_years&#39;] = (today - df[&#39;DateofHire&#39;]).dt.days / 365<br>df[&#39;is_attrition&#39;] = df[&#39;DateofTermination&#39;].notna()<br>df[&#39;is_active&#39;] = df[&#39;DateofTermination&#39;].isna()</pre><p>Now we know how long someone worked, and whether they left or not.</p><p><strong>Handling Missing Values</strong></p><pre>df[&#39;Salary&#39;] = df[&#39;Salary&#39;].fillna(df[&#39;Salary&#39;].median())<br>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].median())</pre><p>Why median? → Because it’s more robust than the mean (less affected by outliers).</p><p><strong>Building Dimension Tables</strong></p><p>At this stage, I moved from cleaning the data to structuring it.</p><p>Instead of keeping repetitive information inside one large table, I started separating descriptive attributes into <strong>dimension tables</strong>.</p><p>This is a key step in building a <strong>star schema</strong>, where each dimension represents a specific aspect of the data.</p><ol><li>Department Dimension</li></ol><pre>dim_department = df[[&#39;Department&#39;]].drop_duplicates().reset_index(drop=True)<br>dim_department[&#39;department_id&#39;] = dim_department.index + 1<br><br>df = df.merge(dim_department, on=&#39;Department&#39;, how=&#39;left&#39;)</pre><p>Here’s what’s happening:</p><ul><li>We extract unique department values</li><li>Assign a surrogate key (department_id)</li><li>Merge it back into the main dataset</li></ul><p>2. Position Dimension</p><pre>dim_position = df[[&#39;Position&#39;]].drop_duplicates().reset_index(drop=True)<br>dim_position[&#39;position_id&#39;] = dim_position.index + 1<br><br>df = df.merge(dim_position, on=&#39;Position&#39;, how=&#39;left&#39;)</pre><p>This follows the same pattern Extract unique positions, Assign IDs, and Link them back to the dataset.</p><p>This makes it easier to group employees by role, and analyze performance by position.</p><p>3. Salary Dimension (with Segmentation)</p><pre>dim_salary = df[[&#39;Salary&#39;]].copy()<br>dim_salary = dim_salary.drop_duplicates().reset_index(drop=True)<br><br>dim_salary[&#39;salary_id&#39;] = dim_salary.index + 1</pre><p>Then we enrich it:</p><pre>dim_salary[&#39;salary_level&#39;] = pd.qcut(<br>    dim_salary[&#39;Salary&#39;],<br>    3,<br>    labels=[&#39;Low&#39;, &#39;Medium&#39;, &#39;High&#39;],<br>    duplicates=&#39;drop&#39;<br>)</pre><p>This dimension doesn’t just store values — it adds <strong>business meaning</strong>:</p><ul><li>Raw salary → numerical</li><li>Salary level → categorical insight</li></ul><p>Now we can easily answer questions like <em>“How many employees fall into high salary groups?”.</em></p><p>3. And Dimension so on…</p><p><strong>Fact Table</strong></p><pre>fact_employees = df[[<br>        &#39;EmpID&#39;,<br>        &#39;Employee_Name&#39;,<br>        &#39;Sex&#39;,<br>        &#39;Age&#39;,<br>        &#39;age_group&#39;,<br>        &#39;tenure_years&#39;,<br>        &#39;is_attrition&#39;,<br>        &#39;is_active&#39;,<br>        &#39;DateofHire&#39;,<br>        &#39;DateofTermination&#39;,<br>        &#39;department_id&#39;,<br>        &#39;position_id&#39;,<br>        &#39;salary_id&#39;<br>    ]].copy()</pre><p>This is the <strong>main table</strong> containing:</p><ul><li>employee info</li><li>foreign keys (department_id, etc.)</li></ul><p><strong>Salary Segmentation (Fun but tricky)</strong></p><pre>pd.qcut(..., 3)</pre><p>Splits salary into Low, Medium, and High.</p><p>We used qcut,because it creates <strong>equal distribution groups</strong>, not equal ranges.</p><h3>Step 3 — Load</h3><pre>df.to_csv(path, index=False)</pre><p>At this stage, the transformed data is saved into structured files.</p><p>Instead of storing everything in one place, I organized the outputs into two categories:</p><ul><li><strong>Processed data</strong> → cleaned and structured tables (fact &amp; dimensions)</li><li><strong>Analytics data</strong> → aggregated tables for reporting</li></ul><pre>if &quot;agg&quot; in name:<br>    path = f&quot;data/analytics/{name}.csv&quot;<br>else:<br>    path = f&quot;data/processed/{name}.csv&quot;</pre><ul><li>Tables containing &quot;agg&quot; are treated as analytics outputs</li><li>The rest are stored as core data tables</li><li>Folders are automatically created using os.makedirs()</li></ul><p>This ensures the pipeline is not only functional but also well-organized and scalable.</p><h3>Step 4 — Insight (Now let’s explore the structured data)</h3><h4>Does manager affect performance?</h4><pre>#Is there any relationship between who a person works for and their performance score?<br><br>df.groupby(&#39;ManagerName&#39;)[&#39;performance_score&#39;] \<br>    .value_counts(normalize=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*tOAEtrMDjer_sDOlSCJzZQ.png" /><figcaption>…so on</figcaption></figure><p>To explore whether a manager has an impact on employee performance, I visualized the distribution of performance scores across different managers.</p><pre>plt.figure(figsize=(10,5))<br>sns.countplot(data=df_analysis, x=&#39;ManagerName&#39;, hue=&#39;performance_score&#39;)<br><br>plt.xticks(rotation=45)<br>plt.title(&#39;Performance Score by Manager&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61jU0ww8izeHiyUkzCxfzw.png" /></figure><p>This chart shows how performance scores are distributed under each manager.</p><blockquote>The majority of employees across almost all managers fall into the <strong>“Fully Meets”</strong> category.</blockquote><p>While some managers have a slightly higher number of “Exceeds” ratings (such as Ketsia Liebig or Brandon Miller), and others show small counts of “Needs Improvement” or “PIP”, these differences are relatively minor.</p><p>Despite minor variations, there is no strong evidence that a specific manager significantly influences employee performance outcomes.</p><ul><li>High performers (“Exceeds”) are distributed across multiple managers</li><li>Underperformance (“Needs Improvement” / “PIP”) appears in small numbers and is not concentrated under a single manager</li><li>Most teams maintain a consistent performance pattern</li></ul><h4>How diverse is the company?</h4><pre>#What is the overall diversity profile of the organization?<br><br># Race<br>df_analysis = df_analysis.merge(<br>    pd.read_csv(&quot;data/processed/dim_race.csv&quot;),<br>    on=&#39;race_id&#39;,<br>    how=&#39;left&#39;<br>)<br><br>df_analysis[&#39;RaceDesc&#39;].value_counts(normalize=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*oDgw4_r02RCyZcfBeMZNyA.png" /></figure><pre>plt.figure(figsize=(8,5))<br>sns.countplot(data=df_analysis, y=&#39;RaceDesc&#39;)<br><br>plt.title(&#39;Race Distribution&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tkM1jozbS98ZB3vcl71dA.png" /></figure><p>In terms of race, the workforce is predominantly <strong>White (60%)</strong>, followed by <strong>Black or African American (26%)</strong> and <strong>Asian (9%)</strong>, while other groups represent a much smaller portion. So, for Racial diversity still has room to improve.</p><pre># Gender<br>df_analysis[&#39;gender&#39;].value_counts(normalize=True)<br><br>df_analysis[&#39;gender&#39;].value_counts().plot(<br>    kind=&#39;pie&#39;,<br>    autopct=&#39;%1.1f%%&#39;<br>)<br>plt.title(&#39;Gender Distribution&#39;)<br>plt.ylabel(&#39;&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*tpPFPtTDIEP8_aWbal9eSw.png" /></figure><p>Gender distribution is relatively balanced, with <strong>56.6% female</strong> and <strong>43.4% male</strong> employees.</p><h4>Best recruiting source for diversity?</h4><pre>#What are our best recruiting sources for diversity?<br><br>cross = pd.crosstab(<br>    df_analysis[&#39;RecruitmentSource&#39;],<br>    df_analysis[&#39;RaceDesc&#39;],<br>    normalize=&#39;index&#39;<br>)<br>cross</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*kU6lSNNSmWIvjQ_tIpRoOQ.png" /></figure><pre>cross.plot(kind=&#39;bar&#39;, stacked=True, figsize=(10,6))<br><br>plt.title(&#39;Diversity by Recruitment Source&#39;)<br>plt.legend(bbox_to_anchor=(1.05,1))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*th2egoFfoqxOjivmKxs2hQ.png" /></figure><ul><li><strong>Diversity Job Fair</strong> stands out immediately — it contributes <strong>100% Black or African American hires</strong>, making it the most targeted diversity channel.</li><li>Platforms like <strong>Indeed</strong> and <strong>LinkedIn</strong> show a <strong>more balanced distribution</strong>, contributing to multiple racial groups.</li><li><strong>Google Search</strong> also brings relatively varied candidates, though still dominated by White hires.</li><li>On the other hand, sources like <strong>Online Web Application</strong> and <strong>Other</strong> are <strong>not diverse at all</strong>, with 100% White representation.</li></ul><p>Note: <strong><em>Not all recruitment channels contribute equally to diversity.</em></strong></p><h4>Bonus — Predicting Attrition</h4><p>Since the ETL pipeline already prepared clean and structured data, I didn’t need to redo preprocessing. I simply used the transformed data and selected a few relevant features — age, tenure (how long someone has worked), salary, and absences.</p><p>These variables are commonly associated with employee behavior, so they made a good starting point.</p><pre>df_analysis = fact \<br>    .merge(absence, on=&#39;emp_id&#39;, how=&#39;left&#39;) \<br>    .merge(salary, on=&#39;salary_id&#39;, how=&#39;left&#39;)<br><br>features = [&#39;age&#39;, &#39;tenure_years&#39;, &#39;absences&#39;, &#39;Salary&#39;]<br>X = df_analysis[features]<br><br>y = df_analysis[&#39;is_attrition&#39;]<br><br>X = X.fillna(X.median())<br><br>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br>from sklearn.ensemble import RandomForestClassifier<br><br>model = RandomForestClassifier(random_state=42)<br>model.fit(X_train, y_train)<br><br>from sklearn.metrics import accuracy_score, classification_report, confusion_matrix<br><br>y_pred = model.predict(X_test)<br><br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(&quot;\nClassification Report:\n&quot;, classification_report(y_test, y_pred))<br>print(&quot;\nConfusion Matrix:\n&quot;, confusion_matrix(y_test, y_pred))<br><br>importance = pd.Series(model.feature_importances_, index=features)<br>print(&quot;\nFeature Importance:\n&quot;, importance.sort_values(ascending=False))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*_vdwLll39E__UKSEMhlnxg.png" /></figure><p>I used a <strong>Random Forest Classifier</strong>, a simple but powerful model for classification tasks.</p><p>After splitting the data into training and testing sets, I trained the model and evaluated its performance.</p><p>Here’s what I got <strong>Accuracy:</strong> 71%, <strong>Precision (attrition):</strong> 59%, and <strong>Recall (attrition):</strong> 59%.</p><p>Confusion Matrix:</p><ul><li>Correctly predicted stay: 32</li><li>Incorrectly predicted leave: 9</li><li>Missed actual attrition cases: 9</li><li>Correctly predicted leave: 13</li></ul><p>The model shows <strong>moderate predictive ability</strong>.</p><p>It can capture general patterns in the data, but it’s not highly reliable — especially when it comes to identifying employees who will actually leave.</p><p>A recall of 59% means —<em> The model can detect more than half of attrition cases, but still misses a significant portion.</em></p><p>One of the most interesting parts is understanding <em>what actually drives the predictions</em>:</p><ul><li><strong>Tenure</strong> → most important (~47%)</li><li><strong>Salary</strong> → second (~23%)</li><li><strong>Absences</strong> → moderate impact</li><li><strong>Age</strong> → least impact among the features</li></ul><h3>Final Thoughts</h3><p>This project started as — <em>“just analyze HR data”.</em></p><p>But it turned into:</p><ul><li>building an ETL pipeline</li><li>designing data models</li><li>answering business questions</li><li>applying machine learning</li></ul><h4>If You’re Learning Data Too…</h4><p>Don’t just analyze clean datasets. But, build pipelines, break things, and fix messy data.</p><p>Because that’s where real learning happens.</p><p>And remember — <em>Data is not valuable because it exists. It becomes valuable when you </em><strong><em>transform it into insight</em></strong><em>.</em></p><p>And boom, done! 💥 You can find the complete flow and all the code on my GitHub. Dive in and have fun exploring!</p><p><a href="https://github.com/jihanKamilah/ETL-HR-Analytics-Project">GitHub - jihanKamilah/ETL-HR-Analytics-Project: Turning messy HR data into clean, structured insights using ETL, star schema, and machine learning.</a></p><p><em>The contents of external submissions are not necessarily reflective of the opinions or work of </em><a href="http://mavenanalytics.io/"><em>Maven Analytics</em></a><em> or any of its team members.</em></p><p><em>We believe in fostering lifelong learning and our intent is to provide a platform for the data community to share their work and seek feedback from the Maven Analytics data fam.</em></p><p><a href="https://medium.com/learning-data/how-to-get-your-work-published-by-learning-data-with-maven-analytics-7df21e466a3e?source=friends_link&amp;sk=020dfac485597d602e218968d9ffb395"><em>Submit your own writing here</em></a><em> if you’d like to become a contributor.</em></p><p><em>Happy learning!</em></p><p><em>-Team Maven</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d520e7da561" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-data/this-is-what-real-data-looks-like-and-how-i-turned-it-into-insights-3d520e7da561">This Is What Real Data Looks Like (And How I Turned It Into Insights)</a> was originally published in <a href="https://medium.com/learning-data">Learning Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Makes a Song Popular?]]></title>
            <link>https://medium.com/data-and-beyond/what-makes-a-song-popular-694dbb54f378?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/694dbb54f378</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spotify-analytics]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 11:13:50 GMT</pubDate>
            <atom:updated>2026-04-28T11:13:50.785Z</atom:updated>
            <content:encoded><![CDATA[<h4>Predicting Hit Songs with R and Machine Learning from Spotify Audio Features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGXMQ0Y57XDYe328Uunxzg.png" /></figure><p>I’ve been using Python for most of my data projects lately. Pandas, Scikit-learn, Matplotlib — hmm.. you know the drill.</p><p>But before that, I had briefly learned R, though not as much as Python. So recently, I thought — <em>What if I go back to R, but focus on building something fun instead of relearning everything from scratch?</em></p><p>Something fun. Something everyone can relate to.</p><p>So I picked music. And one question instantly came to mind:</p><blockquote>What makes a song popular? Can we learn it from Spotify data? Can we even predict whether a song will become a hit?</blockquote><p>That became the perfect excuse to reconnect with R — while building something portfolio-worthy hehehe. Btw, I built this project using <strong><em>Kaggle Notebooks (R environment)</em></strong>, which made it easy to explore the dataset, run analysis, and develop the machine learning model in one place.</p><p>For music platforms like Spotify, popularity isn’t just a vanity metric.</p><p>It influences recommendations, playlist placement, discovery algorithms, chart rankings, label investments</p><p>If we can understand what characteristics are associated with popular songs, we’re touching a real product problem — <strong><em>How can streaming platforms surface songs people are more likely to love?</em></strong></p><h3>Exploring the Dataset</h3><p>I used a <a href="https://www.kaggle.com/datasets/maharshipandya/-spotify-tracks-dataset"><strong>Spotify Tracks Dataset</strong></a> containing song-level audio features such as danceability, energy, loudness, acousticness, valence (musical positivity), speechiness, tempo, popularity score (0–100), etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b17QvzZ0ynENR1VHZyJCvA.png" /><figcaption>Dataset</figcaption></figure><h4>Step 1: Selecting Relevant Columns</h4><pre>df &lt;- df %&gt;%<br>  select(<br>    track_name, artists, track_genre, popularity,<br>    energy, valence, tempo,<br>    danceability, loudness, acousticness, speechiness<br>  )</pre><p>The raw dataset contained many columns, but not all were necessary for this project. So I focused on:</p><ul><li>track name</li><li>artist</li><li>genre</li><li>popularity</li><li>danceability</li><li>energy</li><li>valence</li><li>loudness</li><li>acousticness</li><li>speechiness</li><li>tempo</li></ul><p>This keeps the analysis focused on variables that may relate to popularity.</p><h4>Step 2: Checking Missing Values</h4><p>Before analyzing anything, I checked whether the dataset had missing values.</p><pre>sum(is.na(df))<br><br># Output : 0</pre><p>Good news — There were zero missing values. That meant the dataset was already clean enough to move forward safely.</p><h4>Step 3: Final Cleaning</h4><p>Even though there were no missing values, I still used na.omit() as a final safeguard.</p><pre>df &lt;- na.omit(df)</pre><p>This is a common habit in exploratory workflows to ensure no incomplete rows remain.</p><h3>Exploring Popularity and Audio Features</h3><p>With the dataset cleaned and ready, I moved into the fun part — exploring the patterns behind song popularity.</p><p>Before jumping into machine learning, I wanted to answer a simpler question first — <strong><em>Do certain audio characteristics appear more often in popular songs?</em></strong></p><p>Spotify provides several measurable features that describe how a track sounds — things like energy, danceability, loudness, and mood. So I started by exploring them one by one.</p><h4>Popularity Distribution</h4><p>The first thing I checked was the distribution of popularity scores.</p><pre>ggplot(df, aes(x = popularity)) +<br>  geom_histogram(bins = 30) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*lIqCTK5U2v7wwHSNZiZ0cg.png" /></figure><p>Most songs were concentrated in the lower popularity range, while highly popular tracks were much less common.</p><p>That’s actually what we would expect. In music, thousands of songs get released constantly — but only a smaller number break into mainstream attention.</p><p>This means most songs don’t become hits. This also means predicting popular songs will be more challenging later, since hit tracks are naturally rarer than average ones.</p><h4>Core Feature Analysis: Energy</h4><p>Next, I explored <strong>energy</strong> — a feature that reflects intensity, excitement, and activity.</p><pre>ggplot(df, aes(x = energy, y = popularity)) +<br>  geom_point(alpha = 0.3) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*gHOz4cMsu-1SKXs4IDmNUQ.png" /></figure><p>Songs with medium-to-high energy levels appeared more frequently across stronger popularity ranges. Very low-energy tracks were less represented among top-performing songs.</p><p>This makes sense. Energetic songs often fit:</p><ul><li>workout playlists</li><li>party settings</li><li>driving moods</li><li>replay-friendly environments</li></ul><p>So, high energy may give songs a popularity advantage, even if it doesn’t guarantee success.</p><h4>Core Feature Analysis: Valence</h4><pre>ggplot(df, aes(x = valence, y = popularity)) +<br>  geom_point(alpha = 0.3) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*9EtVFSuFJuVgCkJnCfMKQw.png" /></figure><p>Valence measures musical positivity. Higher valence usually means brighter, happier, more uplifting songs. But the relationship with popularity looked far less obvious.</p><p>Popular songs appeared across low, medium, and high valence levels.</p><p>Which is interesting. People stream heartbreak songs.<br>People stream feel-good anthems.<br>People stream emotional damage at midnight, haha...</p><p>So, Mood matters, but there is no single “happy songs always win” pattern.</p><h4>Core Feature Analysis: Danceability</h4><p>Danceability was one of the more interesting features.</p><pre>ggplot(df, aes(x = danceability, y = popularity)) +<br>  geom_point(alpha = 0.3) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*T2ZNvgyJuHWsWlOSTRur1w.png" /></figure><p>Most songs clustered between moderate to high danceability, and there was a slight upward trend with popularity. More danceable songs tended to perform somewhat better. Still, the effect wasn’t dramatic. Many non-danceable songs were still successful.</p><p>We will say Danceability helps, but it is not a guaranteed formula for popularity.</p><h4>Core Feature Analysis: Loudness</h4><p>Loudness showed a clearer pattern.</p><pre>ggplot(df, aes(x = loudness, y = popularity)) +<br>  geom_point(alpha = 0.3) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*z1Y83x2YSrlkx8iEQ3uFOQ.png" /></figure><p>Songs with higher loudness levels (closer to 0 dB) tended to have stronger popularity scores. Very quiet tracks were less likely to appear among top songs. This may reflect modern production preferences, where polished and punchy tracks grab attention quickly.</p><h4>Core Feature Analysis: Speechiness</h4><p>Speechiness measures how much spoken-word content exists in a track.</p><pre>ggplot(df, aes(x = speechiness, y = popularity)) +<br>  geom_point(alpha = 0.3) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*e_17C-hFYtrK4JC7p9qrUA.png" /></figure><p>Most songs had relatively low speechiness, which is expected for mainstream music. Tracks with very high speechiness levels tended to have lower popularity.</p><p>This could mean songs that feel too talk-heavy are less broadly replayable.</p><blockquote><strong>So, to conclude our exploration…</strong></blockquote><h4>Early Insights Before Modeling</h4><p>Even before using machine learning, a few patterns were already emerging:</p><ul><li>Popular songs often lean energetic</li><li>Danceability helps</li><li>Loudness shows stronger signals than expected</li><li>Mood alone is unpredictable</li><li>Spoken-heavy tracks are less common among hits</li></ul><p>Of course, these are tendencies — not rules. And that’s exactly why the next step was exciting — <strong><em>Could a machine learning model combine these signals and predict a hit song?</em></strong></p><h3>Going Deeper: What actually makes popular songs different from less popular ones?</h3><p>Instead of looking at songs one by one, I grouped tracks into categories and compared them directly.</p><h4>Creating a Popularity Category</h4><p>To simplify the problem, I converted popularity scores into two groups:</p><ul><li><strong>High Popularity</strong> → songs with popularity above 70</li><li><strong>Low Popularity</strong> → everything else</li></ul><p>The code looked like this:</p><pre>df &lt;- df %&gt;%<br>  mutate(high_popularity = ifelse(popularity &gt; 70, &quot;High&quot;, &quot;Low&quot;))</pre><p>Why do this? Because comparing groups is often easier than comparing thousands of raw scores.</p><p>Instead of asking — <em>“What does popularity 63 vs 67 mean?”</em></p><p>We can ask — <em>“How are hit songs different from non-hit songs?”</em></p><h4>Comparing Average Audio Features</h4><p>Next, I summarized the average features for each popularity group:</p><pre>df %&gt;%<br> group_by(high_popularity) %&gt;%<br> summarise(<br>   avg_energy = mean(energy),<br>   avg_valence = mean(valence),<br>   avg_danceability = mean(danceability),<br>   avg_loudness = mean(loudness),<br>   avg_acousticness = mean(acousticness)<br> )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*aN8qzq317ozaDNHSq3de9g.png" /></figure><p>Compared with low-popularity songs, high-popularity tracks were:</p><ul><li><strong>More energetic</strong> (0.67 vs 0.64)</li><li><strong>More positive in mood</strong> (0.51 vs 0.47)</li><li><strong>More danceable</strong> (0.62 vs 0.56)</li><li><strong>Louder</strong> (-6.56 vs -8.33)</li><li><strong>Less acoustic</strong> (0.22 vs 0.32)</li></ul><p>So, popular songs often feel cleaner, punchier, more movement-friendly, and more polished for mainstream listening.</p><p>This doesn’t guarantee success. But it suggests certain production styles are more common among hit songs.</p><h4>Boxplot: Danceability vs Popularity Group</h4><p>After comparing average values, I wanted to go one step deeper. Because averages are useful… but they can also be misleading.</p><p>Two groups might have different means while still sharing very similar distributions. So I visualized <strong>danceability</strong> using a boxplot. Why a boxplot? — Because averages can hide overlap. The chart showed high-popularity songs had a slightly higher median danceability, but both groups overlapped heavily.</p><p>Why danceability? Because earlier analysis suggested it had a <strong>positive relationship with popularity</strong>. Not huge — but noticeable enough to investigate further.</p><pre>ggplot(df, aes(x = high_popularity, y = danceability)) +<br>  geom_boxplot() +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*tTzJUrKnsP6yqzLITZjy5w.png" /></figure><p>Here high-popularity songs had a <strong>slightly higher median danceability</strong> than low-popularity songs. That means hit songs are, on average, more rhythm-friendly and easier to move to.</p><p>But then the important part appeared —<strong> Heavy overlap</strong>.</p><p>Both groups shared a large portion of the same range.</p><p>So the takeaway became clearer. <strong>Being danceable can help a song travel farther — but it does not guarantee success. </strong>That was the first strong sign that popularity likely comes from a <strong>combination of small signals</strong>, not one dominant feature.</p><h4>Mood Classification: Can Emotion Influence Popularity?</h4><p>Numbers like energy and valence are useful. But I wanted to translate them into something more human.</p><p>Because listeners do not say —<em> “I want a track with valence 0.73.”</em></p><p>They say — I want something happy, I want something chill, or I want something emotional.</p><p>So I converted Spotify metrics into simple mood categories.</p><pre>df &lt;- df %&gt;%<br>  mutate(<br>    mood = case_when(<br>      valence &gt;= 0.6 &amp; energy &gt;= 0.6 ~ &quot;Happy&quot;,<br>      valence &lt; 0.4 &amp; energy &lt; 0.4 ~ &quot;Sad&quot;,<br>      TRUE ~ &quot;Neutral&quot;<br>    )<br>  )</pre><p><strong>Why these variables?</strong></p><p>I used:</p><ul><li><strong>Valence</strong> = emotional positivity</li><li><strong>Energy</strong> = intensity / activity level</li></ul><p>Together, they create a surprisingly intuitive emotional map.</p><p>Examples:</p><ul><li>High valence + high energy = upbeat / joyful</li><li>Low valence + low energy = sad / mellow</li><li>Everything else = neutral / mixed mood</li></ul><h4>Visualizing the Mood Space</h4><pre>ggplot(df, aes(x = valence, y = energy, color = mood)) +<br>  geom_point(alpha = 0.4) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*k5dDH7WzkPbVJS3V13WdYw.png" /></figure><p>So… what was the purpose of this chart? — Because this chart was not about prediction. It was about <strong>understanding the emotional landscape of songs</strong>. And it revealed something interesting:</p><p><strong>Most songs lived in the middle, </strong>The Neutral category dominated the chart. That suggests mainstream music often avoids emotional extremes. Instead of being super happy or deeply sad.</p><p>It means extreme moods can be powerful. But moderate moods may be more commercially adaptable. Which might explain why many chart songs feel relatable rather than dramatic.</p><h4>Mood vs Popularity</h4><p>Then I tested whether these moods actually mattered.</p><pre>df %&gt;%<br>  group_by(mood) %&gt;%<br>  summarise(avg_popularity = mean(popularity)) %&gt;%<br>  arrange(desc(avg_popularity))</pre><p>We got:</p><ul><li>Neutral ≈ highest average popularity</li><li>Sad ≈ slightly lower</li><li>Happy ≈ slightly lower</li></ul><h4>Genre Analysis: Which Genres Win?</h4><p>At this point, I had studied audio features.</p><p>But music is not just sound. It is also identity, culture, fanbases, trends, and communities. So I explored genre-level popularity.</p><pre>df %&gt;%<br>  group_by(track_genre) %&gt;%<br>  summarise(avg_popularity = mean(popularity)) %&gt;%<br>  arrange(desc(avg_popularity)) %&gt;%<br>  head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*aaYUon2dvBBDrzYScUwMTA.png" /></figure><p>Then visualized it:</p><pre>df %&gt;%<br>  group_by(track_genre) %&gt;%<br>  summarise(avg_popularity = mean(popularity)) %&gt;%<br>  arrange(desc(avg_popularity)) %&gt;%<br>  head(10) %&gt;%<br>  ggplot(aes(x = reorder(track_genre, avg_popularity), y = avg_popularity)) +<br>  geom_col() +<br>  coord_flip() +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*3GZFpoDr7V9gvitwx0QC-A.png" /></figure><p><strong>What stood out?</strong></p><p>Genres like pop-film, K-pop, chill, sad, grunge, and anime ranked near the top. This was a reminder that popularity is not purely acoustic. Genres often carry:</p><ul><li>strong fandoms</li><li>media exposure</li><li>cultural momentum</li><li>playlist ecosystems</li><li>niche loyalty</li></ul><p>So even if two songs sound similar, genre identity can change reach dramatically.</p><h4>Correlation Check: What Truly Connects With Popularity?</h4><p>Then I tested the raw numeric relationships.</p><pre>cor(numeric_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNRqe06Gz98dlcv543d2-g.png" /></figure><p>or here the viz.</p><pre>corr &lt;- cor(numeric_df)<br><br>corrplot(<br>  corr,<br>  method = &quot;color&quot;,<br>  type = &quot;upper&quot;,<br>  tl.cex = 0.8<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*zERFO5fi3re0SadVx_0kOQ.png" /></figure><p>We notice that most correlations with popularity were tiny. Even the strongest values were weak:</p><ul><li>loudness ≈ +0.05</li><li>danceability ≈ +0.03</li><li>tempo ≈ +0.01</li></ul><p>So, no single audio feature strongly explains popularity. That is huge. You cannot say — <em>“Just make songs louder.” </em>Or — <em>“Just make songs happier.”</em></p><p>Reality is more complex.</p><h4>But Feature Relationships Were Strong</h4><pre>correlation_popularity &lt;- cor(numeric_df)[,&quot;popularity&quot;]<br><br>sort(correlation_popularity, decreasing = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*f31u94lKvEzS_g0ZIzCQQQ.png" /></figure><p>Can’t imagine yet? Here the viz:</p><pre>corr_df &lt;- data.frame(<br>  feature = names(correlation_popularity),<br>  corr = as.numeric(correlation_popularity)<br>)<br><br>corr_df %&gt;%<br>  filter(feature != &quot;popularity&quot;) %&gt;%<br>  ggplot(aes(x = reorder(feature, corr), y = corr)) +<br>  geom_col() +<br>  coord_flip() +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*Ud9rlQ0cuQgrrhG-3_LkuQ.png" /></figure><p>We know that, no single Spotify audio feature had a strong linear relationship with popularity. Even the top feature, <strong>loudness</strong>, was only around <strong>0.05</strong>.</p><p>That is extremely small.</p><p>So if someone says — <em>“Just make the song louder and it will be a hit.”</em></p><p>The data says —<em> Not really.</em></p><p>But, weak correlations do <strong>not</strong> mean the dataset is bad. They mean that popularity is more complex than one metric. A song can be amazing on paper and still flop. Another can go viral for reasons completely outside audio quality.</p><h4>High vs Low Popular Songs</h4><p>Before building a machine learning model, I wanted one final human-level check. Do hit songs actually look different from regular songs?</p><p>So I split tracks into two groups:</p><ul><li><strong>High Popularity</strong> = popularity score 70 or above</li><li><strong>Low Popularity</strong> = below 70</li></ul><pre>df &lt;- df %&gt;%<br> mutate(pop_group = ifelse(popularity &gt;= 70, &quot;High&quot;, &quot;Low&quot;))</pre><p>This created a simpler comparison between likely hit songs and everyone else.</p><h4>Comparing Average Audio Features</h4><p>Then I compared the average values of key Spotify features.</p><pre>df %&gt;%<br> group_by(pop_group) %&gt;%<br> summarise(<br>   danceability = mean(danceability),<br>   energy = mean(energy),<br>   loudness = mean(loudness),<br>   acousticness = mean(acousticness)<br> )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*gyqm-ZqOqOzbb8sdgoC-Cg.png" /></figure><p>We got, popular songs were generally:</p><ul><li><strong>More danceable</strong></li><li><strong>More energetic</strong></li><li><strong>Louder</strong></li><li><strong>Less acoustic</strong></li></ul><p>That pattern actually feels realistic. Many mainstream hits are polished, energetic, and designed for replay value. Meanwhile, lower-popularity songs leaned more acoustic and softer overall.</p><h4>Final Boxplot: Danceability Still Matters</h4><p>To confirm the difference visually, I revisited danceability with a cleaner comparison.</p><pre>ggplot(df, aes(x = pop_group, y = danceability)) +<br> geom_boxplot() +<br> theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*8jkDVM5nkLsJ65mnEPsPdw.png" /></figure><p>High-popularity songs again had a higher median danceability. But there was still a strong overlap. Meaning:</p><ul><li>Danceability helps</li><li>But it does not guarantee popularity</li><li>Some hits are not highly danceable</li><li>Some danceable songs never become hits</li></ul><h3>Building a Hit Song Prediction Model</h3><p>At this point, I stopped asking — <em>Which feature matters most?</em></p><p>And started asking — <em>Can multiple weak signals predict success together?</em></p><p>So I created a target label.</p><pre>df &lt;- df %&gt;%<br> mutate(hit_song = ifelse(popularity &gt;= 70, &quot;Hit&quot;, &quot;Not Hit&quot;))</pre><p>Now the problem became binary classification — Hit or not Hit.</p><h4>Selecting Model Features</h4><p>I used Spotify audio features only.</p><pre>model_df &lt;- df %&gt;%<br> select(<br>   hit_song,<br>   danceability,<br>   energy,<br>   valence,<br>   loudness,<br>   acousticness,<br>   speechiness,<br>   tempo<br> )</pre><p><strong>Why these variables?</strong> Because they describe how a song feels sonically:</p><ul><li>danceability → groove/movement</li><li>energy → intensity</li><li>valence → emotional positivity</li><li>loudness → production punch</li><li>acousticness → organic vs produced</li><li>speechiness → spoken-word style</li><li>tempo → speed</li></ul><p>Then I converted the target into factor format.</p><pre>model_df$hit_song &lt;- as.factor(model_df$hit_song)</pre><h4>Train-Test Split</h4><p>To evaluate fairly, I used an 80/20 split.</p><pre>set.seed(123)<br><br>sample_rows &lt;- sample(1:nrow(model_df), 0.8*nrow(model_df))<br>train &lt;- model_df[sample_rows, ]<br>test &lt;- model_df[-sample_rows, ]</pre><p>That means, we use 80% data for learning and 20% data for testing.</p><h4>First Model: Random Forest</h4><p>I started with Random Forest because it handles nonlinear patterns well and works nicely with tabular data.</p><pre>library(randomForest)<br><br>rf_model1 &lt;- randomForest(<br>  hit_song ~ .,<br>  data = train,<br>  ntree = 100<br>)</pre><p>Nothing special parameters. But here we use ntree, and what’s that? — It means how many decision trees are built.</p><p>More trees usually improve stability.</p><ul><li>100 = fast baseline</li><li>300 = stronger and more stable</li><li>too high = slower training</li></ul><h3>Prediction Results</h3><pre>pred1 &lt;- predict(rf_model1, test)<br><br>mean(pred1 == test$hit_song)</pre><p><strong>The accuracy we got is 97.7%.</strong></p><p>That sounded incredible. Until I checked the confusion matrix.</p><pre>table(Predicted1 = pred1, Actual = test$hit_song)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*dwrjn7C43lwRrvvWRmVUTg.png" /></figure><p>Here, we noticed that the dataset had a class imbalance. There were far more <strong>Not Hit</strong> songs than <strong>Hit</strong> songs.</p><p>So the model became very good at predicting — <em>Probably not a hit.</em></p><p>That boosted accuracy automatically. But it still missed many real hits.</p><ul><li>Correct Hit predictions = 628</li><li>Missed actual Hits = 471</li></ul><p>Meaning it failed to catch a large chunk of successful songs.</p><h4>Second Model: Rebalancing the Classes</h4><p>So I gave more importance to Hit songs.</p><pre>rf_model &lt;- randomForest(<br>  hit_song ~ .,<br>  data = train,<br>  ntree = 300,<br>  classwt = c(Hit = 3, &quot;Not Hit&quot; = 1)<br>)</pre><p>The model now gets penalized more for missing Hits. So instead of playing too safe, it tries harder to detect them.</p><p>Updated Prediction Results</p><pre>mean(pred == test$hit_song)</pre><p>For this model, we got <strong>Accuracy at 96.63%.</strong></p><p>Slightly lower than the first model. But accuracy alone does not tell the full story.</p><pre>table(Predicted = pred, Actual = test$hit_song)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*GFFTE9sPNARafW-sEVpU1g.png" /></figure><p>Compared with the first model, the second model caught <strong>66 more hit songs</strong> while missing <strong>66 fewer real hits</strong>.</p><p>Yes, it also flagged more false positives. But if the business goal is discovering future successful songs…</p><p>That tradeoff can be worth it. But, why…?</p><p>Imagine working at a music label.</p><p>Would you rather:</p><ul><li>Miss tomorrow’s breakout star? or</li><li>Review a few extra candidates that might become hits?</li></ul><p>Most teams would choose option two. That is why the second model is often more useful in the real world, despite slightly lower accuracy.</p><h3>Feature Importance: What Influenced the Model Most?</h3><p>Then I checked which variables the Random Forest relied on most.</p><pre>importance(rf_model)<br>varImpPlot(rf_model)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*XhPwUv1iYYA8rqgtisO2tg.png" /></figure><p>The most influential variables were:</p><ul><li><strong>Acousticness</strong></li><li><strong>Energy</strong></li><li><strong>Loudness</strong></li><li><strong>Valence</strong></li></ul><p>That means the model paid close attention to:</p><ul><li>how produced vs acoustic a song sounds</li><li>how intense it feels</li><li>how strong the production is</li><li>emotional tone</li></ul><p>But, you need take a note, feature importance is different from correlation.</p><p>A variable may have weak direct correlation with popularity but still become useful when combined with others. That is exactly what machine learning captures.</p><h3>Conclusion</h3><p>So… <strong>what actually makes a song popular?</strong></p><p>After exploring Spotify audio features, testing correlations, comparing hit vs non-hit tracks, and building a machine learning model, one thing became clear —<strong> <em>There is no single magic formula for creating a hit song</em></strong><em>.</em></p><p>Popularity is more complex than just energy, danceability, or tempo.</p><p>No individual feature showed a strong linear relationship with popularity. Even the strongest correlation was still weak. That means listeners do not fall in love with songs because of one number.</p><p>But patterns still existed. Hit songs in this dataset tended to be:</p><ul><li>More danceable</li><li>Slightly more energetic</li><li>Louder</li><li>Less acoustic</li><li>More polished for mainstream listening</li></ul><p>And when those features were combined through Random Forest, the model became much better at recognizing hit-like patterns.</p><p>That is the key lesson — <em>Popularity is usually created by combinations, not isolated traits.</em></p><p>Music success often happens when production style, mood, energy, timing, audience fit, and discoverability all align at the right moment… and of course, the artist’s name and reputation often play a major role too.</p><p>In other words — A great song matters. But context matters too.</p><h3>Recommendations for Artists, Labels, and Agencies</h3><p>This analysis shows that no single feature guarantees a hit song, but data can still support better decisions.</p><h4>1. Use Data as Guidance</h4><p>Popular songs in this dataset tended to be More danceable, More energetic, Louder, or Less acoustic. Use these patterns as references, while still protecting the artist’s unique identity.</p><h4>2. Focus on Replay Value</h4><p>Songs that are catchy, emotionally balanced, and easy to revisit may perform better on streaming platforms. Consider factors like hook strength, playlist fit, or listener retention.</p><h4>3. Timing Matters</h4><p>Even strong songs can underperform with poor release timing. Combine song analysis with trend monitoring, release calendar strategy, and marketing momentum.</p><h4>4. Artist Name Still Has Power</h4><p>A known artist often has an advantage through fanbase, visibility, trust, and reach. So branding and audience growth remain critical.</p><h4>5. Use Models as Support Tools</h4><p>Prediction models should not replace creative decisions.But they can help labels or agencies prioritize tracks with stronger commercial signals.</p><blockquote>The best strategy is not creativity vs data — it is using both together.</blockquote><h3>The End…?</h3><p>If you’d like to explore the full code, notebook, and project files, you can check them out here:</p><p><a href="https://github.com/jihanKamilah/Spotify-Hit-Song-Prediction-with-R">GitHub - jihanKamilah/Spotify-Hit-Song-Prediction-with-R: A data science project in R that explores Spotify audio features to understand song popularity and predict hit songs using Random Forest. Includes EDA, feature analysis, classification modeling, and business recommendations for artists and music labels.</a></p><p>But wait… this is only <strong>Part 1</strong>.</p><blockquote>Coming Next: Part 2 🎧</blockquote><p>I’m planning to turn this same dataset into a <strong>Music Recommendation System</strong> using the patterns we discovered in this project.</p><p>That means moving from:</p><blockquote>Can this song become a hit?</blockquote><p>to</p><blockquote>Which songs will you probably love next?</blockquote><p><strong>Stay tuned and follow me so you don’t miss the next part.</strong> And, If you enjoy exploring real-world data projects like this, feel free to check out my profile for more builds, case studies, and experiments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=694dbb54f378" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/what-makes-a-song-popular-694dbb54f378">What Makes a Song Popular?</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Rain Isn’t Just Rain: Building a Flood Risk Dashboard from Weather Data]]></title>
            <link>https://medium.com/data-and-beyond/when-rain-isnt-just-rain-building-a-flood-risk-dashboard-from-weather-data-794c4fbf0d1e?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/794c4fbf0d1e</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[weather-forecasts]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 08:17:43 GMT</pubDate>
            <atom:updated>2026-04-27T09:02:14.067Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How I turned real-time weather data into a simple flood monitoring and prediction system</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDmSBxrSkOJXvMgrg_arPg.png" /></figure><p>Lately, I’ve been noticing how unpredictable the weather has become —especially in Indonesia.<br>Clear skies in the morning can quickly turn into heavy rain in the afternoon — sometimes without any warning.</p><p>This kind of sudden rainfall made me wonder:</p><blockquote><em>“Is there a simple way to not just </em>see<em> the weather, but actually </em>understand the risk behind it<em>?”</em></blockquote><p>Especially in urban areas, where heavy rainfall can quickly lead to flooding, having even a simple risk indicator could be useful.</p><p>That curiosity led me to build this project.</p><h3>Objective</h3><p>The goal of this project is simple:</p><ul><li>Transform raw weather data into meaningful insights</li><li>Provide a simple flood risk indicator (LOW, MEDIUM, HIGH)</li><li>Build an interactive dashboard that is easy to explore</li></ul><p>Instead of just showing numbers like <em>“Rainfall: 16 mm”. </em>I wanted the system to answer <em>“So… is this risky or not?”</em></p><h3>How the Idea Evolved</h3><p>Initially, I only planned to build a basic weather dashboard:</p><ul><li>fetch real-time data</li><li>visualize it</li></ul><p>But then I realized:</p><blockquote><em>A dashboard that only shows data is informative, but not actionable.</em></blockquote><p>So I decided to add a <strong>risk prediction layer</strong> on top of it.</p><p>Not a complex machine learning model, but something interpretable and practical.</p><h3>Data Source</h3><p>For this project, I used OpenWeather API (3-hour forecast data).</p><p>The variables used for Rainfall, Humidity, and Wind speed.</p><p>These are simple, but already give a strong signal for weather conditions.</p><h3>From Data to Flood Risk (Core Logic)</h3><p>At first, I experimented with a machine learning approach.</p><h4><strong>Why Not Machine Learning?</strong></h4><p>At this point, you might be wondering, <em>“Why not just use a machine learning model?”</em></p><p>I actually tried that approach first, using Random Forest. However, there were a few problems:</p><ul><li>The dataset from the API is relatively small</li><li>The labels (flood vs no flood) are not well-balanced</li><li>The model didn’t produce stable or meaningful results</li></ul><p>So instead of forcing ML, I switched to a <strong>rule-based scoring system.</strong></p><h4><strong>Why a Rule-Based Approach Works Better Here</strong></h4><ul><li>It’s <strong>interpretable</strong> → we know exactly why a risk is HIGH or LOW</li><li>It’s <strong>stable</strong> → no randomness from small datasets</li><li>It’s <strong>practical</strong> → easy to adjust thresholds based on domain knowledge</li></ul><p>In real-world scenarios, not every problem needs machine learning.</p><h3>Flood Scoring Logic</h3><p>The scoring system is designed to mimic how flood risk is usually interpreted.</p><h4>Rainfall (Main Driver)</h4><ul><li>&lt; 20 mm → low contribution</li><li>20–55 mm → moderate</li><li>55–100 mm → high</li><li>100 mm → very high</li></ul><h4>Supporting Factors</h4><ul><li>High humidity → increases risk</li><li>Strong wind → possible storm indicator</li></ul><p>Each component contributes to a total score (0–100).</p><h3>Risk Classification</h3><p>The final score is mapped into categories:</p><ul><li>LOW → &lt; 30</li><li>MEDIUM → 30–70</li><li>HIGH → ≥ 70</li></ul><p>This makes the output easier to interpret for users.</p><h3>Dashboard Features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ma688NNGz3LlRF8U-GRx2Q.png" /></figure><p>The dashboard includes:</p><ul><li><strong>🎛️ User Controls (Sidebar)</strong> → To make the dashboard interactive, I added a sidebar that allows users to control what they see.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*BQ3wME88hcq4t5Ecwv-baA.png" /></figure><ul><li>📈 <strong>Rainfall and 24-hour accumulation trends →</strong> along with forecasted <strong>rainfall </strong>and <strong>rain_24h projections</strong>, are presented to highlight both short-term intensity and cumulative precipitation over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyBMF7Vk_WTE5JtWxY1WDQ.png" /></figure><ul><li>📊 <strong>Flood risk probability trend →</strong> presents flood risk level, probability percentage, condition-based recommendations, and temporal risk trends.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3eiOzeesbsL1PlEMha_ig.png" /></figure><ul><li>🗺️ <strong>Interactive flood risk map with city-level insights with Heatmap for risk distribution →</strong> displays flood risk probability, rainfall, 24-hour accumulation, risk level with location-based insights, recomendation action for user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiWehgrkFZU_LOx5NVCoKA.png" /></figure><ul><li>🧾<strong>Table of raw data based on the selected filter → </strong>select province and city, filter risk levels, and switch between map views.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhSLhnRbtfsOIGk4DNGAKw.png" /></figure><h3>Understanding the Visualizations (What Are We Actually Seeing?)</h3><p>At this point, we’re not just building a dashboard — we’re telling a story through data.</p><p>Let’s break down each visualization and why it exists.</p><h4>1. User Controls (Sidebar)</h4><p>To make the dashboard interactive, I added a sidebar that allows users to control what they see.</p><p>Here’s the core part of the implementation:</p><pre>st.sidebar.header(&quot;Filter Panel&quot;)<br>selected_province = st.sidebar.selectbox(&quot;Select Province&quot;, list(province_map.keys()))<br>cities = province_map[selected_province]<br>city = st.selectbox(&quot;Select City&quot;, cities)<br><br>risk_filter = st.sidebar.multiselect(<br>    &quot;Select Risk Level&quot;,<br>    [&quot;HIGH&quot;,&quot;MEDIUM&quot;,&quot;LOW&quot;],<br>    default=[&quot;HIGH&quot;,&quot;MEDIUM&quot;,&quot;LOW&quot;]<br>)<br>show_heatmap = st.sidebar.checkbox(&quot;Show Heatmap&quot;, True)<br>show_marker = st.sidebar.checkbox(&quot;Show Markers&quot;, True)</pre><p><strong>What does the sidebar do?</strong></p><p>The sidebar acts as the <strong>control panel</strong> for the dashboard. Users can:</p><ul><li>Select a province → dynamically updates available cities</li><li>Choose a specific city for detailed analysis</li><li>Filter which risk levels to display (HIGH, MEDIUM, LOW)</li><li>Toggle map layers like heatmap and markers</li></ul><p><strong>How the logic works</strong></p><p>The interaction is designed to be simple but powerful:</p><ul><li><strong>Province → City dependency</strong><br> When a province is selected, the list of cities updates automatically</li></ul><pre>cities = province_map[selected_province]</pre><ul><li><strong>Risk filtering</strong><br> Only selected risk levels will be displayed in the dashboard and map:</li></ul><pre>if risk not in risk_filter:<br> continue</pre><ul><li><strong>Map layer control</strong><br> Users can turn heatmap or markers on/off using checkboxes:</li></ul><pre>if show_heatmap:<br> HeatMap(…)</pre><h4>2. Rainfall Trend (What’s Happening Right Now?)</h4><pre>px.line(df, x=&#39;datetime&#39;, y=&#39;rainfall&#39;)</pre><p>This chart shows rainfall every 3 hours.</p><p><strong>Why this matters:</strong></p><ul><li>It captures <strong>sudden spikes</strong></li><li>Helps us see <strong>short-term weather changes</strong></li></ul><p>Sometimes flooding doesn’t come from long rain, but from <strong>intense rain in a short time</strong>.</p><p>This chart answers <em>“Is it raining heavily right now?”</em></p><h4>3. 24-Hour Rain Accumulation (The Real Flood Signal)</h4><pre>px.line(df, x=&#39;datetime&#39;, y=&#39;rain_24h&#39;)</pre><p>This is where things get more interesting.</p><p>Instead of looking at rainfall per 3 hours, we calculate:</p><pre>df[&#39;rain_24h&#39;] = df[&#39;rainfall&#39;].rolling(8).sum()</pre><p>Because 1 data point = 3 hours; 8 points = 24 hours.</p><p><strong>Why this matters:</strong></p><p>Flood risk is not about <em>current rain</em>, but about <strong>accumulated water</strong>.</p><p>This chart answers <em>“Has it been raining continuously?”</em></p><h4>4. Flood Risk Probability (The “So What?” Layer)</h4><pre>px.line(df, x=&#39;datetime&#39;, y=&#39;ml_proba&#39;)</pre><p>This is the most important chart. It translates raw weather data into something meaningful — <strong>risk level over time.</strong></p><p><strong>Why this matters:</strong></p><ul><li>Users don’t think in mm or humidity %</li><li>They think in <strong>risk</strong></li></ul><p>So instead of <em>“Rainfall is 55 mm”, </em>We show <em>“Flood risk is increasing”.</em></p><p>This chart answers <em>“Is the situation getting dangerous?”</em></p><h4>5. Real-Time Metrics (Quick Snapshot)</h4><pre>col1.metric(&quot;Rainfall (Max 24h)&quot;, ...)<br>col2.metric(&quot;Humidity&quot;, ...)<br>col3.metric(&quot;Wind&quot;, ...)</pre><p>This is designed for <strong>quick reading</strong>.</p><p><strong>Why this matters:</strong></p><ul><li>Not everyone wants to read charts</li><li>Some users just want a quick answer</li></ul><p>So we show:</p><ul><li>max rainfall (last 24h window)</li><li>current humidity</li><li>current wind</li></ul><p>This answers <em>“What’s the situation right now, instantly?”</em></p><h4>6. Flood Risk Map (Spatial Awareness)</h4><p>This is where the dashboard becomes much more powerful. Each city is plotted using:</p><pre>folium.CircleMarker(<br>    location=coords[c],<br>    radius=8,<br>    color=&quot;red&quot; if prob&gt;70 else &quot;orange&quot; if prob&gt;40 else &quot;green&quot;,<br>)</pre><p><strong>Why use a map?</strong></p><p>Because flood risk is <strong>location-based</strong>.</p><p>Charts show time. Maps show <strong>where things are happening</strong>.</p><h4>Province vs City View</h4><p>The dashboard supports two modes:</p><ul><li><strong>Province View</strong> → compare multiple cities</li><li><strong>Single City View</strong> → deep dive</li></ul><p>This is controlled by:</p><pre>st.radio(&quot;Map View Mode&quot;, [&quot;Province View&quot;,&quot;Single City View&quot;])</pre><p><strong>Why this matters:</strong></p><ul><li>Province view → macro insight</li><li>City view → detailed analysis</li></ul><p>This answers <em>“Where is the risk happening?”</em></p><h4>7. Heatmap Layer (Intensity View)</h4><pre>HeatMap(heat_data).add_to(m)</pre><p>Instead of just markers, we add a heatmap.</p><p><strong>Why this matters:</strong></p><ul><li>Shows <strong>density of risk</strong></li><li>Makes patterns easier to spot visually</li></ul><p>This answers <em>“Which areas are more intense overall?”</em></p><h4><strong>8. Data Preview (Exploring the Dataset)</strong></h4><p>At the bottom of the dashboard, I added a simple but useful feature: a <strong>data preview table</strong>.</p><pre>n = st.selectbox(&quot;Rows&quot;, [5,10,20,30])<br>st.dataframe(df.tail(n))</pre><p>This allows users to choose how many rows of data they want to see.</p><p><strong>Why this matters</strong></p><p>Even though the dashboard already provides visualizations, I still wanted users to be able to <strong>see the raw data directly</strong>. Because the table shows the actual values behind it.</p><p>This helps answer questions like:</p><ul><li><em>“What exactly is the rainfall value at this time?”</em></li><li><em>“How does humidity change over each interval?”</em></li></ul><p><strong>How it works</strong></p><ul><li>The selectbox lets users choose the number of rows (5, 10, 20, or 30)</li><li>df.tail(n) shows the latest data points</li><li>st.dataframe() renders it as an interactive table</li></ul><p>So instead of overwhelming users with all the data, we give them <strong>control</strong> over how much they want to explore.</p><h3>Challenges</h3><p>Some interesting challenges along the way:</p><ol><li><strong>Missing rainfall data, </strong>Not all API responses include rainfall → needed fallback handling.</li><li><strong>ML approach didn’t perform well, </strong>Due to limited data → switched to rule-based logic.</li><li><strong>Multi-city data fetching, </strong>Each city requires separate API calls → affects performance.</li></ol><h3>Deployment</h3><p>The app is deployed using <strong>Streamlit Cloud</strong>, connected directly to GitHub.</p><p>Here’s a quick overview of how it works:</p><ul><li>Push your project (e.g. app.py and requirements.txt) to a GitHub repository</li><li>Go to <strong>Streamlit Cloud</strong> and create a new app</li><li>Select your repository and set app.py as the main file</li></ul><p>For the API key, instead of hardcoding it in the code, I used <strong>Streamlit secrets</strong>:</p><ul><li>Open <strong>App Settings → Secrets</strong></li><li>Add your API key like this:</li></ul><pre>API_KEY = &quot;your_api_key_here&quot;</pre><ul><li>Then access it in your code using:</li></ul><pre>API_KEY = st.secrets[&quot;API_KEY&quot;]</pre><p>This way, the API key stays secure and the app can still run properly when deployed.</p><h3>Future Improvements</h3><p>There’s still a lot that can be improved:</p><ul><li>Integrating historical rainfall data</li><li>Adding anomaly detection</li><li>Building a more robust predictive model</li><li>Improving UI/UX for better user experience</li></ul><h3>Closing Thoughts</h3><p>This project started from a simple curiosity:</p><blockquote>“What if weather data could directly tell us about risk?”</blockquote><p>Even with a simple approach, it’s possible to turn raw data into something more meaningful and actionable.</p><p>If you’re learning data or building your portfolio, try building something like this.</p><p>Start simple.<br>Make it useful.<br>Then improve it step by step.</p><p>If you’d like to try the dashboard yourself:</p><p><a href="https://indonesia-flood-risk-dashboard.streamlit.app/">https://indonesia-flood-risk-dashboard.streamlit.app/</a></p><p>And if you’re curious how everything works behind the scenes,<br>you can check out the full code here:</p><p><a href="https://github.com/jihanKamilah/Indonesia-Flood-Risk-Dashboard">GitHub - jihanKamilah/Indonesia-Flood-Risk-Dashboard: Real-time flood risk monitoring and predicting dashboard using weather data and interactive maps (Streamlit + Folium).</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794c4fbf0d1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/when-rain-isnt-just-rain-building-a-flood-risk-dashboard-from-weather-data-794c4fbf0d1e">When Rain Isn’t Just Rain: Building a Flood Risk Dashboard from Weather Data</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Was Tired of Weekly Reports… So I Automated the Entire Thing]]></title>
            <link>https://medium.com/learning-data/i-was-tired-of-weekly-reports-so-i-automated-the-entire-thing-f63f88de59ce?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f63f88de59ce</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 13:31:02 GMT</pubDate>
            <atom:updated>2026-04-21T13:31:02.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>An end-to-end Python pipeline that generates PDF reports and sends them automatically every week</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5melpTVSrCiLLleqUmbhjQ.png" /></figure><p>Let me be honest for a second.</p><p>Weekly reporting sounds simple… until you’re the one doing it.</p><p>Every week, it’s the same cycle:<br>You pull data from multiple sources, clean it, calculate metrics, build charts, format everything nicely… and then send it to stakeholders.</p><p>And then next week?</p><p>You do it all over again.</p><p>At some point, I realized:</p><blockquote>“Why am I repeating the same process every week… manually?”</blockquote><p>So instead of optimizing the steps, I decided to eliminate the repetition entirely. I built a system that does everything for me.</p><p>And in this article, I’ll walk you through how we can build it together.</p><h3>The Idea: Turn a Weekly Task into a System</h3><p>Instead of thinking:</p><blockquote>“How do I make reporting faster?”</blockquote><p>I reframed the question into:</p><blockquote>“How do I make reporting run by itself?”</blockquote><p>That shift changed everything. What I wanted was simple:</p><ul><li>A system that processes data</li><li>Turns it into a clean, structured report (in PDF format)</li><li>Sends it automatically</li><li>And runs every week without me touching anything</li></ul><p>Basically… a mini production system.</p><h3>Who Is This Actually For?</h3><p>This system is not just about automation for the sake of it. It’s designed to make life easier for people who deal with reporting every week.</p><p>For example:</p><ul><li><strong>Data Analysts</strong> no longer need to repeat the same reporting process</li><li><strong>Business Teams</strong> receive consistent and structured reports</li><li><strong>Managers &amp; Stakeholders</strong> can quickly understand performance without digging into raw data</li></ul><p>Instead of spending hours preparing reports, teams can focus on what really matters — analyzing results and making decisions.</p><h3>Why It Matters in a Real Business</h3><p>In real-world environments, reporting is often inconsistent, manual, time-consuming.</p><p>This system solves those problems by:</p><ul><li>standardizing report formats</li><li>reducing human error</li><li>ensuring reports are always delivered on time</li></ul><p>In short, it turns reporting from a task… into a reliable system.</p><h3>Let’s Build the Pipeline Together</h3><p>I broke the entire process into small pieces, just like how a real data pipeline works. It starts with raw data… and ends with a report landing in someone’s inbox.</p><h4>Step1 — Everything starts with raw data</h4><p>Everything starts with raw data.</p><p>In this project, I worked with multiple datasets: orders, customers, products, payments, and reviews.</p><p>The data comes from a <a href="https://www.kaggle.com/datasets/olistbr/brazilian-ecommerce">public e-commerce dataset</a> provided by Olist, which is available on Kaggle — a great resource if you want to explore real-world business data yourself.</p><p>Individually, they don’t tell much. But once we bring them together — that’s when the story begins.</p><pre>def load_data():<br>    return {<br>        &quot;orders&quot;: pd.read_csv(&quot;data/olist_orders_dataset.csv&quot;),<br>        &quot;customers&quot;: pd.read_csv(&quot;data/olist_customers_dataset.csv&quot;),<br>        &quot;items&quot;: pd.read_csv(&quot;data/olist_order_items_dataset.csv&quot;),<br>        &quot;payments&quot;: pd.read_csv(&quot;data/olist_order_payments_dataset.csv&quot;),<br>        &quot;products&quot;: pd.read_csv(&quot;data/olist_products_dataset.csv&quot;),<br>        &quot;reviews&quot;: pd.read_csv(&quot;data/olist_order_reviews_dataset.csv&quot;)<br>    }</pre><p>We’re simply loading each dataset. Nothing fancy yet.</p><p>But the real magic happens here:</p><pre>df = data[&quot;orders&quot;] \<br>    .merge(data[&quot;customers&quot;], on=&quot;customer_id&quot;, how=&quot;left&quot;) \<br>    .merge(data[&quot;items&quot;], on=&quot;order_id&quot;, how=&quot;left&quot;) \<br>    .merge(data[&quot;payments&quot;], on=&quot;order_id&quot;, how=&quot;left&quot;) \<br>    .merge(data[&quot;products&quot;], on=&quot;product_id&quot;, how=&quot;left&quot;) \<br>    .merge(data[&quot;reviews&quot;], on=&quot;order_id&quot;, how=&quot;left&quot;)</pre><p>We combine everything into one single dataset.</p><p>Now, we can see <strong>who bought what, how much they paid, how long delivery took, and how satisfied they were.</strong></p><p>This is the moment raw data becomes something meaningful.</p><h4>Step 2 — Turning Data into Business Metrics</h4><p>At this stage, we stop thinking like a programmer… and start thinking like a business analyst.</p><p>But before we jump into metrics, we need to prepare the data properly.</p><pre>df[&quot;order_purchase_timestamp&quot;] = pd.to_datetime(df[&quot;order_purchase_timestamp&quot;])<br>df[&quot;order_delivered_customer_date&quot;] = pd.to_datetime(df[&quot;order_delivered_customer_date&quot;])<br>df[&quot;order_estimated_delivery_date&quot;] = pd.to_datetime(df[&quot;order_estimated_delivery_date&quot;])</pre><p>Here, we convert raw timestamps into proper datetime format.<br>This allows us to calculate time-based insights like delivery duration and delays.</p><p>Then we start adding logic:</p><pre>df[&quot;delay_days&quot;] = (<br>    df[&quot;order_delivered_customer_date&quot;] - df[&quot;order_estimated_delivery_date&quot;]<br>).dt.days<br><br>df[&quot;is_delayed&quot;] = df[&quot;delay_days&quot;] &gt; 0</pre><p>Now we can clearly identify which orders are delayed. And for customer behavior:</p><pre>df[&quot;is_repeat_customer&quot;] = df[&quot;order_purchase_timestamp&quot;] &gt; df[&quot;first_order_date&quot;]</pre><p>This helps us understand whether customers are new or returning.</p><p>This step may look simple, but it’s what transforms raw data into something ready for real analysis.</p><p>We’re no longer just cleaning data — we’re shaping it into something decision-makers can use. Here’s where we define key metrics:</p><pre>df[&quot;revenue&quot;] = df[&quot;price&quot;] + df[&quot;freight_value&quot;]<br>df[&quot;profit&quot;] = df[&quot;price&quot;] - df[&quot;freight_value&quot;]<br><br>#......and so on</pre><p>Simple, but powerful. We’re translating transactions into:</p><ul><li>Revenue (what the business earns)</li><li>Profit (a basic profitability estimate)</li></ul><p>All of these calculations are then organized inside a dedicated metrics function:</p><pre>metrics[&quot;revenue_current&quot;] = df_current[&quot;revenue&quot;].sum()<br>metrics[&quot;orders_current&quot;] = df_current[&quot;order_id&quot;].nunique()<br><br>metrics[&quot;aov_current&quot;] = (<br>    metrics[&quot;revenue_current&quot;] / metrics[&quot;orders_current&quot;]<br>)</pre><p>But it doesn’t stop there. The system also builds deeper insights like:</p><pre>monthly = df.groupby(&quot;month&quot;).agg({<br>    &quot;revenue&quot;: &quot;sum&quot;,<br>    &quot;profit&quot;: &quot;sum&quot;,<br>    &quot;order_id&quot;: &quot;nunique&quot;<br>})<br><br>monthly[&quot;growth&quot;] = monthly[&quot;revenue&quot;].pct_change() * 100<br>monthly[&quot;moving_avg&quot;] = monthly[&quot;revenue&quot;].rolling(3).mean()</pre><p>Now we’re not just looking at totals — we’re tracking trends, growth, and performance over time.</p><p>Everything is centralized in one place, so every report uses the same logic, the same definitions, and stays consistent.</p><p>Little by little, the dataset evolves. It’s no longer just rows and columns — it becomes a business story.</p><p>One small detail that makes this system feel more real. Instead of processing all data at once, we simulate a reporting cutoff.</p><pre>def simulate_data(df, cutoff_date):<br>    return df[df[&quot;order_purchase_timestamp&quot;] &lt;= cutoff_date].copy()</pre><p>Each time the pipeline runs, it only looks at data up to a certain date.</p><p>This mimics how real business reports work — you only analyze data available up until that reporting period.</p><p>So even though the dataset is historical, the system behaves like a live weekly reporting cycle.</p><h4>Step 3 — Making the Numbers Talk</h4><p>Here’s something I learned — <strong>Metrics alone are not enough.</strong></p><p>You can calculate everything perfectly… but if no one understands what it means, it’s useless. So I added a layer of interpretation.</p><pre>def generate_insights(metrics):<br>    insights = []<br><br>    # PROFIT VS REVENUE<br>    if metrics[&quot;profit_current&quot;] &lt; metrics[&quot;revenue_current&quot;]:<br>        insights.append(&quot;Revenue is growing but profit margin is thin, indicating high logistics or operational costs.&quot;)<br><br>    # GROWTH STABILITY<br>    growth_volatility = metrics[&quot;monthly&quot;][&quot;growth&quot;].std()<br><br>    if growth_volatility &gt; 50:<br>        insights.append(&quot;Revenue growth is highly volatile, indicating unstable business performance.&quot;)<br>    else:<br>        insights.append(&quot;Revenue growth is relatively stable.&quot;)<br><br><br>    #.....and so on</pre><p>This is not machine learning. It’s simple rule-based logic.</p><p>But it does something important —<strong> It turns numbers into decisions.</strong></p><h4>Step 4 — Automatically Generating the Report</h4><p>This is where everything starts to feel real.</p><p>Instead of manually creating slides every week…<br> we let the system generate a report for us.</p><pre>generate_report(metrics, insights, filename=filename)</pre><p>Behind this function, the system:</p><ul><li>Builds charts using matplotlib</li><li>Organizes tables using ReportLab</li><li>Structures everything into a clean PDF</li></ul><p>The report includes:</p><ul><li>executive summary</li><li>KPI comparisons</li><li>revenue, profit, and AOV trends</li><li>product performance</li><li>delivery analysis</li><li>customer insights</li></ul><p>Inside this function, the report is built step by step.</p><p>First, charts are generated and saved:</p><pre>plt.savefig(&quot;revenue_chart.png&quot;)</pre><p>Then those visuals are inserted into the PDF:</p><pre>content.append(Image(&quot;revenue_chart.png&quot;, width=450, height=220))</pre><p>Tables are also created programmatically:</p><pre>table = Table(table_data)</pre><p>So instead of designing reports manually, we’re essentially coding the layout once — and reusing it forever.</p><p>That’s what makes the output consistent, clean, and scalable.</p><p><strong>What the Report Actually Looks Like</strong></p><p>Here’s a snapshot of the generated report from the first run ( June 1st, 2018)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*hhmfGXrDun4c-6-ggNNgRQ.png" /><figcaption>PDF Header</figcaption></figure><p>This section displays only the title and the date the data was last retrieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*8wKB-xCFM6Jp2Ow2cUBdsw.png" /><figcaption>Executive Summary</figcaption></figure><p>From the executive summary alone, we can already see a quick overview of the business:</p><ul><li>Revenue in 2018 (up to the selected week) is lower than 2017 in total</li><li>Total orders also decreased</li><li>AOV remains relatively stable</li><li>Delivery performance shows ~9.36% delay rate</li><li>Customer satisfaction sits at an average score of 3.91</li></ul><p>Even without deep analysis, this section already tells a story — the business might be experiencing a slowdown, but operational performance is still relatively stable.</p><p><strong><em>But keep in mind that 2018 isn’t over yet — we’re still halfway through — so there’s still a chance it could go up!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*9ejA37aU5bmkd38-pS9NFQ.png" /><figcaption>Revenue Analysis</figcaption></figure><p>The revenue trend comparison between 2017 and 2018 shows something interesting.</p><p>At the beginning of the year, 2018 revenue is significantly higher than 2017— even reaching over <strong>600% growth in January</strong>.</p><p>The data shows that there is still a monthly increase compared to 2017. However, there are gradual signs that sales are declining as the months go by.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*QMX5ilDVsqU7RBU9Fy_PJA.png" /><figcaption>Profit Analysis</figcaption></figure><p>The profit trend comparison between 2017 and 2018 also reveals a similar pattern.<br>At the start of the year, 2018 profit is dramatically higher than 2017 — even surpassing 600%+ growth in January.</p><p>The data indicates that profits consistently outperform 2017 in the following months. However, just like the revenue trend, there are gradual signs of slowing growth over time, suggesting that while profitability remains strong, the rate of increase is beginning to stabilize.</p><p>This is a positive signal, as the profit trend closely follows the revenue pattern — indicating that the company is not only generating higher sales but also maintaining healthy profitability alongside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*FsV0C7k0mTUzI4VyUgntaQ.png" /><figcaption>AOV Analysis</figcaption></figure><p><strong>AOV (Average Order Value)</strong> is the average amount of money spent per transaction. In simple terms, it shows how much a customer spends each time they place an order.</p><p>From the chart, we can see that AOV in 2018 is generally <strong>lower than in 2017 across most months</strong>, especially at the beginning of the year with declines ranging from around 2% to nearly 14%. Only in May is there a slight increase compared to the previous year.</p><p>This indicates that even though revenue and profit are increasing, <strong>the value per transaction is actually decreasing</strong>. In other words, the growth is likely driven by <strong>a higher number of transactions</strong>, rather than customers spending more on each purchase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*dr1x2CVGHnuSGUyjqsD5SA.png" /><figcaption>Top Product</figcaption></figure><p>Looking at the top revenue drivers this year, a few categories really stand out:</p><ul><li><strong>relogios_presentes</strong> and <strong>beleza_saude</strong> are basically neck-and-neck at the top, both pulling in <strong>~510K+ revenue</strong>. That’s a strong signal that gifts and beauty/health products are in high demand.</li><li>Right behind them: <strong>informatica_acessorios</strong> and <strong>esporte_lazer</strong> — tech and lifestyle categories are still going strong.</li><li>Home-related categories like <strong>cama_mesa_banho</strong> and <strong>utilidades_domesticas</strong> are also performing solidly → people are still investing in their living spaces.</li></ul><p>On the lower end — <strong>automotivo</strong>, <strong>bebes</strong>, and <strong>cool_stuff</strong> bring in less revenue compared to others.</p><p><strong>Quick takeaway: </strong>Customers seem to be spending more on self-care, gifts, and lifestyle rather than niche or need-based categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*PhlUksSXZ-MgPxnWMzXWNg.png" /><figcaption>Delivery Performance</figcaption></figure><p>Now here’s where things get a bit interesting 👀</p><p><strong>Top 5 States by Delay Rate</strong></p><p><strong>SE (Sergipe)</strong> has the highest delay rate (~33%). Followed by <strong>AL, CE, PA, and MA.</strong></p><p><strong>This suggests</strong>: there may be logistical challenges in certain regions — could be distance, infrastructure, or delivery partners.</p><p><strong>Overall Delivery Stats</strong></p><ul><li><strong>Delay Rate: 9.36%</strong> → roughly 1 in 10 orders is delayed</li><li><strong>Avg Delay: -10.76 days</strong> → this is actually GOOD! It means deliveries are, on average, arriving earlier than expected.</li></ul><p>So even though some areas struggle, overall delivery performance is still pretty solid.</p><p><strong>Product Categories with Highest Delay</strong></p><ul><li><strong>casa_conforto_2</strong> → super high delay rate at <strong>60%</strong> 😳</li></ul><p>Others include:</p><ul><li><strong>moveis_colchao_e_estofado</strong></li><li><strong>fashion_underwear_e_moda_praia</strong></li><li><strong>artigos_de_natal</strong></li><li><strong>audio</strong></li></ul><p>Likely reasons: Bulky items (like furniture) are harder to ship, and Seasonal products (like Christmas items) spike demand and cause delays.</p><p><strong>Quick takeaway:</strong> The bigger or more seasonal the product, the higher the chance of delays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Tz8_sWS-V66-scUvh9_C8w.png" /><figcaption>Payment Behavior</figcaption></figure><p>This one’s very clear-cut:</p><ul><li><strong>Credit Card = 75%</strong> (dominates heavily)</li><li><strong>Boleto = 19.1%</strong></li><li><strong>Voucher = 4.8%</strong></li><li><strong>Debit Card = 1.1%</strong> (barely used)</li></ul><p><strong>Quick takeaway: </strong>Customers love flexibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*k0VczvVE2TuWSbrcYen4zQ.png" /><figcaption>Customer Experience</figcaption></figure><p>The review score distribution tells quite an interesting story about how customers feel.</p><p>Most customers are actually pretty happy — <strong>5-star reviews dominate the chart by a large margin</strong>, which is always a great sign. It means a big chunk of users had a really positive experience.</p><p>That said, it’s not all perfect:</p><ul><li>There’s still a noticeable number of <strong>1-star and 4-star reviews</strong>, showing that some customers didn’t have the best experience.</li><li>The <strong>average review score sits at 3.91</strong>, which puts overall satisfaction in the “good, but not amazing yet” category.</li></ul><p><strong>In short</strong>: customers generally like the service, but there’s still room to level up and turn those “okay” experiences into “wow” moments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*nGLZm3ukfzIWBxH64SJ9pg.png" /><figcaption>Key Insight</figcaption></figure><p>From several supporting charts and analyses, a few important patterns start to emerge:</p><ul><li><strong>Revenue is going up, but profit margins are thin →</strong> This suggests that while the business is making more money, <strong>costs (especially logistics or operations)</strong> are eating into profits.</li><li><strong>Revenue growth is quite volatile →</strong> Some periods show strong spikes, while others dip — meaning the business performance isn’t very stable yet.</li><li><strong>The business relies heavily on new customers →</strong> Growth seems driven more by acquisition rather than retention, which could be risky long-term if not balanced.</li><li><strong>Delayed orders = unhappy customers →</strong> There’s a clear relationship where late deliveries significantly <strong>drag down customer satisfaction scores</strong>.</li><li><strong>Customer satisfaction is decent, but not outstanding →</strong> This aligns with the average score (~3.91), showing there’s still <strong>plenty of room for improvement</strong>.</li><li><strong>Top revenue comes from São Paulo (SP) →</strong> This region is the biggest contributor, making it a key market to focus on.</li><li><strong>Credit cards dominate transactions →</strong> Not only are they the most used payment method, but <strong>credit card users also tend to spend more per order</strong>.</li></ul><p>Take note, all of these insights are based on data <strong>up until June 1st, 2018.</strong></p><p>At the center of everything is one main pipeline.</p><pre>data = load_data()<br>df = transform_data(data)<br>df_sim = simulate_data(df, cutoff_date)<br><br>metrics = compute_metrics(df_sim, cutoff_date)<br>insights = generate_insights(metrics)<br><br>generate_report(metrics, insights, filename=filename)</pre><p>This is where everything connects.</p><p>From raw data → to metrics → to insights → to report → to email.</p><p>Instead of running multiple scripts manually, everything flows in one seamless process. That’s what turns this into a real end-to-end system.</p><h4>Step 5 — Sending It via Email</h4><p>Now imagine this:</p><p>You finish generating the report, and then you still have to send it manually every week.</p><p>That’s exactly what I wanted to eliminate. So I automated it.</p><pre>with smtplib.SMTP_SSL(&#39;smtp.gmail.com&#39;, 465) as smtp:<br>    smtp.login(EMAIL_SENDER, EMAIL_PASSWORD)<br>    smtp.send_message(msg)</pre><p>The system:</p><ul><li>creates the email</li><li>writes the subject dynamically</li><li>attaches the PDF</li><li>and sends it automatically</li></ul><p>The email looks clean and ready — no extra effort needed.</p><p>No more — forgetting to send reports, rewriting email bodies, and attaching the wrong file.</p><p><strong>A Quick Note on Security</strong></p><p>Of course, sending emails like this requires credentials. Instead of hardcoding sensitive information like:</p><ul><li>email address</li><li>app password</li><li>recipient</li></ul><p>I stored them securely using environment variables. In this project, I used <strong>GitHub Secrets</strong> to keep everything safe.</p><h4><strong>Step 6 — Letting It Run on Its Own</strong></h4><p>This is where the project transforms into a real system.</p><p>I used GitHub Actions to schedule everything:</p><pre>on:<br>  schedule:<br>    - cron: &#39;0 1 * * 1&#39;</pre><p>Which means the pipeline runs automatically every Monday.</p><p>No manual execution. No reminders needed.</p><p>You literally wake up, and the report is already delivered.</p><p>That’s when it clicked for me. This is no longer just a script —<strong> This is automation.</strong></p><p><strong>How It All Connects (GitHub + Secrets + Automation)</strong></p><p>To make this work end-to-end, there are a few important pieces behind the scenes.</p><p>First, the project needs to live in a GitHub repository.</p><p>Then, we create a workflow file (.github/workflows/auto-report.yml)<br> that tells GitHub:</p><ul><li>when to run</li><li>what environment to use</li><li>and which script to execute</li></ul><p>But the most important part is setting up the <strong>Secrets</strong>.</p><p>Inside GitHub:</p><ol><li>Go to your repository</li><li>Open <strong>Settings → Secrets and Variables → Actions</strong></li><li>Add the following:</li></ol><ul><li>EMAIL_SENDER → your email address</li><li>EMAIL_PASSWORD → your app password (not your actual email password)</li><li>EMAIL_RECEIVER → recipient email</li></ul><p>Once these are set, GitHub automatically injects them into your workflow as environment variables.</p><p>And that’s how this line works safely:</p><pre>EMAIL_SENDER = os.getenv(&quot;EMAIL_SENDER&quot;)</pre><p>Once everything is set up — the code, the workflow, and the secrets — <br> it’s time to actually run it.</p><p>And this is honestly one of the most satisfying parts.</p><p>You go to your GitHub repository, open the <strong>Actions</strong> tab, and trigger the workflow.</p><p>Just one click. That’s it.</p><p>Behind the scenes, GitHub starts doing everything for you:</p><ul><li>it spins up a virtual environment</li><li>installs all the dependencies</li><li>runs your Python pipeline</li><li>generates the PDF report</li><li>sends the email automatically</li></ul><p>All of this… without touching your local machine.</p><p>The first time you run it, the system generates a report for the initial date:</p><p>👉 <strong>Week ending: 01 June 2018</strong></p><p>Then something interesting happens.</p><p>When you run it again the next week — you don’t change anything manually.</p><p>But the system does.</p><p>Because of this small piece of logic:</p><pre>run_count = get_run_count()<br>cutoff_date = start_date + pd.Timedelta(days=7 * run_count)</pre><p>Each run automatically shifts the reporting date forward by one week.</p><p>So:</p><ul><li>First run → 1 June 2018</li><li>Second run → 8 June 2018</li><li>Third run → 15 June 2018</li></ul><p>And it keeps going.</p><p>Just like a real weekly reporting cycle.</p><h4>Fully Automated Loop</h4><p>And here’s where everything connects beautifully:</p><ol><li>GitHub Actions triggers the workflow every Monday</li><li>The pipeline runs automatically</li><li>A new report is generated</li><li>The email is sent</li><li>The system updates its internal state (state.txt)</li><li>The next run continues from the next week</li></ol><p>No manual tracking. No resetting dates. No human intervention.</p><h3>The Ending — ?</h3><p>What started as a small frustration — weekly reports that were repetitive and time-consuming — turned into something much bigger.</p><p>An automated, end-to-end reporting system.</p><p>Not just a script, but a system that generates reports and delivers them automatically.</p><h4>Final Note</h4><p>This project uses historical data, but the goal is to simulate a real-world reporting workflow — structured, consistent, and automated.</p><p>I’ve got a full technical version of this project up on GitHub — so if you already get the idea from this Medium article, feel free to check it out there and try building your own version!</p><blockquote>Just remember, don’t copy-paste 😉 take the time to understand it and recreate it in your own way — that’s where the real learning happens.</blockquote><p>Also, don’t be shy to hit that clap, drop a reply, or give me a follow hehe. Stay tuned for more projects in my portfolio coming soon — let’s grow together!~~~</p><p><a href="https://github.com/jihanKamilah/Weekly-Business-Report-Automation/">GitHub - jihanKamilah/Weekly-Business-Report-Automation: Automated ETL pipeline with weekly business report generation and email delivery using Python and GitHub Actions.</a></p><p><em>The contents of external submissions are not necessarily reflective of the opinions or work of </em><a href="http://mavenanalytics.io/"><em>Maven Analytics</em></a><em> or any of its team members.</em></p><p><em>We believe in fostering lifelong learning and our intent is to provide a platform for the data community to share their work and seek feedback from the Maven Analytics data fam.</em></p><p><a href="https://medium.com/learning-data/how-to-get-your-work-published-by-learning-data-with-maven-analytics-7df21e466a3e?source=friends_link&amp;sk=020dfac485597d602e218968d9ffb395"><em>Submit your own writing here</em></a><em> if you’d like to become a contributor.</em></p><p><em>Happy learning!</em></p><p><em>-Team Maven</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f63f88de59ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-data/i-was-tired-of-weekly-reports-so-i-automated-the-entire-thing-f63f88de59ce">I Was Tired of Weekly Reports… So I Automated the Entire Thing</a> was originally published in <a href="https://medium.com/learning-data">Learning Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Stock Forecasting Dashboard with Prophet & ARIMA Modeling]]></title>
            <link>https://medium.com/learning-data/building-a-stock-forecasting-dashboard-with-prophet-arima-modeling-68101307a0bf?source=rss-cd3dfd31e5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/68101307a0bf</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[arima]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[prophet]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Jihan Kamilah]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-04-01T13:31:01.587Z</atom:updated>
            <content:encoded><![CDATA[<h4>But… Can We Really Predict Stock Prices?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfrMB-s6lsm5k1GSDYLKBQ.png" /></figure><p>Have you ever stared at a stock chart and wondered:</p><blockquote>“Is there a way to predict where this is going next?”</blockquote><p>had the same thought.</p><p>So instead of just guessing, I decided to build something — a simple dashboard that can <strong>analyze stock prices and generate forecasts</strong>.</p><p>Not something perfect. Not something production-level.</p><p>Just something real, messy, and… learnable Hehe</p><h3>Why I Built This</h3><p>So here’s what happened.</p><p>I started playing around with stock data. Pulled a dataset, plotted it, just exploring.</p><p>Everything was fine… until I thought—<strong><em>“wait, can I actually predict this?”</em></strong></p><p>And that’s where things got tricky.</p><p>I tried reading about forecasting models, but it felt like too much all at once. So instead of trying to understand everything first, I just jumped in and started building.</p><p>No clear plan, honestly.</p><p>I just wanted a simple dashboard where I could see the data, try a model, and see what comes out of it.</p><p>And somehow… that turned into this project.</p><h3>What We’re Building</h3><p>I created a dashboard where you can:</p><ul><li>Select a stock</li><li>Choose a date range</li><li>Forecast future prices</li><li>Compare two models</li></ul><h3>Turning It Into a Real Dashboard</h3><p>So at this point, I wasn’t just experimenting anymore…<br>I wanted something I could actually <em>interact with</em>.</p><p>That’s when I decided to wrap everything into a Streamlit app and Ngrok for options.</p><h3>Setting Up the Interface</h3><pre>st.set_page_config(layout=&quot;wide&quot;)<br>st.title(&quot;📊 Stock Forecast Dashboard&quot;)</pre><p>Nothing fancy here — just setting up a clean layout and a title so it doesn’t look empty.</p><h3>Sidebar Interactive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*ZdUA5Lh2KKdrnuDgrUdCVg.png" /><figcaption>Siderbar</figcaption></figure><p>Then I moved to the sidebar, because I wanted this to feel interactive.</p><pre>start_date = st.sidebar.date_input(&quot;Start date&quot;, datetime.date(2020,1,1))<br>end_date = st.sidebar.date_input(&quot;End date&quot;, datetime.date(2021,1,1))</pre><p>So now, I can control the time range without touching the code.</p><h4>Choosing Stocks Dynamically</h4><p>Instead of hardcoding a ticker, I used a list:</p><pre>ticker_list = pd.read_csv(&#39;Code &amp; Tickers Data/yahoo_tickers.txt&#39;, header=None)[0].tolist()ticker = st.sidebar.selectbox(<br>    &quot;Stock&quot;,<br>    ticker_list,<br>    index=ticker_list.index(&quot;AA&quot;)<br>)</pre><p>This part made a huge difference.</p><p>Now I can just switch stocks from a dropdown instead of rewriting code every time.</p><h4>Forecast Control</h4><p>I also added a slider:</p><pre>n_day = st.sidebar.slider(&quot;Forecast Days&quot;, 1, 60, 7)</pre><p>So I can quickly test — short forecasts and longer forecasts without rerunning everything manually.</p><h3>Load Data (and avoiding pain)</h3><p>At first, I was calling the API directly every time…</p><p>Which was slow and honestly kinda wasted time. So I added caching:</p><pre>@st.cache_data<br>def load_data(ticker):<br>    data = yf.download(ticker, start=start_date, end=end_date)<br>    data.reset_index(inplace=True)</pre><p>This basically tells app — <strong>“<em>hey, don’t fetch the same data again if nothing changed”. </em></strong>Super helpful &gt;&lt;</p><h3>Cleaning Weird Data</h3><p>Then I ran into something random.</p><p>Sometimes the columns came in a weird format (MultiIndex). So I added this:</p><pre>if isinstance(data.columns, pd.MultiIndex):<br>    data.columns = data.columns.get_level_values(0)</pre><p>Not something I expected… but yeah, real data is kinda messy.</p><h3>Adding KPI Cards (so it’s not just charts)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-x3oZMwt6zcPCemXCs1rA.png" /><figcaption>KPI Cards</figcaption></figure><p>At some point, I realized— <em>“Hmm, charts are nice… but I kinda want a quick summary too.”</em></p><p>So I added this section:</p><pre>last_price = float(data[&#39;Close&#39;].iloc[-1])<br>first_price = float(data[&#39;Close&#39;].iloc[0])<br><br>change = last_price - first_price<br>pct_change = (change / first_price) * 100</pre><p>Basically, I’m pulling:</p><ul><li>The <strong>latest price</strong></li><li>Calculating how much it changed and the percentage</li></ul><p>Then I display it like this:</p><pre>col1.metric(&quot;Last Price&quot;, f&quot;{last_price:.2f}&quot;)<br>col2.metric(&quot;Change&quot;, f&quot;{change:.2f}&quot;)<br>col3.metric(&quot;% Change&quot;, f&quot;{pct_change:.2f}%&quot;)</pre><p>And I like this part a lot.</p><p>Because instead of reading through the whole chart, I can instantly see:</p><ul><li>Where the price is now</li><li>How much did it moved</li><li>Whether it went up or down</li></ul><p>It’s like a quick summary before the deep dive.</p><h3>Adding a Raw Data View (because I needed to see what I’m working with)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6LDXbYmzjP7n3hoPOgroQ.png" /><figcaption>Raw Data Overview</figcaption></figure><p>Before doing anything fancy</p><p>I realized something — <em>Wait… I should probably see the actual data first.</em></p><p>Not just charts. Not predictions. The raw numbers.</p><p>So I added a simple section:</p><pre>st.subheader(&quot;Raw Data&quot;)</pre><p>Instead of hardcoding it, I made it flexible:</p><pre>show_last = st.number_input(<br>    &quot;Rows&quot;,<br>    min_value=5,<br>    max_value=len(data) if not data.empty else 100,<br>    value=20,<br>    step=5,<br>    label_visibility=&quot;collapsed&quot;<br>)</pre><p>So now I can control — How many rows I want to seewithout touching the code.</p><p>Then I connect it to the dataframe:</p><pre>st.dataframe(data.tail(int(show_last)), use_container_width=True)</pre><p>This just shows the latest rows based on the number I selected.</p><h3>Preparing Data for Models</h3><p>Then came the usual step again:</p><pre>df = data[[&#39;Date&#39;,&#39;Close&#39;]].copy()<br>df.columns = [&#39;ds&#39;,&#39;y&#39;]<br>df = df.dropna()</pre><p>At first, this looked like just renaming column — but it’s actually me getting the data into the exact format the models expect.</p><p>I’ve learned the hard way that <strong>if Prophet doesn’t see </strong><strong>ds and </strong><strong>y, it just refuses to work.</strong></p><h3>Guarding Against Errors</h3><p>This part saved me multiple times, as the API sometimes returns nothing.</p><pre>if data.empty:<br>    st.stop() <br>if df.shape[0] &lt; 10:<br>    st.stop()</pre><h3>Running the Models (for real this time)</h3><p>Then I plugged the models into the app.</p><p><strong>Prophet:</strong></p><pre>prophet_model = Prophet()<br>prophet_model.fit(df)<br>future = prophet_model.make_future_dataframe(periods=n_day)<br>forecast_prophet = prophet_model.predict(future)</pre><p>Prophet is designed to handle time series data that has clear trends and seasonality. This model actually —</p><ul><li>Automatically captures trends over time</li><li>Can model seasonality (like weekly or yearly patterns)</li></ul><p>So instead of manually figuring out patterns, Prophet kind of <em>does that for you</em>.</p><p>In this case, I just feed it the data, tell it how many days I want to forecast, and it generates future predictions.</p><p><strong>ARIMA:</strong></p><pre>model = ARIMA(df[&#39;y&#39;], order=(5,1,0))<br>model_fit = model.fit()</pre><p>ARIMA is a bit more “classical” compared to Prophet.</p><p>It doesn’t automatically detect patterns the same way — instead, it relies on past values (autoregression), differences between values (to remove trends), and moving averages.</p><p>Which means — you actually have to think more about the data. But that’s also its strength.</p><p>ARIMA works really well when:</p><ul><li>The data is relatively stable</li><li>Patterns are consistent</li><li>You want a more statistical approach</li></ul><h3>Visualizing Everything Together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzgTzKdz0RAD5k5u9kfpsg.png" /><figcaption>Model Prediction Comparison</figcaption></figure><p>This was probably my favorite part. I built a single chart that combines:</p><ul><li>Actual data</li><li>Prophet forecast</li><li>ARIMA forecast</li></ul><pre>fig = go.Figure()<br>fig.add_trace(go.Scatter(<br>    x=df[&#39;ds&#39;],<br>    y=df[&#39;y&#39;],<br>    name=&#39;Actual&#39;<br>))</pre><p>Then I layered the models on top. And it all made sense visually.</p><h3>Making It Interactive</h3><p>I didn’t want the chart to be static, so I added controls:</p><pre>model_option = st.selectbox(<br>    &quot;Select Model&quot;,<br>    [&quot;All&quot;, &quot;Prophet Only&quot;, &quot;ARIMA Only&quot;]<br>)<br>show_ci = st.checkbox(&quot;Show Confidence Interval&quot;)<br>highlight_forecast = st.checkbox(&quot;Highlight Forecast Area&quot;)</pre><p>So now I can toggle things on and off.</p><p>Looks like small detail, hmmm.. But it makes exploring way more fun.</p><h3>Measuring Performance</h3><p>I didn’t want to just eyeball the results. So I split the data.</p><pre>split = int(len(df) * 0.8)<br>train = df.iloc[:split]<br>test = df.iloc[split:]</pre><p>Then calculated it.</p><pre>mae_prophet = mean_absolute_error(test[&#39;y&#39;], prophet_pred)<br>rmse_prophet = np.sqrt(mean_squared_error(test[&#39;y&#39;], prophet_pred))</pre><p>Same for ARIMA. And this is where things got interesting — sometimes Prophet wins, sometimes ARIMA does.</p><h3>Picking the Winner</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5WgrqXIBRg1zvEVebdK7Q.png" /><figcaption>Example of Model Performance</figcaption></figure><p>At this point, I already had the predictions.</p><p>But then I got stuck for a second. <em>“How do I actually </em>compare<em> them?”</em></p><p>Because just plotting two lines isn’t enough.</p><p>I needed something clearer.</p><h4>Showing the performance side by side</h4><p>So I thought — <em>what if I just put both models next to each other?</em></p><p>Same metrics. Same format. Easy to scan. So I wrote this:</p><pre>col1, col2 = st.columns(2)<br><br>with col1:<br>    st.markdown(&quot;### Prophet&quot;)<br>    st.metric(&quot;MAE&quot;, f&quot;{mae_prophet:.4f}&quot;)<br>    st.metric(&quot;RMSE&quot;, f&quot;{rmse_prophet:.4f}&quot;)<br>    st.metric(&quot;MAPE&quot;, f&quot;{mape_prophet:.2f}%&quot;)<br>with col2:<br>    st.markdown(&quot;### ARIMA&quot;)<br>    st.metric(&quot;MAE&quot;, f&quot;{mae_arima:.4f}&quot;)<br>    st.metric(&quot;RMSE&quot;, f&quot;{rmse_arima:.4f}&quot;)<br>    st.metric(&quot;MAPE&quot;, f&quot;{mape_arima:.2f}%&quot;)</pre><p>So now instead of digging through numbers. I can just <em>see</em> which one is better.</p><p><strong><em>But now, I still need something that gives me a quick conclusion.</em></strong></p><p>So I added a simple rule.</p><pre>if rmse_prophet &lt; rmse_arima:<br>    winner = &quot;Prophet&quot;<br>    best_mape = mape_prophet<br>    best_rmse = rmse_prophet<br>else:<br>    winner = &quot;ARIMA&quot;<br>    best_mape = mape_arima<br>    best_rmse = rmse_arima</pre><p>Why RMSE? — Because it punishes bigger errors more, and I felt like that mattered more here.</p><p>Then I just display it:</p><pre>st.success(f&quot;{winner} performs better based on RMSE&quot;)</pre><p>So I don’t have to think every time.</p><h4>Making the numbers easier to understand</h4><p>But then I hit another problem. Even after all this — I still had to <em>interpret</em> the numbers myself.</p><p>So I added this small helper:</p><pre>def interpret_mape(mape):<br>    if mape &lt; 10:<br>        return &quot;✅ Good Model&quot;<br>    elif mape &lt; 20:<br>        return &quot;⚠️ Acceptable Model&quot;<br>    else:<br>        return &quot;❌ Poor Model&quot;</pre><p>And then:</p><pre>st.markdown(f&quot;**Model Quality:** {interpret_mape(best_mape)}&quot;)<br>st.markdown(f&quot;**MAPE:** {best_mape:.2f}%&quot;)</pre><p>Now it’s not just numbers anymore. It actually tells me something.</p><h4><strong>Adding a bit more context (because RMSE alone felt incomplete)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*kG4aqm9P-KMnlg-dYVg8iw.png" /><figcaption>Additional Insight</figcaption></figure><p>Right when I thought I was done. I realized something felt off.</p><p>RMSE is useful, but it depends on scale. So I added one more piece:</p><pre>avg_price = test[&#39;y&#39;].mean()</pre><p>Just to understand the typical price.</p><h4>Normalizing the error</h4><p>Then I compared the error to that average.</p><pre>relative_rmse = (best_rmse / avg_price) * 100</pre><p>This changed everything. Now I can tell <strong><em>— not just how big the error is, but how big it is</em></strong><em> </em>relative to the price.</p><p>And I think that’s a much better question to ask.</p><h3>Making It Accessible</h3><p>Once everything worked, I wanted to share it.</p><p>So I tried two approaches.</p><h4><strong>(1) Streamlit Cloud</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cb4vGhZVu8R2Fx6gKzX_Hw.png" /><figcaption>Streamlit Cloud Result (1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uhvztl01lccdMB8rd7Q2Mw.png" /><figcaption>Streamlit Cloud Result (2)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BKv9um7I1r-t_wNty7Jww.png" /><figcaption>Streamlit Cloud Result (3)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*fjsg_7etn1uEcu3WW322eQ.png" /><figcaption>Streamlit Cloud Result (4)</figcaption></figure><p>This was the cleanest solution.</p><p>Push to GitHub → deploy → get a public link and… Done.</p><p>Perfect for showing the project.</p><h4>(2) Ngrok</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALeMEm0tK7UnIDiZY-67zA.png" /><figcaption>Ngrok Result (1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sx_6J10MkgeJT428ZDXkgw.png" /><figcaption>Ngrok Result (2)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwH8FPPx8P73jBAVgGnzdQ.png" /><figcaption>Ngrok Result (3)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*OcasaABjG3NFXuzrfHNALw.png" /><figcaption>Ngrok Result (3)</figcaption></figure><p>Before that, I tried running it locally.</p><pre>from pyngrok import ngrok<br>ngrok.connect(8501)</pre><p>It gives you a temporary public URL.</p><p>Super useful for testing… but yeah, not really stable for long-term use, so i recommend Streamlit Cloud.</p><h4>(3) What’s the best?</h4><p>As you can see, performance ultimately depends on the specific stock chosen. We can’t say which one is the best here; it all comes down to the individual case, and each indicator must be taken into account.</p><p>Here, we use an example where the Prophet model performs better for stock “A” but for stock “GOOGL” the ARIMA model performs better, producing a much smaller RMSE.</p><h3>Looking Back</h3><p>At some point, I realized — I didn’t just build a forecasting tool.</p><p>I built something that helped me <em>understand</em> forecasting.</p><p>If you want to play around with it or see how everything is put together,<br>I’ve shared the full code (and how to run it) on GitHub.</p><p>Go check it out here.</p><p><a href="https://github.com/jihanKamilah/MarketPulse-Stock-Forecast-App">GitHub - jihanKamilah/MarketPulse-Stock-Forecast-App: Stock price forecasting dashboard using Prophet and ARIMA with interactive visualization (Ngrok and Streamlit deployment options).</a></p><p>And if you end up building something from it. I’d love to see it —just reach me here😄</p><p>And honestly… that’s what made it worth it to work with.</p><p><em>The contents of external submissions are not necessarily reflective of the opinions or work of </em><a href="http://mavenanalytics.io/"><em>Maven Analytics</em></a><em> or any of its team members.</em></p><p><em>We believe in fostering lifelong learning and our intent is to provide a platform for the data community to share their work and seek feedback from the Maven Analytics data fam.</em></p><p><a href="https://medium.com/learning-data/how-to-get-your-work-published-by-learning-data-with-maven-analytics-7df21e466a3e?source=friends_link&amp;sk=020dfac485597d602e218968d9ffb395"><em>Submit your own writing here</em></a><em> if you’d like to become a contributor.</em></p><p><em>Happy learning!</em></p><p><em>-Team Maven</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68101307a0bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-data/building-a-stock-forecasting-dashboard-with-prophet-arima-modeling-68101307a0bf">Building a Stock Forecasting Dashboard with Prophet &amp; ARIMA Modeling</a> was originally published in <a href="https://medium.com/learning-data">Learning Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>