Skip to content

Forecasting System — Technical Documentation

Overview

The forecasting system forecasts future member spending (turnover) for deals (PSAs/arrangements) based on historical data. It uses a statistical model combining historical averages, seasonal adjustment, year-over-year growth trends, and a self-correcting accuracy feedback loop. Projected turnover then feeds into rebate calculations so users can see estimated future rebate payments alongside actual ones.

The model itself is projectionModel (one per 3.8 module): a plain SQL builder that takes a deal, an as-of date and a correction factor and returns the SELECT producing one projected row per member, stream and month. Every read of turnover is limited to periods before the as-of date and recency is measured from it. figuresService.storeMonthlyProjections() wraps that SELECT in an INSERT into turnoverProjection with as-of = now; the backfillProjections task wraps the same SELECT in an aggregated INSERT into projectionHistory with as-of = a past month, so historical snapshots are a true replay of the live model rather than a second one. doProjectionHistorySnapshot(), getCorrectionFactor() (which delegates to the model), getProjectionAccuracyReport() and purgeExpiredProjections() sit alongside in figuresService. The spend calendar reads the history through spend.calendarProjections.


The Forecasting Formula

Each projected monthly value is calculated as:

projected_value = avg_historical_value
                × seasonality_factor
                × POWER(1 + annual_growth_rate, months_ahead / 12.0)
                × correction_factor

Exactly one projected row is produced per member, stream (figures entry) and month. That matches the dupeLock unique key on turnoverProjection (figuresID, period, memberID); if the model ever produced two rows for the same key, only the last one written would survive.

Component Breakdown

1. avg_historical_value

A recency-weighted mean (exponential decay, 5% per month) of all actual turnover values for a given member + stream combination, across all historical periods, less the stream's outlier months (see Outlier months below). This establishes the baseline "typical monthly spend" for each member-supplier relationship.

The grouping is deliberately only member + stream. It must not include contactID or the denormalised name columns: imported rows carry contact 0 while supplier submissions carry the submitting contact, so grouping on them split one member's history into several partial series, each projected on its own, and the single-month "average" of the most recent submission frequently won the duplicate-key race. That bug (October 2026) roughly doubled many deals' projections.

Only members with activity in the last 12 months are included — if a member hasn't submitted any spend data in a year, they are excluded from projections entirely (assumed inactive). Once a renewal has three or more months of its own figures, a member inherited from its predecessor must also have reported on the renewal itself: otherwise a member who left at the renewal would be projected for a year on the strength of the old deal (about £0.5m a month across site 183's April 2026 renewals). Rows dated before the deal's start month are ignored (they are placeholders, typically zeros).

Occasional buyers

A member stream that was bought in half or fewer of its last 12 reported months (with at least three months reported) is flagged sporadic. Its projection is unchanged, the average month including the zeros, because nobody can predict which month an occasional buyer will buy in and any rule that zeroed some months and loaded others would be wrong more often, and wrong in the totals and projected rebates too. What changes is the display: the flag, with the count of months bought in, is stored on each projected row (turnoverProjection.sporadic, activeMonths, windowMonths) and the agreement's Spend grid shows those cells muted with a tooltip saying the figure is an average month.

Outlier months

A month that is totally out of line with the rest of a series is not a reliable benchmark, so it does not count in an average. The rule is projectionModel.outlierMonths(), and the projection SELECT applies the same rule in SQL (the MemberOutlierMonths and DealOutlierMonths blocks) so the live model, the backfill, the track-record switch and the Projection Analyser agree on which months are ignored. It is applied twice: to each member stream's months for the model's baseline, and to the deal's monthly money totals for the simple method.

A month is an outlier when all of the following hold:

  • the series has at least six reported months and its median month is above zero;
  • the month's distance from the median is more than 3.5 scaled median absolute deviations (MAD × 1.4826, the usual modified z-score cut-off) and more than half the median, so a very steady series does not flag ordinary noise;
  • neither neighbouring month is out on the same side. Two or more high months in a row are a new level (a renewal at a different scale, a member joining), not a blip, and are kept; the first month of a step change is the one case that is excluded until the next month confirms it;
  • no more than a quarter of the series' months qualify. If more would go, the series is volatile rather than steady with blips, and every month of it is evidence, so nothing is excluded.

Low months are excluded as well as high ones: a partial submission misleads an average as much as a one-off order. The rule is scale-free, so it treats a £500 stream and a £500k deal alike. Nothing else changes: an excluded month is still actual turnover everywhere it is shown, still counts as a reported month for the occasional-buyer test, and is still scored against both methods when the switch decides which to publish. The constants are OUTLIER_MIN_MONTHS (6), OUTLIER_MAD_MULTIPLIER (3.5), OUTLIER_MAD_SCALE (1.4826), OUTLIER_MIN_RELATIVE (0.5) and OUTLIER_MAX_SHARE (0.25).

On site 169's live deals as of October 2026 the rule removes 30 of 692 deal-months; on site 18, 101 of 5,607. The largest case was Aico at site 169, whose £8.3m March 2026 against a £1.5m typical month had lifted the deal's average month to £2.3m.

Seasonality factors and year-on-year growth are built from the same turnover but are not filtered by this rule: a spike in one deal-year is already diluted by volume weighting across years and deals, and growth already drops moves beyond ±50%.

Renewals inherit their predecessor

Most deals renew each year as a new arrangement, and the renewal has no history of its own until its first month is reported. When arrangement.previousDealID points at a deal on the same site for the same supplier, the model treats that deal's turnover up to the renewal's start month as the renewal's own history:

  • each predecessor stream is mapped onto the renewal's stream with the same inputCode (when both carry one) or, failing that, the same name and input type; a predecessor stream with no counterpart is left out. Rebate calculation reads projected rows by the deal's own figuresEntry ids, so an inherited row must carry the successor's stream id or it would be invisible to projected rebates;
  • inherited rows take the successor stream's category, and are rescaled once the renewal has two or more months of its own on the mapped streams: by the renewal's total for those months over the predecessor's total for the same calendar months a year earlier (capped to 0.25–4). A renewal at a different scale (Kartell went from £150k to £400k a month in April 2025) still gets its predecessor's pattern, at its own level;
  • only the immediate predecessor is used, never a chain;
  • the correction factor's comparisons include the predecessor's, so the feedback loop carries across the renewal (within its six-month window, see below).

This means a renewal can be projected before it has any figures, as soon as it exists with its predecessor linked and its streams defined. The monthly task includes deals that start within the next three months for that reason, so a January renewal created in November carries projections, and projected rebates, from the 1 December run. A deal with no linked predecessor (or whose predecessor has no turnover) is still unprojectable until it has reported a month; the Projection Analyser labels that spend.

2. seasonality_factor

A per-calendar-month multiplier that captures seasonal spending patterns. It is built from monthly totals of money streams only (unit types 1, 105 and 109; quantity and weight streams are never averaged with pounds), normalised within each deal-year:

factor(deal, year, month) = monthly_total(deal, year, month) / average_month(deal, year)
seasonality_factor(month) = volume-weighted AVG over deal-years of factor(deal, year, month)

Normalising per deal-year rather than per supplier-calendar-year matters because deals renew and change scale mid-year. Kartell's old deal ran at £150k a month in Jan–Mar 2025 and its renewal at £400k from April; normalised across the calendar year that read as "January is 0.42 of a normal month" and dragged the following January's projection 40% low. Within a deal the scope is constant, so the scale step never enters. Months with no money turnover are ignored (they are placeholders), deal-years with fewer than six months are ignored, and deal-years are weighted by volume so a small deal's noise does not swamp a large one. Only the last four years are read.

Two levels are tried in order:

  1. Supplier seasonality — the supplier's own pattern across the whole site, used when the month has at least two deal-years of data.
  2. Site/category seasonality — the same construction over all turnover in the deal's categories, used when it rests on at least two different deals (a category that is one other supplier's deal is that deal's history, not a pattern).
  3. If neither exists, the factor is 1.

3. annual_growth_rate

Year-over-year growth, computed only between consecutive, complete calendar years (12 distinct months of money turnover) using LAG():

yoy = (this_year - last_year) / last_year

A year-on-year move beyond ±50% is treated as bad data (a member or category that was only partly tracked in the earlier year) and dropped rather than averaged in. Partial years — including the current one — never take part. The member's own growth is used when it has at least two usable year-on-year points, otherwise the deal's category growth, otherwise 0% (flat).

The growth is applied as compound interest over fractional years via POWER(1 + rate, months_ahead / 12.0). A projection 6 months out applies half a year's growth; 18 months out applies 1.5 years.

4. correction_factor

A self-correcting bias adjustment derived from comparing past projections against actual outcomes. This is the feedback loop that makes projections improve over time.

correction_factor = SUM(actual) / SUM(projected)

over every projection of this deal (or its predecessor) snapshotted in the last six months that was made 1 to 12 months ahead of the month it describes, compared at the grain the history is stored at (deal / month / category / sub-category / supplier). A ratio of sums is used rather than an average of row ratios so that small, volatile categories do not dominate.

The window matters. A pooled all-time ratio never forgot anything: the thin early snapshots of a lineage (projecting a whole year from a few months of a smaller predecessor) left site 183's renewals carrying a factor of about 1.2 through 2026, on top of months they were already over-projecting, and the model's one-month-ahead accuracy fell to 91%. With the window it is about 98%.

If projections have been systematically 15% too high, the ratio will be ~0.85, meaning future projections will be multiplied by 0.85 to compensate.

Currently switched off. CORRECTION_STRENGTH in projectionModel scales how much of the measured bias is applied (1 = the full ratio, 0 = none) and is set to 0 since 28 October 2026. On site 183's replay the factor behaved as a lagging multiplier: a strong January and February lifted the next six months of a deal by 26% just as its spend fell back, and over the whole site it lowered one-month-ahead accuracy in three of four tested snapshots. The ratio is still calculated and logged (the backfill prints correction=) so it can be re-enabled, but the feedback loop now works by choosing the method instead - see Which method is published.

Safeguards: - Minimum data threshold: Requires at least 6 completed comparison rows before applying any correction. New deals or deals with limited history get a factor of 1.0 (no adjustment). - Cap: Clamped between 0.5 and 1.5 to prevent extreme corrections from bad or anomalous data. - Error handling: Any error in the correction calculation falls back to 1.0 silently (with error logging).


What is published: the model, moved towards the simple method on its track record

Every projection run decides, per deal, how far to move the model's figures towards the simple method: the deal's reported months to date, averaged, times the site's rebateProjectionPercentile (the same figure the Projection Analyser shows as "simple"). A renewal's months to date include its predecessor's months before the renewal began, as the model's history does, until the renewal has reported three months of its own (SIMPLE_OWN_MONTHS); from then on only its own months are averaged, so a deal running well above or below last year is not pulled back to last year's level. From that point the percentile is also applied to the whole deal year, not only to the months still to come: the year is put at average month × months in the deal × percentile, and what has not yet been reported is spread evenly over the months after the last reported one (projectionModel.simpleMonthly(); never below zero). That is the hand calculation to date / months × 12 × percentile, so the simple year end equals it. A deal longer than SIMPLE_YEAR_MAX_MONTHS (12) keeps the plain average month × percentile, as does a renewal still on its predecessor's months. projectionModel.chooseMethod() scores the two on the deal's last three reported months, one month ahead and like for like:

  • the model's figure for month M is the newest snapshot in projectionHistory taken before M started (its modelValue, so a month that was published as a blend still scores the model, not the blend);
  • the simple figure for M is the average of the months reported before M, less any outlier months among them (the same rule the published simple figure applies, so the switch scores the figure it would publish), times the percentile (applied over the whole deal year once the deal is on its own months, as described above);
  • both are compared with the actual money turnover for M and the absolute errors are summed. When the model's total over the window is more than SWITCH_MODEL_NET_TOLERANCE (5%) away from the actual total, the published figure is the model's moved towards the simple method's by simpleWeight = model error / (model error + simple error): equally accurate splits the difference, and the worse the model has been the further it moves. Each stream's published value is modelValue + simpleWeight × (simpleValue − modelValue), so the published figure always lies between the two and a deal no longer flips from one method to the other from month to month. The 5% test is on the total, not the months, so a model that is right overall but a month out (a high February that lands in March) is left as it is. Until 24 Nov 2026 this was an all-or-nothing switch scored over six months; history from then carries method = 'simple' for months published wholly by the simple method.

With fewer than three comparable months the model is published as it is. A renewal is scored on its lineage: for the months before it began, the predecessor's actuals and the predecessor's snapshots stand in for its own, so the choice carries across a renewal rather than resetting to the model. The constants are SWITCH_LOOKBACK_MONTHS (3), SWITCH_MIN_MONTHS (3), SWITCH_MODEL_NET_TOLERANCE (0.05), SIMPLE_OWN_MONTHS (3) and SIMPLE_YEAR_MAX_MONTHS (12).

The SELECT built by buildProjectionSelect() always computes both figures per member and stream. value is the published one; modelValue is the model's; method is model when the model was published as it is and blend when it was moved (the weight is not stored: it is (modelValue − value) / (modelValue − simple), which is how the Analyser shows it). All three are stored on turnoverProjection and carried into projectionHistory by the snapshot. A simple-method deal figure is computed exactly as the Analyser computes it, from turnover directly: the lineage's turnover to date (the renewal's own months only once it has three), less the deal's outlier months, divided by the months that remain, times the percentile (applied over the whole deal year once the deal is on its own months, as described above). It is then shared out across the streams the model would project, in proportion to each stream's own lineage turnover (per unit type), so the streams add up to the deal-level figure even where predecessor streams map onto nothing on the renewal or a member has since left.

Why a switch rather than a blend: the simple method is flat and ignores seasonality, but on site 183's history it was within 10% of actual at most sliders, while the model is better on deals with a clear seasonal shape and worse on erratic ones. Letting each deal's own recent record pick the method keeps the model where it earns its place and falls back to the figure users already trust where it does not.

Member Lifecycle Handling

The projection engine respects member leave dates. For each member in the deal, it looks up company.leaveDate:

  • If a member has a valid leave date, projections stop at that month — no projected spend is generated for months after the member leaves.
  • If a member has no leave date (or 0000-00-00), projections continue to the deal's period_to date.

Projection Date Generation

Future months are generated using a recursive CTE that starts from the month after the last actual turnover entry and increments month by month up to the deal's period_to date (extended by projections.minimumProjectionMonth months when the deal is about to end and that setting is configured).


When projections are rebuilt

storeMonthlyProjections() runs for a deal when turnover is imported for it, when an amendment is confirmed, when the admin "calculations" reindex runs, and once a month from the scheduled task projectionsMonthly (03:00 on the 1st) for every deal that has not ended, starts within the next three months, and has turnover of its own or a linked predecessor's. The monthly task first calls purgeExpiredProjections(), which removes the projected rows of any deal whose period_to has passed, so a deal that ends or stops reporting no longer carries stale projections into the spend calendar, the projection search index or site totals.

Setting up a renewal so it is projected from day one. Create the new arrangement with previousDealID set to the deal it replaces (same site and supplier) and its streams named as on the old deal (or carrying the same inputCode). Nothing else is needed: the next monthly run, or a "calculations" reindex of the deal, projects it from the old deal's history. A stream whose name changed on renewal simply has no history until the renewal reports it; an explicit mapping would need a column on figuresEntry and is not built.


Projection history and snapshots

After every rebuild, doProjectionHistorySnapshot() copies the projected money values just built to projectionHistory, aggregated per deal / month / category / sub-category / supplier (memberID and figuresID are stored as 0). Each snapshot records dataThrough, the month its figures ran to (the month before the first projected month), and monthsAhead, how many months beyond that each projected month lies. The unique key uk_history is (snapshotDate, psaID, period, subCategoryID, categoryID, supplierID, siteID), so every rebuild is its own snapshot. A rebuild repeated before new figures arrive simply adds another snapshot with the same dataThrough; readers take the newest.

The original key had no snapshotDate and no category/supplier, so later runs silently overwrote earlier ones while keeping the old date, and the categories of a deal collapsed into one row; ensureProjectionSchema() rebuilds the key and adds dataThrough on first use after deploy (see projections-schema-migration.sql). History written under the old key is not a point-in-time record and should be regenerated with the backfillProjections task (:reset=true replaces a site's earlier backfill rows), which replays the live model one snapshot per month from the turnover history.

The spend calendar "time machine"

The Projection Analyser slider selects the month figures are known through (S): the right-hand end is the last completed month, each step left is one month earlier. Actuals run from 12 months back to the last completed month, and so do the projections on the site Analyser; the deal page asks for them to carry on 12 months past it (monthsAhead), so its chart shows the forecast ahead of the slider position. For every month M in that range, spend.calendarProjections takes, per deal, the newest snapshot whose dataThrough is the latest month on or before min(S, M − 1):

  • months up to S show the last projection made for them before they began (from figures to the month before);
  • months after S, including those not yet completed, show the projection built from figures to S.

Deal boundaries are marked ("new deal") on the charts and the deal grid, so an empty projection for a deal with no linked predecessor reads as what it is.

So at the latest position every month is compared with the most recent projection that existed for it, and moving the slider back answers "what did the figures to that month say about the rest of the year". Because snapshots are selected by the month their figures ran to rather than by when they were run, "February" means February's figures were in, however late they were submitted. The back-test lines and the Back-test accuracy figure compare each method like-for-like over the completed months of the selected year: the actual spend of the supplier-months that method projected against what it projected, with the share of all actual spend that covers shown alongside. A deal's first month is projectable only when the deal is linked to a predecessor (see Renewals inherit their predecessor); otherwise it is drawn as actual but falls outside both methods' coverage, and the month detail panel labels that spend.

Alongside the model, the endpoint returns the simple method for the same months so the two can be compared on equal terms: for each deal and month, its total money turnover from its start to min(S, the month before), divided by the months it had reported by then, multiplied by rebateProjectionPercentile / 100 from the site settings (applied over the whole deal year once the deal is on its own months, as described above). That is the per-month form of the familiar (existingTotal / existingMonths) × 12 × percentile annual estimate, done the way a category manager would do it by hand. A renewal (arrangement.previousDealID, same site and supplier) counts its predecessor's reported months before its own start, so both methods project a renewal's first months from the deal it replaced and the comparison is like for like; once the renewal has reported three months of its own, only its own months are averaged. A deal with nothing reported by then gets no simple figure for that month. Outlier months are left out of the average here too (see Outlier months), and each supplier's simple block carries the months it ignored (outlierMonths, as of S) so the Analyser can show which months the figure rests on. The Projection Analyser shows both totals and both accuracy rates, scored identically, behind a "Simple method" toggle (off by default, remembered per browser).

The Analyser's chart is an area spline. Actual is the filled line. Each method has a solid back-test line up to the slider month (what it projected for each month before that month began) and a dashed projected line from there to the end of the year (what the figures to the slider month project). It shows running totals to begin with, or each month's own figure. In running totals the right-hand end of each line is the year end and is labelled with it; in a running total a back-test line uses the actual for any deal-month the method did not project, so its distance from the actual line is only what the method got wrong. Bars (off to begin with) add each month's own figures behind the lines, on their own right-hand axis under running totals. Both choices are remembered per browser. Above the chart one line gives the key figures: actual to date, the year end by each method (actual turnover for the selected year up to the slider month plus the method's figure for the rest of that year) and the back-test accuracy of each. Because the simple method applies the percentile to the whole deal year, its year end for a calendar-year deal is to date / months × 12 × percentile. The Analyser asks the endpoint for projections to the end of the calendar year for this (monthsAhead).

The calendar's actuals window ends at the end of last month in both endpoints: the current month never has spend yet because turnover is submitted in arrears.

The review list

The same response carries a review block for the month after S: for each deal with a snapshot built from figures to S, the figure that was published for that month and the method it came from, the model's own figure beside it, and the simple figure for the same month. Where the model and the simple method differ by more than 25% of the larger, the deal is flagged. The Analyser's Review view lists the flagged deals (or all projected deals) with a badge showing which method is in the forecast, so the deals where the two methods disagree most can be looked at by a person rather than trusted to either. At the latest slider position that is next month's forecast; moved back, the review month has completed, its actual is shown and each row says which method came closer.

One deal at a time

A deal's Spend tab shows the same Analyser underneath the grid while its Projections switch is on, scoped to that deal: <projection-analyser psa-id="…"> (defined with the Analyser controller in turnover/calendar.js, lazy-loaded by the agreements state) passes the deal's id to both endpoints, which then return only its actuals, snapshots, simple figure and review row. The deal's own months are shown; a renewal's simple figure still counts its predecessor's months until it has three of its own.


Accuracy Tracking

How Accuracy Is Measured

getProjectionAccuracyReport() joins projectionHistory (projections made ahead of their month, monthsAhead > 0) to actual money turnover rolled up to the same grain.

Variance formula:

variance% = (actual - projected) / projected × 100

  • Positive variance = under-projected (actual exceeded forecast)
  • Negative variance = over-projected (forecast exceeded actual)

Accuracy bands: - Within ±5% = accurate - Within ±10% = acceptable - Beyond ±5% = over/under-projected

The scheduled task projectionAccuracyCheck logs this report for the last 12 complete months.

The Self-Correction Loop

The accuracy data feeds back into projections:

projectionHistory (past predictions, modelValue per month)
        ↓
    compared with turnover (actual outcomes) for the deal's last three reported months
        ↓
    chooseMethod(): model error vs simple error
        ↓
    the model, moved towards simple by its share of the error, is published (method, value, modelValue stored)
        ↓
    New projections stored → snapshotted to projectionHistory
        ↓
    (cycle repeats)

Each run learns from the last three months of one-month-ahead comparisons. The window is deliberate: an all-time pool lets a bias from a year ago outweigh what the model has got wrong recently. The correction factor (a multiplier on the model's figures) is still measured, over its own six-month window, but is not applied: see CORRECTION_STRENGTH above.


Diagnosing a deal

The verifyProjectionModel task runs the model for one deal as of a date and prints the projected total per month and unit type (:psaID=78727 :asOf=2026-01-01); :version=v3_8_1 runs another module's copy of the model, which is the quickest way to see what a model change does to a deal. The backfillProjections task takes the same :version= (default v3_8_2), so a replayed history carries that model's rules, the outlier-month exclusion included. The diagnoseProjections task is a read-only command-line task that reports, for a site, the history key, snapshots per day, what the calendar endpoint would return, current projections against trailing actuals per deal, the unit-type mix, and whether the feedback joins match; with :psaID= it adds a per-deal breakdown of baseline, seasonality and growth inputs.

Run it with :siteID=183, or :siteID=183 :psaID=78727 for the per-deal breakdown.


Example Scenario

A deal runs from Jan 2024 to Dec 2025. It's now July 2025. Actual turnover exists through June 2025.

  1. storeMonthlyProjections() is called for this deal.
  2. The system finds the last actual data is June 2025.
  3. Existing projections are snapshotted to projectionHistory with snapshotDate = now() and monthsAhead values of 1-6 (for Jul-Dec 2025).
  4. turnoverProjection is cleared and rebuilt with:
  5. Actual rows from Jan 2024 – Jun 2025 (copied from turnover)
  6. Projected rows for Jul 2025 – Dec 2025 (calculated)
  7. For the projections, suppose:
  8. Member A's historical average monthly spend is £10,000
  9. The September seasonality factor is 1.15 (15% above average)
  10. The annual growth rate is 5% (0.05)
  11. The correction factor is 0.92 (projections have been 8% too high historically)
  12. September is 3 months ahead
  13. Member A's projected September 2025 value:
    £10,000 × 1.15 × POWER(1.05, 3/12) × 0.92
    = £10,000 × 1.15 × 1.0123 × 0.92
    = £10,714
    
  14. When actual September data comes in later, the system can compare £10,714 against the real value, and this comparison feeds into future correction factors.