Dealing with Financial Time Series in SQL: Sessionization, Gaps, and Contiguous Intervals – No Stored Procedures Required

Financial time series calculations are rarely simple SQL queries. Three kinds are common: splitting an account’s transaction records into sessions based on the time gap between them; filling in the prices missing on days a stock is halted; and finding the longest run of consecutive gains in a series of closing prices. In SQL, all three have one thing in common: they produce intermediate states along the way, such as session groups, the source of each filled value, and interval numbers, and these intermediate columns never appear in the final result set.
There must be a place to store the intermediate states. The common approach is to write a stored procedure or create temporary tables, save the intermediate results there, and process them step by step. There’s nothing wrong with this approach, except that the intermediate states end up locked inside the procedure: change one condition and you have to re-read the whole procedure, and you can’t stop at an intermediate step to check the result. This article introduces a different approach to deal with three financial time-series examples. No stored procedure and temporary tables are required, only a few easy-to-read steps that keep the intermediate state in each result table. Each step runs on its own. Each can be checked on its own, and the compiler then generates native SQL.
Of course, modern AI can write this logic as a single SQL statement. But whether a human or an AI writes it, the statement becomes too complex. It‘’s hard to audit for correctness, and hard to debug when something goes wrong. So, the hard part isn’t writing the SQL. It’s whether the result can be audited and validated at low cost. The step-based approach makes that easy for analysts, and it suits AI generation better too.

Sessionization: Where does one session end and the next begin?

The first kind is sessionization. A transaction activity table records accounts and transaction timestamps, and the task is to split each account’s transactions into sessions: a transaction that comes within one hour of the previous one belongs to the same session, and one that comes more than an hour later starts a new session. Besides the session number, you also need the sequence number within each session. Here’s the conventional SQL:
SELECT account, trade_time, session_id, seq
FROM (
  SELECT account, trade_time, session_id
    , ROW_NUMBER() OVER (PARTITION BY account, session_id ORDER BY CASE
      WHEN account IS NULL THEN 1
      ELSE 0
    END, account ASC, CASE
      WHEN trade_time IS NULL THEN 1
      ELSE 0
    END, trade_time ASC, account) AS seq
  FROM (
    SELECT account, trade_time
      , 1 + SUM(CASE
        WHEN (prev_time + INTERVAL 3600 SECOND <= trade_time) THEN 1
        ELSE 0
      END) OVER (PARTITION BY account ORDER BY CASE
        WHEN account IS NULL THEN 1
        ELSE 0
      END, account ASC, CASE
        WHEN trade_time IS NULL THEN 1
        ELSE 0
      END, trade_time ASC ROWS UNBOUNDED PRECEDING) AS session_id
    FROM (
      SELECT account, trade_time
        , LAG(trade_time) OVER (PARTITION BY account ORDER BY CASE
          WHEN account IS NULL THEN 1
          ELSE 0
        END, account ASC, CASE
          WHEN trade_time IS NULL THEN 1
          ELSE 0
        END, trade_time ASC) AS prev_time
      FROM trading_activity
    ) sub__3
  ) sub__4
) sub__5
ORDER BY CASE
  WHEN account IS NULL THEN 1
  ELSE 0
END, account ASC, CASE
  WHEN trade_time IS NULL THEN 1
  ELSE 0
END, trade_time ASC, account

This SQL runs correctly, but one computation is split across four layers of subqueries. LAG in the innermost layer gets the previous transaction timestamp; the next layer out computes cumulative sum over the gaps to get session_id; the layer after that uses ROW_NUMBER to generate sequence numbers (seq); and the outermost layer just picks four columns and sorts them. The session_id is an intermediate column, and the boundary condition sits inside a CASE expression. To check an account’s session boundaries, you have to compare the final result with the original data and trace back row by row. Change the threshold value, and all four layers need to be re-validated.
If the intermediate states are invisible, you can’t verify them along the way. The step-based approach takes a different line: make each intermediate state an actual column in the result table, rather than hiding them inside a subquery or a temporary table. The three examples below are all implemented in SQLazy. SQLazy turns the logic into a workflow of ordered steps. Each step runs on its own, and the result can be viewed separately.
Sessionization takes three steps in SQLazy:


Name

Anchor

Statement


trading_activity

sort account asc, trade_time asc



segment condition ((trade_time[-1] elapse 3600 second)<= trade_time) partition account as session_id



compute # as seq partition account, session_id

Step 1 is sort account asc, trade_time asc. This sorts the focus table by account and then by trade time. Every later reference to a relative position depends on this order, so sorting has to come first.

Step 2 is the core. segment generates group number for each record within each account in order. Increment the group number by 1 whenever the condition holds. A conditional expression is used here: trade_time[-1] is the previous row’s trade time (a negative number in square brackets represents a relative position), and elapse 3600 second moves that time one hour later. As a whole, the condition judges whether “the previous row’s time plus one hour” is no later than the current row’s time”. <= means a row exactly one hour after the previous one still belongs to the same session; with <, a record on the boundary would be cut into a new session. partition account makes each account number independently, without affecting each other. The result of this step is that each session ends up with its own session_id.

Step 3 is compute # as seq partition account, session_id. This computes sequence numbers within each session. # is the row number column. After rows are partitioned by account and session, row numbers restart from 1 in each partition, and those are exactly the sequence numbers we expect.

At this point, session_id and seq are both actual columns in the result table, so you can query and inspect them directly. Let’s check the boundaries against the data. For example, account A1024’s first two transactions, at 09:31:05 and 09:58:40, are less than one hour apart, so both belong to session 1; the next one, at 11:02:11, comes more than one hour after 09:58:40 (09:58:40 plus one hour is 10:58:40, which is earlier than 11:02:11), so a new session starts there, and seq restarts at 1. Account B2048’s three transactions, at 14:05:33, 14:47:10, and 15:02:00, are all within one hour of each other, so they all belong to session 1, with seq values being 1, 2, 3 in order.

Picture4png
The three steps are for humans to read. The database still needs SQL, so the next step is compilation. The compiler translates the workflow into native SQL for the target database, such as Oracle, MySQL, and Hive. The generated SQL runs as is. To switch dialects, compile the same SQLazy code again.

Picture5png
The compiled SQL uses CTEs to separate the intermediate results, so it is clearer and easier to modify than the multilayer nested SQL above.

WITH Value_2 AS (
    SELECT account, trade_time
      , 1 + SUM(CASE
        WHEN (col__2 + INTERVAL 3600 SECOND <= trade_time) THEN 1
        ELSE 0
      END) OVER (PARTITION BY account ORDER BY CASE
        WHEN account IS NULL THEN 1
        ELSE 0
      END, account ASC, CASE
        WHEN trade_time IS NULL THEN 1
        ELSE 0
      END, trade_time ASC ROWS UNBOUNDED PRECEDING) AS session_id
    FROM (
      SELECT Value_1.*
        , LAG(trade_time) OVER (PARTITION BY account ORDER BY CASE
          WHEN account IS NULL THEN 1
          ELSE 0
        END, account ASC, CASE
          WHEN trade_time IS NULL THEN 1
          ELSE 0
        END, trade_time ASC) AS col__2
      FROM Value_1
    ) sub__3
  )
SELECT account, trade_time, session_id
    , ROW_NUMBER() OVER (PARTITION BY account, session_id ORDER BY CASE
      WHEN account IS NULL THEN 1
      ELSE 0
    END, account ASC, CASE
      WHEN trade_time IS NULL THEN 1
      ELSE 0
    END, trade_time ASC, account) AS seq
FROM Value_2
ORDER BY CASE
  WHEN account IS NULL THEN 1
  ELSE 0
END, account ASC, CASE
  WHEN trade_time IS NULL THEN 1
  ELSE 0
END, trade_time ASC, account

Gaps: Carrying prices forward through trading halts

The second kind is gap filling. In the market data table, dates with a trading halt or missing data still have records, but the price is NULL. Before time-series analysis, you need to fill these NULLs with the nearest preceding valid price for the same stock. In other words, during a halt, the last price from before the halt carries forward.

Here’s the SQL implementation:

SELECT ticker, quote_date,
    MAX(close_price) OVER (PARTITION BY ticker, grp) AS close_price
FROM (
    SELECT ticker, quote_date, close_price,
        SUM(has_quote) OVER (
            PARTITION BY ticker ORDER BY quote_date
            ROWS UNBOUNDED PRECEDING
        ) AS grp
    FROM (
        SELECT ticker, quote_date, close_price,
            CASE WHEN close_price IS NOT NULL
                THEN 1 ELSE 0 END AS has_quote
        FROM quote_gap
    ) flag_rows
) grp_rows
ORDER BY ticker, quote_date;

Again, three layers of nested subqueries. The innermost layer judges whether the price is NULL. The next layer out computes cumulative sum to get the group number. The outermost layer takes the maximum price within each group and fills it back. Group number grp is a computed value, and the backfilling depends on a window MAX. From this SQL alone, you can’t tell which price filled a given day’s NULL. You have to split it up and run the pieces.

The task takes 4 steps in SQLazy:

Name

Anchor

Statement


quote_gap

sort ticker asc, quote_date asc



compute if((close_price notnull) then 1 else 0) cum as grp



compute max close_price as filled_price; partition grp



derive ticker, quote_date, filled_price as close_price

Step 1 sorts data by stock and date. ticker can’t be omitted: a NULL can only be filled with the price from the directly previous row of the same stock, and including the ticker in the sort keeps different stocks from getting mixed together.

Step 2 generates the group marker. notnull judges whether a value is non-NULL, if returns 1 or 0 depending on the result, and cum computes a cumulative sum. As a result, every position where a valid price appears advances the group number by one, and the consecutive NULLs after it fall into the same group. grp is the most critical intermediate state in the whole logic, and the hardest column to validate with the traditional approach.

Step 3 reads compute max close_price as filled_price; partition grp. This takes the maximum closing price from each group. In each group, only the first row has a valid value and the rest are NULL, so the maximum is the group’s only valid price.

Step 4 changes the filled columns back to their original names, and output three columns: stock, date, and closing prices.

Check it against the data. For example, AAPL’s prices on 2024-01-03 and 01-04 are NULL. They fall into the same grp, and filled_price is 185.64 for both. 01-09 falls into the group of 185.56. To see which price filled which NULL, just look at grp and filled_price columns. Note that the group number runs continuously across stocks: MSFT’s first row follows AAPL’s last, and numbering does not restart at 1. Since the fill is partitioned by grp, each group contains only one stock, so the result is not affected.

SQL and stored procedures are both hard to debug for this kind of logic. The intermediate results either sit in temporary tables or are buried in subqueries built around window functions, so when something is off, the only option is to edit the whole block of code and rerun it to see whether the result changes. Financial time series have large data volumes and many boundary cases, so repeated trial and error costs even more. SQLazy offers step-by-step execution: each click runs one step, and the results of the current step and all earlier steps are visible, so you can see directly at which row grp jumps.

Picture6png

Contiguous intervals: no order-dependent logic in nested subqueries

The third kind is contiguous intervals. A market data table records daily closing price of each stock. The task is to find the start date and the end date of the longest interval of consecutive gains for a given stock. Note that several intervals may tie for the longest length.

Below is the SQL:

with seq_calc as (
    select DT, CL,
        sum(UpDownTag) over(order by DT) NoRisingDays
    from (
        select DT, CL,
            case when CL>lag(CL) over(order by DT)
                then 0 else 1 end UpDownTag
        from stock
        where CODE = 100046
    ) tag_calc
),
streak_len as (
    select NoRisingDays, count(*) ContinuousDays
    from seq_calc
    group by NoRisingDays
)
select start_date, end_date
from (
    select NoRisingDays,
        min(DT) as start_date, max(DT) as end_date
    from (
        select DT, NoRisingDays
        from seq_calc
        where NoRisingDays in (
            select NoRisingDays
            from streak_len
            where ContinuousDays = (
                select max(ContinuousDays) from streak_len
            )
        )
    ) target_rows
    group by NoRisingDays
) agg_rows;

This SQL uses two common CTEs to pull out the LAG and cumulative-sum logic, and that part is reasonable. The problem is in the second half: it first aggregates the length of each interval, then compares it with the maximum, then goes back to the interval groups to get the first and last dates. Several layers of subqueries sit in between, and NoRisingDays and the date columns are passed up through them layer by layer. To add a filter condition anywhere in there, you have to work through the layers from the inside out and confirm that none of them has its meaning broken.

The task takes six steps in SQLazy:

Name

Anchor

Statement


stock

filter CODE = 100046



sort DT asc



segment CL down as NoRisingDays



compute count DT as ContinuousDays; partition NoRisingDays



rank ContinuousDays max



summarize min DT as start_date, max DT as end_date; group NoRisingDays

Step 1 filters for the target stock. Step 2 sorts by date in ascending order, because the order determines the direction of the “rise” comparison.

Step 3 reads segment CL down as NoRisingDays. This is the fixed-condition form. down means the group number goes up by one when the current value is less than the previous row’s. So, whenever a closing price is lower than the day before, the interval number changes, and every run of consecutive rises gets the same interval number.

Step 4 partitions by interval number and counts the rows, which gets the number of days in each interval. Step 5 reads rank ContinuousDays max, where max is the filter condition. The condition gets all records that match the maximum value, not just one. This matters. If two intervals in the stock’s history tie for the longest length, both are retained and neither is dropped.

Step 6 groups by the interval number and takes the earliest and the latest dates, which are the start and end dates of each longest interval.

Here, too, the intermediate states are visible. NoRisingDays is the interval number, and ContinuousDays is the interval length. The result records of step 5 directly show which intervals are the longest.

As before, the compiler handles these six steps, and the generated native SQL runs as is.

In closing

Looking back, all three examples do the same thing. They take a process that originally happens in phases out of a single end-state SQL statement or a stored procedure, and turn it into a sequence of ordered steps. Intermediate states such as the session number, the group marker and the interval number are temporary values hidden in subqueries and temporary tables in the conventional approach. Here, they are actual columns in the result table.

This approach has a cost, too. It isn’t worth it for simple filters or simple CRUD: no need to split into steps what one SELECT statement can do. It is intended for analytical logic that is complex enough. There’s nothing wrong with writing a stored procedure, except that the intermediate states are locked inside it. Nobody else can validate it step by step, and whoever takes it over can only guess.

AI writes the logic. A compiler writes the SQL.

If you also have time-series logic of your own that’s hard to maintain, run it in SQLazy and see how many steps it becomes.

Example library: https://github.com/SPLWare/SQLazy/tree/master/examples