<?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 JUMMA MOHAMMAD TELI on Medium]]></title>
        <description><![CDATA[Stories by JUMMA MOHAMMAD TELI on Medium]]></description>
        <link>https://medium.com/@jummamohammad477?source=rss-a961e31db953------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vLeS7RXLovOKk9vsEjJSFw.jpeg</url>
            <title>Stories by JUMMA MOHAMMAD TELI on Medium</title>
            <link>https://medium.com/@jummamohammad477?source=rss-a961e31db953------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:29:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jummamohammad477/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[I Built a Neural Network to Forecast Electricity Demand. A Ridge Regression Beat It.]]></title>
            <link>https://medium.com/@jummamohammad477/i-built-a-neural-network-to-forecast-electricity-demand-a-ridge-regression-beat-it-2eb5d2eebb39?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb5d2eebb39</guid>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 13:08:49 GMT</pubDate>
            <atom:updated>2026-09-13T13:08:49.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VpRtG7zKc_EJ4f9j" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A fully reproducible benchmark on six years of real GB electricity demand, where the neural network loses, the small one fails outright, and the failure turns out to be the most useful result in the repository.</p><h3>The pitch that nobody audits</h3><p>Every forecasting project starts the same way. Somebody says the word <strong>neural network</strong>, and the room nods.</p><p>What almost never happens next is the boring part: running the same experiment five times with a different random seed to see whether the result survives.</p><p>I did that. The neural network lost, and it lost by <strong>less than its own seed variance</strong>.</p><p>That is the whole article. The rest is how I measured it, and why the honest version is more useful than the version where the deep model wins.</p><h3>The setup: real data, one held-out year</h3><p>The data is <strong>NESO Historic Demand Data</strong>, the National Energy System Operator’s published half-hourly settlement periods for GB electricity, 2019 to 2024, under the NESO Open Data Licence. It is open, it is real, and it needs no account.</p><p><strong>105,222 half-hourly readings</strong>, aggregated to <strong>2,192 complete days</strong> of mean National Demand.</p><p>That word <em>complete</em> is doing work. A day with a partial set of settlement periods averages to something lower than the day actually was, and there is no flag on it saying so.</p><pre>def to_daily(hh: pd.DataFrame) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;Daily mean National Demand (MW).</pre><pre>    Days without a full 46-50 settlement periods are dropped rather than<br>    averaged over a partial day, which would look like a demand dip that<br>    never happened. Clock-change days legitimately have 46 or 50.<br>    &quot;&quot;&quot;<br>    g = hh.groupby(&quot;date&quot;)[&quot;ND&quot;]<br>    daily = g.mean().to_frame(&quot;demand_mw&quot;)<br>    daily[&quot;periods&quot;] = g.size()<br>    complete = daily[(daily[&quot;periods&quot;] &gt;= 46) &amp; (daily[&quot;periods&quot;] &lt;= 50)]<br>    return complete.drop(columns=[&quot;periods&quot;]).sort_index()</pre><blockquote><em>The 46-to-50 window is not sloppiness. Clock-change days genuinely have 46 or 50 half-hour periods. Hard-coding </em><em>== 48 would silently delete two real days a year and leave you wondering why your lag features have holes in them.</em></blockquote><p>After lag features, including a 365-day lag, <strong>1,827 usable days</strong> remain. The split is chronological and the whole of <strong>2024 is held out</strong>: 1,462 training days, 365 test days.</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKcvHtN2sk4mAdjqjJGpeA.png" /></figure><h3>Why this stack, and what I gave up</h3><pre>Choice                                     Why                                                                                                                 What I gave up<br>-----------------------------------------  ------------------------------------------------------------------------------------------------------------------  -----------------------------------------------------------------------------<br>scikit-learn over PyTorch or TensorFlow    1,462 rows does not need autograd. MLPRegressor gives a real multi-layer network with early stopping in four lines  No custom loss, no sequence model, no GPU path<br>Ridge as the reference, not &quot;no baseline&quot;  A penalised linear model on lag features is the actual bar in this problem class                                    Nothing. This is the choice most projects skip<br>HistGradientBoostingRegressor              Fast, handles the feature set without tuning, and is a fair non-linear competitor                                   Less tunable than XGBoost or LightGBM<br>Seasonal naive as the floor                Last week, same weekday. Costs one line and disqualifies any model that cannot clear it                             Nothing<br>No hyperparameter search                   One sensible configuration each, so the comparison is not confounded by uneven tuning effort                        The MLPs might do better with a search, which I say out loud rather than hide</pre><blockquote><em>If your benchmark has no naive baseline, you do not have a benchmark. You have a number. </em><em>test[&quot;lag_7&quot;] took one line here and it immediately told me that three of my four models were worth keeping and one was not.</em></blockquote><h3>The result</h3><p>Five models, identical features, identical split.</p><pre>Model                       MAE (MW)  MAPE    RMSE<br>--------------------------  --------  ------  -------<br>Ridge regression            985.7     3.83%   1,263.7<br>Gradient boosting           1,016.3   3.94%   1,275.9<br>Neural network (128-64-32)  1,040.1   4.01%   1,315.4<br>Seasonal naive              1,689.4   6.33%   2,206.6<br>Neural network (32)         8,258.2   32.47%  9,807.5</pre><p><strong>A ridge regression wins.</strong> It beats gradient boosting, it beats the deep network, and all three comfortably clear the naive floor.</p><p>The deep network is not embarrassing. It is <strong>5.5% worse on MAE</strong> and it clearly learned the structure. It is simply not the right tool for 1,462 rows of a strongly autoregressive series once seasonality is already encoded as features. That is territory a penalised linear model is very hard to beat in.</p><h3>The part that actually matters</h3><p>Here is the run I almost did not do. Same data, same features, same split. <strong>Only the random seed changes.</strong></p><pre>Model              0        1        2        3        4        mean     std<br>-----------------  -------  -------  -------  -------  -------  -------  -------<br>ridge              985.7    985.7    985.7    985.7    985.7    985.7    1.3e-13<br>gradient_boosting  1,016.3  1,016.3  1,016.3  1,016.3  1,016.3  1,016.3  1.3e-13<br>mlp_deep           1,018.1  1,025.2  1,022.3  1,060.4  1,060.8  1,037.4  21.37<br>seasonal_naive     1,689.4  1,689.4  1,689.4  1,689.4  1,689.4  1,689.4  0.00<br>mlp_small          8,725.0  8,425.8  9,023.7  8,712.7  8,960.5  8,769.5  236.88</pre><p>Do the arithmetic on the deep network:</p><ul><li>Its <strong>deficit against ridge</strong> is 1040.05 - 985.73 = <strong>54.3 MW</strong>.</li><li>Its <strong>swing across seeds</strong> is 1060.8 - 1018.1 = <strong>42.7 MW</strong>.</li></ul><p>Those are the same order of magnitude. On seed 0 the network posts 1,018 and looks like it beat gradient boosting. On seed 4 it posts 1,061 and looks like it lost by twice as much.</p><p><strong>Same code. Same data. Two different conclusions.</strong></p><blockquote><em>The three deterministic models return an identical number every time. Their </em><em>1.3e-13 is floating-point noise in the standard-deviation calculation, not variation in the model. The neural networks are the </em><strong><em>only</em></strong><em> models in this comparison whose score moves when nothing else does.</em></blockquote><p>Anyone reporting a single MLP run is reporting <strong>a sample of size one</strong>. If the gap you are claiming is smaller than the spread you never measured, you have not found a result. You have found a seed.</p><p>The sweep is eleven lines:</p><pre># stability across seeds: is any ranking difference real or just noise?<br>runs = []<br>for s in (0, 1, 2, 3, 4):<br>    r = run_all(train, test, FEATURES, target=TARGET, seed=s).set_index(&quot;model&quot;)[&quot;mae&quot;]<br>    runs.append(r.rename(s))<br>stab = pd.concat(runs, axis=1)<br>stab[&quot;mean&quot;] = stab.mean(axis=1); stab[&quot;std&quot;] = stab.iloc[:, :5].std(axis=1)</pre><h3>The failure I refused to patch</h3><p>The 32-unit network lands at <strong>8,258 MAE against ridge’s 986</strong>. Eight times worse. A 32% MAPE.</p><p>My first instinct was to fix it before anyone saw it. That would have been the wrong call, because <strong>the failure is the lesson</strong>.</p><p>The target is GB demand in megawatts, of order <strong>27,000</strong>. The features are standardised by the pipeline. The target is not.</p><pre>&quot;mlp_small&quot;: make_pipeline(<br>    StandardScaler(),                      # scales X only, never y<br>    MLPRegressor(hidden_layer_sizes=(32,), max_iter=3000,<br>                 early_stopping=True, n_iter_no_change=25,<br>                 random_state=seed)),</pre><p>StandardScaler inside a Pipeline transforms <strong>X and nothing else</strong>. A 32-unit network has to span an output range of ~27,000 from small initial weights within its iteration budget, and it does not get there. Ridge and gradient boosting are completely indifferent to the scale of y.</p><blockquote><strong><em>Neural networks are sensitive to target scale in a way linear models are not.</em></strong><em> The fix is </em><em>TransformedTargetRegressor, and it is easy. But if you apply it before you print the table, you have hidden a real cost of choosing a neural network. I left the failure in and pinned it with a test instead.</em></blockquote><p>That test is the point:</p><pre>def test_small_mlp_fails_on_unscaled_target_a_documented_finding(frame):<br>    &quot;&quot;&quot;Documents a real and instructive failure. [docstring trimmed]&quot;&quot;&quot;<br>    train, test = chronological_split(frame, test_days=365)<br>    res = run_all(train, test, FEATURES, target=TARGET, seed=0).set_index(&quot;model&quot;)<br>    assert res.loc[&quot;mlp_small&quot;, &quot;mae&quot;] &gt; 3 * res.loc[&quot;ridge&quot;, &quot;mae&quot;], (<br>        &quot;small MLP now competitive; update the README finding&quot;)</pre><p>Note the assertion message. It does not say <em>fix the model</em>. It says <strong>update the write-up</strong>, because if that test ever fails the repository’s published claim has become untrue and that is the thing needing attention.</p><p>If someone later adds target scaling, that test fails loudly and forces them to update the write-up. A finding that is not asserted is a finding that rots.</p><h3>The leakage guards</h3><p>The failure mode that makes a forecast look brilliant and be worthless is a rolling window that includes the day it is predicting.</p><pre>for lag in (1, 2, 3, 7, 14, 365):<br>    out[f&quot;lag_{lag}&quot;] = out[&quot;demand_mw&quot;].shift(lag)<br>for win in (7, 28):<br>    # shift(1) first: today&#39;s value must never enter its own rolling mean<br>    out[f&quot;roll_mean_{win}&quot;] = out[&quot;demand_mw&quot;].shift(1).rolling(win).mean()<br>    out[f&quot;roll_std_{win}&quot;] = out[&quot;demand_mw&quot;].shift(1).rolling(win).std()</pre><p>That one .shift(1) is the difference between a real 3.83% MAPE and a fantasy. It is checked against a hand-computed value in the suite, along with lag alignment against the raw series and the assertion that train.index.max() &lt; test.index.min().</p><h3>Benchmarks and reproducibility</h3><pre>Before          After<br>-----------------------  --------------  -----------------------------------<br>Baseline for comparison  None stated     Seasonal naive at 1,689 MAE<br>Reported MLP score       One run         Five seeds, mean and std<br>Rolling-window leakage   Assumed absent  Asserted in a test<br>Split integrity          Assumed         Asserted chronological and disjoint<br>Known weaknesses         Quietly fixed   Pinned by two tests<br>Verification             Local only      CI on Python 3.11 and 3.12</pre><p>The repository runs <strong>14 tests at 79% coverage</strong> in continuous integration on every push, on both Python versions. Every number in this article regenerates from a clean checkout with three commands.</p><p>Getting that CI green cost two red builds, both worth knowing about:</p><ul><li><strong>An unpinned linter fails builds on days nobody touched the code.</strong> The runner installed a newer ruff than my local one and failed on import ordering alone. Pin the exact version.</li><li><strong>pytest and </strong><strong>python -m pytest are not the same command.</strong> Only the -m form puts the working directory on sys.path. CI ran the bare form and could not import src/. The fix belongs in pytest.ini as pythonpath = ., not in the workflow, so contributors get it too.</li></ul><h3>What I would tell you to take away</h3><ul><li><strong>Run it five times.</strong> A seed sweep is the cheapest experiment in machine learning and it is the one that tells you whether your headline gap is real. If the spread is bigger than the gap, you do not have a result yet.</li><li><strong>Set the naive bar before you build anything.</strong> Last week, same weekday cost one line and gave every subsequent number meaning.</li><li><strong>StandardScaler in a pipeline does not touch </strong><strong>y.</strong> That single fact explains an eight-fold failure that looks like a broken model.</li><li><strong>Assert your weaknesses, not just your strengths.</strong> Two tests in this repository exist to fail if a documented failure ever stops happening. That is how a finding survives the next contributor.</li><li><strong>Publish the loss.</strong> A benchmark where the fancy model wins tells a reader nothing they can act on. One where it loses tells them when not to reach for it.</li></ul><h3>The honest limits</h3><p>The data is real, openly licensed, and the test year is genuinely held out. The model set is deliberately plain, and it is missing things:</p><ul><li><strong>No weather covariate.</strong> The NESO demand file carries no temperature column, and temperature is the largest known omitted driver of electricity demand. A production forecast would need it, and it is the most likely route by which a non-linear model would finally earn its place here.</li><li><strong>The 2020 COVID period is left in the training data untouched.</strong></li><li><strong>No hyperparameter search</strong>, so the MLPs are not shown at their best.</li></ul><p>So read the <strong>3.83% MAPE as what these features support on this series</strong>, not as a claim about achievable accuracy in an operational setting. What transfers is the method, not the megawatts.</p><h3>Try it, and try to break it</h3><p>The repository is here, with the CI badge, the full test suite, and every figure in this article reproducible from a clean checkout:</p><p><strong>GitHub: </strong><a href="https://github.com/jumma786/demand-forecast-neural-network"><strong>github.com/jumma786/demand-forecast-neural-network</strong></a></p><pre>git clone https://github.com/jumma786/demand-forecast-neural-network.git<br>cd demand-forecast-neural-network<br>pip install -r requirements.txt<br>python -m src.download      # fetch the NESO CSVs, ~9 MB<br>python run_analysis.py</pre><p>Two tests in there deliberately assert <strong>weaknesses</strong> of the neural networks. If you make one of them fail, that is a finding worth a pull request description, not a test to relax.</p><p>I would genuinely like to be proved wrong on the ranking. Add a temperature series, run a proper search over the MLP, and if the network wins on a fair five-seed comparison, open a PR and I will update the article.</p><p><strong>What is the largest gap you have seen between a reported result and its own seed variance? I would like to hear about it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb5d2eebb39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Ran the Same Monte Carlo Twice.]]></title>
            <link>https://medium.com/@jummamohammad477/i-ran-the-same-monte-carlo-twice-2ea23e04cd18?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ea23e04cd18</guid>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 13:08:33 GMT</pubDate>
            <atom:updated>2026-09-13T13:08:33.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Ran the Same Monte Carlo Twice. The Only Difference Was One Assumption, and It Moved the Answer 12x.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uTDpJk_OUP5t1hip" /><figcaption>Photo by <a href="https://unsplash.com/@federize?utm_source=medium&amp;utm_medium=referral">Federico Beccari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Six years of real GB electricity demand, two identical simulations, and a measured demonstration that reaching for a normal distribution out of habit overstates the tail by a factor of four exactly where capacity decisions live.</p><h3>The line of code nobody reviews</h3><p>Somewhere in most Monte Carlo models there is a line like this:</p><pre>noise = np.random.normal(0, sigma, n_sims)</pre><p>It gets written in about four seconds. It never comes up in code review. And it is a <strong>distributional assumption about the real world</strong>, made silently, that propagates straight into the tail percentile someone is about to make a capacity decision on.</p><p>I wanted to measure what that habit actually costs. Not argue about it. Measure it.</p><p>So I built the same simulation twice, changed <strong>only</strong> how day-to-day variation is drawn, and compared the tails.</p><p><strong>The fitted normal overstated the probability of exceeding 46 GW by a factor of twelve.</strong></p><h3>The data, and why peaks specifically</h3><p><strong>NESO Historic Demand Data</strong>, the National Energy System Operator’s published half-hourly settlement periods for GB electricity, 2019 to 2024, under the NESO Open Data Licence.</p><p><strong>105,222 half-hourly readings</strong>, aggregated to <strong>2,192 complete days</strong>.</p><p>For a capacity question you do not care about the average day. You care about <strong>winter weekday peaks</strong>, November to February, Monday to Friday, because that is when the system is stressed. That narrows it to <strong>516 observations</strong>.</p><pre>g = hh.groupby(&quot;date&quot;)[&quot;ND&quot;]<br>daily = pd.DataFrame({&quot;peak_mw&quot;: g.max(), &quot;periods&quot;: g.size()})<br># partial days would understate the peak; drop rather than average<br>daily = daily[(daily[&quot;periods&quot;] &gt;= 46) &amp; (daily[&quot;periods&quot;] &lt;= 50)]</pre><blockquote><em>Dropping partial days matters more for peaks than for averages. If a day is missing its evening settlement periods, the </em><strong><em>maximum you compute is not the maximum that happened</em></strong><em>. You have quietly invented a low peak and it will sit in your residual pool forever. The 46-to-50 window keeps genuine clock-change days, which really do have 46 or 50 periods.</em></blockquote><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxylYMY88ZIdMljTCa7qBA.png" /></figure><p>The only judgement in the entire model is structural, and it is one line:</p><blockquote><em>peak = last winter&#39;s level + a year-on-year shift + day-to-day variation</em></blockquote><p><strong>Everything feeding that line is measured.</strong> There are no hand-tuned constants to argue about, which is precisely what makes the A/B comparison clean: the two variants differ in exactly one place.</p><h3>Design tradeoffs</h3><pre>Choice                                                          Why                                                                                What I gave up<br>--------------------------------------------------------------  ---------------------------------------------------------------------------------  ----------------------------------------------------------------------------------------------------------------<br>Bootstrap the residuals instead of fitting a parametric family  The empirical distribution is the data. No family to misspecify                    A bootstrap cannot generate a value outside the observed range, so it understates genuinely unprecedented events<br>Additive structure, not multiplicative                          Peak demand in MW is a level, not a growth process                                 Cannot express proportional shocks<br>numpy and scipy only                                            The whole model is arithmetic on arrays. 200,000 iterations run in under a second  No probabilistic programming, no MCMC, no posterior over parameters<br>Winter weekdays only                                            It is the population a capacity question is about                                  516 observations instead of 2,192, so a smaller residual pool<br>Year-on-year term fitted from 5 transitions                     It is what the data supports                                                       Five points is a thin basis for a variance estimate, which I state rather than hide</pre><h3>What the data says before any simulation runs</h3><p>This is the part most simulation write-ups skip straight past.</p><pre>Year  Mean winter weekday peak (MW)  SD     n<br>----  -----------------------------  -----  --<br>2019  43,278                         2,555  86<br>2020  42,043                         1,891  87<br>2021  42,172                         2,585  86<br>2022  40,286                         3,407  85<br>2023  39,212                         2,847  85<br>2024  39,420                         2,813  87</pre><p>Year-on-year change averages <strong>-772 MW</strong> with a standard deviation of <strong>911 MW</strong> across five transitions. The decline is real but noisy, and <strong>two of the five years went up</strong>. A model that treats that trend as deterministic is overconfident before it starts.</p><p>Weekday peaks exceed weekend peaks by <strong>3,172 MW</strong> (Welch t-test, p = 1.15e-29), which confirms the population was worth isolating.</p><p><strong>And the distribution is not normal.</strong></p><pre>detrended = w[&quot;peak_mw&quot;] - w[&quot;year&quot;].map(by_year[&quot;mean&quot;])<br>ks = stats.kstest((detrended - detrended.mean()) / detrended.std(ddof=1), &quot;norm&quot;)</pre><p>De-trended skew: <strong>-0.687</strong>. Kolmogorov-Smirnov p-value against normal: <strong>0.0145</strong>.</p><blockquote><em>That is </em><strong><em>two lines</em></strong><em>. De-trend, then KS test the standardised residuals. If you are about to draw from a normal, this is the cheapest insurance in your pipeline. Note the de-trending step: skipping it tests the wrong thing, because a multi-year level shift will look like non-normality even when the within-year residuals are perfectly Gaussian.</em></blockquote><h3>The experiment</h3><p>Two variants. 200,000 iterations each. <strong>Identical</strong> year-on-year term, identical everything, one difference:</p><pre>res = _residuals(daily)<br>if variation == &quot;empirical&quot;:<br>    day = rng.choice(res, size=n_sims, replace=True)   # bootstrap<br>elif variation == &quot;normal&quot;:<br>    day = rng.normal(0.0, res.std(ddof=1), n_sims)</pre><p>Note that the normal variant is not a straw man. It uses <strong>the standard deviation measured from the same residuals</strong>. It is exactly what a competent analyst would write. The only thing it gets wrong is the shape.</p><h3>The result</h3><pre>Percentile  Empirical bootstrap  Fitted normal<br>----------  -------------------  -------------<br>P50         38,843 MW            38,656 MW<br>P90         42,135 MW            42,304 MW<br>P99         44,275 MW            45,265 MW</pre><p>Look at how the error behaves. At the <strong>median</strong> the two agree to within 200 MW, about 0.5%. Anyone sanity-checking the model at its centre would sign it off.</p><p>Now the tail:</p><pre>Exceedance           Empirical  Normal  Overstatement<br>-------------------  ---------  ------  -------------<br>P(peak &gt; 44,000 MW)  1.47%      3.00%   2.0x<br>P(peak &gt; 45,000 MW)  0.30%      1.30%   4.3x<br>P(peak &gt; 46,000 MW)  0.04%      0.48%   12x</pre><blockquote><strong><em>The error is not constant. It compounds the further into the tail you look.</em></strong><em> 2x at 44 GW, 4.3x at 45 GW, 12x at 46 GW. And the deep tail is the only region a capacity margin decision actually cares about. The assumption is most wrong exactly where it matters most, and most right where you would think to check it.</em></blockquote><p>The mechanism is simple once you see it. The real distribution is <strong>left-skewed</strong>, with a long tail toward low peaks and a short one toward high peaks. A normal is symmetric, so fitting one takes the spread from the long left tail and mirrors it onto the right, manufacturing upper-tail mass that the data never showed.</p><p>An analyst who fits a normal without testing it plans for a peak roughly <strong>four times less likely than their model claims</strong>.</p><h3>Where the uncertainty actually comes from</h3><p>Having built the thing, the next question is where to spend effort improving it. So I split the output variance.</p><pre>Component             Share of variance<br>--------------------  -----------------<br>Day-to-day variation  89.6%<br>Year-on-year shift    10.2%</pre><p><strong>Nine tenths of the spread is weather and behaviour on the day, not the trend.</strong></p><p>This is an actionable result. If I spent a month refining the trend estimate, I would be working on 10% of the problem. The payoff is entirely in modelling daily variation better, which in practice means <strong>getting a temperature series in</strong>.</p><blockquote><em>Run a variance attribution before you plan your next sprint on a model. It is cheap, and it routinely shows that the component everyone argues about in meetings is not the one driving the answer.</em></blockquote><h3>The convergence check nobody runs</h3><p>A Monte Carlo result quoted without this is a number of unknown precision.</p><pre>Iterations  P50     P99     P99 shift vs previous<br>----------  ------  ------  ---------------------<br>1,000       38,827  44,006<br>5,000       38,780  44,140  134<br>25,000      38,839  44,274  134<br>100,000     38,821  44,207  68<br>200,000     38,843  44,275  68<br>500,000     38,823  44,241  34</pre><p>The median is stable almost immediately. <strong>The P99 is still moving by over 130 MW at 5,000 iterations</strong>, which is enough to change a margin decision on its own.</p><p>Tail percentiles converge far more slowly than central ones, for the obvious reason that at 1,000 iterations only ten samples inform the P99. If you quote a P99, converge at the P99, not at the mean.</p><h3>Benchmarks and reproducibility</h3><pre>Typical approach     This repository<br>-------------------  -------------------  --------------------------------------------------<br>Input distributions  Assumed, hand-tuned  Fitted from 2,192 days of real data<br>Normality            Assumed              Tested: KS p = 0.0145, skew -0.687<br>Tail sensitivity     Unknown              Measured: 12x at the 46 GW threshold<br>Effort allocation    Guessed              Attributed: 89.6% day-to-day vs 10.2% trend<br>Iteration count      Round number         Converged, and the convergence table published<br>Verification         None                 15 tests, 84% coverage, CI on Python 3.11 and 3.12</pre><p>Every finding above is asserted in the test suite. <strong>Including the non-normality</strong>, which is the one that matters most:</p><pre>def test_data_rejects_normality(daily):<br>    &quot;&quot;&quot;The finding the whole README rests on; assert it so it cannot rot.&quot;&quot;&quot;<br>    f = fit_winter_weekday_peaks(daily)<br>    assert f[&quot;ks_pvalue_vs_normal&quot;] &lt; 0.05, &quot;normality no longer rejected&quot;<br>    assert f[&quot;detrended_skew&quot;] &lt; -0.3, &quot;left skew has changed&quot;<br></pre><pre>def test_normal_overstates_the_upper_tail(daily):<br>    &quot;&quot;&quot;The headline result, asserted.&quot;&quot;&quot;<br>    emp = simulate(daily, n_sims=200_000, seed=42, variation=&quot;empirical&quot;)<br>    nor = simulate(daily, n_sims=200_000, seed=42, variation=&quot;normal&quot;)<br>    assert exceedance(nor, 45_000) &gt; 2 * exceedance(emp, 45_000)</pre><p>A finding that lives only in a README rots the first time someone refreshes the data. A finding that lives in a test <strong>announces its own death</strong>.</p><h3>What I would tell you to take away</h3><ul><li><strong>De-trend, then KS test, before you draw from a normal.</strong> Two lines. It is the single highest-return check in a simulation pipeline, and almost nobody runs it.</li><li><strong>Validate at the percentile you intend to quote.</strong> These two models agree to 0.5% at the median and disagree by 12x in the deep tail. Checking the centre proves nothing about the tail.</li><li><strong>A bootstrap has its own blind spot.</strong> It cannot produce a value outside the observed range, so it will understate genuinely unprecedented events. It is more honest about shape and less capable at extrapolation. That is a trade, not a free win.</li><li><strong>Attribute your variance before you plan your next sprint.</strong> 89.6% of the answer sat in one component. That fact redirects effort better than any amount of discussion.</li><li><strong>Convergence is a property of the statistic, not of the simulation.</strong> Your median converged thousands of iterations before your P99 did.</li></ul><h3>The honest limits</h3><p>The data is real and openly licensed. <strong>The megawatt figures are a method demonstration, not an operational forecast.</strong></p><p>The structure is a deliberate simplification and it carries:</p><ul><li><strong>No weather covariate.</strong> The NESO demand file has no temperature column, and temperature is the largest known omitted driver of demand. Given that 89.6% of variance is day-to-day, this is the gap that matters most.</li><li><strong>No explicit COVID adjustment</strong> for 2020, left in the sample untouched.</li><li><strong>No embedded-generation treatment</strong>, which shifts what “demand” even means across a six-year window.</li><li><strong>An iid bootstrap</strong>, which ignores that cold spells cluster. A block bootstrap would be the honest next step for multi-day events.</li></ul><p>A production forecast would need all four. What transfers is the method: fit inputs from data instead of assuming them, test the distributional assumption before relying on it, find out where the uncertainty actually lives, and converge at the percentile you intend to publish.</p><h3>Run it yourself</h3><p><strong>GitHub: </strong><a href="https://github.com/jumma786/water-demand-monte-carlo"><strong>github.com/jumma786/water-demand-monte-carlo</strong></a></p><pre>git clone https://github.com/jumma786/water-demand-monte-carlo.git<br>cd water-demand-monte-carlo<br>pip install -r requirements.txt<br>python -m src.download      # fetch the NESO CSVs, ~9 MB<br>python run_analysis.py      # the full comparison, in about a second</pre><p>The whole comparison is three lines once the data is loaded:</p><pre>emp = simulate(daily, variation=&quot;empirical&quot;)<br>nor = simulate(daily, variation=&quot;normal&quot;)<br>exceedance(emp, 46_000), exceedance(nor, 46_000)   # (0.000385, 0.00483)</pre><p><strong>Try it on your own series.</strong> Take whatever simulation you are currently running, de-trend the residuals, run one KS test, and then run your model both ways. If your data is close to normal you lose ten minutes. If it is not, you have just found out that your published tail is wrong, and you found out before someone made a decision on it.</p><p><strong>I would like to hear what your KS test says. Especially if it surprises you.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ea23e04cd18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a UK BBSI Reporting Pipeline That Refuses to Plug the Difference]]></title>
            <link>https://medium.com/@jummamohammad477/building-a-uk-bbsi-reporting-pipeline-that-refuses-to-plug-the-difference-5f92b86e6946?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f92b86e6946</guid>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 13:15:54 GMT</pubDate>
            <atom:updated>2026-09-05T13:15:54.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Regulatory reporting is often described as an extraction problem.</p><p>In practice, extraction is only the beginning. The difficult questions are whether the records belong to the right tax year, whether the reportable person can be matched, whether joint-account interest has been allocated correctly, and whether the final return reconciles back to the ledger.</p><p>That was the motivation for my UK Bank and Building Society Interest, or BBSI, Tax Reporting Pipeline.</p><p>The goal was not to build a live HMRC submission system. The goal was to model the assurance controls that should exist before a file is allowed anywhere near a filing process.</p><p>Starting with the control question</p><p>The project is organized around one question:</p><p>Can the return be explained back to the ledger without plugging the difference?</p><p>That question shaped the architecture. Every exclusion must be visible. Every allocation must tie back. Every blocking data-quality issue must be separated from advisory remediation work.</p><p>Step 1: establish the data contract</p><p>The pipeline models three source tables:</p><p>- holders: identity and address fields required for matching<br>- accounts: account-product relationships and ownership links<br>- postings: interest credited to each account with a posting date</p><p>In a real bank, these would arrive from operational or warehouse feeds. For the control tests, the repository includes a deterministic fixture that produces repeatable records and deliberately injects known defects.</p><p>The synthetic fixture is not customer data. It exists so the pipeline can be tested against missing NINOs, malformed NINOs, incomplete addresses, missing dates of birth, out-of-period postings, joint accounts, and ISA interest.</p><p>Step 2: get the tax-year boundary right</p><p>The UK tax year runs from 6 April to 5 April.</p><p>That boundary is easy to describe and easy to implement incorrectly. A posting on 5 April belongs to the closing tax year. A posting on 6 April belongs to the next one.</p><p>The tax_year.py module owns this rule so it is not reimplemented in several places. The pipeline filters postings into the tax year and retains a separate out-of-period total.</p><p>The principle is important: an excluded record is not a deleted record. The report must say how many postings were excluded and how much interest they represented.</p><p>Step 3: validate matchability without overclaiming</p><p>The NINO validator implements structural rules: allowed prefixes, six digits, and a valid suffix.</p><p>It does not pretend that structural validation proves identity. A value can have a valid shape and still belong to the wrong person. The module answers the narrower question that a data pipeline can safely answer: could this value be structurally valid?</p><p>This distinction keeps the control useful without turning a format check into a false identity assertion.</p><p>Step 4: turn errors into an operational queue</p><p>Not every defect has the same filing impact.</p><p>The pipeline separates:</p><p>- Blocking issues, such as missing or malformed NINOs.<br>- Advisory issues, such as incomplete addresses or missing dates of birth.</p><p>Blocking holders are held back from the return. Advisory records remain visible for remediation without stopping the entire output.</p><p>This makes the exception report actionable. Operations teams can prioritize what prevents filing and what can be corrected through a follow-up process.</p><p>Step 5: allocate joint-account interest once</p><p>Joint accounts are a common source of reconciliation breaks.</p><p>The pipeline aggregates interest to account level, joins ownership links, counts the holders, and allocates the account interest equally. The allocation occurs in one function rather than being repeated in separate reporting paths.</p><p>The tests then regroup the allocated values and compare them with the original account interest. If the parts do not sum back, the return is not trustworthy.</p><p>This is a small example of a broader design principle: when a transformation can affect financial totals, implement it once and prove the conservation rule around it.</p><p>Step 6: build the return and reconcile it</p><p>The return-building stage applies the explicit reporting rules:</p><p>- Keep only postings inside the tax year.<br>- Hold back blocked holders.<br>- Exclude ISA interest from reportable interest.<br>- Aggregate the remaining interest to the reportable-person grain.</p><p>The reconciliation stage then explains the bridge:</p><p>Ledger interest<br>minus out-of-period postings<br>minus blocked data exceptions<br>minus exempt ISA interest<br>minus interest reported<br>equals unexplained residual</p><p>The residual is compared with a tolerance derived from the number of rounding events. A flat cash tolerance becomes inappropriate as volume grows, so the tolerance scales with the source of the rounding drift.</p><p>Most importantly, the pipeline never adjusts the output to make it agree. A break is a diagnostic signal. It triggers investigation of the tax-year filter, joint-account allocation, duplicate postings, or another upstream issue.</p><p>Why the reconciliation is the central product feature</p><p>It is tempting to treat reconciliation as a final checkbox. In this project it is the organizing principle.</p><p>Every stage is designed so that the final bridge can explain what happened to the source total. Date filtering explains out-of-period records. Validation explains blocked holders. Product rules explain exempt ISA interest. Allocation explains how account interest reaches the holder grain. Rounding explains the small amount of unavoidable numerical drift.</p><p>That structure changes how failures are handled. If the residual is large, the response is not to add an adjustment row. The response is to ask which stated transformation failed. A reconciliation break therefore becomes a useful incident diagnostic rather than a cosmetic reporting problem.</p><p>The difference between a valid file and a trustworthy file</p><p>A file can satisfy a format check and still be wrong. It might contain a valid-looking NINO attached to the wrong holder, a posting from the wrong tax year, duplicated interest, or a joint-account amount allocated twice.</p><p>This is why the pipeline separates structural validation from business assurance. The NINO module can identify impossible formats, but it cannot establish identity. The reconciliation module can prove that totals tie, but it cannot prove that the source ledger itself is complete. Each control is explicit about what it can and cannot establish.</p><p>That honesty is a design strength. It prevents a narrow automated check from being presented as a broader control than it really is.</p><p>Making the pipeline operational</p><p>The source code is organized so an operations or data-quality team could understand the work queue:</p><p>- validate.py emits one row per failed check and assigns severity.<br>- exception_summary turns those rows into counts and population percentages.<br>- build_return.py applies blocking rules consistently rather than relying on a manual filter.<br>- reconcile.py produces a bridge that can be reviewed alongside the return extract.</p><p>This matters at scale. A list of thousands of defects is not a process. A list that distinguishes filing blockers, advisory remediation, affected holders, affected interest, and the remaining residual is an operational control.</p><p>Testing the failure modes, not just the happy path</p><p>The tests are intentionally focused on failure modes:</p><p>- The fifth of April and sixth of April are tested as different tax years.<br>- A structurally invalid NINO is rejected while a structurally valid one is not over-claimed as verified.<br>- Joint-account allocations are regrouped and compared with account totals.<br>- ISA interest is held back rather than accidentally included in the report.<br>- Blocked holders cannot reach the submission extract.<br>- A material reconciliation break remains a break even when the rounding tolerance scales with volume.</p><p>This style of testing is more valuable than asserting only that a sample output has the expected number of rows. Row counts can remain stable while the meaning of the return changes.</p><p>What the demonstration numbers mean</p><p>The 2025–26 run processes 40,000 synthetic holders and 320,548 postings. Those numbers are useful for exercising scale and reconciliation behavior, but they are not an estimate of a bank’s population, exception rate, or interest income.</p><p>The meaningful result is the control behavior: 12,674 postings are explicitly outside the tax year, 3,302 holders have exceptions, 1,964 are blocked, and the final residual is GBP 0.03 against a derived GBP 603.81 tolerance. The bridge explains the difference rather than hiding it.</p><p>Production extensions I would make next</p><p>If this were being prepared for a live reporting environment, I would add:</p><p>1. Schema contracts for each upstream feed, including data types, uniqueness, and freshness.<br>2. Secure ingestion and access controls for identity data.<br>3. Immutable run IDs linking source files, code version, outputs, and approvals.<br>4. Duplicate-posting detection and a source-ledger completeness control.<br>5. Currency and account-ownership change rules with explicit effective dates.<br>6. A current HMRC template adapter tested against the latest published specification.<br>7. A gated deployment workflow that blocks publication when reconciliation fails.</p><p>These are platform controls around the core logic. The important part is that the core logic already exposes the contracts those controls need to enforce.</p><p>The demonstration run</p><p>The deterministic 2025–26 run processes:</p><p>- 40,000 holders<br>- 84,943 account-holder links<br>- 320,548 interest postings<br>- 307,874 postings inside the tax year<br>- 3,302 holders with exceptions<br>- 1,964 blocked holders</p><p>The reported interest is GBP 75.8 million against a GBP 88.4 million ledger. The reconciliation residual is GBP 0.03, within the derived GBP 603.81 rounding tolerance.</p><p>The number that matters is not simply that the residual is small. It is that the difference is explained line by line before the output is treated as safe.</p><p>Adding official public data</p><p>Real BBSI account-level records are confidential and are not published by HMRC. That means a public repository should not manufacture names, NINOs, account numbers, or postings and call them real.</p><p>To provide a real-data workflow, I added a public report runner for HMRC Table 3.7, Property, interest, dividend and other income. The published table contains aggregate taxpayer counts and bank/building-society interest amounts by income band.</p><p>The public runner produces a normalized CSV and provenance summary. It is deliberately an aggregate context report, not a fabricated submission file.</p><p>The result is an honest split:</p><p>1. Official HMRC aggregate statistics for real-world context.<br>2. Deterministic synthetic records for testing account-level controls.</p><p>Adding SQL parity</p><p>The core return and reconciliation logic is also expressed in sql/bbsi_return.sql. The SQL version uses CTEs, grouped account interest, ownership allocation, exception filtering, and reconciliation checks.</p><p>This makes the project useful beyond a Python demo. The same control logic can be reviewed by analytics engineers and translated into a warehouse implementation.</p><p>Verification and documentation</p><p>The final test suite covers:</p><p>- Tax-year boundaries<br>- NINO structural rules<br>- Exception severity<br>- Date filtering<br>- Joint-account allocation<br>- ISA exclusion<br>- Blocked-holder handling<br>- Ledger reconciliation</p><p>The project finishes with 34 passing tests. The README was then rebuilt around the control story, public-data provenance, architecture, limitations, and operational workflow.</p><p>A practical review checklist</p><p>For a regulatory data pipeline, I would review these questions before trusting the output:</p><p>- Are statutory dates centralized and covered by boundary tests?<br>- Can every excluded record be quantified and explained?<br>- Are identity checks limited to what the data actually proves?<br>- Do financial allocations conserve the original total?<br>- Are blocking and advisory defects operationally distinct?<br>- Is the reconciliation tolerance derived from known numerical behavior?<br>- Does a failed reconciliation stop publication rather than trigger a manual plug?<br>- Are public examples clearly separated from confidential production data?</p><p>The checklist is intentionally broader than code style. In reporting systems, correctness includes the process around the calculation and the claims made about the result.</p><p>What I learned</p><p>The strongest regulatory data pipelines are not the ones that produce the cleanest-looking file. They are the ones that make it difficult to produce an unexplained file.</p><p>The most important lessons were:</p><p>- Make statutory boundaries executable and testable.<br>- Separate structural validation from identity verification.<br>- Treat exception severity as an operational design decision.<br>- Prove that financial allocations conserve the source total.<br>- Preserve every exclusion in the reconciliation bridge.<br>- Never plug a difference merely because the output needs to balance.<br>- Use public aggregate data honestly when account-level data is confidential.</p><p>This project is therefore an engineering demonstration, not tax advice and not a live HMRC filing service. Its value is in showing how extraction, validation, remediation, allocation, and reconciliation fit together into a defensible reporting control.</p><p>Explore the project</p><p>GitHub repository: <a href="https://github.com/jumma786/uk-bbsi-tax-reporting-pipeline">https://github.com/jumma786/uk-bbsi-tax-reporting-pipeline</a></p><p>HMRC public Table 3.7 data: <a href="https://www.gov.uk/government/statistics/investment-income-2010-to-2011">https://www.gov.uk/government/statistics/investment-income-2010-to-2011</a></p><p>HMRC BBSI return guidance: <a href="https://www.gov.uk/guidance/bank-and-building-society-interest-returns">https://www.gov.uk/guidance/bank-and-building-society-interest-returns</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f92b86e6946" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Wealth KPI Engine That Explains Growth Instead of Just Reporting It]]></title>
            <link>https://medium.com/@jummamohammad477/building-a-wealth-kpi-engine-that-explains-growth-instead-of-just-reporting-it-782a6c7ca375?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/782a6c7ca375</guid>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 13:01:11 GMT</pubDate>
            <atom:updated>2026-09-05T13:07:33.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Most wealth reports begin with a headline: assets grew, revenue increased, or retention remained high.</p><p>The problem is that a headline rarely explains why.</p><p>Assets can rise because markets performed well, even while the business lost clients. Fee yield can fall because the client mix changed, even when nobody reduced their price. AUM can be overstated when administrative assets are reported as if they were actively managed.</p><p>That was the starting point for my Wealth KPI Engine project: build a small, auditable calculation layer that explains the movement behind the headline.</p><p>The starting point: define the business questions</p><p>Before writing code, I translated the reporting problem into measurable questions:</p><p>- How much is genuinely under discretionary management?</p><p>- How much is administered, advised, held in custody, or execution-only?</p><p>- How much of the change came from net new money?</p><p>- How much came from market movement?</p><p>- Did fee yield change because prices changed or because the asset mix changed?</p><p>- Does client retention tell the same story as asset retention?</p><p>Those questions became the foundation of the project rather than a dashboard added at the end.</p><p>Step 1: model the grain</p><p>The core data model uses five analytical frames:</p><p>- clients: segment, mandate, join month, starting value, and fee rate</p><p>- positions: monthly client asset snapshots</p><p>- flows: inflows, outflows, and attrition events</p><p>- revenue: monthly fee revenue by client</p><p>- market: period-level market movement</p><p>The most important design choice was to make the grain explicit. The AUMA view covers the whole asset population. The discretionary AUM view filters both positions and flows to discretionary mandates.</p><p>That sounds simple, but it prevents a subtle and damaging error: comparing whole-book flows with discretionary-only assets and then allowing the difference to disappear into a residual.</p><p>Step 2: make AUM and AUA separate concepts</p><p>The project does not treat AUM and AUA as the same metric with a filter hidden somewhere in the code.</p><p>The definitions are explicit:</p><p>- AUM contains discretionary mandates where the firm makes investment decisions.</p><p>- AUA contains advisory, execution-only, and custody assets.</p><p>- AUMA is the combined view.</p><p>This protects the report from a common presentation failure: using the larger AUMA figure when a stakeholder thinks they are looking at managed assets.</p><p>Step 3: calculate the waterfall</p><p>The central calculation is the asset bridge:</p><p>Closing AUMA = Opening AUMA + Net New Money + Market Movement</p><p>Net New Money is calculated from client activity. Market movement is then derived as the residual after the opening asset base and aligned flows are known.</p><p>The residual is deliberate. It means the waterfall always tells us what remains unexplained. If the number looks commercially or economically implausible, the next step is investigation rather than adjustment.</p><p>In the deterministic demonstration run, the opening AUM was GBP 1.64 billion and closing AUM was GBP 1.66 billion. The headline AUMA change was GBP 83.7 million, but that hid GBP 249.7 million of net new money and GBP 182.1 million of negative market movement.</p><p>The business story is therefore very different from the headline: the book won substantial new money while markets worked against it.</p><p>Step 4: explain fee-yield movement</p><p>The project also decomposes fee yield into rate and mix effects.</p><p>The calculation uses average assets rather than closing assets. Using closing assets can make a yield change look like a pricing change when it is actually caused by market movement.</p><p>The demonstration keeps each segment’s fee rate fixed. That makes the rate effect zero and isolates the mix effect. The resulting lesson is useful even though the input is a test fixture: a blended yield can fall when the business wins more assets in lower-margin segments.</p><p>In a production implementation, the same framework could accept historical pricing, mandate, product, or client-tier rates and show both effects together.</p><p>Turning definitions into a usable calculation layer</p><p>The implementation is intentionally small. There is no database, web application, or visualization framework hiding the logic. That is a feature for this type of project: a reviewer can open src/kpi.py, follow the definitions, and compare them directly with the tests.</p><p>The calculation layer receives ordinary pandas frames and returns either scalar measures or reviewable tables. That keeps the boundary between data preparation and business logic visible. It also makes it possible to move the logic into SQL later without changing the meaning of the measures.</p><p>For example, the monthly report does not calculate market movement from a market-index return and then assume the result must be correct. It calculates opening AUMA, current AUMA, and net new money over the same month, then derives the unexplained movement. This is more robust for a reporting bridge because it tells the analyst what the accounting identity says happened in the data.</p><p>Why the output is more useful than a dashboard number</p><p>A dashboard can show that AUMA increased. The KPI engine can answer the follow-up questions a finance or commercial leader will ask:</p><p>- Was the change driven by new mandates, partial withdrawals, or client exits?</p><p>- Did markets help or hurt the reported result?</p><p>- Are we talking about managed assets or administered assets?</p><p>- Did the fee yield move because of pricing or because of mix?</p><p>- Are we retaining many clients with small balances, or fewer clients with meaningful balances?</p><p>Those questions are not separate from the metric design. They are the reason the metrics are separated in the first place. A result that cannot support the next question is usually not a finished KPI.</p><p>Designing the synthetic fixture responsibly</p><p>The fixture is deliberately shaped to make common mistakes visible. It includes multiple mandates, uneven segment sizes, large and small relationships, new joins, withdrawals, attrition, and negative market months. A perfectly smooth book would make the calculations look correct without exercising the hard paths.</p><p>The random seed is fixed, which gives the project repeatability. A future code change can be compared against the same baseline, and a reviewer can reproduce the figures in the README. At the same time, the fixture is kept separate from the public-data loader so no one mistakes a generated client record for an observation from a real institution.</p><p>This separation is important in portfolio work. A synthetic dataset can be excellent for demonstrating engineering controls, but it should not be used to imply evidence about actual customer behavior, market returns, or wealth-manager performance.</p><p>SQL parity and verification</p><p>The metric logic is also expressed in sql/wealth_kpis.sql using CTEs and window functions. That makes the project relevant to analytics engineering teams where the production implementation may ultimately live in a warehouse.</p><p>The final verification suite covers the failure modes that matter most:</p><p>- AUM and AUA separation<br>- NNM excluding market movement<br>- Average-balance fee yield<br>- Waterfall reconciliation<br>- Client-count versus asset-weighted retention</p><p>The project finishes with 20 passing tests and reproducible public-data outputs.</p><p>A practical review checklist</p><p>When reviewing a similar wealth KPI implementation, I would ask:</p><p>- Does the AUM definition match the mandate definition used by the business?<br>- Are opening and closing snapshots comparable, including acquisitions and closures?<br>- Are flows assigned to the same population as the asset balance they explain?<br>- Is revenue aligned to average assets and the correct period?<br>- Can a reader distinguish a market-driven change from a commercially driven change?<br>- Are public and confidential data paths separated?<br>- Can every number in the narrative be regenerated from a command?</p><p>These checks are more valuable than simply asking whether the code runs. Reporting logic can execute successfully and still produce a misleading business conclusion.</p><p>What I learned</p><p>The strongest reporting systems do not simply calculate a number. They make the number explainable.</p><p>The key practices from this project were:</p><p>- Define the business grain before writing the formula.<br>- Keep related metrics separate when their meanings differ.<br>- Treat residuals as diagnostic signals, not places to hide errors.<br>- Use public data honestly and label aggregate limitations.<br>- Keep synthetic data where it is valuable for tests, not where it could be mistaken for evidence.</p><p>The result is not a dashboard mock-up. It is a small metric-governance layer that shows how an analytics team can move from a plausible number to a defensible one.</p><p>Explore the project</p><p>GitHub repository: <a href="https://github.com/jumma786/wealth-kpi-engine">https://github.com/jumma786/wealth-kpi-engine</a></p><p>ONS public data: <a href="https://www.ons.gov.uk/peoplepopulationandcommunity/personalandhouseholdfinances/incomeandwealth/datasets/financialwealthwealthingreatbritain">https://www.ons.gov.uk/peoplepopulationandcommunity/personalandhouseholdfinances/incomeandwealth/datasets/financialwealthwealthingreatbritain</a></p><p>Bank of England series LPMZ3U9: <a href="https://www.bankofengland.co.uk/boeapps/database/fromshowcolumns.asp?CSVF=TT&amp;DAT=RNG&amp;FD=1&amp;FM=Jan&amp;FNY=Y&amp;FY=2021&amp;Filter=N&amp;FromSeries=1&amp;SeriesCodes=LPMZ3U9Building">https://www.bankofengland.co.uk/boeapps/database/fromshowcolumns.asp?CSVF=TT&amp;DAT=RNG&amp;FD=1&amp;FM=Jan&amp;FNY=Y&amp;FY=2021&amp;Filter=N&amp;FromSeries=1&amp;SeriesCodes=LPMZ3U9Building</a> a Wealth KPI Engine That Explains Growth Instead of Just Reporting It</p><p>SQL parity and verification</p><p>The metric logic is also expressed in sql/wealth_kpis.sql using CTEs and window functions. That makes the project relevant to analytics engineering teams where the production implementation may ultimately live in a warehouse.</p><p>The final verification suite covers the failure modes that matter most:</p><p>- AUM and AUA separation<br>- NNM excluding market movement<br>- Average-balance fee yield<br>- Waterfall reconciliation<br>- Client-count versus asset-weighted retention</p><p>The project finishes with 20 passing tests and reproducible public-data outputs.</p><p>A practical review checklist</p><p>When reviewing a similar wealth KPI implementation, I would ask:</p><p>- Does the AUM definition match the mandate definition used by the business?<br>- Are opening and closing snapshots comparable, including acquisitions and closures?<br>- Are flows assigned to the same population as the asset balance they explain?<br>- Is revenue aligned to average assets and the correct period?<br>- Can a reader distinguish a market-driven change from a commercially driven change?<br>- Are public and confidential data paths separated?<br>- Can every number in the narrative be regenerated from a command?</p><p>These checks are more valuable than simply asking whether the code runs. Reporting logic can execute successfully and still produce a misleading business conclusion.</p><p>What I learned</p><p>The strongest reporting systems do not simply calculate a number. They make the number explainable.</p><p>The key practices from this project were:</p><p>- Define the business grain before writing the formula.<br>- Keep related metrics separate when their meanings differ.<br>- Treat residuals as diagnostic signals, not places to hide errors.<br>- Use public data honestly and label aggregate limitations.<br>- Keep synthetic data where it is valuable for tests, not where it could be mistaken for evidence.</p><p>The result is not a dashboard mock-up. It is a small metric-governance layer that shows how an analytics team can move from a plausible number to a defensible one.</p><p>Explore the project</p><p>GitHub repository: <a href="https://github.com/jumma786/wealth-kpi-engine">https://github.com/jumma786/wealth-kpi-engine</a></p><p>ONS public data: <a href="https://www.ons.gov.uk/peoplepopulationandcommunity/personalandhouseholdfinances/incomeandwealth/datasets/financialwealthwealthingreatbritain">https://www.ons.gov.uk/peoplepopulationandcommunity/personalandhouseholdfinances/incomeandwealth/datasets/financialwealthwealthingreatbritain</a></p><p>Bank of England series LPMZ3U9: <a href="https://www.bankofengland.co.uk/boeapps/database/fromshowcolumns.asp?CSVF=TT&amp;DAT=RNG&amp;FD=1&amp;FM=Jan&amp;FNY=Y&amp;FY=2021&amp;Filter=N&amp;FromSeries=1&amp;SeriesCodes=LPMZ3U9">https://www.bankofengland.co.uk/boeapps/database/fromshowcolumns.asp?CSVF=TT&amp;DAT=RNG&amp;FD=1&amp;FM=Jan&amp;FNY=Y&amp;FY=2021&amp;Filter=N&amp;FromSeries=1&amp;SeriesCodes=LPMZ3U9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=782a6c7ca375" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infrastructure as Code]]></title>
            <link>https://medium.com/@jummamohammad477/infrastructure-as-code-583bd28b92bf?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/583bd28b92bf</guid>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 13:37:56 GMT</pubDate>
            <atom:updated>2026-09-02T13:37:56.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your Terraform approval gate is probably theatre</h3><p><em>Three bugs I found reviewing my own MLOps pipeline. Every one of them would have passed code review.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TC_zhS3nbP3p8cR8" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Terraform · Azure Container Apps · GitHub Actions8 min read</p><p>I wrote Terraform to serve a machine learning model on Azure Container Apps — container registry, managed identity, HTTPS ingress, autoscaling, health probes, log routing. Then, before deploying it, I reviewed it the way I would review someone else’s.</p><p>It had three bugs.</p><p>The configuration was not the problem. terraform validate passed, the resource arguments were correct, the comments explained the reasoning. Every bug was in the <em>process</em> — in what CI actually did with a perfectly correct configuration.</p><p>That is what makes them worth writing up. A reviewer reading the diff would have approved all three.</p><p>BUG 01</p><h3>The pipeline that works exactly once</h3><p>A plan that reports on nothing.</p><p>The backend block was commented out, with a reasonable justification sitting right above it:</p><p>providers.tf</p><pre># Remote state. Commented out so `terraform init` works locally on a first run.<br>#<br># backend &quot;azurerm&quot; {<br>#   resource_group_name  = &quot;rg-tfstate&quot;<br>#   storage_account_name = &quot;sttfstate&lt;unique&gt;&quot;<br>#   container_name       = &quot;tfstate&quot;<br>#   key                  = &quot;mlops-iac.tfstate&quot;<br># }</pre><p>Local state means someone can clone the repo and run terraform init with zero setup. Defensible for a first run on a laptop.</p><p>Except CI ran the same configuration.</p><p>A GitHub Actions runner is ephemeral. terraform init with no backend writes state into the runner&#39;s working directory, and that runner is destroyed when the job ends. So:</p><p>Every pull request plan reported a full create — <em>N to add, 0 to change, 0 to destroy</em> — regardless of what actually existed in Azure. The plan comment on the PR was decorative. The first merge to main applied cleanly. The second one failed:</p><p>Error: A resource with the ID &quot;/subscriptions/.../resourceGroups/rg-mlopsapi-dev&quot; already exists - to be managed via Terraform this resource needs to be imported into the State.</p><p>My README described remote state as optional — “for anything shared.” For CI it is not optional; it is the thing that makes the pipeline mean anything. A pipeline that plans from empty state is not reporting on your infrastructure. It is describing a hypothetical one.</p><p>The fix is not to hardcode a storage account into the repo. It is a <em>partial</em> backend configuration: declare the backend, supply the values at init time.</p><p>providers.tf</p><pre>backend &quot;azurerm&quot; {<br>  # Authenticate to the state container with Azure AD rather than a<br>  # storage account key, so no long-lived secret exists anywhere.<br>  use_azuread_auth = true<br>}</pre><p>terraform.yml</p><pre>terraform init -input=false \<br>  -backend-config=&quot;resource_group_name=${{ vars.TFSTATE_RESOURCE_GROUP }}&quot; \<br>  -backend-config=&quot;storage_account_name=${{ vars.TFSTATE_STORAGE_ACCOUNT }}&quot; \<br>  -backend-config=&quot;container_name=${{ vars.TFSTATE_CONTAINER }}&quot; \<br>  -backend-config=&quot;key=mlops-iac.tfstate&quot;</pre><p>The same files now serve three contexts: local work reads a gitignored backend.hcl, CI passes flags, and the lint job runs terraform init -backend=false so it needs no cloud credentials at all — which also means it passes on forks.</p><p>BUG 02</p><h3>The approval gate that approved nothing</h3><p>This is the one worth the article.</p><p>The workflow looked textbook. Plan on every pull request, posted as a PR comment. Apply on merge to main, gated on a GitHub production environment so a human approves before infrastructure changes land.</p><p>Here is the plan step. Note -out=tfplan — it writes a plan file:</p><p>terraform.yml · plan job</p><pre>- name: terraform plan<br>  id: plan<br>  run: terraform plan -no-color -input=false -out=tfplan</pre><p>terraform.yml · apply job</p><pre>- name: terraform apply<br>  run: terraform apply -auto-approve -input=false</pre><p>The plan file is never uploaded. The apply job never downloads it. terraform apply -auto-approve with no plan file argument generates a <em>fresh</em> plan and applies that one.</p><p>So the real sequence is: CI plans. A human reads that plan and approves it. CI then plans <em>again</em> — minutes or hours later, against whatever state looks like now — and applies the second plan without showing it to anyone.</p><p>Most of the time the two plans are identical and nothing goes wrong. That is precisely what makes it dangerous.</p><p>It works until the moment it matters.</p><p>Someone runs terraform apply from a laptop while the approval sits pending. Someone edits a resource in the portal. A data source resolves differently. The approval said yes to one thing; the pipeline did another, and no record exists of what the difference was.</p><p>The fix is to treat the plan as an artifact, because that is exactly what it is:</p><p>−Before</p><pre># plan job<br>- run: terraform plan -out=tfplan</pre><pre># ...plan file discarded<br>#    with the runner</pre><pre># apply job<br>- run: terraform apply -auto-approve</pre><p>+After</p><pre># plan job<br>- run: terraform plan -out=tfplan<br>- uses: actions/upload-artifact@v4<br>  with:<br>    name: tfplan-${{ github.sha }}<br>    path: terraform/tfplan<br>    retention-days: 1</pre><pre># apply job<br>- uses: actions/download-artifact@v4<br>  with:<br>    name: tfplan-${{ github.sha }}<br>    path: terraform<br>- run: terraform apply -input=false tfplan</pre><p>Now the gate means something. And a second property arrives for free: a saved plan records the state serial it was generated against. If state moved while the approval was pending, Terraform refuses to apply it.</p><p>Error: Saved plan is stale The given plan file can no longer be applied because the state was changed by another operation after the plan was created.</p><p>That is not a failure. That is the guard working. Re-plan, re-review, re-approve.</p><p>Two things to know before copying this. A plan file embeds resource attributes — including values you may consider sensitive — and a build artifact is downloadable by anyone with repository read access, so set a short retention. And add a concurrency group, or two merges landing together will race each other into the same state file:</p><p>terraform.yml</p><pre>concurrency:<br>  group: terraform-${{ github.ref }}<br>  cancel-in-progress: false</pre><p>cancel-in-progress: false is the important half. You never want a half-finished apply killed partway through.</p><p>BUG 03</p><h3>The deploy that doesn’t deploy</h3><p>Terraform is right, and the deployment is wrong.</p><p>The container image was pinned like this, with a comment that already knew better:</p><p>variables.tf</p><pre>variable &quot;image_tag&quot; {<br>  description = &quot;Image tag to deploy. Pin a digest or explicit tag in prod<br>                 rather than &#39;latest&#39;.&quot;<br>  type        = string<br>  default     = &quot;latest&quot;<br>}</pre><p>The comment knows. The default does not.</p><p>Here is what latest does in a Terraform-managed deployment. The image string is part of the container spec: myacr.azurecr.io/readmission-api:latest. You train a better model, build a new image, push it under the same tag. Then you run terraform apply:</p><p>No changes. Your infrastructure matches the configuration.</p><p>The string did not change, so there is no diff, so there is no new revision. The old model keeps serving traffic. Terraform is behaving correctly — nothing in the <em>configuration</em> changed — and the deployment is silently wrong.</p><p>In Kubernetes you would reach for imagePullPolicy: Always and a rollout restart. Under Terraform there is no equivalent, because Terraform&#39;s entire model is that the configuration describes the desired state. A mutable tag makes the configuration lie.</p><p>So I made it a hard error rather than a comment:</p><p>variables.tf</p><pre>variable &quot;image_tag&quot; {<br>  type    = string<br>  default = null</pre><pre>  validation {<br>    condition     = var.image_tag != &quot;latest&quot;<br>    error_message = &quot;image_tag must be immutable. Re-pushing &#39;latest&#39; changes nothing in the plan, so the running revision would never pick the new image up. Use a build SHA, a version tag, or a sha256 digest.&quot;<br>  }<br>}</pre><p>Deploys are now terraform apply -var &quot;image_tag=$SHA&quot;. The tag change <em>is</em> the diff that creates a revision.</p><p>And rollback becomes the same command with an older SHA — which is the real prize here. There is no separate recovery path that only ever gets exercised during an incident.</p><p>BONUS</p><h3>A first apply that cannot succeed</h3><p>Less a bug than an ordering problem worth naming.</p><p>Terraform creates the registry and the container app in a single apply. The app references myacr.azurecr.io/readmission-api:&lt;tag&gt;. On a first apply that image does not exist — you cannot push to a registry Terraform has not created yet.</p><p>My README acknowledged this: <em>“The app will report an unhealthy revision until an image exists.”</em> True, and not good enough. A first terraform apply that leaves you staring at a failed revision teaches everyone who runs it that red output is normal.</p><p>The fix is a bootstrap mode. With no tag set, run a public placeholder instead, and let ingress and the probes follow whichever image is actually running:</p><p>main.tf</p><pre>locals {<br>  bootstrap = var.image_tag == null</pre><pre>  container_image = local.bootstrap<br>    ? var.bootstrap_image<br>    : &quot;${azurerm_container_registry.this.login_server}/${var.image_name}:${var.image_tag}&quot;</pre><pre>  # The placeholder serves plain HTTP on its own port and has no /health.<br>  app_port = local.bootstrap ? var.bootstrap_port : var.container_port<br>}</pre><p>main.tf · probes follow the image</p><pre>dynamic &quot;liveness_probe&quot; {<br>  for_each = local.bootstrap ? [] : [1]</pre><pre>  content {<br>    transport = &quot;HTTP&quot;<br>    port      = var.container_port<br>    path      = &quot;/health&quot;<br>    # ...<br>  }<br>}</pre><p>First apply: green, serving a placeholder. Push an image, set the tag, apply again: green, serving the model. Two applies, no red output, and nobody learns to ignore a failed revision.</p><p>CHECKLIST</p><h3>Six things to check in your own pipeline</h3><p>Each of these takes under a minute.</p><ol><li>Does CI have remote state?Run the plan job twice without changing anything. If both runs say “N to add,” your pipeline is planning against nothing.</li><li>Does apply consume the plan file?Search the workflow for -auto-approve. If it appears without a plan file argument, your approval gate is decorative.</li><li>Does the environment gate actually gate?GitHub silently creates a missing environment with no protection rules. environment: production pointing at one that does not exist approves nothing, and looks identical in the YAML.</li><li>Can a re-pushed image tag produce a deploy?If the image reference is a mutable tag, the answer is no — and the failure is silent.</li><li>Does a first apply succeed on an empty account?Not “eventually converges.” Succeeds, on the first run, with green output.</li><li>Is there a concurrency group?Two merges, one state file. Without one, they race.</li></ol><h3>The honest part</h3><p>None of this has been applied against a live subscription. fmt, validate, TFLint and Trivy are green, every variable validation is exercised, both bootstrap branches are confirmed — and terraform plan and apply against real Azure credentials have not been run. The repository&#39;s README says exactly that, in a table.</p><p>I mention it because it is the same class of problem as everything above. “It validates” is not “it deploys,” in the same way that “there is an approval step” is not “changes are approved.” The gap between a control existing and a control working is precisely where these three bugs lived.</p><p>Worth reviewing your own pipeline for.</p><p><a href="https://github.com/jumma786/mlops-iac-terraform">github.com/jumma786/mlops-iac-terraform →</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=583bd28b92bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Gave an AI Access to a Real Database. Then I Spent Weeks Making Sure It Couldn’t Do Any Damage.]]></title>
            <link>https://medium.com/@jummamohammad477/i-gave-an-ai-access-to-a-real-database-then-i-spent-weeks-making-sure-it-couldnt-do-any-damage-06cb7a73dbb5?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/06cb7a73dbb5</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 13:21:11 GMT</pubDate>
            <atom:updated>2026-08-04T13:21:11.530Z</atom:updated>
            <content:encoded><![CDATA[<p>The story of building an AI that answers questions about your data in plain English — and the security flaws I only found by turning that same scrutiny on my own code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXYB0j3turP4Cwxz61bNxA.png" /></figure><p>The forty-second demo</p><p>You type a question the way you’d say it out loud:</p><p>“total revenue by country”</p><p>Forty seconds later, working against a real database of just over a million UK retail transactions, the system hands back a clean, correct answer: the United Kingdom on top at £17.7 million, Ireland next, then the Netherlands.</p><p>Nobody wrote the instructions to get there. A person typed five ordinary English words, and a piece of software worked out on its own which part of the database held the sales figures, which numbers to add up, and how to rank them. It had never seen this database before. The question didn’t name a single table or column. And the answer matched a hand-written reference exactly.</p><p>The clever part isn’t that a computer printed some numbers. It’s that a person asked a question in plain English and got a real answer from real data, with no analyst in the middle and no technical knowledge required.</p><p>It’s a satisfying demo. It’s also, if you stop and think about what just happened, a little alarming: an AI wrote an instruction, and something ran that instruction against a real database.</p><p>That single sentence is the entire problem this project exists to solve. What follows is the honest version of the story — what the thing does, why it’s built the way it is, and the real security flaws I found when I stopped adding features and started auditing my own work.</p><p>Why “it wrote a query and we ran it” should worry you</p><p>Modern AI models are, at their core, extremely good guessers. They produce the most plausible-looking answer, which is usually right and occasionally isn’t. When the output is a paragraph of text, a wrong guess is just an embarrassment you can read and dismiss.</p><p>When the output is an instruction that a database will carry out, a wrong guess becomes an action. Databases don’t only answer questions — the same language that reads data can also delete it, empty entire tables, or overwrite records. And the database can’t tell the difference between an instruction that came from careful human thought and one an AI invented half a second ago. It simply does as it’s told.</p><p>So the failure mode nobody mentions in the tutorials is always the same: it works beautifully in the demo, and then one day the AI decides that wiping a table is a reasonable reading of “clean up the test data.”</p><p>The real question behind this whole project, then, isn’t a feature. It’s this: what happens when the AI is wrong — and does the system catch it before the damage or after?</p><p>Everything below is built around answering that.</p><p>What this actually is, in plain terms</p><p>Strip away the buzzwords and it’s a familiar idea: a way to ask a database questions in plain English, so someone who doesn’t know how to write database code can ask “what were our top products last quarter” and get a real answer instead of waiting on an analyst. Plenty of companies sell a version of this.</p><p>What’s different here is that the interesting engineering isn’t the language part at all. It’s everything standing between the AI and the database — the safeguards that decide whether an instruction is allowed to run.</p><p>Think of it as three layers, like a bank.</p><p>The three layers</p><p>The part you see and click is like the bank’s front desk. There are seven simple pages — a dashboard, a place to upload data, a place to connect a database, a chat window, document search, reports, and settings. Crucially, this part holds no connection to the database at all. It can only pass messages to the layer beneath it, the way a customer can talk to a teller but can’t walk into the vault. Every message carries a kind of signed wristband proving you logged in.</p><p>The middle layer is the teller. It receives your messages, checks the wristband, and decides what to do. It re-checks who you are on every single request rather than trusting the wristband once at the door. That sounds like pointless bureaucracy until you picture a cancelled account — with these constant checks, access stops the instant the account is closed, rather than lingering until the wristband happens to expire.</p><p>The bottom layer is where the real work happens, and it’s worth walking through slowly.</p><p>Following one question from start to finish</p><p>Say you ask “total revenue by country.” Here’s what actually happens, step by step.</p><p>First, the system looks up what’s in the database. Before anything else, it needs to know what data exists — the names of the tables, the columns, and how they connect. It takes this inventory once, when you first connect, and remembers it. Without it, the AI would just be guessing at names, and it would guess wrong.</p><p>Second, it asks the AI to write the instruction. Your question, plus that inventory, plus the conversation so far, goes to whichever AI is set up — a commercial one, or a free one running privately on your own machine. Out comes a single instruction: the read-only kind, the sort that looks things up but can’t change anything.</p><p>Third — and this is the part I’d defend hardest — it checks that instruction with no AI involved whatsoever. The reason this step is trustworthy is precisely that it’s dumb. It doesn’t reason. It doesn’t have opinions. It applies the same fixed rules every time: allow only a single lookup and nothing else; block the old trick of smuggling a second, destructive instruction in behind the first; strip out hidden text where a banned command might lurk; check what’s left against a list of forbidden words — the vocabulary of deleting and overwriting; and cap the number of rows so a careless question can’t drag back ten million records.</p><p>If any check fails, everything stops. The instruction is never run. Not run-with-a-warning, not logged-and-ignored — never run. A safeguard only counts if failure means the dangerous thing didn’t happen.</p><p>And this is deliberately a second line of defence, not the only one. The system is also meant to connect using an account that simply lacks permission to delete anything in the first place — so even an instruction that slipped past the checker would be refused by the database itself. Two independent layers, so that one mistake is never enough.</p><p>Fourth, it runs the approved instruction, with a time limit attached so a monstrously expensive question gets cut off rather than tying everything up.</p><p>Fifth, it picks a chart — again, with no AI. This is just a simple rule of thumb based on the shape of the results: a couple of number columns suggests one kind of chart, a handful of categories another. It’s a short piece of ordinary code that can’t invent a nonsensical chart, and you can test it by feeding it a known input and checking the output.</p><p>Sixth, it asks the AI to explain the result in a sentence or two — but it only shows the AI the summarised figures, not the raw data. The less the AI can see, the less it can get wrong.</p><p>Two databases, kept deliberately apart</p><p>An easy detail to miss: the app uses two entirely separate databases.</p><p>One holds your actual business data — the one your questions query. This is the one that should use the locked-down, read-only account.</p><p>The other holds the app’s own housekeeping: accounts, logins, saved reports, uploaded documents.</p><p>Keeping them apart isn’t cosmetic. It’s what lets your business data stay genuinely read-only while the app can still record the things it needs to record. Merge them, and “read-only” becomes either a lie or a broken sign-up page.</p><p>That second, housekeeping database defaults to a single file sitting on the computer — the simplest possible setup, needing no configuration at all. Hold on to that word “default.” It turns out to be the most dangerous line in the whole project, for a reason I didn’t spot until much later.</p><p>The other half: talking to documents, not just data</p><p>Running alongside all this is a separate feature for documents. Upload a text file, a PDF, or a Word document, and it gets broken into passages and stored in a space reserved for your account alone.</p><p>The clever bit is that it searches by meaning, not by matching words. I tested it with a question that appears nowhere in the source document — “how long do I have to get my money back?” — against a refund policy that only ever says “returns within thirty days.” Completely different words. It found the right passage and answered correctly.</p><p>And it shows you the passages it used. You don’t have to take the answer on faith — you can check it against the source it came from. That’s the whole point.</p><p>The ideas that actually mattered</p><p>A few principles run through the entire project, and they’re the part worth taking away, more than any specific piece of code.</p><p>The AI is never trusted with anything that can be checked instead. Not the database connection, not the choice of chart, not the figures. Wherever the AI’s output can be verified by plain, predictable code, it gets verified before anything acts on it.</p><p>Predictable work is kept away from the AI, even when the AI could do it. Choosing a chart could be an AI’s job. It would work most of the time. It would also be impossible to test and occasionally wrong in baffling ways. A short, fixed rule does the job better and can be proven correct.</p><p>And the tests refuse to lie. This one deserves its own section.</p><p>The testing decision that caught a real flaw</p><p>When software is tested automatically, the slow external pieces are usually swapped out for fast stand-ins. It’s a normal practice. The temptation here was to swap out the AI itself.</p><p>But a fake AI that hands back an instruction you wrote yourself only proves that your own fake is well-formed. It proves nothing about whether the real AI can actually do the job — which is the entire thing being tested. It’s marking your own homework.</p><p>So the rule became: any test claiming the system works must use a real AI, or skip loudly and say why — never quietly pass on a technicality.</p><p>This wasn’t box-ticking. It caught a genuine flaw. A hidden two-minute time limit was buried in the code, invisible to every test that used a fake AI, because a fake responds instantly no matter what. A real AI doing real work does not respond instantly. The first time the tests ran against an actual local model, the truth surfaced: that model needed longer than two minutes for its first, cold answer, and was being cut off. A fully faked test suite would have shipped that limit to everyone — with every test showing a cheerful green tick the whole time.</p><p>Then I stopped building and started hunting for my own mistakes</p><p>Once the system worked, I went back through it specifically looking for real, reachable flaws — not hypothetical ones. I found three.</p><p>The first was a report feature that saved every report under the same filename for everyone. Two people generating a report at the same moment would silently overwrite each other, and the loser would open their report to find someone else’s numbers. The fix gave every report a unique name, recorded who owned it, and checked ownership before handing it over. If you’re not the owner, it says “not found” rather than “not allowed” — because “not allowed” quietly confirms the report exists, which is a hint you shouldn’t be given.</p><p>The second was a lock-out feature meant to stop someone guessing passwords. It counted failed attempts inside a single running copy of the program. But busy apps run several copies at once, each keeping its own count — so the real limit silently multiplied the more successful the app became. Nothing errored. The protection just quietly weakened. I rebuilt it so the count is genuinely shared across every copy and survives a restart.</p><p>The third was the subtlest, and worth unpacking. The app lets you supply a database address for it to connect to. There’s a well-known attack that abuses this: you can’t reach a company’s internal systems from your own laptop, but the company’s server can — so instead of attacking directly, you trick the server into fetching something on your behalf. The prize is a hidden internal service, run by every major cloud provider, that hands out the keys to the whole account. My defence was a list of approved names. The flaw: a name and the actual address it points to are two separate things, and the link between them can be quietly rigged. An approved-looking name could be pointed at the forbidden address, and my check — which only ever read the spelling — would wave it through. The fix was to look up the real address before connecting and reject the dangerous ones. Deliberately not a blanket ban on all internal addresses, because ordinary private ones are completely normal for a self-hosted database — and a safeguard that blocks the normal case is one people simply switch off.</p><p>All three were live and reachable. All three were fixed, with tests to keep them fixed.</p><p>The flaw that wasn’t in the code at all</p><p>The three above were mistakes in the code. The next one was different, and I only found it when I went to release the thing.</p><p>Releasing means packing the whole app into a self-contained bundle and shipping it to a server. My packing instructions said, in effect, “include everything in this folder” — and I’d never told it what to leave out. So everything went in, including the file where passwords and keys are meant to live.</p><p>I’ll be honest about how bad it actually was: at that moment the file held only a placeholder and a throwaway password for a database reachable from nowhere but my own machine. Nothing real leaked. But what existed was a mechanism that would leak real secrets, silently and permanently, the very first time real ones were added — which is exactly what getting ready to release means. Eleven lines fixed it.</p><p>Then I found the one that would actually have hurt.</p><p>Remember that housekeeping database — accounts, logins, saved reports — defaulting to a single file? Released apps usually run in disposable boxes that get rebuilt from scratch with every update. Anything written inside is discarded on the next release. Not corrupted. Not backed up. Gone.</p><p>So: release it, sign up, use it, everything works perfectly. Push any small update. Every account, every uploaded document, every saved report — vanished. And no error, because nothing went wrong as far as the app could tell. It starts cleanly on an empty database and waits politely for you to sign up again. You’d hear about it days later from a confused user, with nothing in any log to point at.</p><p>What makes this nastier than the first three is that the default isn’t wrong. A single file is exactly right for someone trying the project on their own laptop. The code is correct. The default is correct. It only turns destructive when the situation changes — and nothing in the system knew the situation had changed.</p><p>The usual answer is documentation, and it’s a weak one. I’d already written the warning into the guide. A warning in a document you’re meant to have read isn’t a safeguard — it fails precisely when someone’s moving fast, which is precisely when it matters.</p><p>So now the app simply refuses to start. If you tell it this is a real release while that setting still points at a disposable file, it stops immediately with a message naming the problem and what it would have cost you. The failure shows up in your release log within thirty seconds, instead of showing up as missing users a week later.</p><p>And then this very safeguard nearly repeated the mistake it was built to prevent. My first instinct was to be clever and guess the situation from other clues — but the clue I picked was one I’d genuinely set up on my own machine that same afternoon. The check would have refused to start my own development version. A safeguard that fires on the normal, everyday path doesn’t get fixed — it gets switched off, and a switched-off safeguard protects nothing. So I made it a plain, explicit setting instead. The clever guess was worse than the boring switch — a lesson I seem to have to relearn about once a year.</p><p>What I’m still not claiming</p><p>The project keeps a section called “Known limitations,” and it’s meant to stay uncomfortable to read rather than get quietly deleted the moment it’s inconvenient.</p><p>There are still no roles or permissions — every logged-in user has identical rights. Your own things are kept separate from other people’s, but there are no administrators and no sharing. That’s fine for a single team and not fine for serving multiple separate organisations.</p><p>The shared lock-out count only works if you set up the shared storage; leave it off and you’re back to the weaker behaviour — now documented rather than silently assumed away.</p><p>Logins can’t be cut short mid-session; a stolen wristband works until it naturally expires.</p><p>The address check happens a moment before connecting rather than at the exact instant of connection, leaving a narrow, well-timed opening that the tools involved don’t let me fully close. I’d rather say so than imply the fix is complete.</p><p>And the headline demo — that revenue-by-country answer — is one question, against one small model, on one dataset. It shows the whole path works end to end. It is explicitly not a measure of accuracy, and I’m not offering one.</p><p>Who this is actually for</p><p>Nothing here is tied to retail data — that’s just what proves the thing works against something real. The pattern fits anywhere a database exists and non-technical people need answers from it: internal reporting for operations and marketing teams, customer-support tools, or document-heavy compliance work where the document side matters more than the data side.</p><p>It is not ready, as it stands, for anything serving multiple separate organisations or handling regulated data. The permissions gaps above are exactly why.</p><p>Where it’s most useful to someone else, beyond running it directly, is as a worked example of one idea: the AI generates, plain predictable code stands guard, and the tests refuse to lie about which parts have actually been checked. The retail dashboard is just the vehicle. That idea is the cargo.</p><p>The actual point</p><p>The value of this project was never “an AI can write database code.” Any recent AI can do that — it’s not the achievement. The value is in the boring half nobody films for the demo: a guard that never trusts the thing it’s guarding, tests that refuse to fake the one part whose reliability is actually in question, and the discipline to audit your own work with the same suspicion you’d bring to a stranger’s.</p><p>If you’re building anything that lets an AI actually do something — run a query, send a message, move money — the question worth asking isn’t “does it work in the demo.” It’s: what happens the one time it’s wrong, and does your system catch it before the damage or after?</p><p>Get that answer right, and the demo takes care of itself.</p><p>The project is open source under an MIT licence.</p><p><a href="https://github.com/jumma786/ai-data-analysis-agent">https://github.com/jumma786/ai-data-analysis-agent</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06cb7a73dbb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the World Suddenly Cares About: Detecting Attention Spikes from Wikipedia Traffic]]></title>
            <link>https://medium.com/@jummamohammad477/what-the-world-suddenly-cares-about-detecting-attention-spikes-from-wikipedia-traffic-82b5f3870ed1?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/82b5f3870ed1</guid>
            <category><![CDATA[zero-cost]]></category>
            <category><![CDATA[wikipedia]]></category>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 15:13:56 GMT</pubDate>
            <atom:updated>2026-07-30T15:13:56.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XXkPGaOLS-_-CJ6C" /><figcaption>Photo by <a href="https://unsplash.com/@planetvolumes?utm_source=medium&amp;utm_medium=referral">Planet Volumes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>A zero-cost, keyless anomaly detector — and the four decisions that separate a real one from a toy</h3><p>When something happens in the world, people look it up.</p><p>An earthquake, a product launch, a company nobody had heard of yesterday — the first thing a lot of us do is search for it, and a surprising number of those searches end on Wikipedia. That makes daily Wikipedia pageviews a public, global, keyless proxy for human attention. The data is free, it covers millions of topics, and it needs no account to read.</p><p>So I built a tool around that signal. It watches a list of topics, flags the days that break pattern, and then reads the article’s own edit history to say what the day was about. It runs unattended, on a schedule, at zero cost — no API keys, no paid services, no accounts.</p><p>Here’s the kind of thing it produces:</p><pre># Attention digest — 2025-02-01</pre><pre>1 of 12 topics moved in the last 3 days.</pre><pre>## DeepSeek<br>241,590 views on 2025-01-30 — 76.1× the 3,175/day baseline (z=172.6)</pre><pre>93 edits by 31 editors:<br>- Real cost and export restrictions: rewrite for grammar and clarity<br>- Development and release history: add a table for Major Versions</pre><p>That output was generated by a scheduled job with nobody watching. One process can do the same for hundreds of topics at once.</p><p>The tool itself is a few hundred lines of Python. What I actually want to write about is the part underneath it — because “flag the days that are unusually high” sounds trivial, and the naive version of it fails in ways that are quiet, plausible, and completely wrong.</p><h3>Why the obvious approach is worse than no approach</h3><p>The textbook way to flag an outlier is the standard z-score: take how far today sits from the mean, and divide by the standard deviation. Anything past three-ish is “unusual.”</p><p>On attention data, this breaks on precisely the days you care about.</p><p>Picture an article that normally gets a few thousand views a day, and then has one day at forty times that. When you compute the mean and standard deviation over a window that <em>includes</em> that day, the spike drags the mean upward and inflates the standard deviation enormously. The yardstick you’re measuring the spike with has been stretched by the spike itself. The result is that the most dramatic day scores far <em>lower</em> than it should — sometimes low enough to slip under the threshold entirely.</p><p>Statisticians call this <strong>masking</strong>: the outlier conceals itself. And it’s the worst possible failure mode for a monitoring tool, because it fails silently on the exact events the tool exists to catch. A green dashboard that missed the one thing that mattered is more dangerous than no dashboard at all.</p><p>Everything interesting about this project is a response to that class of problem. Four decisions carry most of the weight.</p><h3>1. A robust baseline, because outliers corrupt ordinary statistics</h3><p>The fix is to measure with statistics that don’t flinch at a single freak value. Instead of mean and standard deviation, the detector scores each day against a <strong>median and median absolute deviation (MAD)</strong>:</p><pre>views − median(baseline)<br>mod_z  =  ─────────────────────────────────<br>                  MAD / 0.6745</pre><p>The median of a window barely moves when one day goes vertical — swap a normal day for a 40× one and the middle value is essentially unchanged. The MAD is similarly stubborn. The 0.6745 constant rescales MAD into units comparable to a standard deviation, so the conventional cutoff of 3.5 keeps its usual meaning (this is the Iglewicz–Hoaglin modified z-score, if you want the reference).</p><p>There’s an edge case that matters more than it looks: on very low-traffic articles, the MAD can collapse to zero, because more than half the window shares the same value. Divide by that and every score is undefined — and the most blatant spikes are the ones that vanish. So where MAD is zero, the code falls back to the mean absolute deviation, and then floors the whole spread at a minimum. The unglamorous fallback is what keeps the detector from silently missing the easy cases.</p><h3>2. A trailing window, because a day must not inform its own baseline</h3><p>Here’s a bug that will make your detector look <em>better</em> in testing and can never be reproduced in production: letting a day help define the baseline it’s measured against.</p><p>If today’s value is inside the window used to compute today’s expectation, you’ve leaked the future into the past. In a backtest this flatters your numbers. In the real world, at the moment you’d actually score today, you don’t yet have today’s context. The two don’t match, and the gap is invisible unless you go looking.</p><p>The fix is one line — shift the baseline window back by a day so each day is scored strictly against days before it — but the important part is that this is <strong>enforced by a test, not a comment</strong>. Leakage is too easy to reintroduce during a refactor for a code comment to protect it.</p><h3>3. Day-of-week adjustment, because attention has a weekly rhythm</h3><p>Pageviews breathe on a weekly cycle. Weekdays and weekends have systematically different traffic, and if you ignore that, two bad things happen at once. The cycle itself gets mistaken for news — every busy Monday looks like an event — and the extra variance it adds inflates your estimated spread, which desensitizes the detector to the real events buried underneath.</p><p>So each day gets a multiplicative weekday factor estimated from its own recent history. A factor of 0.75 means “Saturdays for this article normally run 25% below a typical day.” Scoring happens on the deseasonalized series, but results are reported back in raw views, so the baseline reads as <em>expected traffic for this weekday</em>.</p><p>This one isn’t cosmetic. On a genuinely busy Saturday for the Microsoft Excel article:</p><p>Expected Score Flagged? Unadjusted 4,187 z = −0.68 no Adjusted 3,008 z = +3.50 yes</p><p>Without the adjustment, a busy weekend reads as <em>below average</em> — because a busy Saturday still sits under the all-days median — and the detector calls a real event quiet. Across weekday-cyclical articles, the estimated noise floor roughly halved, which is a direct doubling of sensitivity to actual news.</p><h3>4. Two independent gates, because significance alone is not enough</h3><p>Statistical significance turns out to be necessary but nowhere near sufficient.</p><p>On a very stable article, the MAD is tiny. That means a completely meaningless 1.2× nudge can clear a z-score of 3.5, because relative to almost-zero noise, any movement is “extreme.” The math is right and the conclusion is useless.</p><p>The first live run of the watchlist proved the point without my help. It reported Cobalt on a 1.2× move with zero edits that day, and Nvidia on the strength of a single edit that read <em>&quot;Filled in 1 bare reference(s) with reFill 2.&quot;</em> Technically anomalous. Completely not news.</p><p>So for unattended reporting, a day has to clear <strong>two</strong> gates: statistical significance (the z-score), and <strong>materiality</strong> — a real multiple of its own baseline, 2× by default. A report that cries wolf stops being read, and a monitoring tool nobody reads is worse than nothing.</p><h3>The newest piece: corroboration</h3><p>Everything above scores one topic in isolation. The most recent addition looks across the whole watchlist at once, and it’s my favorite part.</p><p>One topic spiking is a prompt to investigate. Several <em>unrelated</em> topics spiking on the same day is a lead — because one event tends to light up its whole neighborhood of topics at once. A chip-export headline moves Nvidia, DeepSeek, and Rare-earth element together. A lone Cobalt flag is easy to dismiss; the same flag sitting next to two related surges on the same date is a story.</p><p>So the digest now groups movers whose peaks fall on the same or adjacent days and surfaces those clusters at the top, above the per-topic detail:</p><pre>## Co-spikes<br>Topics that surged together — a shared date is often a shared cause.</pre><pre>- 2025-01-30 — DeepSeek, Nvidia, Rare-earth element</pre><p>The clustering is deliberately simple: single-linkage over the peak dates, with a tolerance you can widen if you want to catch spikes a day apart. The recent window is only a few days wide, so the usual failure mode of single-linkage — chaining across a huge range — can’t happen here. And a co-spike needs at least two topics; a group of one is just a mover, already listed below. It’s a small amount of code that turns a flat list of flags into “these three moved together, and here’s when.”</p><h3>Testing something that depends on the outside world</h3><p>The project leans on two live APIs it doesn’t control — one for pageviews, one for edit history — and that shaped how it’s tested. There are 92 tests, split by whether they touch the network.</p><p>The offline suite stubs both APIs and runs on every push. The rule is that these must <em>never</em> fail because a third party had a bad night; a Wikimedia outage should never put a red X on an unrelated commit. But an integration you depend on will eventually change shape, and you want to find out on your terms. So a separate set of live contract tests runs nightly against the real APIs.</p><p>That split earned its keep immediately. On their very first run, the contract tests caught that the pageview endpoint path had been wrong all along — while a fully green offline suite was cheerfully reporting perfect health. The offline tests were testing my code against my assumptions. Only the live tests were testing my assumptions against reality.</p><h3>What it can’t do</h3><p>A monitoring tool that oversells itself is worse than one that’s honest about its edges, so, plainly:</p><p>Pageviews are <strong>coincident, not leading</strong>. People read about a thing after it happens. The value here is breadth and speed — one process watching hundreds of topics — not foresight. A flag is a prompt to investigate, not a finding: the data is noisy, includes some automated traffic, and a day can spike with no edits to explain it at all. The edit context is evidence, not proof. The weekday model assumes a stable weekly shape and doesn’t know about holidays. And the counts themselves are revised slightly after publication, so the tool records the access date every time.</p><p>None of that makes the signal worthless. It makes it a good first question rather than a final answer, which is exactly what an attention detector should be.</p><h3>Why I built it</h3><p>Partly because the signal is genuinely useful — a cheap, broad early-warning system for “the public suddenly cares about X” has obvious uses in comms, research, and public health, and Wikipedia traffic has a real track record in things like disease nowcasting.</p><p>But mostly because it’s a compact example of the thing I find most interesting in engineering: the gap between the version that demos well and the version that’s actually correct. Every one of those four decisions came from the naive approach failing in a way that looked fine until I pushed on it. The robust baseline, the leakage test, the two gates — none of them are clever. They’re just the difference between a detector you can trust and one that quietly lies to you.</p><p>The code is open source. If you fork it, point the User-Agent string at your own project — Wikimedia’s guidelines ask for it, and it’s the polite way to use a free, keyless API that a lot of people quietly depend on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82b5f3870ed1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an Invoice-Finance Risk Monitor From a Public Retail Dataset — Here’s What I Learned About…]]></title>
            <link>https://medium.com/@jummamohammad477/i-built-an-invoice-finance-risk-monitor-from-a-public-retail-dataset-heres-what-i-learned-about-08657f9142ea?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/08657f9142ea</guid>
            <category><![CDATA[invoice-financing]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 13:21:11 GMT</pubDate>
            <atom:updated>2026-07-15T13:21:11.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built an Invoice-Finance Risk Monitor From a Public Retail Dataset — Here’s What I Learned About Exposure, Dilution, and Honest Prediction</h3><p>How I turned 824,364 rows of retail transactions into a lender’s early-warning system — and why the hardest part wasn’t the model, it was refusing to cheat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtyXswoHIdN1KXq41Dwb4A.png" /></figure><p>I’m Jumma Mohammad Teli, a Data Analyst at UBS in London with 5+ years across financial services, telecom, and public-sector analytics. I build portfolio projects that use real data and honest framing — because I’d rather defend a believable result than impress with one I can’t. This is one of them.</p><p>Most analyst portfolios I see fall into one of two traps. Either they’re a Titanic notebook dressed up with nicer charts, or they’re a “real” business project built on data that was quietly engineered to make the model look brilliant. I wanted to build something that would survive a conversation with an actual credit risk manager — where the numbers are real, the framing maps onto a real lending product, and the model’s performance is believable because it isn’t perfect.</p><p>So I built an SME Invoice Finance Risk &amp; Exposure Monitor: a pipeline that turns a raw transaction ledger into the exact set of metrics, fraud flags, and early-warning scores that a data analyst at an invoice finance lender produces every week. It runs end-to-end on real data, writes a set of CSVs an operations team could actually work from, and generates a self-contained HTML dashboard you can open in any browser with no server.</p><p>This is the story of how I built it, the decisions that mattered, and the one principle I refused to compromise on.</p><p>First, what is invoice finance?</p><p>If you haven’t worked in this corner of lending, here’s the whole business in two sentences. An invoice finance lender advances cash to a business against its unpaid invoices — typically around 80% of the invoice value up front, with the remainder (less fees) paid when the invoice settles. The lender’s entire risk lives in one question: what is our exposure, and where is risk quietly building before it becomes a loss?</p><p>That question breaks down into four jobs an analyst does constantly.</p><p>Exposure monitoring is about how much cash is advanced and outstanding right now. Credit risk is about dilution, debtor concentration, arrears, and dormancy. Early warning is about which clients are heading for trouble next. And fraud detection is about invoices that don’t look like honest trading.</p><p>I wanted every one of these four functions represented by a real output, computed from real data. That constraint drove everything else.</p><p>The data problem — and the framing that solved it</p><p>There is no public, labelled invoice-finance ledger. Lenders don’t publish their books. So the honest options are: fabricate data (worthless), or find real transactional data whose shape matches an invoice ledger and adapt the framing without touching the numbers.</p><p>I used the UCI Online Retail II dataset — 824,364 real transactions from a UK online retailer, covering 5,942 customers over two years. The mapping is clean and defensible.</p><p>Customers become clients: each customer is a business the lender funds. Invoices stay invoices — they already are invoices. And credit notes become dilution. In the raw data, returns and cancellations appear as invoices with a C prefix. In invoice finance, exactly this — credit notes that reduce the value of a ledger the lender has already advanced against — is called dilution, and it’s one of the single most important risk signals there is.</p><p>That last point is the whole trick. Dilution isn’t a metaphor I bolted on; the credit-note structure in retail data is structurally the same event as dilution in a funded ledger. The framing is adapted. The numbers are real. I put that disclaimer directly in the README and the code, because the moment you hide an assumption like that, you’ve built the second kind of dishonest portfolio.</p><p>Building the metrics: the SQL an analyst lives in, written in pandas</p><p>The core of the pipeline is one function that collapses 824k transaction rows into one row per client, carrying the metrics a lender acts on. A few of them are worth explaining because they are the job.</p><p>Funding-in-use is the actual cash at risk. Net ledger is gross invoicing minus credit notes; funding-in-use is 80% of that, floored at zero. Across the whole portfolio this comes to £13.4M of funding-in-use — the headline exposure number.</p><p>Dilution rate is credit notes as a share of gross invoicing. Portfolio-wide dilution lands at 6.2%. On a single client, a creeping dilution rate is often the first visible sign that something is wrong — goods coming back, disputes rising, or worse.</p><p>Debtor concentration measures how lopsided a client’s ledger is. I proxy it with the largest single stock line as a share of the client’s total. The naive way to compute this is a per-client Python apply, which is fine on a sample and unusable on a million rows. Vectorising it was the difference between a toy and something that scales.</p><p>Dormancy is days since the client’s last invoice. A funded client who stops invoicing is a client whose ledger is running off, and a running-off ledger is where a lender’s advance can get stranded.</p><p>Put together, the top of the exposure table tells its own story: a handful of clients carrying hundreds of thousands of pounds each. Client 18102 alone carries £478,572 of funding-in-use at just 1.7% dilution and zero days since activity; client 14646 carries £418,674 at 1.0% dilution; client 14156 carries £237,252 at 5.5% dilution and nine days quiet.</p><p>This is already a useful artefact. But a table of metrics is descriptive. The interesting question — and the one that separates an analyst from a report generator — is which clients are about to go wrong.</p><p>Fraud flags: cheap rules that catch real signatures</p><p>Before the modelling, a rules-based pass over every invoice catches two classic signatures.</p><p>Round-number invoices come first — a £10,000.00 invoice is far rarer in honest trading than in fraud. Then duplicate invoices: same client, same value, same day, the fingerprint of an invoice submitted twice for funding. On the full ledger this flags 253 invoices. Rules like these will never be your whole fraud strategy, but they’re transparent, they’re instant, and every flag is explainable to a human who has to action it. Sometimes the boring tool is the right tool.</p><p>Early warning, part 1: a scorecard you can defend in an audit</p><p>My first early-warning output is deliberately not a machine-learning model. It’s a transparent, weighted scorecard — the kind of thing a credit committee can read, challenge, and sign off. Dilution carries half the weight, with concentration and dormancy splitting the rest, and each signal is capped so one extreme value can’t dominate: dilution saturates at 30%, dormancy at 90 days.</p><p>Each signal is normalised to 0–1, capped, and blended by weights that live in one place at the top of the file — the single, auditable spot where the lender’s risk appetite is expressed. There’s no trained label here, so there’s nothing to leak. That’s a feature, not a limitation: this is exactly how real credit scorecards work.</p><p>But a raw risk score has a failure mode: it happily gives a maxed-out score to a dormant client with £0 advanced. That’s a note, not an emergency. So the number the watchlist actually ranks on is priority — risk score multiplied by funding-in-use.</p><p>This is an expected-loss-style ranking. It floats the clients where real money meets real risk to the top, and pushes the dramatic-but-harmless cases down. Across the portfolio, £1.58M of exposure sits in critical-risk clients — and now I know exactly which ones.</p><p>Early warning, part 2: predicting run-off without cheating</p><p>Here’s where most portfolio projects quietly fall apart, and where I spent most of my thinking time.</p><p>The tempting move is to grab a labelled dataset — say, Lending Club’s loan defaults — and train a classifier to predict “default.” It would produce a big impressive AUC. It would also be completely meaningless, because Lending Club borrowers share no join key with these retail clients. Attaching those labels wouldn’t be modelling; it would be inventing labels and hoping nobody checks. I refused to do it.</p><p>Instead, I let the ledger label itself, using time. This is an out-of-time design. I pick a cutoff date — 2011–06–10, six months before the data ends. Features come strictly from behaviour before the cutoff. And the label comes from behaviour after it: did the client stop invoicing entirely in the following 182 days? If so, their ledger ran off.</p><p>Because the label is strictly in the future relative to the features, there is no way for outcome information to leak backwards into a feature. This is the single most important design decision in the entire project. Leakage is the reason so many models look brilliant in a notebook and fall over in production — the model was secretly reading the answer. An out-of-time split makes that structurally impossible.</p><p>I train a RandomForestClassifier (300 trees, class-weight balanced because run-off is the minority outcome), evaluate it on a held-out 25% split, and — crucially — score the transparent scorecard on the exact same forward label as the baseline to beat.</p><p>The result: across 3,657 clients with a 38.5% run-off rate, the scorecard baseline scored 0.730 AUC and the trained model scored 0.782 on a hold-out of 915. The top features were days since activity at 22%, funding-in-use at 14%, gross invoicing at 13%, and top-line concentration at 11%.</p><p>0.782 AUC. Not 0.98. And that’s the point. A believable, leakage-free model that adds a real, measurable +0.05 AUC over a strong transparent baseline is worth a hundred suspiciously-perfect notebook models. The feature importances also pass the sniff test: days since activity dominates, which is exactly what a human analyst would tell you predicts a client going quiet.</p><p>From prediction to action: deploying the model forward</p><p>A hold-out AUC is a validation number, not a business output. The last step is the one that makes this a monitor rather than an experiment: refit the model on all available history, then point it at every current client as of the latest date to predict who runs off in their next six months or so.</p><p>Deployed forward, the model scores 4,477 current clients, flags 1,629 at a run-off probability of 0.5 or higher, and — the number a lender actually cares about — surfaces £1.9M of expected exposure at risk (probability multiplied by funding) over the next six months.</p><p>And here’s the payoff that justified the whole out-of-time detour: this forward ranking genuinely differs from the scorecard. The scorecard tells you who looks risky today. The model tells you who will run off next — and those aren’t the same clients. A client can look pristine on today’s dilution and concentration while the model, reading subtler behavioural patterns, still flags them as likely to go quiet. That difference is the entire value of a predictive early-warning system over a descriptive one.</p><p>Wrapping it in something a human can use</p><p>Every run writes a set of CSVs — per-client metrics, fraud flags, the scorecard watchlist, the forward watchlist, the weekly ledger trend, and the model’s training population with its predictions. But CSVs don’t get looked at in a Monday risk meeting. A dashboard does.</p><p>So the pipeline injects each run’s own data into an HTML template and writes a single self-contained dashboard.html — KPIs, ledger trend, an exposure vs dilution-and-concentration view, the priority-ranked watchlist with each client’s run-off probability, the model validation panel, and the fraud flags. No server, no build step, no dependencies. Open it in a browser and it’s all there.</p><p>Drop the full online_retail_II.xlsx into the data folder and it runs on all ~1M rows; leave it out and a bundled sample runs automatically so anyone can reproduce it in seconds.</p><p>What I’d actually build next</p><p>I’m treating this as a living project, and the honest limitations point straight at the roadmap.</p><p>First, calibrate the probabilities. A random forest’s predict_proba is a ranking, not a true probability. Platt scaling or isotonic regression would make the run-off probability mean what it says — important the moment anyone multiplies it by pounds.</p><p>Second, temporal cross-validation. One cutoff gives one estimate. Rolling the cutoff across several dates would test whether 0.782 holds up across time or got lucky on one window.</p><p>Third, true ageing. The trend view is currently a flow — new invoicing per week. With settlement dates, I could build genuine outstanding-balance ageing, the real-world version of what a lender watches.</p><p>And fourth, enrich with real company data via the Companies House API, turning anonymous client IDs into businesses with sectors and filing histories.</p><p>The one thing I want you to take from this</p><p>The model was never the hard part. RandomForestClassifier is one import. The hard part — the part that took real discipline — was refusing to let the project lie to me.</p><p>It would have been easy to bolt on an external default label and post a 0.97 AUC. It would have been easy to compute dilution in a way that leaked. It would have been easy to rank the watchlist on a pure risk score and quietly ignore that half the top of the list had no money at risk. Every one of those shortcuts would have made the project look better and made it worth less.</p><p>Instead I built something where every number is real, every assumption is stated out loud, and the model’s 0.782 AUC is exactly as good as it honestly is. If you’re building an analytics portfolio, that’s the bar I’d aim for. A believable project you can defend beats an impressive one you can’t — every single time.</p><p>The full code and dashboard are on GitHub:</p><p><a href="https://github.com/jumma786/invoice-finance-risk-monitor">https://github.com/jumma786/invoice-finance-risk-monitor</a></p><p>Thanks for reading — I’m always happy to talk about invoice finance, leakage-free modelling, or turning messy transaction data into something a business can act on.</p><p>About the author</p><p>Jumma Mohammad Teli is a Data Analyst at UBS in London, based in Birmingham, with 5+ years of experience across financial services, telecom, and public-sector analytics. He holds an MSc in Computer Science from Queen Mary University of London and works across Power BI, SQL, Python, and the modern data stack. Connect with him on LinkedIn (linkedin.com/in/jumma-mohammad) or explore more projects on GitHub (github.com/jumma786).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08657f9142ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Deliberately Shipped a Worse Model. Here’s Why It Made the Project.]]></title>
            <link>https://medium.com/@jummamohammad477/i-deliberately-shipped-a-worse-model-heres-why-it-made-the-project-edb29497506b?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/edb29497506b</guid>
            <category><![CDATA[hospital-risk-management]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[healthcare-technology]]></category>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 13:35:40 GMT</pubDate>
            <atom:updated>2026-07-13T13:35:40.745Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What building an honest hospital-risk system on five years of messy government data taught me about the difference between impressive and useful.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ZqwuJU71schZZQxGoqjCXg.png" /></figure><p>There’s a version of this project that would have scored 0.99 and told you nothing. I built the 0.90 version on purpose. That single decision — choosing the honest number over the impressive one — is the whole story, and it’s the part of data work that no leaderboard rewards but every hiring manager should care about.</p><p>Let me walk you through it.</p><p><strong>The decision that framed everything</strong></p><p>Picture a state health department. It oversees a couple hundred hospitals but can only send auditors to a handful each quarter. Two questions decide where real money and real scrutiny go: which hospitals do we inspect first, and once we’re there, what should they actually fix?</p><p>Triage and root cause. Not academic exercises — resource-allocation problems with consequences. I wanted a project built around that reality rather than the usual clean-CSV-to-accuracy-score victory lap. So I picked a domain where quality genuinely matters and the data genuinely fights back: US hospitals, using public CMS Care Compare data covering more than 5,800 facilities.</p><p>The result, Hospital Quality Intelligence, runs the full arc: SQL exploration, two explainable machine-learning models, a five-year trend analysis, and a live dashboard anyone can open. Here’s how it came together, including the parts that broke.</p><p><strong>First, I had to earn the right to model</strong></p><p>Before touching machine learning, I wrote 75 SQL queries across five perspectives — geography, ownership, clinical safety, timeliness, and patient experience. This wasn’t warm-up busywork. Real CMS data is a minefield: star ratings stored as text, literal “Not Available” strings masquerading as values, and three separate tables that only join cleanly on a single facility ID.</p><p>Window functions, CTEs, and views turned thousands of raw hospital records into rankings, per-state leaders, and a composite risk score. The final query stitched all three datasets into one national scorecard. By the end I understood the data’s shape, its lies, and its gaps — which is exactly what made the next decision possible.</p><p><strong>The trap I almost walked into</strong></p><p>I built two Random Forest models. One predicts a hospital’s patient-satisfaction star rating. The other flags likely underperformers for audit triage. The classifier landed at a ROC-AUC of 0.90 with 84% recall. The regressor came in at R² = 0.44.</p><p>Now here’s where it gets interesting. CMS’s overall star rating is mechanically derived from a defined set of mortality, safety, and readmission measure counts. If I had fed those counts into a model predicting the rating, I’d have scored near-perfect — and proven absolutely nothing. The model wouldn’t be learning about hospital quality. It would be reverse-engineering a formula I already had.</p><p>That’s data leakage, and it’s the quiet failure mode behind a lot of suspiciously beautiful portfolio numbers.</p><p>A model that scores 0.99 by cheating is worth less than one that scores 0.90 honestly. Knowing the difference is the job.</p><p>So I excluded those columns entirely and trained only on structural and experiential features — hospital type, ownership, location, emergency services, survey engagement, process-of-care scores. The models got weaker and honest. Then, because discipline that lives only in your head doesn’t survive the next refactor, I moved the forbidden columns into one place and wrote an automated test that fails the build if any of them ever reach the feature matrix. The judgment is now enforced by code, not memory.</p><p><strong>A risk score nobody understands is a risk score nobody uses</strong></p><p>If an administrator can’t see why a hospital landed on the watchlist, the number is dead on arrival. I used SHAP to open the box and show which factors push a hospital’s predicted satisfaction up or down.</p><p>The finding that mattered: survey response rate and timely-care performance carried far more weight than ownership type. That’s directly actionable. It tells an administrator where investment actually moves the needle, rather than leaving them to guess. “Why” isn’t a nice-to-have here — it’s the product.</p><p><strong>Five years of data, and a war story</strong></p><p>A single snapshot can’t tell you where a hospital is heading. So I pulled the real CMS archives — 24 quarterly releases from January 2021 to May 2026 — and stacked them into a longitudinal panel of 5,830 hospitals. That let me compute each hospital’s trajectory and flag 817 of them as being on a sustained decline: an early-warning list that surfaces trouble before a hospital ever shows up as low-rated.</p><p>Assembling it was the messiest, and most realistic, part of the whole project. The 2021–2022 archives used an older CMS schema with renamed columns and categorical quality fields instead of numeric counts. Some files were UTF-8; others were Windows-1252 and crashed the parser on a single en-dash. The pipeline now resolves column aliases across schema versions, treats missing risk counts as genuinely unknown rather than a misleading zero, and auto-detects file encoding — so 24 heterogeneous releases collapse into one clean panel.</p><p>The trends themselves are real and a little surprising. Timely-care scores climbed through 2023, then dropped sharply in late 2024 — a CMS measure-set change, not a collapse in care. Patient satisfaction held steady around 3.2 stars. And survey response rates quietly eroded from 25% to 23%, a faint national signal of survey fatigue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_268i5hHGsVxWt0mj3KMyw.png" /></figure><p><strong>What turns a notebook into a product</strong></p><p>The unglamorous infrastructure is what separates a demo from something you’d trust. The project ships with a 13-test suite covering the cleaning logic, the leakage guard, and the trend math, all running automatically on every push through GitHub Actions across two Python versions. And it’s deployed as a live, interactive Streamlit dashboard: pick a state and get a ranked risk list, pick a hospital and see its drivers.</p><p>Tested, CI-verified, documented, deployed. Not a one-off notebook.</p><p><strong>What I’d tell my past self</strong></p><p>The hard part of analytics was never the model. It was the messy data and the honest framing. Chase the right number, not the biggest one — guarding against leakage mattered more than any leaderboard score. Explainability isn’t optional for decision-support; “why” is the deliverable. And real-world data is heterogeneous over time. Schema drift and encoding chaos are the norm, not the exception you get to ignore.</p><p><strong>See it, break it, tell me where it’s wrong</strong></p><p>The full project — code, tests, and write-up — is open source, and the dashboard is live.</p><p>Live demo:</p><p><a href="https://hospital-quality-intelligence-puoehkx7u7po2laff5rv6y.streamlit.app/">https://hospital-quality-intelligence-puoehkx7u7po2laff5rv6y.streamlit.app/</a></p><p>Code:</p><p><a href="https://github.com/jumma786/hospital-quality-intelligence">https://github.com/jumma786/hospital-quality-intelligence</a></p><p>If you’re building your own portfolio project, one piece of advice: pick a problem where being honest is harder than being impressive. That’s where the real learning lives — and it’s the real signal to the people deciding whether to hire you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edb29497506b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What 9.4 Million Taxi Trips Taught Me About Building a Pipeline That Won’t Lie to You]]></title>
            <link>https://medium.com/@jummamohammad477/what-9-4-million-taxi-trips-taught-me-about-building-a-pipeline-that-wont-lie-to-you-3e07b7adf362?source=rss-a961e31db953------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e07b7adf362</guid>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[JUMMA MOHAMMAD TELI]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 13:18:19 GMT</pubDate>
            <atom:updated>2026-07-13T13:18:19.722Z</atom:updated>
            <content:encoded><![CDATA[<p>Anyone can load the NYC taxi dataset and write a GROUP BY. I wanted to build the thing an analytics team actually ships — layered, tested, orchestrated, portable across two warehouses, and with a dashboard you can open in a browser right now. Then the tests caught a bug I’d never have found otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZxIYDDTfDbDEKCh2RyglQ.png" /></figure><p>The demo everyone builds, and the one almost nobody does</p><p>The NYC taxi dataset is the “hello world” of data engineering. That’s exactly the problem. The standard project ends the moment the data lands in a warehouse and someone writes their first aggregate. It proves you can move data. It doesn’t prove you can be trusted with it.</p><p>The difference between those two things is the entire job. A pipeline that produces a number is easy. A pipeline that produces a number you’d stake a decision on is a different discipline — it has structure, it has tests, it fails loudly when the data is wrong, and it runs the same way on a laptop as it does in the cloud.</p><p>So I built that version. Raw NYC yellow-taxi Parquet — about 9.4 million Q1 2024 trips straight from the Taxi &amp; Limousine Commission — flows through four dbt layers into analytics-ready tables, and a Streamlit dashboard reads the result. dbt handles the transformations, DuckDB is a free embedded warehouse for local work, BigQuery runs the identical models in the cloud, Airflow orchestrates the run, GitHub Actions tests every push, and Streamlit serves the dashboard for free with no database attached.</p><p>That’s the tour. The interesting part is why each piece is there.</p><p>Layers aren’t bureaucracy — they’re how you stay honest</p><p>The core of the project is dbt, structured the way analytics engineers actually structure it: every layer does one job, and you can point at any number and trace it back to raw.</p><p>Staging is thin cleanup, materialized as cheap views. This is where I generate a surrogate key for each trip — the TLC data ships no primary key — by hashing vendor, timestamps, locations, and amount. Types get cast consistently, and a data-quality gate drops the obviously invalid: null timestamps, dropoffs before pickups, negative distances. Nothing clever. Just a clean boundary between the messy outside world and everything downstream.</p><p>The intermediate layer joins trips to the zone lookup twice — once for pickup, once for dropoff — so every trip gains a human-readable borough and zone instead of a bare numeric ID. It also derives the metrics analysts actually ask for: trip duration via a reusable Jinja macro, pickup hour, tip percentage.</p><p>The marts are the finished products, materialized as tables: a fact table with one row per trip, a zone dimension, and a daily revenue aggregate summarizing revenue, trips, and averages per borough per day. Fact plus dimension is a star schema — the pattern that has quietly underpinned analytics warehouses for thirty years, and still the right answer here.</p><p>The feature that separates “I used dbt” from “I understand dbt”</p><p>The fact table is incremental. The first run full-loads it. Every run after that, dbt processes only trips newer than the latest one already loaded — download another month, re-run, and instead of grinding through 9 million rows it touches only the new ones.</p><p>This is a small amount of code and a large shift in thinking. It’s the difference between a script that rebuilds the world every time and a pipeline that understands its own state. On a toy dataset you’d never notice. At 9.4 million rows, reprocessing everything on every run is the thing that quietly makes a pipeline too slow to actually operate.</p><p>The bug I only found because I tested at full scale</p><p>Here’s the part I’d put on a poster.</p><p>I wired up dbt tests — the generic ones for uniqueness, non-null, referential integrity, accepted ranges — plus a custom reconciliation test asserting that the total fare is at least the sum of its parts, fare plus tip plus tolls, within a cent of tolerance.</p><p>Built against a single month of data, everything passed. Green across the board. Then I ran the full three months, and two tests failed.</p><p>The reconciliation test caught three trips where the total was less than its own components. Corrupt records — arithmetic that literally does not add up. And the uniqueness test caught a duplicate surrogate key, because the TLC data ships duplicate trip rows in the raw feed.</p><p>Neither of these was a bug in my code. That’s the whole point. The tests were doing their job — catching real dirty data that a GROUP BY demo would have silently folded into the averages and reported as fact. Nobody would have noticed. The dashboard would have looked fine. The numbers would have been wrong.</p><p>I fixed it at the boundary, in staging: a reconciliation gate that drops the corrupt rows and a dedup that keeps one row per key. A full build now passes all 22 nodes clean — and I bumped CI to build all three months, so it exercises that exact path on every single push. The bug can’t come back without the pipeline turning red.</p><p>That sequence — passed on a sample, failed at scale, fixed at the boundary, guarded in CI — is the actual craft. Small samples lie. Tests only earn their keep when you run them against the full, ugly dataset.</p><p>One repository, two warehouses</p><p>The dbt source is target-aware. On my laptop it resolves to reading local Parquet through DuckDB. In the cloud it points at a BigQuery table. Same models, same tests, two backends — DuckDB for free, fast iteration; BigQuery for scale. The production config is driven entirely by environment variables, so no secrets ever touch the repo.</p><p>This matters more than it sounds. Designing for a second warehouse from day one means the choice between “free and local” and “cloud and scaled” is a config flag, not a rewrite. You never get locked into the tool you happened to prototype in.</p><p>The dashboard problem worth solving</p><p>Clean tables are invisible. A dashboard is what makes anyone care. So the marts feed a Streamlit dashboard: KPI tiles for revenue, trips, passengers, and average tip, plus revenue by borough, trips by hour, and a daily trend — with date and borough filters and a colorblind-safe palette that keeps each borough on a fixed hue.</p><p>The interesting engineering problem was deployment. The dashboard reads a 160 MB DuckDB file with 9.4 million rows, and you cannot ship that to a free host. So I gave the app two backends behind one code path. Locally, it attaches the full warehouse read-only. In the cloud, where no warehouse exists, it reads tiny pre-aggregated Parquet files — about 85 KB total — committed to the repo. The app deploys to Streamlit Community Cloud with no database and no raw data, and the code that draws the charts has no idea which backend it’s on. Same principle as the two-warehouse setup: separate what the chart needs from where the data lives, and both problems get easy.</p><p>You can open the live dashboard here:</p><p><a href="https://nyctaxidbt-as6niaviukjr4sinhjdpyz.streamlit.app/">https://nyctaxidbt-as6niaviukjr4sinhjdpyz.streamlit.app/</a></p><p>What 9.4 million trips actually say</p><p>Once the dashboard was live, a few things jumped out. Across Q1 2024, roughly 9.4 million trips generated about $258M in fares. Manhattan dominates — around $196M of that, dwarfing every other borough combined. Trips peak at 6 PM, the evening rush. And the average tip lands near 20.5%, so New Yorkers, for all their reputation, tip well.</p><p>Four things I’d tell someone starting this</p><p>Structure your transformations in layers. Staging to intermediate to marts isn’t ceremony — it’s what makes a project legible and testable, and it’s what lets you trace any number back to raw when someone questions it.</p><p>Write tests, then run them on the full dataset. A sample that passes proves nothing. My tests only earned their keep at 9.4 million rows, and that’s where the real bug was hiding.</p><p>Separate compute from your laptop’s limits. DuckDB reading Parquet is astonishingly capable for local work, and designing for a second warehouse from the start kept the door to scale open for the price of a config flag.</p><p>Ship a consumption layer. The most correct tables in the world are worthless if nobody can see them. The dashboard is the part that turns a pipeline into something people use.</p><p>The whole thing — models, tests, macros, the Airflow DAG, the loader, and the dashboard — is on GitHub. Clone it, run a build, open the dashboard. It runs free on your laptop in a couple of minutes.</p><p><a href="https://github.com/jumma786/nyc_taxi_dbt">https://github.com/jumma786/nyc_taxi_dbt</a></p><p>I’m Jumma Mohammad Teli — I write about data engineering and analytics. Connect with me on LinkedIn.</p><p><a href="https://linkedin.com/in/jumma-mohammad">https://linkedin.com/in/jumma-mohammad</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e07b7adf362" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>