Skip to main content

07 - Cost forecasting AI: predict month cost before spend, burndown chart, anomaly alert

Controlling AI spend within the month: weekly-profile projection, burndown, anomalies with median and MAD, and thresholds measured in precision and recall.

What do you think about this article?

07 - Cost forecasting AI: predict month cost before spend, burndown chart, anomaly alert
AI Cost OptimizationPhoto:Pavel DanilyukPexels

At a Glance

Controlling AI spend within the month: weekly-profile projection, burndown, anomalies with median and MAD, and thresholds measured in precision and recall.

Controlling AI spend within the month: projection, burndown and alarms that do not ring for nothing

It is day ten of the month, you have spent a third of the budget and you wonder whether you will make it to the end. The answer you need is not the twelve-month forecast, but a month-end estimate that updates every day, an indication of when the budget would run out if the pace stayed like this, and a signal when something drifts from normal. This article builds the three pieces on four executed listings, with an invented and declared daily series, and measures something that is usually taken for granted: what alarm thresholds are worth, in precision, recall and delay.

The scope is deliberately narrow, because the long-term forecasting methods live elsewhere. The four-driver model, the comparison of methods with a retrospective test and the twelve-month scenarios are in the article on spend forecasting, and I do not repeat them: here you start from a budget that is already set and look at one month at a time. The daily data you work with comes from the log and the attribution described in the first article of the group and in the one on cost tracking.

Projecting the month: the simple average is wrong in a predictable way

The most common projection is the spend to date divided by the days elapsed and multiplied by the days in the month. It is fine if spend is uniform, and AI spend almost never is: a product used during office hours costs less at the weekend, and if the first days of the month contain more weekends than usual the projection underestimates, if they contain fewer it overestimates. The simplest remedy is to estimate a weekly profile (how much each day of the week weighs relative to the average) from the previous month, remove the profile from the observed days to obtain a level, and reapply it to the days that remain.

In the first listing the series has weekdays at weight 1 and weekends at 0.45, a slight growth of 0.4% a day and 6% noise with a fixed seed. The profilo function estimates the weights from last month, proiezione_con_profilo divides each observed day by the weight of its day of the week (the "deseasonalisation"), averages them and adds to the elapsed days the projection of the remaining days. The test month starts on a Wednesday, the previous one on a Friday: the profile does not depend on the calendar, and that is the point.

"""Projecting month-end spend from the days already elapsed: simple average against average with a weekly profile.
INVENTED DAILY series (high weekdays, low weekends, slight growth, noise with a fixed seed)."""
import random
from statistics import mean

PESO = [1.0, 1.0, 1.0, 1.0, 1.0, 0.45, 0.45]       # Mon..Sun: the real profile must be estimated from your data
def mese(giorni, primo_giorno, base, crescita, seme):
    rng = random.Random(seme)
    return [base * (1 + crescita) ** g * PESO[(primo_giorno + g) % 7] * rng.uniform(0.94, 1.06) for g in range(giorni)]

precedente = mese(31, 4, 50.0, 0.004, 1)   # last month started on a Friday (4)
corrente = mese(30, 2, 55.0, 0.004, 2)     # this month starts on a Wednesday (2)
reale = sum(corrente)

# Weekly profile estimated from last month: mean spend of each weekday / overall mean
def profilo(serie, primo_giorno):
    per_giorno = [[] for _ in range(7)]
    for g, v in enumerate(serie):
        per_giorno[(primo_giorno + g) % 7].append(v)
    m = mean(serie)
    return [mean(x) / m for x in per_giorno]
P = profilo(precedente, 4)

def proiezione_semplice(speso, d, giorni=30):
    return sum(speso) / d * giorni

def proiezione_con_profilo(speso, d, primo_giorno, giorni=30):
    livello = mean(v / P[(primo_giorno + g) % 7] for g, v in enumerate(speso))      # "deseasonalised" spend
    resto = sum(livello * P[(primo_giorno + g) % 7] for g in range(d, giorni))
    return sum(speso) + resto

print(f"actual spend for the month: {reale:.1f} EUR")
print(f"{'day':>6s} {'simple':>10s} {'error':>8s} {'with profile':>12s} {'error':>8s}")
for d in (3, 5, 7, 10, 14, 21, 28):
    s = corrente[:d]
    a, b = proiezione_semplice(s, d), proiezione_con_profilo(s, d, 2)
    print(f"{d:6d} {a:10.1f} {a / reale - 1:+8.1%} {b:12.1f} {b / reale - 1:+8.1%}")

# Output:
# actual spend for the month: 1491.3 EUR
#    day     simple    error with profile    error
#      3     1686.9   +13.1%       1453.1    -2.6%
#      5     1311.9   -12.0%       1437.1    -3.6%
#      7     1430.7    -4.1%       1442.7    -3.3%
#     10     1513.0    +1.5%       1451.0    -2.7%
#     14     1434.8    -3.8%       1448.5    -2.9%
#     21     1457.0    -2.3%       1472.1    -1.3%
#     28     1471.6    -1.3%       1487.9    -0.2%

The simple method is off by +13.1% on the third day and by -12.0% on the fifth, because it depends on how many weekends have already passed, and it settles within 2% only after the twenty-first day. The method with a profile sits between -2.6% and -3.6% from the third day, and the constant sign is a useful clue: in the series spend grows day after day, the level is computed as the average of the elapsed days and therefore lags behind the current level. It is not a programming error, it is the limit of the method: if you have a trend, the projection is an underestimate, and it is worth weighting recent days more or using a method that also estimates the trend, such as Holt-Winters, which I did not run here. The profile also needs at least a few weeks of history; with a product just launched there is none, and the simple average remains the only honest thing.

The burndown: how much is left and on which day it will run out

The burndown is the budget being consumed over time. The most common version compares cumulative spend with an ideal straight line, but that line ignores the weekly profile and leads you astray, as the second listing shows: with a budget of 1,400 euros, on the seventh day spend is at 23.8% against an ideal of 23.3%, that is nothing looks visibly out of line, yet the month will end at 1,491 euros. What a useful burndown computes is the month-end projection and the day on which cumulative spend would exceed the budget.

"""Budget burndown: how much is left, and on which day it runs out if the pace does not change. Same INVENTED series as the
previous listing (30-day month starting on a Wednesday), budget of 1,400 EUR."""
import random
from statistics import mean

PESO = [1.0, 1.0, 1.0, 1.0, 1.0, 0.45, 0.45]
rng = random.Random(2)
corrente = [55.0 * 1.004 ** g * PESO[(2 + g) % 7] * rng.uniform(0.94, 1.06) for g in range(30)]
BUDGET = 1400.0

def giorno_esaurimento(serie_reale):
    cum = 0.0
    for g, v in enumerate(serie_reale, start=1):
        cum += v
        if cum >= BUDGET:
            return g
    return None

def esaurimento_previsto(speso, d, primo_giorno=2, giorni=30):
    """Pace = mean deseasonalised spend of the elapsed days, projected with the weekly profile."""
    livello = mean(v / PESO[(primo_giorno + g) % 7] for g, v in enumerate(speso))
    cum = sum(speso)
    for g in range(d, giorni):
        cum += livello * PESO[(primo_giorno + g) % 7]
        if cum >= BUDGET:
            return g + 1
    return None

def proiezione_fine_mese(speso, d, primo_giorno=2, giorni=30):
    livello = mean(v / PESO[(primo_giorno + g) % 7] for g, v in enumerate(speso))
    return sum(speso) + sum(livello * PESO[(primo_giorno + g) % 7] for g in range(d, giorni))

print(f"day on which the budget really runs out: {giorno_esaurimento(corrente)}; final spend {sum(corrente):.1f} EUR")
print(f"{'day':>6s} {'spent':>8s} {'budget used':>13s} {'linear ideal':>15s} {'projection':>11s} {'projected exhaustion':>21s}")
for d in (7, 14, 21):
    speso = sum(corrente[:d])
    prev = esaurimento_previsto(corrente[:d], d)
    print(f"{d:6d} {speso:8.1f} {speso / BUDGET:13.1%} {BUDGET * d / 30:15.1f} {proiezione_fine_mese(corrente[:d], d):11.1f} {str(prev or 'beyond the month'):>21s}")

# Output:
# day on which the budget really runs out: 29; final spend 1491.3 EUR
#    day    spent   budget used    linear ideal  projection  projected exhaustion
#      7    333.8         23.8%           326.7      1445.2                    30
#     14    669.6         47.8%           653.3      1450.9                    30
#     21   1019.9         72.9%           980.0      1474.3                    29

In the series the budget really runs out on day 29. The month-end projection, already from day 7, indicates 1,445 euros against a budget of 1,400, so the signal is there three weeks in advance; the projected exhaustion day is 30 (that is "at the end of the month or slightly before") up to day 14 and becomes 29 on day 21. The esaurimento_previsto function accumulates the projected spend day by day and returns the first day on which it exceeds the budget. The number to look at is not the date, which has an uncertainty of a day or two, but the difference between projection and budget: knowing that you will overshoot by 3% is a different conversation from knowing that you will overshoot by 30%.

To read the burndown in practice, three questions are enough to decide what to do, in this order:

  • Does the month-end projection exceed the budget? If not, nothing else is needed.
  • By how much, and from which feature or customer? This is where labels and attribution come in.
  • Has the pace changed recently, or has it always been like this? In the second case it is a budget error, not an incident.

The order is not random: the third question makes sense only after the first two, and it changes the action. A pace that changed recently is an anomaly to hunt for, a pace that has always been the same is a budget to renegotiate or a feature to optimise with the techniques of the articles on reducing tokens or on the comparison between your own server and an API.

Anomalies: why the mean and the standard deviation get fooled

To flag an anomalous day you usually compute the z-score: how many standard deviations separate the day from the recent mean. The NIST statistical handbook points out the limit: with little data the maximum possible value of the z-score is bounded by (n-1)/√n, and I add on my own account that the mean and the standard deviation are both dragged by the very anomaly you want to find. The authors cited by the handbook, Iglewicz and Hoaglin, recommend the modified z-score, which uses the median and the median absolute deviation (MAD) and a threshold of 3.5.

The third listing puts four variants to the test on 35 invented days, with two injected events: an isolated spike of four times normal on day 20 and a level shift of 60% from day 25. Each variant looks at a 14-day window; the "deseasonalised" version divides each value by the weight of its day of the week before the comparison, the raw one does not. The output lists the flagged days.

"""Anomalies in daily spend: classic z-score against modified z-score (median and MAD),
with and without removing the weekly profile. INVENTED series with a fixed seed; two injected events:
an isolated spike on day 20 (x4) and a level shift from day 25 (x1.6)."""
import random
from statistics import mean, median, pstdev

PESO = [1.0, 1.0, 1.0, 1.0, 1.0, 0.45, 0.45]
rng = random.Random(5)
serie = []
for g in range(35):
    v = 50.0 * PESO[(2 + g) % 7] * rng.uniform(0.94, 1.06)
    if g == 19: v *= 4.0          # spike (day 20, counting from 1)
    if g >= 24: v *= 1.6          # new level (from day 25)
    serie.append(v)

def z_classico(x, finestra):
    return (x - mean(finestra)) / pstdev(finestra)

def z_modificato(x, finestra):
    """0.6745 * (x - median) / MAD: the form recommended by Iglewicz and Hoaglin (NIST), threshold 3.5."""
    m = median(finestra)
    mad = median(abs(v - m) for v in finestra)
    return 0.6745 * (x - m) / mad if mad else 0.0

def segnala(destagionalizza, z, soglia):
    out = []
    for g in range(14, len(serie)):                              # window: the 14 previous days
        f = serie[g - 14:g]
        x = serie[g]
        if destagionalizza:                                      # compare with the same weekday
            f = [v / PESO[(2 + i) % 7] for i, v in zip(range(g - 14, g), f)]
            x = x / PESO[(2 + g) % 7]
        if abs(z(x, f)) > soglia:
            out.append(g + 1)
    return out

for nome, dest, z, s in (
    ("classic z > 3, raw", False, z_classico, 3.0),
    ("modified z > 3.5, raw", False, z_modificato, 3.5),
    ("classic z > 3, deseasonalised", True, z_classico, 3.0),
    ("modified z > 3.5, deseasonalised", True, z_modificato, 3.5),
):
    print(f"{nome:36s} flagged days: {segnala(dest, z, s)}")

# Output:
# classic z > 3, raw                   flagged days: [20]
# modified z > 3.5, raw                flagged days: [18, 19, 20, 27, 28]
# classic z > 3, deseasonalised        flagged days: [20]
# modified z > 3.5, deseasonalised     flagged days: [20, 25, 26, 27, 28, 29, 30]

The results read well with two observations. First, the raw methods are fooled by the weekend: the raw modified z-score flags days 18 and 19, which are a Saturday and a Sunday with normally lower spend: two false alarms, because the comparison with the weekdays in the window makes them look like a collapse. It then flags days 27 and 28, which are two weekdays of the new level and are real. After deseasonalisation the false alarms on days 18 and 19 disappear. Second, the classic z-score finds the spike on day 20 and misses the level shift entirely, because the spike, staying in the 14-day window, inflates the standard deviation and "masks" what comes after; the median and the MAD are not inflated by an isolated value, and the deseasonalised modified method flags days 25 to 30. After a few days the window moves onto the new level and the alarm falls silent, which is the right behaviour for a permanent change: report it once, not every day.

Thresholds: precision, recall and delay are paid for by each other

Google's SLO Workbook describes four attributes by which an alert is judged: precision (the share of alerts that corresponded to a significant event), recall (the share of significant events that generated an alert), detection time and reset time. The context is that of reliability objectives, but the reasoning applies unchanged to a spend alarm. The fourth listing measures it on 400 simulated months, half with an event (spend rises by 1.8 times from a random day between the eleventh and the twenty-fourth and stays there) and half without, with 15% lognormal noise. A rule fires when the deseasonalised day exceeds k times the median of the previous 14 days, for one or two days in a row.

"""What is an alarm threshold on spend worth? It is measured the way an SLO alert is measured:
precision, recall and detection time (SRE Workbook). 400 SIMULATED months with a fixed seed, lognormal noise
(sigma 0.15, more realistic than uniform noise), half with an event: from day d0 the spend rises by x1.8 and stays."""
import random
from statistics import median

PESO = [1.0, 1.0, 1.0, 1.0, 1.0, 0.45, 0.45]
N, GIORNI = 400, 30

def un_mese(rng):
    primo = rng.randrange(7)
    evento = rng.random() < 0.5
    d0 = rng.randrange(10, 24) if evento else None
    spesa = []
    for g in range(GIORNI):
        v = 50.0 * PESO[(primo + g) % 7] * rng.lognormvariate(0, 0.15)
        if evento and g >= d0: v *= 1.8
        spesa.append(v / PESO[(primo + g) % 7])               # already deseasonalised with the known profile
    return spesa, d0

def primo_allarme(spesa, k, consecutivi):
    run = 0
    for g in range(10, GIORNI):
        rif = median(spesa[max(0, g - 14):g])
        run = run + 1 if spesa[g] > k * rif else 0
        if run >= consecutivi:
            return g
    return None

rng = random.Random(11)
mesi = [un_mese(rng) for _ in range(N)]
print(f"{'rule':32s} {'precision':>10s} {'recall':>9s} {'mean delay':>14s} {'false alarms/month':>21s}")
for k, c in ((1.3, 1), (1.5, 1), (2.0, 1), (1.3, 2), (1.5, 2)):
    tp = fp = 0
    eventi = sum(d0 is not None for _, d0 in mesi)
    ritardi = []
    for spesa, d0 in mesi:
        a = primo_allarme(spesa, k, c)
        if d0 is None:
            fp += a is not None
        elif a is None:
            pass                                              # event not detected
        elif a < d0:
            fp += 1                                           # alarm before the event: a false one
        else:
            tp += 1; ritardi.append(a - d0)
    prec = tp / (tp + fp) if tp + fp else 0
    ric = tp / eventi          # an event whose first alarm is a false one does not count as detected
    nome = f"threshold {k:.1f}x, {c} day{'' if c == 1 else 's'} in a row"
    print(f"{nome:32s} {prec:10.1%} {ric:9.1%} {sum(ritardi) / len(ritardi):9.2f} days {fp / N:21.2f}")

# Output:
# rule                              precision    recall     mean delay    false alarms/month
# threshold 1.3x, 1 day in a row        46.6%     77.2%      0.02 days                  0.42
# threshold 1.5x, 1 day in a row        84.5%     95.2%      0.19 days                  0.08
# threshold 2.0x, 1 day in a row       100.0%     67.7%      1.54 days                  0.00
# threshold 1.3x, 2 days in a row       93.4%     97.4%      1.03 days                  0.03
# threshold 1.5x, 2 days in a row      100.0%     99.5%      1.46 days                  0.00

The trade-off is plain. A threshold at 1.3 times with a single day detects everything at once but almost one alarm in two is false (precision 46.6%, and about 0.42 false alarms a month); at 2 times it is never wrong but misses one event in three because in the noise a jump of 1.8 times often does not exceed 2. The rule of two days in a row at 1.5 times gets 100% precision and 99.5% recall at the price of a mean delay of about a day and a half: exactly the trade-off between detection time and precision that the Workbook describes. The result holds for this simulation, with a weekly profile known exactly and an event of 1.8 times: on your series the noise will be different, and the thresholds must be tuned by counting the false alarms on history, not copied from here.

An absolute rule, for example "the month-end projection exceeds the budget by 10%", goes alongside the relative one and covers the case where the drift is slow: no single day is anomalous with respect to the previous 14, but the projection climbs. The two rules answer different questions and it is worth keeping both.

When all this is not worth it

With less than four weeks of history the weekly profile cannot be estimated, and the simple average with a wide interval is more honest than a deseasonalisation on a few points. With very low traffic, a few euros a day, noise dominates and any relative threshold fires continuously: what counts there is an absolute threshold on the cumulative total. And in a product that changes every week (new features, new models) a projection from the recent past is wrong by construction: the projection serves to say "at this pace", not to predict Wednesday's launch.

Frequently asked questions

What is the simplest way to project month-end spend?

Estimate a weekly profile from the previous month, remove the profile from the observed days and reapply it to the remaining days. In the article's listing this reduces the error of the first days from over 12% to under 4%, with a downward bias if spend is growing.

Why use the median instead of the mean to detect anomalies?

Because an isolated spike drags the mean and the standard deviation of the window and makes what follows less visible. The modified z-score, with median and MAD and a threshold of 3.5, recommended by Iglewicz and Hoaglin in the NIST handbook, is less sensitive to this effect.

How do I choose the threshold of a spend alarm?

Measure precision, recall and delay on your own history, as in the fourth listing, and choose the trade-off you can sustain: a low threshold generates false alarms that the team stops reading, a high one misses the small events.

What you can do now

You can project month-end spend with a weekly profile and you know why an underestimate is a clue to a trend. You can read a burndown by looking at the difference between projection and budget instead of the ideal line, flag anomalies with median and MAD after removing the weekend, and judge a threshold with precision, recall and delay measured on the past. The series and the parameters are invented: put in your own data and retune the thresholds. The next step is to reduce the spend, with the optimisation techniques by layer.

Sources

  • Detection of Outliers (NIST/SEMATECH e-Handbook of Statistical Methods) - bound on the z-score, modified z-score with median and MAD, threshold of 3.5 recommended by Iglewicz and Hoaglin; consulted on 2026-11-13
  • Alerting on SLOs (Google SRE Workbook) - precision, recall, detection time and reset time as attributes of an alert; consulted on 2026-11-13
  • Forecasting: Principles and Practice, section "Time series cross-validation" (Hyndman) - evaluating a forecast at every time origin, as in the first listing; consulted on 2026-11-12
  • Local runs: python3 -I on the four listings (standard library), each twice with identical output; series, budget, events and noise invented for the example. Holt-Winters was not run

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects