<?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 Youssef Bouraha on Medium]]></title>
        <description><![CDATA[Stories by Youssef Bouraha on Medium]]></description>
        <link>https://medium.com/@bourahayoussaf?source=rss-6f9e4363b569------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7RzSknJD1BL-OdbI</url>
            <title>Stories by Youssef Bouraha on Medium</title>
            <link>https://medium.com/@bourahayoussaf?source=rss-6f9e4363b569------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:24:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bourahayoussaf/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[Creating Powerful Time Series Features with MLForecast From Nixtla’s]]></title>
            <link>https://medium.com/@bourahayoussaf/creating-powerful-time-series-features-with-mlforecast-from-nixtlas-35cbb7360041?source=rss-6f9e4363b569------2</link>
            <guid isPermaLink="false">https://medium.com/p/35cbb7360041</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Youssef Bouraha]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 15:49:31 GMT</pubDate>
            <atom:updated>2025-10-17T15:49:31.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inroduction</h3><p>Here’s a secret most beginners miss: <strong>Machine learning models don’t feel time. </strong>To them, a timestamp like 2024-06-07 14:30:00 is just a number — not a Friday afternoon, not the start of summer, not that moment when people rush to the store.</p><p>The truth is, <strong>time is the heartbeat of every dataset.</strong> From energy spikes at sunrise to weekend sales surges, our data moves in rhythm. To help our models catch that rhythm, we build <strong>time features</strong> — tiny signals that turn timestamps into meaning.<br>By breaking timestamps into meaningful parts (like hour, weekday, or season) and adding historical memory through lag and rolling transformations, we help our models <em>understand the passage of time.</em></p><p><strong>And the best part?</strong><br> You don’t have to reinvent the wheel — <strong>Nixtla’s MLForecast</strong> makes it effortless to create these powerful features with just a few lines of code.</p><p>In this post, we’ll explore <strong>three essential types of time-based features</strong> every data scientist should know:<br> 🕐 <strong>Time Features</strong> — turning timestamps into model-friendly signals.<br> 🔁 <strong>Lag Features</strong> — giving your model memory of the past.<br> 🔄 <strong>Lag Transforms</strong> — summarizing historical patterns with rolling, expanding, and seasonal windows.</p><p>By the end, you’ll not only understand how they work — you’ll know how to create them <em>effortlessly and elegantly</em> using <strong>MLForecast</strong>.</p><h3><strong>Nixtla’s </strong><strong>MLForecast</strong></h3><p>Before diving into these features, let’s look at the tool that makes them so easy to build — <strong>Nixtla’s </strong><strong>MLForecast</strong>.</p><p>This class lets you use any traditional machine learning model (like LinearRegression or XGBoost) for time series forecasting.<br> When you create it, you define:</p><ul><li>models: the ML models you want to use</li><li>freq: the frequency of your data (&#39;D&#39; for daily, &#39;H&#39; for hourly, etc.)</li><li>Optional arguments like date_features or lags to automatically create time-based features</li></ul><p><strong>Code :</strong></p><p>This is the basic setup of MLForecast — it initializes the model with the data frequency and prepares it for training with fit().</p><pre>from mlforecast import MLForecast<br>from sklearn.linear_model import LinearRegression<br><br># Initialize MLForecast<br>fcst = MLForecast(<br>    models=[LinearRegression()],<br>    freq=&#39;D&#39;,  # Daily frequency<br><br>    #..... features will be created later<br>)<br><br># Fit the model <br>fcst.fit(data)</pre><p><strong>Note : </strong>The dataset should contain three essential columns: the timestamp (ds), a unique identifier (unique_id), and the target variable (y).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*4kL6P7HfzZ11-lCKeyv_yQ.png" /></figure><h3>1. Time Features</h3><p>When working with time series data, each observation is tied to a specific moment — a <strong>timestamp</strong> like 2024-06-07 14:30:00.<br> However, machine learning models don’t automatically understand what that timestamp means — they just see it as a <strong>black box</strong>.</p><p>That’s why we use <strong>time features</strong>.<br> They break a timestamp into meaningful parts — like <strong>hour</strong>, <strong>day of week</strong>, or <strong>month</strong> — just as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8HzY77mODthzv5ejWA6oQ.jpeg" /><figcaption>From Timestamp to Time Features</figcaption></figure><p>These features help models spot <strong>patterns linked to time</strong>, for example:</p><ul><li>🛍️ Higher sales on weekends</li><li>⚡ Energy consumption peaks during certain hours</li><li>🌦️ Seasonal effects like warmer months increasing air conditioner use</li></ul><p>Common time features include:hour, minute, day of week, day of month, month, year, quarter, week of year, and even flags like is_weekend.</p><p><strong>Code:</strong></p><p>You can easily create these features using the <strong>MLForecast</strong> class from <strong><em>Nixtla</em></strong><em>. </em>By specifying the argument date_features=[&#39;dayofweek&#39;, &#39;month&#39;]</p><pre><br># 1 Time features<br><br>fcst = MLForecast(<br>    models=[LinearRegression()],<br>    freq=&#39;D&#39;,  # Daily data<br><br>    date_features=[&#39;hour&#39;,&#39;dayofweek&#39;, &#39;month&#39;] # add others here<br>)<br><br>features_df = fcst.preprocess(data)<br>features_df.head()<br></pre><p>✅ <strong>What happens here:</strong><br> MLForecast automatically adds columns like dayofweek and month,converting timestamps into numerical features your model can use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*I7paqn1LfuWqOu5MkpvCWw.png" /><figcaption>Time Features</figcaption></figure><p>Normally, these features are built automatically when you call fit().<br> But here, we’ll use <strong>preprocess()</strong> instead — just to <em>see and understand</em> the features being generated before any model training happens.</p><h3><strong>2. Lag Features in Time Series</strong></h3><p>Lag features are crucial building blocks in time series forecasting. They represent past values of the target variable (or other features) that help a model predict future values. Essentially, they give the model “memory” to learn from historical patterns.</p><p>For example, a lag of 7 in a daily time series refers to the value from 7 days ago.</p><p>To illustrate, when predicting the value for Day 7, we might use the following lag features, as shown in the image below:</p><ul><li><strong>Lag 1</strong>: Value from Day 6 (one day prior)</li><li><strong>Lag 2</strong>: Value from Day 5 (two days prior)</li><li><strong>Lag 3</strong>: Value from Day 4 (three days prior)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcaRUkZY09hgkxvnczIBrQ.png" /><figcaption>Lag Features</figcaption></figure><p>In simple terms: <em>To predict what happens at time </em>t<em>, we use values from </em>t-1<em>, </em>t-2<em>, </em>t-3<em>, and so on.</em></p><h3>Example Dataset with Lag Features</h3><p>You can easily create lag features using the <strong>MLForecast</strong> class <em>. </em>By specifying the argument lags=[1, 2]</p><pre># 2 Create lag features<br><br>fcst = MLForecast(<br>    models=[LinearRegression()],<br>    freq=&#39;D&#39;, <br><br>    lags=[1,2,3]# add others here<br>)<br><br>features_df = fcst.preprocess(data)<br>features_df.head()</pre><p><strong>Output Example:</strong></p><p><strong>Lag features with NaNs:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Z8lRWOopNNpytUNx_M2bkA.png" /><figcaption>Lag features with NaNs</figcaption></figure><p>NaN values appear in lag features for the first k rows because there isn’t enough past data to fill a lag-k feature.</p><p><strong>After Dropping NaNs (Training-Ready)</strong></p><p>MLForecast drops these NaNs automatically<strong> </strong>during training (fit()/preprocess), so you don’t need to worry about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*qzCacwwv9Sgs2HWQU8Qn_g.png" /><figcaption>Lag features after dropping NaNs</figcaption></figure><p><strong>Note:</strong> Using lag features will reduce your dataset size — the first max(lags) rows will be dropped.</p><h3>3. Lag Transforms:</h3><p>We can create more features by applying functions to lags, which summarize historical data over different windows to help the model capture complex patterns. The main types of lag-based features are <strong>rolling transforms</strong>, <strong>expanding transforms</strong>, and <strong>seasonal rolling transforms.</strong></p><h4><strong>3.1 Rolling Transforms</strong></h4><p>Calculates a statistic (e.g., mean, std, max, etc) over a fixed-size sliding window of past values, see animation below. It helps capture short-term trends and recent volatility. For example, the average sales over the last 7 days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wyUCwkPOTJ23xlj15SSyoQ.gif" /><figcaption>Time Series Sliding Window</figcaption></figure><h4><strong>Example code:</strong></h4><p>In this example, we apply RollingMean(window_size=3, min_samples=1) to compute the average of the last 3 days and RollingStd(window_size=3, min_samples=1) to measure variability over the same period.</p><pre><br>from mlforecast.lag_transforms import RollingMean, RollingStd<br><br>fcst = MLForecast(<br>    models=[LinearRegression()],<br>    freq=&#39;D&#39;,<br>    lags=[1], # create lags first<br><br>    lag_transforms={<br>        1: [ # apply transforms on lag 1<br>            RollingMean(window_size=3, min_samples=1),<br>            RollingStd(window_size=3, min_samples=1)<br>        ]<br>    }<br>)<br><br>X = fcst.preprocess(data)<br>X.head()<br></pre><p><strong>Notes:</strong></p><p>🔹<strong>lag_transforms</strong> tells the model to apply special transformations to some lags.</p><p>🔹window_size: number of past steps to include (e.g., 3→ last 3 days).</p><p>🔹min_samples: minimum number of samples required to compute the statistic.</p><p>🔹Note :the rolling transforms are applied to <strong>lag features</strong>, not directly on the target variable y. Make sure the transformed lag is <strong>created first</strong> before applying these transforms.</p><p><strong>Output Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*XixnPuzyrfL7SBVs2JDbEA.png" /></figure><p><strong>Other rolling transforms you can use:</strong><br> RollingMin, RollingMax, RollingQuantile(p), RollingMedian, RollingVar, etc. Each gives a different way to summarize the same moving window.</p><h4>3.2 <strong>Expanding Transforms</strong></h4><p>Expanding transforms are similar to rolling transforms, but instead of a fixed-size window, they summarize <strong>all past lag values up to the current point</strong>. This helps capture <strong>long-term trends or cumulative changes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*f3BGqV_qqb-NC8dE8ndU1g.gif" /><figcaption>Time series expanding window</figcaption></figure><p><strong>⚙️ Example — Expanding Mean and Std</strong></p><p>We’ll use ExpandingMean and ExpandingStd applied to <strong>lag 1</strong>, just like we did for rolling transforms:</p><pre>from mlforecast.lag_transforms import ExpandingMean, ExpandingStd<br><br>fcst = MLForecast(<br>    models=[LinearRegression()],<br>    freq=&#39;D&#39;,<br>    lags=[1],  # create lag 1 first<br>    lag_transforms={<br>        1: [ # apply transforms on lag 1<br>            ExpandingMean(),<br>            ExpandingStd()<br>        ]<br>    }<br>)<br><br>X = fcst.preprocess(data)<br>X.head()</pre><p><strong>Notes:</strong></p><p>🔹Similar to lag features, the missing values (NaNs) introduced by rolling transformations are also automatically handled by the `MLForecast` class during training.</p><p>🔹<strong>Other Expanding Options:</strong> ExpandingMax, ExpandingMin, ExpandingQuantile(p), etc., give alternative ways to summarize all past lag values.</p><h4><strong>3.3. Seasonal Rolling Transforms</strong></h4><p>calculate a statistic over a window of specific seasonal periods. For example, to forecast sales for the next Monday, we can take <strong>the average or median of sales from the last four Mondays.</strong> This approach helps capture stable seasonal patterns, like weekly or monthly trends, in the data.</p><p><strong>Code</strong></p><p>In this example, We’ll use the SeasonalRollingMean class</p><pre>from mlforecast.lag_transforms import SeasonalRollingMean<br><br># Define the model<br>fcst = MLForecast(<br>    models=[LinearRegression()],<br>    freq=&#39;D&#39;,<br>    lags=[7],  # create the lag first<br><br>    lag_transforms={<br>        7: [  # apply transforms on lag 7<br>            SeasonalRollingMean(window_size=4, season_length=7)<br>        ]<br>    }<br>)<br><br>X = fcst.preprocess(data)<br>print(X.head(10))</pre><p><strong>Notes:</strong></p><p>🔹<strong>SeasonalRollingMean(window_size=4, season_length=7)</strong> means: for each observation, the model looks back <strong>every 7 days</strong> (same weekday) and takes the <strong>average of the last 4 such observations</strong> — for example, the average of the previous 4 Mondays.</p><p>🔹Other seasonal rolling transforms in mlforecast include: <strong>SeasonalRollingMax</strong> , <strong>SeasonalRollingMin</strong> , <strong>SeasonalRollingStd</strong>, and <strong>SeasonalRollingQuantile</strong>.</p><h3>Conclusion</h3><p>Feature engineering is where <strong>data science meets creativity</strong> — it’s not just about feeding data into models, but about teaching models how to <em>see</em> the world as we do.</p><p>Time features tell the model <em>what time it is</em>.<br> Lag features remind it <em>what has happened before</em>.<br> Lag transforms teach it <em>how history tends to repeat itself</em>.</p><p>Together, they transform raw timestamps into the language of patterns — the language machine learning truly understands.</p><p>With <strong>Nixtla’s MLForecast</strong>, creating these features becomes not just faster, but smarter. It lets you focus on insights, storytelling, and model design — the parts that make data science feel like art.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35cbb7360041" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>