<?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 Simon Müller on Medium]]></title>
        <description><![CDATA[Stories by Simon Müller on Medium]]></description>
        <link>https://medium.com/@simon.peter.mueller?source=rss-3584ae2be8ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cjyY7ilXxuZXb560PwdaMg.jpeg</url>
            <title>Stories by Simon Müller on Medium</title>
            <link>https://medium.com/@simon.peter.mueller?source=rss-3584ae2be8ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:22:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simon.peter.mueller/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[From Raw Ticks to Robust Alpha: A Hands-On Guide to Financial Feature Engineering]]></title>
            <link>https://medium.com/@simon.peter.mueller/from-raw-ticks-to-robust-alpha-a-hands-on-guide-to-financial-feature-engineering-816d7e2af2a1?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/816d7e2af2a1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 13:45:07 GMT</pubDate>
            <atom:updated>2026-02-25T13:45:07.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>A hands-on guide to using Rust-powered tooling to build robust financial machine learning pipelines.</h3><p>Marcos Lopez de Prado opens Advances in Financial Machine Learning (AFML) with a provocative claim: most machine learning models deployed in finance are doomed to fail.</p><p>The reason isn’t that our algorithms are weak. It’s because the data pipelines feeding them are fundamentally flawed. Financial data looks like any other tabular dataset — rows of features and a column of labels — but beneath the surface lurk “silent killers”: serial correlation, non-stationarity, label overlap, and selection bias.</p><p>When you train a model on naively constructed features, it isn’t learning market structure; it’s memorizing noise. The backtest looks like a “holy grail,” but live performance is a disaster.</p><p>In this article, we’ll explore the “antidote” provided by the AFML toolkit, implemented using <a href="http://github.com/sipemu/mlfinance"><strong>pymlfinance</strong></a>. This library utilises a Rust-based engine for high-throughput processing and zero-copy NumPy interoperability, allowing you to run heavy-duty financial math at native speeds while writing idiomatic Python.</p><h4>The Core Primitive: Why Simple Moving Averages Fail</h4><p>Every quantitative pipeline starts with moving averages and volatility. However, standard rolling windows often react too slowly to regime shifts.</p><p>The <strong>Exponentially Weighted Moving Average</strong> (EWMA) is the workhorse of robust finance. It applies decaying weights, ensuring recent observations matter more. This is critical for creating adaptive thresholds. Whether it’s volatility-scaled barriers or CUSUM filters, your model needs to adjust dynamically to whether the market is in a “quiet” period or a “crash” state.</p><pre>import pymplfinance as ml<br><br># Log returns and EWMA Volatility<br>log_rets = ml.core.log_returns(prices)<br>vol = ml.core.ewma_std(log_rets, span=30)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jj9VrWoZ99a-uM7Se9lW9g.png" /></figure><p><strong>Note</strong>: In the distribution plot of your returns, notice the “Fat Tails.” Standard normal distributions assume these outliers don’t happen; AFML assumes they do.</p><h4>Stop Thinking in Time: Information-Driven Bars</h4><p>One of the most transformative ideas in AFML is to <strong>stop sampling the market at fixed time intervals</strong>.</p><p>A “1-hour bar” on a quiet Monday is fundamentally different from a “1-hour bar” during a Fed announcement. Time bars contain unequal amounts of information. Information-driven bars fix this by sampling based on activity:</p><ul><li><strong>Tick Bars</strong>: New bar every N trades.</li><li><strong>Volume Bars:</strong> New bar every V units of volume.</li><li><strong>Dollar Bars:</strong> New bar every $D of value exchanged.</li></ul><p>During high volatility, you get more bars (capturing the action); during quiet periods, you get fewer (ignoring the noise). This produces data that is much closer to IID (independent and identically distributed), which is a core requirement for almost every ML algorithm.</p><pre># Aggregating 12,000 ticks into Dollar Bars<br>dollar_agg = ml.data.DollarBarAggregator(threshold=500000.0)<br>dollar_bars = dollar_agg.process_ticks(ticks)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1tJiYrpTOIpE9S9Y-bJbQ.png" /></figure><h4>The CUSUM Filter: Capturing Structural Breaks</h4><p>Training on every single bar is inefficient and leads to overfitting on noise. Instead, we use the <strong>CUSUM</strong> Filter to detect “interesting” events. This filter identifies shifts in the mean value of a series that exceed a specific threshold.</p><p>By generating a training sample only when a significant structural break occurs, we filter out the “churn” of the market and focus the model on the moments that actually drive price discovery.</p><pre># Detect events where cumulative returns exceed a dynamic volatility threshold<br>events = ml.filters.cusum_filter(prices, threshold=vol * 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Jf6hSFoyNT44cq08tVMUw.png" /></figure><h4>Triple-Barrier Labelling: A Realistic Trade Framework</h4><p>Standard “fixed-horizon” labelling (e.g., where will the price be in 5 days?) is unrealistic. In the real world, you have stop-losses and take-profit limits.</p><p>The <strong>Triple-Barrier Method</strong> sets three boundaries:</p><ul><li><strong>Upper Barrier</strong>: Take-profit.</li><li><strong>Lower Barrier</strong>: Stop-loss.</li><li><strong>Vertical Barrier</strong>: Expiration (time-out).</li></ul><p>This labels the data based on which barrier was hit first. It transforms the problem from a simple regression into a classification task that reflects actual trading constraints.</p><pre># Labeling based on profit taking, stop loss, and time-out<br>labels = ml.labeling.get_bins(prices, events, pt_sl=[1, 1], target=vol)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4uD0yKJZPpv4ppNORSpTw.png" /></figure><h4>Beyond Standard Normalisation: Fractional Differentiation</h4><p>The “Stationarity vs. Memory” dilemma is the classic quant struggle.</p><ul><li><strong>Prices</strong> have memory but are non-stationary (bad for ML).</li><li><strong>Returns</strong> are stationary but lose all memory of price levels (also bad).</li></ul><p><strong>Fractional Differentiation</strong> allows you to stay in a “middle ground.” It removes just enough trend to make the series stationary while preserving as much memory (long-term dependencies) as possible.</p><pre># Frac-diff to achieve stationarity while preserving memory<br>frac_diff_series = ml.features.frac_diff(prices, d=0.4)</pre><h4>Validation: The Purged K-Fold Cross-Validation</h4><p>Standard K-Fold cross-validation fails in finance because labels often overlap in time. If trade A starts at 10:00 and ends at 10:30, and trade B starts at 10:15, they share information. Using trade A in your training set and trade B in your test set is <strong>data leakage</strong>.</p><p><strong>Purged K-Fold</strong> prevents this by:</p><ul><li><strong>Purging</strong>: Removing training samples that overlap with the test set.</li><li><strong>Embargoing</strong>: Removing samples immediately after the test, to account for serial correlation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWS24uDVkYGb5HwhcVhbKQ.png" /></figure><h4>Summary: The Minimum Standard</h4><p>If you’re serious about applying machine learning to finance, these techniques aren’t optional — they are the minimum standard for avoiding self-deception. Using a high-performance implementation like <strong>pymlfinance</strong> ensures that you spend less time waiting for data to process and more time refining your alpha.</p><p><strong>Getting Started:</strong></p><pre>pip install pymlfinance</pre><p>Source: <a href="http://github.com/sipemu/mlfinance">github.com/sipemu/mlfinance</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=816d7e2af2a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Ported R’s Regression Algorithms to WebAssembly]]></title>
            <link>https://medium.com/@simon.peter.mueller/why-i-ported-rs-regression-algorithms-to-webassembly-70cc89052b24?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/70cc89052b24</guid>
            <category><![CDATA[machinelerning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 15:52:58 GMT</pubDate>
            <atom:updated>2026-01-13T15:52:58.042Z</atom:updated>
            <content:encoded><![CDATA[<p>Why I Ported R’s Regression Algorithms to WebAssembly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrTGHPMPnoHotoBY5b8JEw.png" /></figure><p>How WebAssembly allows us to run rigorous statistical inference directly in JavaScript.</p><h3>The Need for Statistical Inference in JavaScript</h3><p>The JavaScript ecosystem has excellent tools for machine learning and simple curve fitting. Libraries like simple-statistics or regression-js They are great for quick predictions or visualising trends.</p><p>However, sometimes “Prediction” isn’t enough. In fields like econometrics, engineering, and scientific research, we often need <strong>Inference</strong>. We don’t just need to know <em>what</em> the future value will be; we need to know <em>how certain</em> we are about that value.</p><ul><li>Is this trend statistically significant?</li><li>What are the confidence intervals?</li><li>Is the relationship real, or just noise?</li></ul><p>Historically, developers had to send data to a Python or R backend to answer these questions. We built <a href="https://www.google.com/search?q=%5Bhttps://www.npmjs.com/package/%40sipemu/anofox-regression%5D(https://www.npmjs.com/package/%40sipemu/anofox-regression)&amp;authuser=1"><strong>@sipemu/anofox-regression</strong></a> to bring these capabilities directly to JavaScript developers.</p><p>Powered by <strong>Rust</strong> and compiled to <strong>WebAssembly (Wasm)</strong>, Anofox provides a suite of regression models that offer the same statistical rigour you expect from R, running purely in your Node.js app or browser.</p><p>Here is how you can use it to gain deeper insights from your data.</p><h3>1. Deep Statistical Insight: OLS with Inference</h3><p>Standard linear regression gives you a slope and an intercept. Anofox goes further by offering an option to compute full statistical inference. By enabling .setComputeInference(true). You gain access to standard errors, t-statistics, and p-values.</p><pre>import init, { OlsRegressor } from &#39;@sipemu/anofox-regression&#39;;<br><br>async function runAnalysis() {<br>  // 1. Initialize the Wasm module (only needed once)<br>  await init();<br><br>  // 2. Prepare data (e.g. Marketing spend vs. Sales)<br>  // Format: [TV Spend, Social Media Spend]<br>  const x = new Float64Array([<br>     230.1, 37.8,  // Row 1<br>     44.5,  39.3,  // Row 2<br>     17.2,  45.9,  // Row 3<br>     151.5, 41.3   // Row 4<br>     // ... more data ...<br>  ]);<br>  const y = new Float64Array([22.1, 10.4, 9.3, 18.5]); <br>  <br>  // 3. Configure the model<br>  const model = new OlsRegressor();<br>  model.setWithIntercept(true);<br>  model.setComputeInference(true); // &lt;--- Enables p-values and confidence intervals<br><br>  // 4. Fit (x, rows, cols, y)<br>  const fitted = model.fit(x, 4, 2, y);<br>  const results = fitted.getResult();<br><br>  // 5. accurate statistics<br>  console.log(&quot;R²:&quot;, results.rSquared.toFixed(4)); <br>  // Output: 0.8972<br>  <br>  console.log(&quot;P-Values:&quot;, results.pValues); <br>  // Output: [0.0001, 0.034] -&gt; Indicates statistical significance<br>}<br><br>runAnalysis();</pre><h3>2. Handling Complex Data: Ridge &amp; Elastic Net</h3><p>Real-world datasets often contain correlated variables (multicollinearity), which can make standard linear models unstable. To handle this, Data Scientists often turn to regularisation techniques like <strong>Ridge</strong> or <strong>Elastic Net</strong>.</p><p>Anofox brings these advanced solvers to TypeScript, giving you fine-grained control over regularisation parameters.</p><pre>import { RidgeRegressor, ElasticNetRegressor } from &#39;@sipemu/anofox-regression&#39;;<br><br>// Option A: Ridge Regression (L2 Regularization)<br>// Useful when variables are highly correlated<br>const ridge = new RidgeRegressor();<br>ridge.setLambda(1.5); // Regularization strength<br>ridge.setWithIntercept(true);<br><br>const fittedRidge = ridge.fit(xTrain, nRows, nCols, yTrain);<br>console.log(&quot;Ridge Coeffs:&quot;, fittedRidge.getResult().coefficients);<br><br><br>// Option B: Elastic Net (L1 + L2)<br>// Combines feature selection (Lasso) with stability (Ridge)<br>const elNet = new ElasticNetRegressor();<br>elNet.setLambda(0.5);<br>elNet.setAlpha(0.5); // 0.5 = 50% Lasso, 50% Ridge<br><br>const fittedNet = elNet.fit(xTrain, nRows, nCols, yTrain);</pre><h3>3. Generalised Linear Models (GLMs)</h3><p>Linear regression assumes data follow a normal distribution, but many real-world metrics do not.</p><ul><li><strong>Count Data:</strong> Website hits or support tickets (often follow a Poisson distribution).</li><li><strong>Binary Data:</strong> Churn vs. Retention (follows a Binomial distribution).</li></ul><p>Anofox includes a suite of GLMs to accurately model these specific data types.</p><pre>import { PoissonRegressor, BinomialRegressor } from &#39;@sipemu/anofox-regression&#39;;<br><br>// Example: Predicting Website Hits (Count Data)<br>// We use Poisson regression because counts are non-negative integers.<br>const poisson = new PoissonRegressor();<br>poisson.setLink(&#39;log&#39;); <br><br>const trafficModel = poisson.fit(features, nRows, nCols, dailyHits);<br>console.log(trafficModel.getResult().coefficients);<br><br>// Example: Predicting Churn (Binary Data: Yes/No)<br>// We use Binomial (Logistic) regression.<br>const logistic = new BinomialRegressor();<br>logistic.setLink(&#39;logit&#39;);<br><br>const churnModel = logistic.fit(userStats, nRows, nCols, churnFlags);</pre><h3>4. Performance with Float64Array</h3><p>One of the benefits of using WebAssembly is the ability to handle data efficiently. Anofox utilises JavaScript’s typed Float64Array. This enables &quot;Zero-Copy&quot; memory transfers between JavaScript and the Rust backend, ensuring high performance even when processing large datasets.</p><pre>// Using Float64Array allows efficient memory usage<br>const nRows = 100_000;<br>const nCols = 50;<br><br>// Allocate memory once<br>const largeData = new Float64Array(nRows * nCols); <br><br>// Fill with data...<br>for(let i=0; i &lt; largeData.length; i++) {<br>   largeData[i] = Math.random();<br>}<br><br>const model = new OlsRegressor();<br>console.time(&quot;Training Time&quot;);<br>model.fit(largeData, nRows, nCols, yData);<br>console.timeEnd(&quot;Training Time&quot;); <br>// Result: High-performance calculation suited for production workloads</pre><h3>5. Seamless Server-Side Support (Node.js)</h3><p>While WebAssembly is often associated with the browser, it is equally powerful on the server. anofox is designed to work seamlessly in Node.js environments (like AWS Lambda or local scripts) by loading the compiled binary synchronously.</p><pre>import { readFile } from &#39;fs/promises&#39;;<br>import { initSync, OlsRegressor } from &#39;@sipemu/anofox-regression&#39;;<br><br>// 1. Load Wasm from disk (Server-side)<br>const wasmBuffer = await readFile(<br>  &#39;./node_modules/@sipemu/anofox-regression/anofox_regression_js_bg.wasm&#39;<br>);<br><br>// 2. Synchronous initialization<br>initSync(wasmBuffer);<br><br>// 3. Ready to use<br>const ols = new OlsRegressor();</pre><h3>Summary</h3><p>We believe that accurate statistics should be an accessible utility in the web ecosystem. By leveraging Rust and WebAssembly, we can bring the rigorous algorithms typically used in R and Python into our JavaScript and TypeScript applications.</p><p>We invite you to try it out and contribute.</p><ul><li>📦 <strong>NPM:</strong> npm install @sipemu/anofox-regression</li><li>🐙 <strong>GitHub:</strong> <a href="https://github.com/sipemu/anofox-regression">github.com/sipemu/anofox-regression</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70cc89052b24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop the Inventory Death Spiral: Replacing “Syntactic” Rules with Profit-Driven Modelling]]></title>
            <link>https://medium.com/@simon.peter.mueller/stop-the-inventory-death-spiral-replacing-syntactic-rules-with-profit-driven-modelling-0a2b4fa1531d?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a2b4fa1531d</guid>
            <category><![CDATA[supply-chain]]></category>
            <category><![CDATA[logistics]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 13:42:44 GMT</pubDate>
            <atom:updated>2025-12-28T13:42:44.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlM-gz0LbZlEq-w2H2jhkw.png" /></figure><p>Traditional demand classification (Syntactic) is a silent killer of working capital. By forcing dynamic, real-world data into rigid, 40-year-old buckets (ADI/CV²), companies inadvertently trigger two costly failure modes:</p><ol><li><strong>Bloated Inventory:</strong> “Flip-flopping” classification — where a product jumps between “Smooth” and “Lumpy” due to minor noise — forces planners to hold defensive safety stock for volatility that doesn’t exist.</li><li><strong>Lost Revenue:</strong> By failing to distinguish between <em>low demand</em> and <em>stockouts</em> (censored demand), legacy systems bias forecasts downward. You stop buying inventory because the data says “nobody wants it,” when in reality, nobody could buy it.</li></ol><p><strong>The Solution:</strong> AID replaces arbitrary rules with probabilistic rigour. It automatically detects the true nature of demand — handling stockouts, lifecycles, and distributions dynamically. The result is a <strong>stabilised forecast</strong> that reduces manual intervention, rightsizes safety stock, and protects revenue streams from the “death spiral” of censored data.</p><p>This can be done with our DuckDB extension, <a href="https://github.com/DataZooDE/anofox-statistics/tree/main">anofox-statistics</a>, or the Polars extension <a href="https://github.com/DataZooDE/polars-statistics">polars.statistics</a> (PyPi). Try it and have a look at our other <a href="https://anofox.com/">Anofox</a> extensions (forecast and tabular).</p><p><strong>Let us go more technical.<br></strong>The Failure of “Syntactic” Classification. The traditional approach to supply chain analysis, known as Syntactic Classification (SBC), relies on calculating summary statistics — specifically the Average Demand Interval (ADI) and the Coefficient of Variation squared — and mapping them to a matrix with fixed thresholds (classically and ). The paper <a href="https://arxiv.org/html/2504.05894v1">Why do zeroes happen? A model-based approach for demand classification</a> (Svetunkov &amp; Sroginis, 2025) identifies critical failures in this industry-standard approach:</p><ul><li><strong>Arbitrary Boundaries:</strong> The cutoffs (like 1.32) are mathematically derived from specific theoretical assumptions that rarely hold in real-world data. A product with an ADI of 1.31 is treated fundamentally differently from one with 1.33, causing “classification flip-flopping” where stable products jump between categories (e.g., from “Smooth” to “Lumpy”) due to minor noise.</li><li><strong>Ambiguity of Zeros</strong>: SBC counts zeros but ignores their context. It cannot distinguish between Structural Zeros (product not yet launched), Censored Zeros (stockouts), and Stochastic Zeros (pure random intermittency).</li><li><strong>Loss of Distributional Information:</strong> Knowing a product is “Erratic” is not enough to optimise inventory. You need to know if the demand follows a Gamma, Log-Normal, or Negative Binomial distribution to calculate safety stock accurately.</li></ul><p>This DuckDB extension implements the Model-Based Classification (MBC) approach proposed in the paper, which is also available in the R package <a href="https://cran.r-project.org/web/packages/greybox/index.html">greybox</a>. Instead of relying on brittle ADI/CV thresholds, multiple probabilistic models (Poisson, Negative Binomial, Normal, etc.) are fitted to the data. It selects the classification based on Information Criteria (AIC), identifying the model that minimises information loss. This provides a rigorous, statistically stable foundation for all subsequent supply chain decisions.</p><pre>    INSTALL anofox_statistics FROM community;<br>    LOAD anofox_statistics;</pre><h3>Example 1: Basic Demand Classification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QReTy1i0cQJlsZqgS8TTw.jpeg" /></figure><p><strong>Motivation<br></strong>Standard classification rules are susceptible to outliers. A single extreme sales spike can inflate the standard deviation, pushing the above 0.49 and reclassifying a stable product as “Erratic.” This forces the use of complex forecasting models when a simple average would have sufficed.</p><p><strong>Description<br></strong>This query runs aid_agg(demand) to classify a series. Unlike standard SQL math, which blindly checks variance thresholds, this function tests whether the data is better explained by a stable or a variable process, preventing &quot;false erratic&quot; classifications caused by single outliers.</p><pre>    SELECT UNNEST(aid_agg(demand)) as classification<br>    FROM (VALUES (10), (12), (8), (15), (11), (9), (14), (10), (13), (11)) AS t(demand);</pre><h3>Example 2: Intermittent Demand Detection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0_PC6nWFWMkDiZSvPDy-Q.jpeg" /></figure><p><strong>Motivation<br></strong>In the Syntactic approach, intermittency is defined strictly by the average time between sales (ADI). However, on short time series, the ADI is <strong>unreliable</strong>. A slow-moving product might accidentally have two sales in consecutive weeks, lowering its ADI and tricking the system into treating it as a fast mover (“False Smooth”), leading to dangerous stockouts later.</p><p><strong>Description<br></strong>This example extracts is_intermittent by validating the process rather than just the interval. It checks if the sequence of zeros and non-zeros fits a Poisson-like arrival process, correctly identifying intermittency even when random clustering makes the demand look temporarily smooth.</p><pre>    SELECT<br>        result.demand_type,<br>        result.is_intermittent,<br>        result.distribution,<br>        ROUND(result.zero_proportion, 2) AS zero_proportion,<br>        result.n_observations<br>    FROM (<br>        SELECT aid_agg(demand) AS result<br>        FROM (VALUES (0), (0), (5), (0), (8), (0), (3), (0), (0), (6)) AS t(demand)<br>    );sql</pre><h3>Example 3: Multi-SKU Classification with GROUP BY</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uenfwcLXJnqxRN7rrSkCtg.jpeg" /></figure><p><strong>Motivation<br></strong>Applying a “one-size-fits-all” threshold (e.g., “Intermittent if ADI &gt; 1.32”) across a diverse catalogue fails because different categories (e.g., Screws vs. Engines) have different natural variances. Syntactic rules force analysts to manually maintain complex lookup tables of “exception rules” for other item types.</p><p><strong>Description<br></strong>This query demonstrates how to scale the Model-Based approach. Because it uses Information Criteria (relative fit) rather than absolute thresholds, the engine automatically adapts to the scale and behaviour of every individual SKU, eliminating the need for manual category-specific tuning.</p><pre>    WITH sales AS (<br>        -- SKU001: Intermittent (many zeros)<br>        SELECT &#39;SKU001&#39; as sku, val as demand, row_number() OVER () as period<br>        FROM (VALUES (0), (0), (5), (0), (8), (0), (3), (0), (0), (6)) AS t(val)<br>        UNION ALL<br>        -- SKU002: Regular (no zeros, consistent)<br>        SELECT &#39;SKU002&#39; as sku, val as demand, row_number() OVER () as period<br>        FROM (VALUES (45), (48), (42), (50), (47), (44), (49), (46), (51), (43)) AS t(val)<br>        UNION ALL<br>        -- SKU003: New product (leading zeros)<br>        SELECT &#39;SKU003&#39; as sku, val as demand, row_number() OVER () as period<br>        FROM (VALUES (0), (0), (0), (0), (5), (8), (12), (15), (18), (20)) AS t(val)<br>        UNION ALL<br>        -- SKU004: Obsolete product (trailing zeros)<br>        SELECT &#39;SKU004&#39; as sku, val as demand, row_number() OVER () as period<br>        FROM (VALUES (25), (22), (18), (15), (10), (5), (0), (0), (0), (0)) AS t(val)<br>    )<br>    SELECT<br>        sku,<br>        result.demand_type,<br>        result.distribution,<br>        ROUND(result.mean, 1) AS mean,<br>        ROUND(result.zero_proportion, 2) AS zero_pct,<br>        result.is_new_product,<br>        result.is_obsolete_product,<br>        result.has_stockouts<br>    FROM (<br>        SELECT sku, aid_agg(demand ORDER BY period) AS result<br>        FROM sales<br>        GROUP BY sku<br>    ) sub<br>    ORDER BY sku;</pre><h3>Example 4: Simple Anomaly Detection Per Observation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70aMhEc6hwlt0BPsxR_w1A.jpeg" /></figure><p><strong>Motivation<br></strong>Most ERP systems use “3-Sigma” (Standard Deviation) to detect outliers. This assumes a Normal (Bell Curve) distribution. The paper argues this is disastrous for supply chains because demand is often skewed (right-tailed). A 3-Sigma rule will flag valid high demand as an “anomaly,” causing planners to ignore real growth signals. Outlier detection is use case specific. This may be just a rough estimate and may need additional adjustment and/or more sophisticated methods.</p><p><strong>Description<br></strong>This example uses aid_anomaly_agg to detect outliers based on the fitted distribution. If the data follow a Poisson distribution, the engine asks, “Is this value unlikely for a Poisson process?” rather than “Is it 3 deviations from the mean?”, significantly reducing false-positive anomaly flags.</p><pre>    WITH demand_series AS (<br>        SELECT row_number() OVER () as period, demand<br>        FROM (VALUES (0), (0), (5), (0), (8), (0), (0)) AS t(demand)<br>    ),<br>    anomalies AS (<br>        SELECT aid_anomaly_agg(demand ORDER BY period) AS anomaly_flags<br>        FROM demand_series<br>    )<br>    SELECT<br>        ds.period,<br>        ds.demand,<br>        f.stockout,<br>        f.new_product,<br>        f.obsolete_product,<br>        f.high_outlier,<br>        f.low_outlier<br>    FROM demand_series ds, anomalies a, LATERAL UNNEST(a.anomaly_flags) WITH ORDINALITY AS t(f, ord)<br>    WHERE ds.period = t.ord<br>    ORDER BY ds.period;</pre><h3>Example 5: Custom Threshold for Intermittent Classification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNdSdPm8rcv5hFF7VB5PwA.jpeg" /></figure><p><strong>Motivation<br></strong>While Model-Based Classification is statistically superior, organisational inertia often mandates adherence to legacy business rules (e.g., “Marketing defines ‘Slow’ as selling less than 50% of the time”). Pure statistical engines often fail to adopt because they cannot accommodate these operational constraints.</p><p><strong>Description<br></strong>This query demonstrates the flexibility to override the statistical engine. By passing {&#39;intermittent_threshold&#39;: 0.5} . It forces the system to respect a domain-specific constraint, allowing the user to blend the robustness of the AID engine with fixed business logic where necessary.</p><pre>    WITH demand AS (<br>        SELECT val as demand FROM (VALUES (0), (5), (0), (8), (10), (0), (12), (7), (0), (9)) AS t(val)<br>    )<br>    SELECT<br>        &#39;Default (30%)&#39; AS threshold_setting,<br>        result.demand_type,<br>        ROUND(result.zero_proportion, 2) AS zero_proportion<br>    FROM (SELECT aid_agg(demand) AS result FROM demand)<br>    UNION ALL<br>    SELECT<br>        &#39;Custom (50%)&#39; AS threshold_setting,<br>        result.demand_type,<br>        ROUND(result.zero_proportion, 2) AS zero_proportion<br>    FROM (SELECT aid_agg(demand, {{&#39;intermittent_threshold&#39;: 0.5}}) AS result FROM demand);</pre><h3>Example 6: Stockout Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkSRPIak7qiTp7msF1pkdg.jpeg" /></figure><p><strong>Motivation<br></strong>A central blind spot in Syntactic Classification is Censoring. A zero record in the database is ambiguous: it could mean “no customer arrived” or “customer arrived but no stock was available.” Treating stockout zeros as demand zeros distorts the demand probability, leading to a downward-biased forecast that perpetuates the shortage.</p><p><strong>Description<br></strong>This query distinguishes “natural zeros” from “censored zeros” (stockouts). It implements the paper’s requirement to account for inventory availability, ensuring that the demand profile reflects potential sales rather than just recorded sales.</p><pre>    WITH inventory AS (<br>        -- Product A: Has stockouts (zeros in middle of positive demand)<br>        SELECT &#39;Product_A&#39; as product, val as demand, row_number() OVER () as week<br>        FROM (VALUES (50), (45), (0), (0), (52), (48), (0), (55), (47), (51)) AS t(val)<br>        UNION ALL<br>        -- Product B: No stockouts (continuous positive demand)<br>        SELECT &#39;Product_B&#39; as product, val as demand, row_number() OVER () as week<br>        FROM (VALUES (30), (32), (28), (35), (31), (29), (33), (30), (34), (32)) AS t(val)<br>        UNION ALL<br>        -- Product C: Many stockouts<br>        SELECT &#39;Product_C&#39; as product, val as demand, row_number() OVER () as week<br>        FROM (VALUES (20), (0), (18), (0), (0), (22), (0), (19), (0), (21)) AS t(val)<br>    )<br>    SELECT<br>        product,<br>        result.has_stockouts,<br>        result.stockout_count,<br>        ROUND(result.stockout_count::DOUBLE / result.n_observations * 100, 1) AS stockout_pct,<br>        result.demand_type<br>    FROM (<br>        SELECT product, aid_agg(demand ORDER BY week) AS result<br>        FROM inventory<br>        GROUP BY product<br>    ) sub<br>    ORDER BY result.stockout_count DESC;</pre><h3>Example 7: Distribution Recommendation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZEIJnaqBePy-oiIT3oGsg.jpeg" /></figure><p><strong>Motivation<br></strong>Knowing a product is “Lumpy” (Quadrant 4 in SBC) is descriptive but not actionable. To set a safety stock level that achieves a 95% service level, you need the specific Probability Mass Function (PMF). Syntactic rules do not provide this; they only categorise.</p><p><strong>Description<br></strong>This example outputs the recommended_distribution. It bridges the gap between classification and calculation, automating the selection of the mathematical model (e.g., Negative Binomial for overdispersed data) required for precise inventory optimisation.</p><pre>    WITH products AS (<br>        -- Count data (integers, low values) -&gt; Poisson family<br>        SELECT &#39;Low_Count_Data&#39; as category, val as demand<br>        FROM (VALUES (2), (3), (1), (4), (2), (3), (2), (5), (3), (2)) AS t(val)<br>        UNION ALL<br>        -- Overdispersed count data -&gt; Negative Binomial<br>        SELECT &#39;Overdispersed_Counts&#39; as category, val as demand<br>        FROM (VALUES (0), (0), (5), (0), (12), (0), (0), (8), (0), (15)) AS t(val)<br>        UNION ALL<br>        -- Continuous positive data -&gt; Gamma/Lognormal<br>        SELECT &#39;Continuous_Positive&#39; as category, val as demand<br>        FROM (VALUES (10.5), (12.3), (8.7), (15.2), (11.8), (9.4), (14.1), (10.9), (13.5), (11.2)) AS t(val)<br>        UNION ALL<br>        -- Normal-like data -&gt; Normal<br>        SELECT &#39;Normal_Like&#39; as category, val as demand<br>        FROM (VALUES (100), (102), (98), (101), (99), (103), (97), (100), (101), (99)) AS t(val)<br>    )<br>    SELECT<br>        category,<br>        result.distribution AS recommended_distribution,<br>        result.demand_type,<br>        ROUND(result.mean, 2) AS mean,<br>        ROUND(result.variance, 2) AS variance<br>    FROM (<br>        SELECT category, aid_agg(demand) AS result<br>        FROM products<br>        GROUP BY category<br>    ) sub<br>    ORDER BY category;</pre><h3>Example 8: Product Lifecycle Detection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ti13CKN9mIarU0nGLq_VnQ.jpeg" /></figure><p><strong>Motivation<br></strong>Syntactic metrics (ADI/CV) are static averages calculated over a fixed window (e.g., last 12 months). They fail to detect <strong>Structural Breaks</strong> — such as a product dying (End of Life) or being born (NPI). Including “dead” periods in the average creates a “Zombie” forecast that suggests buying stock for a product that will never sell again.</p><p><strong>Description<br></strong>This query identifies “Leading Zeros” and “Trailing Zeros.” It filters out these non-demand periods to prevent them from contaminating the statistical properties of the active lifecycle, ensuring the classification reflects the product’s current reality rather than its history.</p><pre>    WITH lifecycle AS (<br>        SELECT &#39;NewProduct_2024&#39; as product, val as demand, row_number() OVER () as month<br>        FROM (VALUES (0), (0), (0), (5), (12), (25), (40), (55), (70), (85), (95), (100)) AS t(val)<br>        UNION ALL<br>        SELECT &#39;MatureProduct&#39; as product, val as demand, row_number() OVER () as month<br>        FROM (VALUES (80), (82), (78), (85), (81), (79), (83), (80), (84), (82), (81), (80)) AS t(val)<br>        UNION ALL<br>        SELECT &#39;EndOfLife_Legacy&#39; as product, val as demand, row_number() OVER () as month<br>        FROM (VALUES (50), (42), (35), (28), (20), (12), (5), (0), (0), (0), (0), (0)) AS t(val)<br>    )<br>    SELECT<br>        product,<br>        CASE<br>            WHEN result.is_new_product AND NOT result.is_obsolete_product THEN &#39;Introduction Phase&#39;<br>            WHEN result.is_obsolete_product AND NOT result.is_new_product THEN &#39;Decline Phase&#39;<br>            WHEN result.is_new_product AND result.is_obsolete_product THEN &#39;Short Lifecycle&#39;<br>            ELSE &#39;Mature/Stable&#39;<br>        END AS lifecycle_stage,<br>        result.new_product_count AS intro_periods,<br>        result.obsolete_product_count AS decline_periods,<br>        result.n_observations AS total_periods<br>    FROM (<br>        SELECT product, aid_agg(demand ORDER BY month) AS result<br>        FROM lifecycle<br>        GROUP BY product<br>    ) sub<br>    ORDER BY product;</pre><h3>Example 9: Demand Analysis Report</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiYx5z9DX1LfOvGkbNpngg.jpeg" /></figure><p><strong>Motivation<br></strong>In reality, demand data suffers from all these issues simultaneously: non-normality, stockouts, lifecycle changes, and outliers. Disjointed tools that fix only one problem (e.g., just outlier detection) often make the others worse. The paper concludes that a robust system must model the joint probability of these events.</p><p><strong>Description<br></strong>This final example aggregates all AID features into a “Control Tower” view. It represents the Model-Based ideal: a holistic assessment that simultaneously cleans anomalies, accounts for stockouts, fits the distribution, and determines lifecycle status, delivering a single, scientifically valid truth for every SKU.</p><pre>    CREATE OR REPLACE TABLE demand_data AS<br>    SELECT<br>        &#39;SKU&#39; || LPAD(CAST(sku_id AS VARCHAR), 3, &#39;0&#39;) AS sku,<br>        CASE<br>            WHEN sku_id &lt;= 3 THEN &#39;Electronics&#39;<br>            WHEN sku_id &lt;= 6 THEN &#39;Apparel&#39;<br>            ELSE &#39;Food&#39;<br>        END AS category,<br>        week,<br>        -- Generate different demand patterns<br>        CASE<br>            WHEN sku_id = 1 THEN GREATEST(0, 50 + CAST(FLOOR(RANDOM() * 20 - 10) AS INTEGER))<br>            WHEN sku_id = 2 THEN CASE WHEN RANDOM() &lt; 0.4 THEN 0 ELSE CAST(FLOOR(RANDOM() * 30 + 10) AS INTEGER) END<br>            WHEN sku_id = 3 THEN CASE WHEN week &lt;= 4 THEN 0 ELSE CAST(FLOOR(week * 5 + RANDOM() * 10) AS INTEGER) END<br>            WHEN sku_id = 4 THEN GREATEST(0, 100 + CAST(FLOOR(RANDOM() * 30 - 15) AS INTEGER))<br>            WHEN sku_id = 5 THEN CASE WHEN RANDOM() &lt; 0.6 THEN 0 ELSE CAST(FLOOR(RANDOM() * 20 + 5) AS INTEGER) END<br>            WHEN sku_id = 6 THEN CASE WHEN week &gt;= 9 THEN 0 ELSE GREATEST(0, 80 - week * 8 + CAST(FLOOR(RANDOM() * 10) AS INTEGER)) END<br>            WHEN sku_id = 7 THEN GREATEST(0, 200 + CAST(FLOOR(RANDOM() * 40 - 20) AS INTEGER))<br>            WHEN sku_id = 8 THEN CASE WHEN RANDOM() &lt; 0.3 THEN 0 ELSE CAST(FLOOR(RANDOM() * 50 + 20) AS INTEGER) END<br>            ELSE GREATEST(0, 150 + CAST(FLOOR(RANDOM() * 50 - 25) AS INTEGER))<br>        END AS demand<br>    FROM (SELECT * FROM range(1, 10) t1(sku_id), range(1, 13) t2(week));<br><br>    SELECT<br>        sub.category,<br>        sub.sku,<br>        result.demand_type,<br>        result.distribution,<br>        ROUND(result.mean, 1) AS avg_demand,<br>        ROUND(result.zero_proportion * 100, 0) AS zero_pct,<br>        result.has_stockouts,<br>        result.stockout_count,<br>        CASE<br>            WHEN result.is_new_product THEN &#39;New&#39;<br>            WHEN result.is_obsolete_product THEN &#39;EOL&#39;<br>            ELSE &#39;Active&#39;<br>        END AS status,<br>        result.high_outlier_count + result.low_outlier_count AS anomalies<br>    FROM (<br>        SELECT sku, category, aid_agg(demand ORDER BY week) AS result<br>        FROM demand_data<br>        GROUP BY sku, category<br>    ) sub<br>    ORDER BY sub.category, sub.sku;<br><br>    -- Summary by category<br>    SELECT<br>        category,<br>        COUNT(*) AS sku_count,<br>        SUM(CASE WHEN result.is_intermittent THEN 1 ELSE 0 END) AS intermittent_skus,<br>        SUM(CASE WHEN result.has_stockouts THEN 1 ELSE 0 END) AS skus_with_stockouts,<br>        SUM(CASE WHEN result.is_new_product THEN 1 ELSE 0 END) AS new_products,<br>        SUM(CASE WHEN result.is_obsolete_product THEN 1 ELSE 0 END) AS eol_products<br>    FROM (<br>        SELECT category, aid_agg(demand ORDER BY week) AS result<br>        FROM demand_data<br>        GROUP BY sku, category<br>    ) sub<br>    GROUP BY category<br>    ORDER BY category;</pre><h3>Summary: The Ultimate Feature Engine for Forecasting</h3><p>The shift from “Syntactic” rules (fixed thresholds) to <strong>Automatic Identification of Demand (AID)</strong> isn’t just about better reporting — it is about building a rigorous foundation for your entire forecasting pipeline.</p><p>While traditional methods blindly bucket products based on variance, AID uses probabilistic models to validate the <em>nature</em> of demand for each SKU mathematically. It correctly distinguishes between structural zeros (no market), censored zeros (stockouts), and stochastic zeros (randomness), while identifying the specific probability distribution (e.g., Negative Binomial vs. Poisson) that best fits the data.</p><p><strong>The Multiplier Effect for Machine Learning.</strong> Crucially, these insights are not the end of the process — they are the inputs. The rich metadata extracted by AID — <strong>distribution types, lifecycle stages, anomaly flags, and intermittency probabilities</strong> — serve as high-signal features for any downstream Machine Learning model.</p><p>Whether you are running simple regressions or complex Gradient Boosting (XGBoost/LightGBM) models, feeding them these statistically validated features enables the algorithm to understand the <em>structure</em> of demand immediately. Instead of forcing an ML model to “guess” that a product is intermittent based on noisy raw history, AID explicitly tells the model how the data behaves, drastically reducing training time and improving forecast accuracy.</p><h3>Ready to Modernise Your Stack?</h3><p>You don’t need to build these complex statistical engines from scratch. We have packaged this entire Model-Based approach into high-performance extensions for the modern data stack:</p><ul><li><strong>For DuckDB:</strong> simply INSTALL anofox_statistics FROM community;</li><li><strong>For Polars:</strong> pip install polars-statistics</li></ul><p>Once you have mastered your data classification, explore our whole ecosystem to complete your pipeline. Check out <strong>Anofox Forecast</strong> for generating predictions and <strong>Anofox Tabular</strong> for advanced data processing.</p><p><strong>Stop guessing at demand — start modelling it.</strong></p><h3>Let’s Connect</h3><p>Need guidance on implementing this strategy or optimising your supply chain architecture? I offer consulting services to help organisations navigate the shift to model-based forecasting and high-performance data engineering.</p><p><a href="https://www.linkedin.com/in/simon-m%C3%BCller/"><strong>Connect with me on LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a2b4fa1531d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Luck or Skill? A Statistical Guide to Find the Best Forecast Model]]></title>
            <link>https://medium.com/@simon.peter.mueller/luck-or-skill-a-statistical-guide-to-find-the-best-forecast-model-cc66f4ed7e28?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc66f4ed7e28</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[timeseries-forecasting]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 10:44:16 GMT</pubDate>
            <atom:updated>2025-12-09T10:44:16.286Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A lower RMSE isn’t enough. Here is how to statistically prove that your forecast is superior, even when testing many models.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6SP_uy3PjOxg39GY5KumQ.jpeg" /></figure><p>Producing a forecast is relatively easy. The hard part is proving that your forecast isn&#39;t just luck.</p><p>A common mistake in data science is to look at a leaderboard of Mean Squared Errors (MSE) or other error metrics, pick the lowest value, and declare it the winner. This ignores a fundamental truth of statistics: <strong>Data is noisy.</strong> In a volatile time series, a model that is technically “worse” in population can easily beat a “better” model in a specific sample purely by chance.</p><p>To separate signal from noise, we need some help from the statistics of forecast evaluation.</p><p>This guide covers the evolution of predictive testing (maybe not comprehensive):</p><ol><li><strong>Diebold-Mariano:</strong> The standard duel (1 vs 1).</li><li><strong>Clark-West:</strong> The correction for nested models (Small vs Large).</li><li><strong>SPA Test:</strong> The tournament director (1 vs Many).</li><li><strong>The Hybrid:</strong> How to handle multiple nested models without p-hacking.</li></ol><p><strong>DIY (Do It Yourself)</strong><br><a href="https://github.com/DataZooDE/polars-statistics">polars-statistics</a> is a Rust-backed extension that integrates the statistical methods discussed in this article directly into the high-performance Polars API. It allows you to move beyond simple error metrics and perform statistically sound forecast evaluation at scale.</p><h3>The Head-to-Head Duel: Diebold-Mariano (DM)</h3><p><em>When to use it: Comparing two distinct, non-nested models (e.g., Baseline vs. ARIMA).</em></p><p>Introduced in 1995, the <a href="https://ideas.repec.org/a/bes/jnlbes/v13y1995i3p253-63.html"><strong>Diebold-Mariano test</strong></a> is the bedrock of forecast evaluation. It does not care about the model architecture; it only cares about the <strong>loss differential</strong>.</p><h4>The Mechanism</h4><p>Let e1(t) and e2(t) be the forecast errors of two models. We define a loss differential d(t) as:</p><p>d(t) = (e1(t))² - (e2(t))²</p><p>Note: You can use absolute error or any other loss function.</p><p>The null hypothesis H0 is E[d(t)] = 0. The test statistic is a t-test on the mean of d(t), but with one critical feature: <strong>robustness to autocorrelation.</strong></p><p>Forecast errors are rarely independent (if you overpredicted inflation today, you are likely to overpredict it tomorrow). DM uses a <strong>HAC (Heteroskedasticity and Autocorrelation Consistent)</strong> variance estimator to ensure the p-value is accurate even when errors are sticky.</p><p><strong>The Limitations<br></strong>The DM test assumes that under the Null Hypothesis, the parameters of both models are distinct. This assumption breaks down if the models are <strong>nested</strong>.</p><h3>The Nested Trap: Clark-West (CW) Test</h3><p><em>When to use it: Comparing a benchmark against a larger version of itself (e.g., AR(1) vs. AR(2)).</em></p><p>As a forecaster/statistician, we often ask:</p><blockquote><em>“Does adding Feature X improve my model?”</em></blockquote><ul><li><strong>Model A (Restricted):</strong> y = b0 + error</li><li><strong>Model B (Unrestricted):</strong> y =b0 + b1 X + error</li></ul><p>Model A is “nested” inside Model B.</p><h4>The Problem: Estimation Noise</h4><p>If feature X is useless (b1 = 0), Model B should perform the same as Model A. However, in a finite sample, Model B will still try to estimate b1. It will fit the noise, leading to <strong>higher</strong> out-of-sample variance.</p><p>A standard DM test will see this higher variance and conclude that Model B is worse. The Truth: Model B is essentially the same, but it is being penalised for its complexity.</p><h4>One Solution: The “Handicap”</h4><p>The <a href="https://ideas.repec.org/a/eee/econom/v138y2007i1p291-311.html"><strong>Clark-West</strong></a><strong> </strong>test introduces an adjustment term that “refunds” the larger model for the noise it was forced to estimate.</p><p>Instead of testing the raw difference ((e1(t))² - (e2(t))²), we test the <strong>Adjusted Differential f(t)</strong>:</p><p>f(t) = (e1(t))² — (e2(t))² + (e1(t) — e2(t))²</p><p>The term e1(t) — e2(t) )² is the proxy for estimation noise. By adding this positive value, we make it “easier” for the larger model to reject the null, correcting the bias.</p><h3>The Tournament: Superior Predictive Ability (SPA)</h3><p><em>When to use it: Benchmarking against many alternatives.</em></p><blockquote>What if you aren’t testing one model, but 1,000?</blockquote><p>If you run 1,000 Clark-West tests at a 5% significance level, you will find 50 “significant” models <strong>purely by chance</strong>, even if all your data is random noise. This is the <strong>Data Snooping Bias</strong> (or Multiple Testing Problem).</p><p>The <a href="https://ideas.repec.org/a/bes/jnlbes/v23y2005p365-380.html">SPA Test</a> — an improvement on White’s Reality Check — tests a joint null hypothesis:</p><blockquote>H0: The benchmark is superior to ALL alternatives.</blockquote><h4>The Mechanism: Bootstrapping</h4><p>The SPA test doesn’t look up a value in a standard z-table. Instead, it <strong>bootstraps</strong> (resamples) the data thousands of times to simulate the distribution of the “best performing model.”</p><p>It asks: <em>In a world where no model works, how often would the ‘luckiest’ model perform this well?</em> If your best model beats even that ‘lucky’ simulation, then you have actual predictive ability.</p><h3>The Advanced Problem: Multiple Nested Models</h3><p><em>When to use it: Determining which of 50 new features adds value to a base model.</em></p><p>This is the more complex and common scenario in forecasting, combining the problems of the previous two Sections.</p><ul><li>You have a Base Model.</li><li>You have 50 “Unrestricted” models (each adding a different feature to the Base).</li><li><strong>Problem 1:</strong> They are nested (Need Clark-West).</li><li><strong>Problem 2:</strong> There are many of them (Need SPA).</li></ul><p><strong>You cannot simply run SPA on the raw errors (violates Nesting).</strong> <strong>You cannot merely run 50 Clark-West tests (violates the Multiple Testing principle).</strong></p><h4>A Solution: MSPE-Adjusted SPA</h4><p>The standard approach in modern econometrics (see <em>Clark &amp; McCracken, 2012</em>) is to feed the <a href="https://ideas.repec.org/a/eee/econom/v170y2012i1p1-14.html"><strong>Clark-West Adjusted Differentials</strong></a> into the SPA or Bootstrap framework.</p><p><strong>The Algorithm:</strong></p><ol><li>Calculate Adjusted Differentials:</li><li>For each of your 50 alternative models (k=1…50), calculate the Clark-West adjusted series: f(t) = (e1(t))² — (e2(t))² + (e1(t) — e2(t))²</li><li>Bootstrap the Max-t:</li><li>Instead of testing if the mean of fk(t) is zero using a standard table, you use a bootstrap (specifically a block bootstrap to keep time-dependency) to find the distribution of the maximum t-statistic across all k models.</li><li>The Result:<br>This gives you a p-value that answers: “Is the best of these 50 models statistically significant, accounting for the fact that I tried 50 times AND accounting for the fact that they are nested?”</li></ol><h3>Next Steps: The Model Confidence Set (MCS)</h3><p>If SPA rejects the null (meaning <em>some</em> model is better), you still don’t know <em>which</em> one. Do not just pick the lowest error!</p><p>Use the <a href="https://econpapers.repec.org/article/ecmemetrp/v_3a79_3ay_3a2011_3ai_3a2_3ap_3a453-497.htm"><strong>Model Confidence Set</strong></a>. This algorithm starts with all your models and systematically eliminates the worst ones until the remaining set contains the best model with 95% confidence.</p><ul><li>If the set contains 1 model: You have a clear winner.</li><li>If the set contains 10 models, the data is too noisy to distinguish between them. Pick the simplest one (Occam’s Razor).</li></ul><h3>References</h3><p>To cite these methods in your work, refer to the following seminal papers:</p><ul><li><strong>Diebold-Mariano:</strong> Diebold, F. X., &amp; Mariano, R. S. (1995). <em>Comparing Predictive Accuracy.</em> <a href="https://ideas.repec.org/a/bes/jnlbes/v13y1995i3p253-63.html">Journal of Business &amp; Economic Statistics.</a></li><li><strong>SPA Test:</strong> Hansen, P. R. (2005). <em>A Test for Superior Predictive Ability.</em> <a href="https://ideas.repec.org/a/bes/jnlbes/v23y2005p365-380.html">Journal of Business &amp; Economic Statistics.</a></li><li><strong>Clark-West:</strong> Clark, T. E., &amp; West, K. D. (2007). <em>Approximately Normal Tests for Equal Predictive Accuracy in Nested Models.</em> <a href="https://ideas.repec.org/a/eee/econom/v138y2007i1p291-311.html">Journal of Econometrics.</a></li><li><strong>Multiple Nested (MSPE-Adjusted):</strong> Clark, T. E., &amp; McCracken, M. W. (2012). <em>In-sample tests of predictive ability: A new approach.</em> <a href="https://ideas.repec.org/a/eee/econom/v170y2012i1p1-14.html">Journal of Econometrics.</a></li><li><strong>Model Confidence Set:</strong> Hansen, P. R., Lunde, A., &amp; Nason, J. M. (2011). <em>The Model Confidence Set.</em> <a href="https://econpapers.repec.org/RePEc:ecm:emetrp:v:79:y:2011:i:2:p:453-497">Econometrica.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc66f4ed7e28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we slashed data-API costs by 99.8% using flAPI + Google BigQuery + DuckDB]]></title>
            <link>https://medium.com/@simon.peter.mueller/how-we-slashed-data-api-costs-by-99-8-using-flapi-google-bigquery-duckdb-11d045546b2c?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/11d045546b2c</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 20:03:26 GMT</pubDate>
            <atom:updated>2025-11-28T20:03:26.068Z</atom:updated>
            <content:encoded><![CDATA[<p>At DataZoo, we often work with large datasets — sometimes hundreds of gigabytes — and expose aggregated results via internal APIs or dashboards. A recurring problem: querying a big warehouse like BigQuery on every request can be <strong>slow and painfully expensive</strong>.</p><p>But thanks to a clever caching strategy using <a href="https://flapi.io/">flAPI</a> (<a href="https://github.com/datazoode/flapi">GitHub</a>), we were able to cut both <strong>cost and latency</strong> by orders of magnitude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bW72o8a2LiCJnkl0YtbD5g.png" /></figure><h3>🚨 The Problem: Big data + many API calls = exploding costs</h3><p>Imagine a marketing team that needs a dashboard API for a table over 100 GB in BigQuery. Let’s say your service receives <strong>10,000 API calls per day</strong>. If each call triggers a direct BigQuery query, you might end up paying around <strong>$500 per day</strong>, or roughly <strong>$15,000/month</strong> — before counting the latency of 2–5 seconds per request. That’s neither fast enough for interactive dashboards nor sustainable from a budget standpoint. <a href="https://flapi.io/docs/examples/bigquery-caching/">flapi.io</a></p><p>We saw this pattern over and over in real-world projects: periodically aggregated data, many reads, but the underlying dataset rarely changed per request. Something had to change.</p><h3>✅ The Solution: Cache aggregated data + serve from DuckDB</h3><p>Here’s how flAPI comes to the rescue. Instead of hitting BigQuery on each API call, you:</p><ul><li>Execute your heavy aggregation once per hour (or at other intervals).</li><li>Store the result in a lightweight local database — in this case, DuckDB.</li><li>Serve your API requests from this cached dataset — at near-zero cost and with millisecond latencies.</li></ul><p>With this setup, the cache-generation (BigQuery → DuckDB) runs only 24 times per day. All API calls (10,000/day) hit DuckDB — so BigQuery cost becomes negligible. <a href="https://flapi.io/docs/examples/bigquery-caching/">flapi.io</a></p><p>In numbers: cost drops from $15,000/month to roughly <strong>$36/month</strong> — a <strong>99.76% saving</strong>. <a href="https://flapi.io/docs/examples/bigquery-caching/">flapi.io</a> Response time falls from seconds to <strong>1–50 ms</strong>. <a href="https://flapi.io/docs/examples/bigquery-caching/">flapi.io</a></p><h3>🔧 How it works: Configuration &amp; endpoint setup</h3><p>Using flAPI, you can define this with a simple YAML configuration:</p><pre># flapi.yaml<br>project_name: marketing-api<br>template:<br>  path: &#39;./sqls&#39;<br>connections:<br>  bigquery-marketing:<br>    init: |<br>      INSTALL &#39;bigquery&#39;;<br>      LOAD &#39;bigquery&#39;;<br>    properties:<br>      project_id: &#39;my-project-id&#39;<br>      credentials_path: &#39;${GOOGLE_APPLICATION_CREDENTIALS}&#39;<br>duckdb:<br>  db_path: ./flapi_cache.db<br>  access_mode: READ_WRITE</pre><p>Then define an endpoint — e.g. /campaigns/ — with caching enabled:</p><pre># sqls/campaigns.yaml<br>url-path: /campaigns/<br>cache:<br>  enabled: true<br>  table: campaigns_cache<br>  schema: analytics<br>  schedule: 60m  # Refresh every hour<br>  template_file: campaigns_cache.sql<br>request:<br>  - field-name: country     # optional filter<br>    field-in: query<br>    validators:<br>      - type: string<br>        pattern: &#39;^[A-Z]{2}$&#39;<br>  - field-name: campaign_type<br>    field-in: query<br>    validators:<br>      - type: string<br>        enum: [&#39;email&#39;, &#39;social&#39;, &#39;search&#39;, &#39;display&#39;]<br>template-source: campaigns.sql<br>connection:<br>  - bigquery-marketing</pre><ul><li>The cache-refresh SQL (e.g. campaigns_cache.sql) runs hourly — pulling data from BigQuery, aggregating, and storing into DuckDB. <a href="https://flapi.io/docs/examples/bigquery-caching/">flapi.io</a></li><li>The API SQL (e.g. campaigns.sql) reads from the DuckDB cache for every request. <a href="https://flapi.io/docs/examples/bigquery-caching/">flapi.io</a></li></ul><p>As a result, API requests are lightning-fast, and BigQuery cost is confined to the hourly refresh, not per request.</p><h3>📊 Why this pattern matters (especially for heavy-use APIs)</h3><ul><li><strong>Cost efficiency</strong>: Big warehouses are great for storage and batch queries — but not ideal for high-volume, low-latency reads. Caching flips that ratio.</li><li><strong>Latency</strong>: Serving from a small, local database like DuckDB dramatically reduces response times, improving the UX for dashboards or apps.</li><li><strong>Simplicity</strong>: flAPI abstracts away plumbing (scheduling, credential management, connections). You define templates — flAPI wires everything together.</li><li><strong>Scalability</strong>: Even as request volume grows, cost (cache refresh frequency) remains stable, not linear with requests.</li></ul><p>For many applications — marketing dashboards, product analytics, reporting APIs — this is a <em>sweet spot</em> between the power of big data (BigQuery) and responsiveness (DuckDB + flAPI).</p><h3>🚀 Real-World Fit — and Why I’m Excited</h3><p>Given my background: heavy use of Google Cloud, building data-driven services across industries (manufacturing, healthcare, finance), I see this pattern as a game-changer:</p><ul><li>For clients with large data warehouses, you get the power of BigQuery for heavy aggregations — while exposing efficient, low-cost APIs.</li><li>For internal tools (dashboards, metrics, ETL pipelines) — you avoid “big-warehouse-on-every-click” overhead, yet retain flexibility to update cache as needed.</li><li>For MVPs or prototypes: you can start with a BigQuery backend and scale to faster APIs without rewriting your backend — add flAPI + caching.</li></ul><p>Given the vast amounts of data many enterprises collect and the demand for real-time access, this pattern seems to scale well — both technically and economically.</p><h3>🧩 How to adopt this in your project — quick checklist</h3><ul><li>Identify data sources where:</li><li>Data volume is large (BigQuery),</li><li>Queries aggregate/filter / summarize (not row-level operations),</li><li>API traffic is heavy (many reads per minute/hour),</li><li>Real-time freshness is not critical — hourly (or other interval) cache is acceptable.</li><li>Define the SQL for cache refresh (aggregation + filter logic).</li><li>Configure flAPI: BigQuery connection, DuckDB cache, endpoint(s), and scheduling.</li><li>Start serving API: monitor cache size, refresh times, hit rates.</li></ul><p>If you already use tools like Google Cloud — this often means <strong>minimal overhead</strong> to get started, but <strong>massive gains</strong> in cost and performance.</p><h3>✨ Final Thoughts: “Big Data Warehouse” + “Lightweight API Cache” — Best of Both Worlds</h3><p>With flAPI, you don’t have to choose between the strengths of a powerful warehouse and the speed of a lightweight database. You can have both.</p><p>Suppose you’re working on dashboards, analytics APIs, or data-driven services backed by large datasets. In that case, I hope this pattern — BigQuery + DuckDB cache + flAPI — inspires you to build something fast, efficient, and cost-effective.</p><p>Let me know if you want a version with more context (e.g. how to integrate with a BI front end, auth, or monitoring), or even a “full post template” (markdown ready to paste).</p><p>Happy building 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11d045546b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting in SQL: Introducing Anofox Forecast for DuckDB]]></title>
            <link>https://medium.com/@simon.peter.mueller/time-series-forecasting-in-sql-introducing-anofox-forecast-for-duckdb-ab0d6a9593d3?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab0d6a9593d3</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[duckdb]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 15:15:18 GMT</pubDate>
            <atom:updated>2025-11-18T15:19:04.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oqw1jhnES-KU8Uy9co72Mw.png" /></figure><blockquote><em>Generate accurate forecasts directly in your database with 31 models, zero Python overhead, and automatic parallelisation*</em></blockquote><p>— -</p><p>If you’ve ever needed to forecast sales, demand, or any time-based metric, you know the drill: export data from your database, load it into Python or R, run your forecasting models, then import results back. It’s a workflow that works, but it’s far from elegant.</p><p>What if you could do all of this directly in SQL? What if you could generate forecasts for thousands of time series in parallel, without leaving your database? That’s precisely what <strong>Anofox Forecast</strong> brings to DuckDB.</p><h3><strong>What is Anofox Forecast?</strong></h3><p>Anofox Forecast is a time-series forecasting extension for DuckDB that provides 31 forecasting models, data preparation tools, exploratory data analysis, and evaluation metrics — all accessible via pure SQL. No Python subprocess calls, no data serialisation, no context switching between tools.</p><h4><strong>Key Capabilities</strong></h4><ul><li><strong>31 Forecasting Models</strong>: From simple baselines (Naive, Seasonal Naive) to advanced methods (AutoARIMA, AutoETS, TBATS, MSTL)</li><li><strong>Automatic Model Selection</strong>: AutoML models that choose the best configuration for your data</li><li><strong>Data Preparation:</strong> 12 macros for cleaning, gap filling, and transforming time series</li><li><strong>Exploratory Analysis</strong>: 5 functions for data quality assessment and statistics</li><li><strong>Evaluation Metrics</strong>: 12 metrics, including MAE, RMSE, MAPE, and coverage analysis</li><li><strong>Seasonality Detection</strong>: Automatic identification of seasonal patterns</li><li><strong>Changepoint Detection</strong>: Bayesian methods to identify regime changes</li></ul><p>All of this works natively in SQL, leveraging DuckDB’s powerful query engine.</p><h4><strong>Why This Extension Exists</strong></h4><p>Traditional forecasting workflows have several pain points that Anofox Forecast addresses:</p><h4><strong>Zero Python Overhead</strong></h4><p>Most forecasting libraries are written in Python. When you need forecasts in a database context, you typically:</p><ol><li>Export data from the database</li><li>Call Python via subprocess</li><li>Serialise data (JSON, CSV, or binary formats)</li><li>Wait for Python to process</li><li>Deserialise results back into the database</li></ol><p>This creates overhead, complexity, and potential bottlenecks. Anofox Forecast is written in C++ and integrated directly into DuckDB, eliminating all of this overhead.</p><h4><strong>Automatic Parallelization</strong></h4><p>When forecasting multiple time series, DuckDB automatically parallelises the work across CPU cores. If you have 1,000 product sales series to forecast, DuckDB distributes them across available cores without any additional configuration. This is native DuckDB behaviour — the extension works with it.</p><h4><strong>In-Database Forecasting</strong></h4><p>Your data never leaves the database. This means:</p><ul><li>No data movement overhead</li><li>Better security (data stays in your controlled environment)</li><li>Easier integration with existing SQL workflows</li><li>Direct use of DuckDB’s columnar storage and query optimisation</li></ul><h4><strong>Performance</strong></h4><p>C++ performance combined with DuckDB’s query optimiser means you can forecast millions of rows efficiently. The extension is designed for production use, not just prototyping.</p><h4><strong>Multi-Language Support</strong></h4><p>Since it’s all SQL, you can use Anofox Forecast from any language that supports DuckDB: Python, R, Julia, C++, Rust, Node.js, Go, Java, and more. The SQL is identical across all languages.</p><h3><strong>Getting Started</strong></h3><p>Installation is straightforward. If you’re using DuckDB 1.4.2 or later, you can install the extension directly:</p><pre>INSTALL anofox_forecast FROM community;<br>LOAD anofox_forecast;</pre><p>That’s it! All functions are now available in your DuckDB session.</p><h3><strong>How to Use It</strong></h3><p>The extension provides two main forecasting functions:</p><ul><li><strong>TS_FORECAST()</strong>: Forecast a single time series</li><li><strong>TS_FORECAST_BY()</strong>: Forecast multiple time series in parallel (using GROUP BY)</li></ul><p>Both functions follow a similar pattern:</p><pre>TS_FORECAST(<br>  table_name, - Your data table<br>  date_column, - Date/timestamp column<br>  value_column, - The values to forecast<br>  model_name, - Which model to use<br>  horizon, - How many steps ahead to forecast<br>  parameters - Model-specific parameters (as a MAP)<br>)</pre><p>The output includes point forecasts, prediction intervals (lower and upper bounds), and model metadata.</p><h3><strong>Practical Example: Forecasting Airline Passengers</strong></h3><p>Let’s walk through a complete example using the classic <strong>**AirPassengers**</strong> dataset. This dataset contains monthly totals of international airline passengers from 1949 to 1960 — a perfect example of a time series with both trend and seasonality.</p><h4><strong>Step 1: Load the Data</strong></h4><p>First, let’s create the AirPassengers dataset in DuckDB:</p><pre><br>CREATE TABLE air_passengers AS<br>  SELECT<br>    DATE &#39;1949–01–01&#39; + INTERVAL (month_num - 1) MONTH AS date,<br>    passengers<br>  FROM (<br>    VALUES<br>    (1, 112), (2, 118), (3, 132), (4, 129), (5, 121), (6, 135),<br>    (7, 148), (8, 148), (9, 136), (10, 119), (11, 104), (12, 118),<br>    (13, 115), (14, 126), (15, 141), (16, 135), (17, 125), (18, 149),<br>    (19, 170), (20, 170), (21, 158), (22, 133), (23, 114), (24, 140),<br>    (25, 145), (26, 150), (27, 178), (28, 163), (29, 172), (30, 178),<br>    (31, 199), (32, 199), (33, 184), (34, 162), (35, 146), (36, 166),<br>    (37, 171), (38, 180), (39, 193), (40, 181), (41, 183), (42, 218),<br>    (43, 230), (44, 242), (45, 209), (46, 191), (47, 172), (48, 194),<br>    (49, 196), (50, 196), (51, 236), (52, 235), (53, 229), (54, 243),<br>    (55, 264), (56, 272), (57, 237), (58, 211), (59, 180), (60, 201),<br>    (61, 204), (62, 188), (63, 235), (64, 227), (65, 234), (66, 264),<br>    (67, 302), (68, 293), (69, 259), (70, 229), (71, 203), (72, 229),<br>    (73, 242), (74, 233), (75, 267), (76, 269), (77, 270), (78, 315),<br>    (79, 364), (80, 347), (81, 312), (82, 274), (83, 237), (84, 278),<br>    (85, 284), (86, 277), (87, 317), (88, 313), (89, 318), (90, 374),<br>    (91, 413), (92, 405), (93, 355), (94, 306), (95, 271), (96, 306),<br>    (97, 315), (98, 301), (99, 356), (100, 348), (101, 355), (102, 422),<br>    (103, 465), (104, 467), (105, 404), (106, 347), (107, 305), (108, 336),<br>    (109, 340), (110, 318), (111, 362), (112, 348), (113, 363), (114, 435),<br>    (115, 491), (116, 505), (117, 404), (118, 359), (119, 310), (120, 337),<br>    (121, 360), (122, 342), (123, 406), (124, 396), (125, 420), (126, 472),<br>    (127, 548), (128, 559), (129, 463), (130, 407), (131, 362), (132, 405),<br>    (133, 417), (134, 391), (135, 419), (136, 461), (137, 472), (138, 535),<br>    (139, 622), (140, 606), (141, 508), (142, 461), (143, 390), (144, 432)<br>    ) AS data(month_num, passengers);</pre><h4><strong>Step 2: Generate a Simple Forecast</strong></h4><p>Let’s start with AutoETS, which automatically selects the best exponential smoothing model:</p><pre>SELECT<br>  forecast_step,<br>  date,<br>  ROUND(point_forecast, 1) AS forecast,<br>  ROUND(lower, 1) AS lower_bound,<br>  ROUND(upper, 1) AS upper_bound<br>FROM TS_FORECAST(<br>        &#39;air_passengers&#39;,<br>        date,<br>        passengers,<br>        &#39;AutoETS&#39;,<br>        12,<br>        {&#39;seasonal_period&#39;: 12, &#39;confidence_level&#39;: 0.95}<br>        )<br>ORDER BY forecast_step;</pre><p>This generates a 12-month forecast with 95% prediction intervals. AutoETS automatically detects the trend and seasonality patterns in your data.</p><h4><strong>Step 3: Compare Multiple Models</strong></h4><p>One of the strengths of Anofox Forecast is how easy it is to compare different models:</p><pre>WITH forecasts AS (<br>  SELECT &#39;AutoETS&#39; AS model, *<br>  FROM TS_FORECAST(&#39;air_passengers&#39;, date, passengers, &#39;AutoETS&#39;, 12,<br>  {&#39;seasonal_period&#39;: 12})<br>  UNION ALL<br>  SELECT &#39;AutoARIMA&#39; AS model, *<br>  FROM TS_FORECAST(&#39;air_passengers&#39;, date, passengers, &#39;AutoARIMA&#39;, 12,<br>  {&#39;seasonal_period&#39;: 12})<br>  UNION ALL<br>  SELECT &#39;Theta&#39; AS model, *<br>  FROM TS_FORECAST(&#39;air_passengers&#39;, date, passengers, &#39;Theta&#39;, 12,<br>  {&#39;seasonal_period&#39;: 12})<br>)<br>SELECT<br>  model,<br>  forecast_step,<br>  ROUND(point_forecast, 1) AS forecast<br>FROM forecasts<br>WHERE forecast_step &lt;= 6<br>ORDER BY model, forecast_step;</pre><h4><strong>Step 4: Detect Seasonality</strong></h4><p>Before forecasting, it’s often useful to detect seasonal patterns automatically:</p><pre>SELECT TS_DETECT_SEASONALITY(LIST(passengers ORDER BY date)) AS detected_periods<br>FROM air_passengers;</pre><p>This will identify that the data has a strong 12-month seasonal pattern (which makes sense for monthly airline passenger data). The function returns an array of detected periods, with the strongest period first.</p><h4><strong>Step 5: Evaluate Forecast Accuracy</strong></h4><p>If you have actual future values (or want to evaluate on a holdout set), you can calculate accuracy metrics:</p><pre>CREATE TABLE train AS<br>SELECT * FROM air_passengers WHERE date &lt; DATE &#39;1960–01–01&#39;;<br><br>CREATE TABLE test AS<br>SELECT * FROM air_passengers WHERE date &gt;= DATE &#39;1960–01–01&#39;;<br><br><br>CREATE TABLE forecast_results AS<br>  SELECT * <br>    FROM TS_FORECAST(&#39;train&#39;, date, passengers, &#39;AutoETS&#39;, 12, {&#39;seasonal_period&#39;: 12});<br><br>SELECT<br>  TS_MAE(LIST(test.passengers), LIST(forecast_results.point_forecast)) AS mae,<br>  TS_RMSE(LIST(test.passengers), LIST(forecast_results.point_forecast)) AS rmse,<br>  TS_MAPE(LIST(test.passengers), LIST(forecast_results.point_forecast)) AS mape<br>FROM test<br>JOIN forecast_results ON test.date = forecast_results.date;</pre><p>This gives you Mean Absolute Error (MAE), Root Mean Squared Error (RMSE), and Mean Absolute Percentage Error (MAPE) to assess forecast quality.</p><h3><strong>Complete Workflow Example</strong></h3><p>Here’s a more complete example that demonstrates the whole workflow:</p><pre><br>SELECT TS_DETECT_SEASONALITY(LIST(passengers ORDER BY date)) AS detected_periods<br>FROM air_passengers;<br><br>CREATE TABLE forecast_with_fit AS<br>SELECT * FROM TS_FORECAST(&#39;air_passengers&#39;, date, passengers, &#39;AutoETS&#39;, 12, {&#39;seasonal_period&#39;: 12, &#39;return_insample&#39;: true, &#39;confidence_level&#39;: 0.95});<br><br>SELECT<br>  forecast_step,<br>  date,<br>  ROUND(point_forecast, 1) AS forecast,<br>  ROUND(lower, 1) AS lower_95,<br>  ROUND(upper, 1) AS upper_95<br>FROM forecast_with_fit<br>ORDER BY forecast_step;</pre><p>This workflow shows the typical pattern: understand your data’s seasonality, then generate forecasts with appropriate parameters.</p><h3><strong>What’s Next?</strong></h3><p>Anofox Forecast opens time-series forecasting to anyone who knows SQL. Whether you’re forecasting sales, demand, website traffic, or any other time-based metric, you can now do it directly in your database.</p><h4><strong>Key Takeaways</strong></h4><ul><li><strong>31 models</strong> available, from simple to advanced</li><li><strong>Zero Python overhead</strong> — pure C++ performance</li><li><strong>Automatic parallelisation</strong> for multiple series using DuckDB</li><li><strong>Complete workflow</strong> — EDA, data prep, forecasting, and evaluation</li><li><strong>Production-ready </strong>— designed for real-world use</li></ul><h4><strong>Learn More</strong></h4><ul><li><a href="https://github.com/DataZooDE/anofox-forecast"><strong>GitHub Repository</strong></a></li><li><a href="https://www.linkedin.com/in/simon-m%C3%BCller/"><strong>Follow me on LinkedIn</strong></a></li></ul><p>The extension is actively developed and welcomes contributions. If you’re working with time series data in DuckDB, give Anofox Forecast a try — you might find it transforms how you approach forecasting.</p><p>— -</p><p><em>*Have questions or want to share your forecasting use case? Leave a comment below or reach out on GitHub!*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab0d6a9593d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Simpson Paradox & Causality]]></title>
            <link>https://medium.com/@simon.peter.mueller/the-simpson-paradox-causality-3f3c25d24a1f?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f3c25d24a1f</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[causality]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 07:28:14 GMT</pubDate>
            <atom:updated>2025-08-06T07:28:14.217Z</atom:updated>
            <content:encoded><![CDATA[<p>Simpson’s paradox is a paradox from statistics. It describes situations in which initially clear statements are reversed. The paradox has been known for decades. In the article, I would like to raise awareness about this problem, and it should be a warning against blindly trusting a statistic.</p><p><strong>Discrimination against women at Berkeley University?</strong></p><p>The following example from 1973 is intended to approach the Simpson paradox. In the fall of 1973, the University of Berkeley admitted 44% of male applicants but only 35% of female applicants for a place in one of its coveted graduate programs. The difference in admission rates between the sexes is so significant that it can no longer be assumed to be a random fluctuation. As a result, the University of Berkeley was sued for discriminating against female applicants. The success rate concerning the individual departments was then examined during the investigation. It was found that women were more likely to apply to popular departments with more burdensome admission requirements than their male counterparts. No discrimination against women was found when the admission numbers of women and men in each department were compared. In summary, admission figures across the university do not consider gender preferences in the program choice, resulting in different admission rates regardless of gender.</p><p><strong>The Simpson Paradox</strong></p><p>Karl Pearson first discovered this paradox in 1899. It got its name from the British statistician Edward Hugh Simpson, who published the facts in 1951. Simpson’s paradox is a statistical phenomenon in which the statistical relationship is reversed when additional factors are included in the analysis. The case presented above from the University of Berkeley is a classic example of teaching in which the data were erroneously summarised over the entire university. But which of the considerations, departments or universities is the correct one for a concrete application?</p><p><strong>Causal mechanisms of action</strong></p><p>Let us consider a constructed example from medicine. Suppose we have a group of men and women who are ill with a disease. We denote here by (M) the taking of medication, by (H) the cure from the disease, and let (G) be a female patient. Table 1 shows the results. The data summarised in Table 1 shows that by taking the drug, we can see a lower cure rate in both the male and female groups when taking the drug (M) than when not taking the drug. However, if we look at the combined figures, i.e. men and women united, we see a higher cure rate when taking the drug compared to not taking it. How should a physician evaluate this result? In the case that the physician knows the sex of the patient, he would, in any case, advise against taking the drug. If a patient were to call, for example, and the sex could not be found out, he would have to recommend taking the drug based on the table. Such instruction to physicians would be ridiculous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mm6vec8qS6Fg1rTzdWHHkg.png" /></figure><p>In 1981, the statisticians Lindley and Novick wondered whether additional statistical information could lead the observer to the correct chart. They answered no to this question. Let’s continue working with the same numbers from Table 1 but changing the story behind the data (right graph in Flowchart 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTMdoC-mf6SLYDz8JUL8ww.png" /></figure><p>Now let (G) be the patient’s blood pressure, which is affected by the treatment (M) and has an effect on healing (H), just as in the previous example. If we now imagine the impact as paths, there are two paths from the drug intake (M) to the variable cure (H), one direct and one via the blood pressure (G). It is easy to see that in these circumstances of the summarised table, one falls back since the blood pressure (G) does not contribute anything to explaining the case by its non-influence on the drug intake. Thus, if two different causal models produce the same data and we decide to take the drug in one case and not in the other model, it is evident that this decision was made based on causal causes and not on statistical considerations. Whether to look at the pooled data or only at subgroups depends on the causal mechanisms behind the data, i.e., the context in which the question is embedded.</p><p><strong>What kind of machine is man?</strong></p><p>The paradox can be explained very well by the objectivist conception of probability. Still, it contradicts our strongly developed human intuition, which considers such paradoxical situations absurd. This is extremely interesting from a psychological point of view: Where does man possess such a strong intuition, and how is it encoded in our brain? Here, the psychologist assumes that humans have an innate form of causal logic that guides us in our actions and the resulting consequences. Proportions and numbers are generally perceived as transitory, and humans look for stable causal relationships in their environment. This is more in line with the subjectivist view of probability.</p><p><strong>What follows from this?</strong></p><p>Interpreting the collected data requires comprehensive statistical methodological skills and a sound background knowledge of the subject area under investigation. The analysis and subsequent evaluation must be approached with outstanding care, which also includes a critical approach to one’s own and other people’s expectations of the result.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f3c25d24a1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Your Gmail Attachment Workflow: Save Files to Google Drive]]></title>
            <link>https://medium.com/@simon.peter.mueller/automate-your-freelance-invoicing-save-gmail-attachments-to-google-drive-d8e04c1f21ab?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e04c1f21ab</guid>
            <category><![CDATA[google-app-script]]></category>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[productivity-hacks]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 07:59:27 GMT</pubDate>
            <atom:updated>2024-10-16T14:52:51.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*F3UI0wwzP1bJyholEhag2A.png" /></figure><p>As a freelancer, I’ve always been looking for ways to streamline my workflow and minimize the time on repetitive and unpaid time. One task that consistently ate into my productive time was managing invoices. The constant cycle of receiving, downloading, and organizing invoices from various clients was tedious and a time-sink. That’s when I decided to leverage my coding skills to create a solution: a custom Google Apps Script that automatically saves PDF attachments from specified Gmail senders to a designated Google Drive folder.</p><h4><strong>The Freelancer’s Invoicing Dilemma</strong></h4><p>If you’re a freelancer, you likely know the drill. At the end of each month (or more frequently, if you’re lucky), you find yourself:</p><ol><li>Sifting through your Gmail inbox for invoices</li><li>Downloading each PDF attachment</li><li>Renaming files for consistency</li><li>Organizing them into the appropriate folders in your Google Drive</li><li>Insert invoice information into Google Sheets</li><li>Prepare your monthly VAT statement</li><li>And potentially missing invoices in your busy inbox</li></ol><p>This process is not only time-consuming but also prone to human error. A missed invoice could lead to delayed payments or accounting headaches. I needed a solution that could minimize my administrative burden. Many paid solutions on the market help with these administrative tasks, but they are not free, and in some parts, they increase administrative time. The money spent on these tools is unrelated to their promised time savings. Therefore, I started using my coding skills to build customized solutions using Google Workspace.</p><h4><strong>Enter: The Gmail to Google Drive Attachment Saver</strong></h4><p>To solve this problem, I developed a Google Apps Script that automates the entire process. Here’s a breakdown of how it works:</p><ol><li><strong>Email Address Management</strong>: The script reads a list of email addresses from a Google Sheet. These are your clients or invoice senders.</li><li><strong>Intelligent Gmail Search</strong>: It then searches your Gmail for emails from these addresses with attachments.</li><li><strong>Automatic Saving</strong>: PDF attachments are automatically saved to a specified Google Drive folder.</li><li><strong>Duplication Prevention</strong>: The script checks for existing files to avoid creating duplicates.</li><li><strong>Smart Processing</strong>: It keeps track of when it last ran to avoid re-processing old emails, ensuring efficiency.</li></ol><h4><strong>The Benefits: More Than Just Time Savings</strong></h4><p>This automation tool has been a game-changer for my freelance business, and here’s why:</p><ul><li><strong>Time Savings</strong>: The administrative time is reduced, and more personal time is available.</li><li><strong>Flawless Organization:</strong> All my invoices are neatly filed in one place without any manual intervention. There are no more scattered files or misnamed documents. This is partly true, as some invoices are not sent to my Gmail inbox, but this will be a second project.</li><li><strong>Peace of Mind</strong>: I no longer worry about missing an essential invoice in my busy inbox. The system catches everything, ensuring I stay on top of my finances.</li><li><strong>Reduced Errors</strong>: By eliminating manual downloading and filing, I’ve significantly reduced the chance of human error in my invoice management process.</li></ul><h3><strong>How You Can Implement This Solution</strong></h3><p>The best part? I’ve made this tool open-source and available for anyone to use. Here’s a quick guide to get you started:</p><h4><strong>Set Up Your Environment</strong>:</h4><ul><li>Ensure you have a Google account</li><li>Install Node.js and npm on your machine</li><li>Install the Google Apps Script CLI (clasp) globally</li></ul><h4><strong>Create Your Project</strong>:</h4><ul><li>Use <a href="https://github.com/google/clasp">clasp</a> to create a new Google Apps Script project</li><li>Clone the GitHub repository containing the script code</li></ul><h4><strong>Configure Your Settings</strong>:</h4><ul><li>Set up a Google Sheet with a list of email addresses you want to monitor for invoices.</li><li>Configure the script properties in the Google Apps Script editor with your Sheet ID, sheet name, column name, and target Google Drive folder ID</li></ul><h4><strong>Deploy and Schedule</strong>:</h4><ul><li>Deploy the script using <a href="https://github.com/google/clasp">clasp</a></li><li>Set up a time-based trigger in the Google Apps Script editor to run the script automatically at your preferred interval.</li></ul><p>Detailed setup instructions are available in the project’s <a href="https://github.com/sipemu/fetch_pdfs/tree/main">README</a> file on GitHub.</p><h3><strong>Customization Possibilities</strong></h3><p>While I use this tool primarily for invoices, its flexibility allows for various other applications:</p><ul><li><strong>Document Management</strong>: Automatically save essential documents from specific senders</li><li><strong>Expense Tracking</strong>: Organize receipts from business expenses</li><li><strong>Project Deliverables</strong>: Archive attachments from clients or team members for project management</li></ul><p>The script can be easily customized to fit your specific needs. For example, you can modify it to save attachments other than PDFs or adjust the Gmail search criteria to be more or less selective.</p><h3><strong>The Technical Side: A Peek Under the Hood</strong></h3><p>For those interested in the technical details, here’s a brief overview of the script’s structure:</p><ul><li>It’s written in Google Apps Script, a JavaScript-based language that integrates seamlessly with Google services.</li><li>The script is modular, with separate files for configuration, main execution, sheet operations, Gmail operations, and date utilities.</li><li>It uses Google’s Properties Service for secure configuration management.</li><li>The script leverages Gmail’s powerful search functionality and Google Drive’s file management capabilities.</li></ul><h3><strong>Conclusion: Embrace Automation, Focus on Your Craft</strong></h3><p>As freelancers, our time is our most valuable asset. By automating routine tasks like invoice management, we free ourselves to focus on what we do best — our core work. This Gmail to Google Drive Attachment Saver has significantly streamlined my operations, saving me time each month and providing peace of mind.</p><p>The open-source code is free to fork, improve, and share your enhancements with the community. Let’s leverage technology to make our freelance lives more accessible and productive.</p><p>Remember, the key to freelance success isn’t just about working harder and more intelligent. Embrace automation, streamline your processes, and watch your productivity soar.</p><h4>My following automation tools will be on:</h4><ul><li>Automatically parse the invoices and copy relevant information to a Google Sheet for semi-automatic VAT statements.</li><li>Create a script for fetching invoices automatically from websites that do not offer invoices per Email.</li></ul><p>Happy automating!</p><p><a href="https://github.com/sipemu/fetch_pdfs/tree/main">Link to GitHub Repository</a></p><p>#Freelancing #Automation #ProductivityHacks #GoogleAppsScript</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e04c1f21ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Quality in Large Time-Series Databases: A Focus on Comparing and Tracking Slices (Part I)]]></title>
            <link>https://medium.com/@simon.peter.mueller/data-quality-in-large-time-series-databases-a-focus-on-comparing-and-tracking-slices-part-i-ecaa046e1816?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecaa046e1816</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-quality-management]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data-quality]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 15:37:08 GMT</pubDate>
            <atom:updated>2025-11-18T20:26:24.945Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Quality in Large Time-Series Databases: A Focus on Comparing and Tracking Slices</h3><p>Data for forecasting is extracted at different time points (weekly, monthly, …) from a database, e.g., SAP BW, where regular changes are performed between these extractions. These changes are wanted, e.g., new product introductions, phase-outs, and corrections, but there may also be unwanted corrections, errors in data extractions due to failing pipelines, etc. I will briefly describe the challenge and provide a framework for detecting, ranking, and evaluating the difference between the two slices of time series databases. This article does not look at the data quality of a single series, e.g. missing values, change points, or trend changes.</p><p><em>Sounds interesting? Read on, then!</em></p><h3>Introduction</h3><p>In a world that increasingly leans on data for decision-making, assuring the quality of that data has never been more paramount. Data quality has seen extensive research, given its pivotal role in ensuring the validity and reliability of insights drawn from it. Time-series data sets, a common sight in many sectors, from finance to healthcare, can prove particularly challenging. The sheer volume of data and its temporal dimension opens up a host of complexities when attempting to assure its quality.</p><p>However, this aspect becomes even more nuanced when we consider a single snapshot and the comparison of multiple slices over time. This article explores this scenario, mainly using data extracted from a live system for different time points.</p><h3>Context</h3><p>For example, the demand planning process generates regular (weekly, monthly, or quarterly) forecasts for the next 18, 24, or more months. As the enterprises are living organisms, wanted and unwanted changes in the time-series database happen. New products are introduced, products are marked as phase-out products, and even the sales history is corrected. However, there are also uncontrolled changes in the time-series database. A pipeline fails when preparing S&amp;OP data (data is gathered from different sources); definitions are changes that lead to unintended sales time series transformations. A demand planner applies an outlier detection algorithm that automatically changes the history. And so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*10umy7ZU47eSs-5J1jpH3Q.png" /></figure><p>When performing a demand forecast, your intention as a forecaster is to consider the intended changes in the database, e.g. considering the phase-out products. Still, you want to refrain from performing a forecast on malicious input data, as this leads to wrong forecasts and follow-up in wrong planning.</p><p>Therefore, we developed at DataZoo a framework that performs a data quality check between the current and previous slices, considering the intended changes from the last and current forecast runs. Before we start our forecasting engine on the current database, we report possible data quality issues to the subject matter experts (SMEs) for validation.</p><p>Several iterations with the SME were performed to map the business knowledge of regularly performed changes to divide wanted changes from unwanted ones. This is an essential step, as we want to avoid repeatedly delivering False signals from our framework to the SME. The following framework is simplified, presents just the core idea of our data quality checks, and does not include business information about our customers.</p><h4>Statistical Measures for Ranking</h4><p>Besides the business topics, an appropriate statistical measure for generating our ranking must be found. We evaluated four different measures in our experiments:</p><ol><li>The sum of the series.</li><li>The t-statistic</li><li>Wasserstein distance</li><li>Kullback Leibler divergence</li></ol><h4>Simulation Setup</h4><p>The starting point of our simulation was to select a high-quality reference dataset with SMEs. Furthermore, we internally evaluated several usual data changes mapped into our framework. We randomly applied them to the initial dataset to simulate a second one with the intended changes. Afterwards, erroneous behaviour (that we already have seen in the data, but also other possible erroneous behaviour we thought could be possible) was randomly added to the time-series database, and those above four statistical measures were applied to generate a ranking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWc62KxAKJ0UcjuzYJjJow.png" /></figure><p>These steps were repeated 10.000 times, and a ROC and Precision-Recall analysis was performed to evaluate the four selected statistical measures. As we are mainly interested in getting a good ranking, the Precision-Recall curve was our focus, as ranking is our intention.</p><p>The following plots show the ROC and PRC for the sum and t statistic over the performed experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ym7WAJ_ERXFT5HNFhflsqA.png" /></figure><h4>Results</h4><p>For the specific use case, the t statistics performed best because of ROC, but most importantly, they generated a ranking. In addition to ranking the erroneous data (if there is any), the errors were classified so that the SMEs could find the root cause of that erroneous measure directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecaa046e1816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAP Integration in AWS S3]]></title>
            <link>https://medium.com/@simon.peter.mueller/sap-integration-in-aws-s3-9547539a4455?source=rss-3584ae2be8ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/9547539a4455</guid>
            <category><![CDATA[sap]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Simon Müller]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 10:30:43 GMT</pubDate>
            <atom:updated>2024-03-12T10:30:43.402Z</atom:updated>
            <content:encoded><![CDATA[<p>Enhancing Data Analytics: Streamlining SAP Data Integration with AWS S3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*58lkn0hMYSsO4HH45bJvRQ.png" /></figure><h3>Why Amazon S3?</h3><p>Amazon S3 (Simple Storage Service) is a scalable object storage service offered by Amazon Web Services (AWS) that allows you to store and retrieve any data from anywhere on the web. It is designed to make web-scale computing easier for developers by providing a simple web services interface that can be used to store and retrieve any amount of data, anytime, from anywhere on the internet. Our SAP connector ERPL is an efficient and flexible connector for integrating SAP data in S3.</p><h3>Start DuckDB &amp; install and load the ERPL extension</h3><p>The following examples are executed in the CLI but are easily replicable in any other language that supports DuckDB. Let’s start. First, we need to begin DuckDB from CLI using the --unsigned flag.</p><pre>duckdb --unsigned</pre><p>Install and load the RFC extension and set the SAP login parameters:</p><pre>SET custom_extension_repository = &#39;http://get.erpl.io&#39;;<br>FORCE INSTALL erpl;<br>LOAD erpl;<br><br>SET sap_ashost = &#39;localhost&#39;;<br>SET sap_sysnr = &#39;00&#39;;<br>SET sap_user = &#39;DEVELOPER&#39;;<br>SET sap_password = &#39;Htods70334&#39;;<br>SET sap_client = &#39;001&#39;;<br>SET sap_lang = &#39;EN&#39;;</pre><p>To replicate the SAP data to Amazon S3, a connection must be established using your <a href="https://duckdb.org/docs/guides/import/s3_export.html">Amazon S3 credentials</a>. Since duckdb 0.10, the credentials can be saved securely in a secret object in DuckDB. Furthermore, the AWS extension provided by DuckDB can provide credentials by the [AWS Default Credential Provider Chain] (https://duckdb.org/docs/extensions/aws).</p><pre>CREATE SECRET (<br>    TYPE S3,<br>    KEY_ID &#39;[KEY]&#39;,<br>    SECRET &#39;[SECRET]&#39;,<br>    REGION &#39;[REGION]&#39;<br>);</pre><p>If you are working with DuckDB version v0.9.2 and lower, the credentials must be set as follows:</p><pre>SET s3_region=&#39;[REGION]&#39;;<br>SET s3_access_key_id=&#39;[SECRET]&#39;;<br>SET s3_secret_access_key=&#39;[KEY]&#39;;</pre><p>Please follow the instructions on the <a href="https://duckdb.org/docs/guides/import/s3_export.html">DuckDB website</a> if there are any issues with the Amazon S3 connection.</p><p>We assume that the Bucket already exists in the desired target regions for your SAP data.</p><h3>Query your SAP Database using RFC and Copy Data to Amazon S3</h3><p>Create the query for data you want to replicate to Amazon S3. In this example, we will use RFC to extract data for DuckDB. Look at <a href="https://erpl.io/docs/key_tasks/replicate_odp.html">ODP</a> or <a href="https://erpl.io/docs/key_tasks/bw_query.html">BW</a> help pages on creating ODP and BICS queries.</p><pre>COPY (SELECT * FROM sap_rfc_invoke(&#39;BAPI_FLIGHT_GETLIST&#39;, path=&#39;/FLIGHT_LIST&#39;)) TO s3://[YOUR BUCKET]/sflight.parquet</pre><p>With one line of code, your SAP data is placed on S3. Happy analyzing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9547539a4455" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>