PeaBox Lab › PeaLang › Learn › Chapter 18 › Lesson 1

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:

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:

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 measureDownsample withExample
Flow (amount per period)sumUnits sold, revenue, tickets opened
Level or balancelast (or mean for averages over the period)Account balance, inventory on hand
Rate or ratiorecompute from summed numerator and denominatorConversion rate, defect rate
Extremesmax or minPeak 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:

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:

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

Guided practice

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.

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

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.

← Previous Next →