Causal64

Library

54 reference pages on forecasting, model validation and applied statistics. Each one gives the definition, the formula, a worked example in code, the case where the method misleads, and its sources.

These pages are the working reference behind our projects in forecast accuracy, intermittent demand, model validation, credit scoring and small-sample statistics. The worked example of each page is a short Python program, and the output printed under it is produced by running that program when the page is built, so a number on a page is always the number its code gives. Sources are the original papers and open textbooks, cited with their DOI. For studies on real data with full results, see the research notes.

Forecast accuracy: metrics and benchmarks

What each score measures, its formula, and the case where it misleads.

  • MASE: mean absolute scaled errorMASE compares the absolute error of a forecast with the error a naive forecast made on the history. Below 1, the forecast beats that naive benchmark. On series that are mostly zeros, a forecast of zero gets the best score.
  • RMSSE: root mean squared scaled errorRMSSE is the square root of the squared forecast error divided by the squared error of a naive forecast on the history. It rewards forecasting the mean, which is what a stock calculation needs.
  • sMAPE: symmetric mean absolute percentage errorsMAPE was designed to fix the unbounded errors of MAPE. It is bounded, but it penalises a forecast that is too low more than one that is too high by the same amount, and every period with zero demand gets the maximum error.
  • MAPE: mean absolute percentage errorMAPE is easy to explain and is the measure most planning teams already report. It is undefined when the actual value is zero, it explodes on low volumes, and the forecast that minimises it sits below the mean.
  • WAPE: weighted absolute percentage errorWAPE, also called the MAD/mean ratio, is the total absolute error divided by the total demand. It stays defined when some periods are zero and is the percentage measure that survives a catalogue of slow items.
  • Pinball loss (quantile loss)The pinball loss, or quantile loss, is the measure for a quantile forecast, such as the stock level that covers demand 90 % of the time. It is minimised by the true quantile and by nothing else.
  • CRPS: continuous ranked probability scoreThe CRPS scores a full predictive distribution with one number in the units of the data. For a point forecast it reduces to the absolute error, which makes probabilistic and point forecasts comparable.
  • Forecast bias: mean errorBias is the average of forecast minus actual. It says whether a method orders too much or too little over time, which no accuracy measure reports. A biased forecast can have the best accuracy score.
  • MAE or RMSE: which forecast each one rewardsThe absolute error is smallest when the forecast is the median of what can happen, the squared error when it is the mean. On skewed data these are different numbers, so the choice of measure is a choice of forecast.
  • Prediction interval coverage and the Winkler scoreCoverage is the share of outcomes that fall inside the prediction intervals. It is the first check on any interval, and it needs enough periods to mean something. The Winkler score adds a penalty for the interval width.
  • Diebold-Mariano testTwo forecasts never have the same error. The Diebold-Mariano test, the standard tool for forecast comparison, says whether the gap between them is larger than what chance produces on a window of that length, using the paired differences of their losses.
  • The seasonal naive forecast as a benchmarkThe seasonal naive forecast for next Monday is last Monday's value. It has no parameter and no training, and on seasonal data it is hard to beat. A model that does not clearly beat it has not earned its cost.

Intermittent demand and stock

Methods for items that sell rarely, and how a forecast becomes a stock level.

  • Croston's methodCroston's method splits an intermittent series in two: how much is ordered when there is an order, and how long between orders. Each is smoothed separately and the forecast is their ratio. The ratio is biased upward.
  • SBA: the Syntetos-Boylan approximationThe Syntetos-Boylan approximation is Croston's method with one correction factor. It removes most of the upward bias of the original, and slightly over-corrects when demand occurs in almost every period.
  • TSB: the Teunter-Syntetos-Babai methodTSB replaces the interval of Croston's method with a probability of demand that is updated every period. When an item stops selling, the forecast falls toward zero, which Croston and SBA never do.
  • ADIDA: aggregate, forecast, disaggregateADIDA removes zeros by temporal aggregation: months become quarters, and a series that was mostly zeros becomes one that can be smoothed. The forecast is then divided back into the original periods.
  • Demand classification: ADI and CV²Two numbers describe a demand series: how often it sells (ADI) and how much the order sizes vary (CV²). The cut-offs 1.32 and 0.49 split a catalogue into smooth, erratic, intermittent and lumpy items.
  • Simple exponential smoothing on intermittent demandSimple exponential smoothing follows the level of a series with one constant. On intermittent demand its average is right and its timing is wrong: the forecast peaks just after each sale, when the reorder is placed.
  • The zero forecast as a baselineA forecast of zero for every item and every period is useless for stock and has the best absolute error on most intermittent series. Including it in a comparison shows at once whether the error measure can be trusted.
  • Service level and fill rateThe cycle service level is the probability that demand is fully met in a period. The fill rate is the share of units demanded that are delivered from stock. They are different numbers, and for slow items they can be far apart.
  • Safety stock and the normal approximationSafety stock is the stock held above the expected demand over the lead time. The textbook formula assumes that this demand is normally distributed. For slow items it is not, and the service obtained differs from the target.
  • The newsvendor model and the critical ratioThe newsvendor model answers one question: how much to order once, before an uncertain demand. The answer is a quantile of the demand distribution, at a probability set by the two unit costs.
  • Poisson or negative binomial demandA count distribution turns a mean forecast into stock levels. The Poisson distribution assumes the variance equals the mean. When orders come in batches the variance is larger, and the negative binomial fits better.
  • Censored demand: when stock-outs hide salesSales data record what was sold, not what was asked for. On days when the shelf was empty, demand is at least the quantity sold. A forecast trained on sales alone learns the stock policy of the past.
  • Lead-time demand and its bootstrapWhat a reorder point must cover is the total demand between placing an order and receiving it. Its distribution can be estimated by resampling the history, without assuming a shape.
  • Forecast accuracy and inventory performanceA forecast is an input to a stock rule. Two forecasts can be ranked in one order by an accuracy measure and in the opposite order by the service and the stock they produce. The stock outcome is the one that is paid for.
  • How to evaluate a demand forecasting vendorA proof of concept shows an accuracy figure. The figure means something only if the test was set up so that the vendor could fail. These are the questions that separate the two cases, and a script to check the answers on your own data.

Model validation

How a model is tested on data it has not seen, and how a test goes wrong.

  • Walk-forward validationWalk-forward validation, also called rolling-origin evaluation, repeats one honest experiment: train on everything before a date, forecast what comes after, move the date forward. Shuffled cross-validation does not respect that order.
  • Purged k-fold cross-validation with an embargoWhen a label is built from several future periods, neighbouring observations share part of their label. With such overlapping labels, purging removes from training every observation that overlaps the test fold; the embargo adds a gap after it.
  • Data leakage in machine learningA model leaks when something it was trained with would not be available at prediction time, or was computed with the test data. The score then measures the leak. The most common form hides in a preprocessing step.
  • Look-ahead bias and point-in-time dataA backtest has look-ahead bias when it uses, at a past date, information that became available later: a revised figure, a late report, a statistic computed on the whole sample. Point-in-time data stores what was known when.
  • Nested cross-validationWhen cross-validation is used for hyperparameter tuning, to pick the best of many settings, the winning score is no longer an honest estimate: it was selected for being high. Nested cross-validation scores the whole procedure, selection included.
  • The best of N trialsThe best result among many attempts carries a selection bias: it was kept because it was high. The more variants were tried, the better the best one looks, even when none has any real effect.
  • PBO: the probability of backtest overfittingThe probability of backtest overfitting asks one question of a search: when the best configuration is chosen on part of the data, where does it rank on the rest. If it usually falls in the bottom half, the selection found noise.
  • The deflated Sharpe ratioA Sharpe ratio selected among many backtests has to beat more than zero: it has to beat the best ratio that pure noise would produce over the same number of trials. The deflated Sharpe ratio makes that comparison.
  • The placebo test: shuffled labelsShuffle the target, rerun everything, and look at the score. With no relation left between inputs and target, an honest pipeline scores at chance level. If it scores better, the pipeline is reading the answer somewhere.
  • The positive control: a planted effectBefore concluding that nothing is there, check that the test could have seen something. A positive control adds an effect of known size to the data and measures how often the analysis detects it.
  • The sealed test set, read onceA holdout sample gives an unbiased estimate once. Each time a decision is taken after looking at it, a little of it passes into the model. After enough rounds the reported score describes the holdout, not the future.
  • The block bootstrap for time seriesResampling single observations breaks the dependence between neighbours in time. The block bootstrap resamples stretches of consecutive observations instead, and gives confidence intervals that account for autocorrelation.
  • Paired comparison of two modelsTwo models tested on the same rows share most of their luck. Comparing their two confidence intervals ignores that. The interval of the difference, computed on the same resampled rows, is much narrower.
  • Split conformal predictionConformal prediction wraps any model. It measures the errors on data set aside, and uses their quantile as the half-width of the prediction interval. The average coverage is guaranteed without assuming a distribution, under one condition.

Credit scoring

The statistics a scorecard validation report is built on.

  • AUC and the Gini coefficient in credit scoringThe AUC is the probability that a randomly chosen defaulter has a worse score than a randomly chosen good payer. The Gini coefficient rescales it: Gini = 2 AUC − 1. Both measure ranking, and both depend on the population scored.
  • The KS statistic of a scorecardThe Kolmogorov-Smirnov statistic of a scorecard is the maximum distance between two curves: the share of defaulters and the share of good payers below each score. It reads as the best separation achievable with one cut-off.
  • PSI: the population stability indexThe population stability index sums, over score bands, the difference between two shares times the log of their ratio. The usual thresholds of 0.10 and 0.25 are conventions: with small samples or many bands, PSI exceeds them when nothing has changed.
  • Weight of evidence and information valueWeight of evidence turns each bin of a variable into a number: the log of the share of good payers over the share of bad payers. Information value sums the bins into one figure for the variable. It is biased upward by the number of bins.
  • Scorecard scaling: points to double the oddsA scorecard converts a probability of default into points. Three numbers fix the scale: a reference score, the odds of repayment at that score, and the points to double the odds (PDO). The scale changes how the model reads, not what it predicts.
  • Probability calibration: slope and interceptCalibration asks whether predicted probabilities match observed frequencies. Two numbers summarise it: the intercept, for the overall level, and the slope, for the spread. A slope below 1 means predictions that are too extreme.
  • Brier score and log lossThe Brier score and the log loss both score predicted probabilities against what happened, and both are proper: the best expected score goes to the true probability. They differ in how hard they punish a confident mistake.
  • Reject inferenceLenders observe repayment only for the applicants they accepted. Reject inference tries to correct the selection bias of a model built on that sample. Whether a correction is needed, and possible, depends on how the past decisions were taken.
  • Concept drift and data driftA model can stop working in two ways. The population it scores changes, which is data drift. Or the relation between inputs and outcome changes, which is concept drift. Monitoring the inputs detects the first and is blind to the second.

Statistics for small samples and pricing

Estimation when the data are thin, and the models behind a tariff.

  • The Fay-Herriot modelA survey gives a direct estimate for every area, precise for large areas and noisy for small ones. The Fay-Herriot model pulls each estimate toward a regression prediction, more strongly where the survey is less reliable.
  • Poisson GLM with an exposure offsetA policy observed for three months cannot be compared with one observed for a year. In a Poisson model of claim frequency, exposure enters as an offset: the logarithm of the exposure, with a coefficient fixed at 1.
  • The Tweedie GLM for pure premiumMost policies have no claim in a year, and the few that do have costs spread over a wide range. The Tweedie distribution, with a power between 1 and 2, describes that mix in one model of the pure premium.
  • GLM or gradient boosting for insurance pricingA generalised linear model gives a tariff anyone can read: a base rate and one multiplier per factor. Gradient boosting usually predicts better because it picks up interactions and non-linear effects without being told. Most of that gain can often be carried back into a GLM.
Back to home