Part III — Advanced Systems · Chapter 18 · Lesson 1 of 7 · 9 min read
Lesson 1: Date Features, Resampling, Lag, Lead, Differences, and Percentage Change
Lesson level: Advanced
Purpose: Turn raw timestamped records into a regular, well-understood series and derive the basic features — calendar parts, lags, leads, differences, and percentage change — that every later analysis depends on.
Learning objectives
By the end of this lesson you will be able to:
- explain what makes a dataset a time series and why order, frequency, and time zone matter
- extract calendar features such as year, month, weekday, and week of year
- resample irregular events to a regular frequency with an explicit aggregation
- create lag and lead columns and explain the leakage risk of leads
- compute absolute differences and percentage change and handle zero and null bases
- validate a series for duplicates, gaps, and unsorted timestamps
1.1 What makes data a time series
A table becomes a time series when one column — the time index — defines the order in which rows are meaningful. Three properties must be stated explicitly before any calculation is trusted:
- Order. Rows must be sorted by the time index. Every lag, difference, and rolling window silently assumes this.
- Frequency. The spacing between observations: minute, hour, day, week, month. Irregular event logs have no frequency until you resample them.
- Time zone. A timestamp without a zone is ambiguous. Store instants in UTC and convert to a business zone only for calendar features and reporting.
A fourth property, grain, says what one row represents: a single event, a daily total, or a month-end balance. Sums of daily totals are meaningful; sums of month-end balances are not. Write the grain into the schema description so that later aggregations choose the right function.
1.2 Validating the time index
Before deriving features, run a short validation that answers four questions: Is the index sorted? Are there duplicate timestamps? Are there missing periods? Are there nulls in the index? The listing below shows the checks in the Python host, which is where the v0.63 data layer lives.
Illustrative listing — confirm method names in your installed version.
from pealang.data import read
sales = read("daily_sales.csv")
def check_series(df, ts, freq):
issues = []
if df.column(ts).null_count() > 0:
issues.append("null timestamps")
if not df.column(ts).is_sorted():
issues.append("index not sorted")
if df.column(ts).n_unique() != df.height:
issues.append("duplicate timestamps")
expected = df.date_range(ts, freq=freq)
missing = expected.anti_join(df, on=ts)
if missing.height > 0:
issues.append(f"{missing.height} missing periods")
return issues
print(check_series(sales, "date", "1d"))
Treat a non-empty result as a stop condition in scheduled jobs. Duplicates usually mean an upstream join multiplied rows or a load ran twice; missing periods mean either genuine zero activity or lost data, and those two cases need different repairs (Lesson 3).
1.3 Calendar features
Calendar features expose the regular rhythms that drive most business series: weekday versus weekend, month-end, quarter, holiday seasons. Derive them from the timestamp after converting to the business time zone, otherwise an order placed at 23:30 local time on Friday can be counted as Saturday in UTC.
Illustrative listing.
features = (sales
.with_column("local_ts", sales.col("ts").to_zone("Asia/Kolkata"))
.with_column("year", col("local_ts").year())
.with_column("month", col("local_ts").month())
.with_column("weekday", col("local_ts").weekday()) # 0 = Monday
.with_column("week", col("local_ts").iso_week())
.with_column("is_weekend", col("weekday") >= 5)
.with_column("is_month_end", col("local_ts").is_month_end()))
Two rules keep calendar features reliable. First, document the weekday numbering convention, because tools disagree on whether the week starts on Sunday or Monday and whether numbering begins at 0 or 1. Second, use ISO week numbers with the ISO year; the last days of December can belong to week 1 of the next ISO year, and mixing calendar year with ISO week produces a phantom "week 1" in December.
Holidays are not derivable from the date alone. Keep them in a small, versioned reference table keyed by date and region, and join it in. That makes the holiday logic reviewable and lets different regions use different calendars.
1.4 Resampling to a regular frequency
Resampling changes the frequency of a series. Downsampling moves to a coarser frequency (hourly to daily) and needs an aggregation. Upsampling moves to a finer frequency (monthly to daily) and needs a fill or interpolation rule. Neither has a correct default: the right choice depends on the grain.
| Grain of the measure | Downsample with | Example |
|---|---|---|
| Flow (amount per period) | sum | Units sold, revenue, tickets opened |
| Level or balance | last (or mean for averages over the period) | Account balance, inventory on hand |
| Rate or ratio | recompute from summed numerator and denominator | Conversion rate, defect rate |
| Extremes | max or min | Peak load, lowest temperature |
Ratios deserve special care. The monthly conversion rate is total conversions divided by total visits, not the average of daily rates. Resample the numerator and denominator separately and divide afterwards.
Illustrative listing.
daily = (events
.sort("ts")
.resample("ts", every="1d", label="left", closed="left")
.agg(
orders = col("order_id").count(),
revenue = col("amount").sum(),
visits = col("visits").sum(),
)
.with_column("conversion", col("orders") / col("visits")))
Always state which edge of the bucket labels the period and which edge is closed. A daily bucket labelled "2026-10-01" normally covers 00:00 inclusive to 24:00 exclusive in the chosen time zone. A mismatch between producer and consumer conventions shifts every value by one period, an error that is invisible in a chart and devastating in a forecast evaluation.
1.5 Lag and lead
A lag shifts values forward in time so each row can see an earlier value: lag 1 on a daily series is yesterday. A lead shifts the other way so each row can see a later value. Lags are the most important features in forecasting because recent history is usually the best predictor of the near future.
Illustrative listing.
feat = (daily
.sort("date")
.with_column("rev_lag1", col("revenue").shift(1))
.with_column("rev_lag7", col("revenue").shift(7))
.with_column("rev_lead1", col("revenue").shift(-1))) # target only
Three rules apply:
- Shift by period, not by row, when gaps exist. If a date is missing, a row shift of 1 reaches two days back. Regularize the frequency first (Section 1.4 and Lesson 3) or use a time-based shift.
- Leads are targets, never features. A lead column contains the future. Using it as an input is leakage: the model looks brilliant in testing and fails in production.
- The first k rows of a lag k column are null. Decide explicitly whether to drop them or keep them with a flag; do not fill them with zero.
1.6 Differences and percentage change
A difference subtracts an earlier value from the current one: diff 1 is the day-on-day change, and diff 7 on a daily series is the change versus the same weekday last week. Differencing removes a level or a steady trend and is the standard first step before comparing periods or fitting simple models.
Percentage change divides the difference by the earlier value. It makes series of different sizes comparable, but it has two traps: it is undefined when the base is zero, and it is asymmetric — a fall of 50% followed by a rise of 50% does not return to the start.
Illustrative listing.
feat = (feat
.with_column("rev_diff1", col("revenue") - col("rev_lag1"))
.with_column("rev_diff7", col("revenue") - col("rev_lag7"))
.with_column("rev_pct7",
when(col("rev_lag7") > 0)
.then((col("revenue") - col("rev_lag7")) / col("rev_lag7"))
.otherwise(None)))
Return null, not zero or infinity, when the base is zero or missing, and report how many rows were affected. For series that span orders of magnitude, consider the change in the logarithm instead of percentage change; log differences add up across periods and are symmetric for rises and falls.
1.7 Annotated example: week-on-week sales report
A retail analyst needs a daily table showing revenue, the same weekday last week, the change, and the percentage change, for the last 28 days. The design decisions are:
- Resample the order events to days in the store's local time zone with sum, because revenue is a flow.
- Generate the full date range and left-join the daily totals, filling missing days with zero only after confirming that the store was open and the feed was healthy.
- Use lag 7, not lag 1, because weekday effects dominate retail sales.
- Return null percentage change where last week's revenue was zero, and list those days in the report footnote.
- Filter to the last 28 days after computing lags so the first week of the window still has comparison values.
The last point is a frequent source of errors: filtering first leaves the first seven rows of the report with null comparisons. Compute features on the full history, then select the reporting window.
Common mistakes
- Computing lags on unsorted data: sort by the time index (and group key) immediately before every shift.
- Mixing UTC and local dates: convert once, name the column clearly, and derive calendar features from the local version.
- Averaging rates during resampling: resample numerators and denominators, then divide.
- Using a lead as an input feature: leads leak the future; keep them only as targets.
- Filling missing days with zero by default: a missing day may be lost data, not zero activity. Check feed health first.
- Filtering before computing lags: the window loses its comparison values.
Guided practice
- Take an hourly event file and resample it to daily totals in two different time zones. Count how many days change value and explain why.
- Add lag 1, lag 7, diff 7, and percentage change 7 columns. Count the null rows each produces and justify the count.
- Introduce a duplicated day and a missing day into the data. Confirm that your validation function from Section 1.2 detects both.
Hands-on lab: A validated daily feature table
Scenario. You receive a CSV of order events with columns order_id, store_id, ts (UTC), amount, and visits. Build a daily feature table for one store.
- Load the file and validate the time index: nulls, sort order, and duplicate order IDs.
- Convert timestamps to the store's time zone and resample to days. Sum amounts and visits; count orders.
- Generate the full date range and left-join the daily table. Flag missing days in an is_gap column instead of filling them.
- Add calendar features: weekday, ISO week, month, is_weekend, and is_month_end.
- Add lag 1, lag 7, diff 7, and percentage change 7. Return null for zero bases.
- Write a short validation report: row count, date range, gap count, duplicate count, and null counts per derived column.
Expected result. One row per calendar day, no duplicate dates, gaps flagged rather than hidden, and a validation report that a reviewer can read without opening the data.
Review questions
- What four properties must be stated before a table is treated as a time series?
- Why must calendar features be derived after converting to the business time zone?
- How should a flow, a level, and a rate each be downsampled?
- Why is a row-based shift wrong when the series has gaps?
- Why is a lead column dangerous as a model input?
- What should percentage change return when the base is zero, and why?
- Why compute lags before filtering to the reporting window?
Applied challenge
A finance team reports monthly revenue and month-on-month growth. Their source is a ledger of transactions in UTC from stores in three time zones. Design and implement the pipeline: per-store local monthly totals, a combined total, month-on-month change and percentage change, and a reconciliation that proves the monthly totals sum to the ledger total. Document every convention you chose — bucket edges, time zones, and treatment of zero bases.
Lesson summary
A time series is a table whose order is defined by a validated time index with a known frequency, time zone, and grain. Calendar features come from local time; resampling must match the grain; lags and differences require a regular, sorted series; leads are targets only; and percentage change needs explicit handling of zero and missing bases. Compute features on the full history and select the reporting window last.
Transition to Lesson 2
Lags compare one point with another. Lesson 2 summarizes many points at once with rolling, expanding, and exponentially weighted statistics.
Lesson status: Ready for review.