Forecasting and Time-Series Analysis Questions
Analyzing and projecting data that moves over time. Covers trend and seasonality decomposition, forecasting approaches, demand modeling, and anomaly detection on time series. Emphasizes reasoning about baselines, drivers, and forecast reliability.
You inherit an ensemble of forecasting models but the ensemble's prediction intervals are overconfident and too narrow, which has caused inventory shortages. Describe a diagnostic approach to identify why intervals are too narrow, methods to recalibrate intervals (for example variance inflation, isotonic regression on quantile predictions, or re-training quantile regressors), and how to implement a permanent fix and monitoring to prevent recurrence.
Sample Answer
Direct answer
Overconfident (too-narrow) prediction intervals causing real inventory shortages need a systematic diagnostic (is the issue in the point-forecast model, the interval-construction method, or a genuine regime change the intervals haven't adapted to), a recalibration fix matched to the diagnosed cause, and a permanent monitoring layer so the same narrowness doesn't silently recur.
Structured elaboration
- Diagnostic approach: check EMPIRICAL coverage on a genuine holdout first - what fraction of actual outcomes actually fell within the stated interval, compared to the nominal rate (e.g. 90%)? A big gap (say, actual coverage of 60% against a stated 90%) confirms the intervals are indeed miscalibrated, not just unlucky. Then localize the cause: is under-coverage uniform across all series/segments (points to a systematic issue in how the interval-construction method itself works) or concentrated in specific segments (points to those segments having genuinely different, larger variance than the model assumes, e.g. through a Gaussian-residual assumption that's a poor fit for a heavy-tailed or heteroscedastic segment)?
- Recalibration methods: variance inflation (scale up the interval width by an empirically-fit multiplier until holdout coverage matches the nominal target - simple, model-agnostic, but a blunt fix that doesn't address WHY the original interval was wrong); isotonic regression on quantile predictions (a nonparametric recalibration that learns a monotonic correction mapping the model's stated quantiles to empirically-observed quantiles, capable of fixing more complex, non-uniform miscalibration than a single inflation factor); re-training quantile regressors directly against the empirically observed outcomes (the most thorough fix, appropriate when the underlying point-forecast/interval-construction approach itself needs to change, not just be recalibrated post-hoc).
- Implementing a permanent fix and monitoring: choose the recalibration method matched to what the diagnostic revealed (a uniform, modest under-coverage across the board is well-suited to simple variance inflation; segment-specific or complex miscalibration needs isotonic regression or retrained quantile models); critically, add ONGOING calibration monitoring (tracking rolling empirical coverage against the nominal target, the same discipline used for monitoring any forecasting model's drift) so a recurrence - from a genuine regime change, model staleness, or a new segment entering the portfolio - is caught before it again causes real inventory shortages, rather than only being caught the next time someone happens to investigate.
Worked example
If diagnosis shows the intervals were built assuming Gaussian residuals but a meaningful fraction of the portfolio has genuinely heavy-tailed demand (occasional large, rare spikes), a single global variance-inflation factor would either over-correct the well-behaved majority of the portfolio or under-correct the heavy-tailed segment - isotonic regression, or switching that specific segment to a bootstrap or quantile-regression-based interval method (which don't assume Gaussian residuals to begin with), is the more precisely-targeted fix, informed directly by the segment-level diagnostic rather than a uniform blanket correction.
Trade-offs & pitfalls
A recalibration applied once and never re-checked is itself a latent risk - the correction factor (or isotonic mapping) that fixes today's miscalibration can become stale if the underlying process shifts again, so the monitoring step isn't optional cleanup, it's the actual guarantee that this specific operational failure (inventory shortages from overconfident intervals) doesn't recur silently.
You need to reduce inference cost and latency for serving demand forecasts across thousands of zones. Propose model compression and optimization techniques (quantization, pruning, knowledge distillation, batching), and describe how each affects accuracy, memory, and CPU/GPU utilization.
Sample Answer
Direct answer
Reducing inference cost and latency for serving forecasts across thousands of zones means shrinking or speeding up the model itself (quantization, pruning, knowledge distillation) and/or serving more requests per unit of compute (batching) - each technique trades off differently against accuracy, memory footprint, and CPU/GPU utilization, and the right combination depends on which resource (latency, memory, raw compute cost) is actually the binding constraint.
Structured elaboration
- Quantization: reduce the numerical precision of the model's weights/activations (e.g. from 32-bit floats to 8-bit integers) - meaningfully reduces memory footprint and can substantially speed up inference (especially on hardware with native low-precision support), typically at a small, often acceptable accuracy cost; the accuracy impact should always be validated explicitly (a backtest comparing quantized vs full-precision accuracy) rather than assumed to be negligible.
- Pruning: remove weights/connections/whole units that contribute little to the model's output (e.g. near-zero weights, or entire redundant tree branches for a gradient-boosted model), directly reducing the compute needed per inference pass; can be applied more or less aggressively, with a corresponding accuracy/speed trade-off that should be tuned against a validation set rather than a fixed target sparsity chosen blindly.
- Knowledge distillation: train a smaller, faster "student" model to mimic a larger, more accurate "teacher" model's outputs, aiming to retain most of the teacher's accuracy in a cheaper-to-serve package - most valuable when the teacher model is meaningfully more accurate than a directly-trained small model would be, i.e. when there's genuine accuracy to "transfer down," not just compress.
- Batching: rather than compressing the model itself, batch multiple zones' inference requests into one forward pass - amortizes fixed per-inference overhead across many requests, often the SINGLE most effective lever for throughput/cost on GPU hardware specifically (which is heavily optimized for batched, parallel computation), at the cost of adding a small amount of latency for individual requests while the system waits to accumulate a batch (a real trade-off against per-request latency that needs to be tuned against your specific SLA).
- How each affects accuracy, memory, and CPU/GPU utilization: quantization and pruning both directly reduce memory footprint and typically speed up inference, at a (usually modest, but non-zero) accuracy cost that must be validated; distillation aims to preserve accuracy while reducing model size/cost, at the added engineering cost of training and maintaining a separate teacher-student training pipeline; batching doesn't change the model or its accuracy at all, purely improves throughput/cost efficiency, at a latency-per-request trade-off.
Worked example
For a forecasting workload with a genuinely low per-request latency requirement (as in a real-time, on-request forecasting service), aggressive batching may be constrained by how much added per-request latency the SLA can tolerate while a batch fills, making quantization or pruning (which reduce per-inference compute WITHOUT adding a wait-for-batch delay) the more appropriate levers; for a workload that instead runs as a large, scheduled BATCH job across all zones at once (less latency-sensitive per individual forecast), aggressive batching is the most straightforward and highest-leverage cost reduction, since there's no per-request latency SLA constraining how large a batch you can accumulate.
Trade-offs & pitfalls
Applying model-compression techniques (quantization, pruning, distillation) without an explicit accuracy-validation step against a genuine holdout is the most common mistake - a compressed model's speed and memory gains are easy to measure directly, but its accuracy cost is not automatically negligible and must be checked explicitly before deploying, the same discipline that applies to any change to a model that's already in production.
Describe how to build a Bayesian Structural Time Series (BSTS) model to measure the causal impact of a marketing intervention. Discuss prior selection, model components (trend, seasonality, regression terms), MCMC sampling concerns, convergence diagnostics (R-hat, ESS), and interpretation of posterior intervals. Provide an outline of code you would write with PyMC3 or PyStan and discuss computational trade-offs.
Sample Answer
Direct answer
A Bayesian Structural Time Series (BSTS) model for causal impact represents a series as an explicit state-space decomposition (trend, seasonality, and optional regression terms on control covariates), fit with MCMC to a PRE-intervention period, then projected forward as a counterfactual to compare against the actually-observed POST-intervention series - the gap between the counterfactual projection and reality, with its posterior uncertainty, is the estimated causal impact.
Structured elaboration
- Model components: a local-level or local-linear-trend component (capturing the series' baseline trajectory), a seasonal component (if relevant), and optionally regression terms on CONTROL series (other, unaffected series correlated with the target pre-intervention) that help the model build a better counterfactual by leveraging what those unaffected series were ALSO doing during the post-intervention window.
- Prior selection: priors on the state-space variances (how much the trend/seasonal components are allowed to drift period to period) meaningfully affect how flexible the counterfactual projection is - too-flexible priors let the model "explain away" a genuine intervention effect as ordinary trend drift, too-rigid priors produce an overconfident, poorly-fitting counterfactual; priors are typically chosen (or checked) via their effect on PRE-intervention backtested fit, before ever looking at the post-intervention period.
- MCMC sampling concerns and convergence diagnostics: run multiple chains from different starting points; check R-hat (should be close to 1.0 for every parameter, indicating the chains have converged to the same distribution) and effective sample size/ESS (should be reasonably large relative to the number of draws, indicating the chain isn't too autocorrelated to give a reliable posterior estimate) before trusting any posterior interval - skipping this check risks reporting a "confident" causal-impact estimate from a chain that never actually converged.
- Interpreting posterior intervals: the model's posterior distribution over the counterfactual (what the series WOULD have done without the intervention) directly gives a posterior distribution over the CAUSAL EFFECT (observed minus counterfactual) at every post-intervention time point, and can be cumulated over the whole post-period - report the credible interval on the CUMULATIVE effect, not just a point estimate, and treat an interval that comfortably excludes zero as the practical bar for "a detectable effect," analogous to (but not identical to) a frequentist significance test.
- Code outline (PyMC3/PyStan) and computational trade-offs: define the state-space structure (local level + seasonal + optional regression) as a PyMC3
TimeSeries-style model or equivalent, fit via NUTS/MCMC sampling on the PRE-period only, then use the fitted posterior to simulate forward counterfactual draws over the post-period; MCMC-based BSTS is meaningfully more compute-intensive than a point-estimate method (like a plain difference-in-differences regression), which matters if you need to run this analysis across many interventions/series rather than a single one-off causal question.
Worked example
A related, lighter-weight time-series causal-impact technique worth naming for comparison: interrupted time series (ITS) analysis via segmented regression, which tests for a level or slope CHANGE at a specific known intervention date using a simpler regression framework rather than a full Bayesian state-space model - appropriate when you want a faster, more transparent (if less flexible) causal-impact estimate and don't need BSTS's ability to incorporate unaffected control series as covariates.
Trade-offs & pitfalls
The single most important assumption to validate before trusting a BSTS causal-impact estimate: the model's PRE-intervention fit must be genuinely good (the counterfactual projection mechanism has to be trustworthy on data you can actually check it against) - a poor pre-period fit means the post-period counterfactual is unreliable regardless of how confident the posterior interval looks, so always report pre-period backtested fit quality alongside the causal-impact estimate itself, not as an afterthought.
Architect a low-latency forecasting service that must serve per-zone 15-minute demand predictions on request for 10k zones with 500 QPS and 100ms p95 latency. Describe overall architecture (model store, feature store, online features, caching), how you would serve batched predictions, and strategies for availability and rollback.
Sample Answer
Direct answer
A low-latency (100ms p95, 500 QPS, 10k zones) forecasting service needs pre-computed or cached predictions wherever possible (rather than computing a fresh forecast per request), an online feature store fast enough to serve the remaining real-time inputs within the latency budget, a model store supporting fast model loading/versioning, and explicit availability/rollback strategies given the operational stakes of a customer-facing latency SLA.
Structured elaboration
- Model store: hosts versioned, trained models ready for fast loading into the serving layer; at 10k zones, likely one (or a small number of clustered) GLOBAL models rather than 10k independently-loaded per-zone models, both for the same statistical pooling reasons that favor global models at scale and for the practical serving reason that loading 10k separate model artifacts per request path is operationally unworkable within a 100ms budget.
- Feature store, online features: the features needed at inference time (recent lag values, calendar features, any real-time exogenous signal) must be servable with very low latency - a dedicated online feature store (backed by a fast key-value store, not a query against a data warehouse) is standard here, since a warehouse query would blow the 100ms budget on its own.
- Caching: for a request pattern where many requests ask for the SAME zone's forecast within a short window (a very plausible pattern at 500 QPS across "only" 10k zones), caching a recently-computed forecast (invalidated on a schedule matching how often the underlying forecast is genuinely refreshed, e.g. every 15 minutes) avoids recomputing an identical answer repeatedly, and is often the single biggest lever for hitting a tight latency SLA without needing every request to hit the full model-inference path.
- Serving batched predictions: even for on-request serving, batching multiple zones' feature vectors into one model inference call (rather than one model call per zone) amortizes fixed per-call overhead and is usually meaningfully faster in aggregate than fully independent per-request inference, especially for a model architecture (e.g. a global gradient-boosted or neural model) that scales well with batch size.
- Availability and rollback: run multiple redundant serving instances behind a load balancer so a single instance failure doesn't violate the latency SLA for other requests; deploy new model versions via a canary (a small slice of traffic first) with automated rollback if the new version's latency or accuracy regresses, rather than a full instantaneous cutover.
Worked example
A concrete architecture: features refreshed into a fast online store on a schedule (e.g. every few minutes) rather than computed synchronously per-request; a background job pre-computes and caches each zone's forecast at the SAME refresh cadence; the actual request-serving path becomes largely a cache lookup (very fast, easily within 100ms even at 500 QPS) with a fallback to synchronous on-demand inference only for a cache miss (a zone whose forecast hasn't been pre-computed recently, ideally a rare case) - this architecture trades a small amount of freshness (forecasts are as fresh as the last refresh cycle, not literally real-time) for a much more reliable and cheaper latency profile than computing everything synchronously per request.
Trade-offs & pitfalls
The most consequential design trade-off here is freshness vs latency/cost: pure synchronous per-request inference gives the freshest possible forecast but is the most expensive and riskiest way to hit a tight SLA at this request volume; a pre-compute-and-cache architecture is cheaper and more reliably fast but serves a slightly staler forecast - the right balance depends on how much genuine value fresher-than-cache-refresh-cycle forecasts actually provide for THIS specific use case (per-zone 15-minute demand predictions), which is worth validating rather than assuming synchronous freshness is automatically worth its cost.
Define Exponentially Weighted Moving Average (EWMA) and provide the recursive update formula. Explain how the smoothing factor alpha controls responsiveness versus noise reduction and give an example heuristic for choosing alpha when you want to detect a sudden 10% drop in conversion rate.
Sample Answer
Direct answer
EWMA maintains a smoothed value updated recursively as St=αxt+(1−α)St−1, where alpha controls the trade-off between responsiveness (high alpha, reacts fast, passes through more noise) and noise reduction (low alpha, smoother, slower to react); a practical heuristic for choosing alpha to detect a specific-size shift (e.g. a sudden 10% drop) is to pick alpha large enough that the EWMA visibly moves toward the new level within a small number of periods, without being so large that ordinary day-to-day noise alone crosses your alerting threshold.
Structured elaboration and worked example (executed)
import numpy as np
def ewma(values, alpha):
out = np.empty_like(values, dtype=float)
out[0] = values[0]
for t in range(1, len(values)):
out[t] = alpha * values[t] + (1 - alpha) * out[t - 1]
return out
Run with alpha=0.2 on a series with a baseline around 100 that shifts to a sustained ~112 (a +12% shift) partway through:
baseline EWMA mean (last 5 of baseline): [100.88 101.52 100.32 101.03 99.65]
EWMA after shift (last 5): [110.29 109.89 112.19 110.97 110.1]
The EWMA converges close to the new level within roughly 10-15 periods at alpha=0.2. A larger alpha would converge faster but track single-point noise more closely; the choice is a genuine sensitivity/false-alarm trade-off, not something with one universally-correct answer.
- How alpha controls the trade-off: a HIGH alpha weights the newest observation heavily, so the EWMA follows the raw series closely (fast to detect a real shift, but also reacts to a single noisy point - more false alarms if used directly as an alerting signal); a LOW alpha smooths heavily over many past observations (slow to detect a real, sustained shift, but robust to single-point noise).
- Heuristic for choosing alpha to detect a specific target shift: think in terms of an effective "memory" window - an EWMA with parameter alpha weights recent observations roughly like a moving average of window size ≈α2−1; to detect a sustained 10% drop reliably within, say, 5 periods without over-reacting to single-point noise of a known typical size, choose alpha so this effective window is short enough to react within your desired detection latency, then validate empirically (as done above) that ordinary noise alone doesn't cross your intended alerting threshold at that alpha.
Trade-offs & pitfalls
EWMA (like CUSUM) is fundamentally a SMOOTHING/tracking statistic, not by itself a full alerting system - turning it into one requires an explicit threshold and a decision about how to define "baseline" in the first place (especially on a series with its own trend/seasonality, where the EWMA needs to track a MOVING baseline, not a fixed constant, or every seasonal peak will look like a shift). The single most common mistake is choosing alpha (or a threshold) by convention rather than validating against the ACTUAL noise characteristics of the specific metric you're monitoring, since two metrics with very different natural variance need different alpha/threshold combinations to hit the same false-alarm rate.
Unlock Full Question Bank
Get access to all Forecasting and Time-Series Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.