The Modern Forecasting Stack: From ARIMA to Deep Learning and Foundation Models on Google Cloud
From the publisher’s feed, collected in the ZeroLabs newsroom.
The Modern Forecasting Stack: From ARIMA to Foundation Models on Google CloudA hands-on guide to benchmarking TimesFM, ARIMAX, TiDE, TFT, and AutoML across BigQuery and Vertex AI.Never ending race: Which model will be the winner for your business problem?If you have ever tried to forecast inventory demand, cash flow, contact center volume, energy load etc, you know that time series forecasting is a methodical process that goes far beyond selecting an algorithm. Success depends on a deep understanding of the business context and the historical patterns. Finding the winning model often requires rigorous experimentation with models and parameters, as performance depends heavily on your specific data patterns. However, the barrier to entry is dropping fast. Modern tools have commoditized the construction of complex models, making it surprisingly easy to build and benchmark diverse architectures. Instead of getting stuck searching for the perfect model, we can now rapidly test a suite of candidates to accelerate time-to-value and focus on domain insights and operational decisions that actually move the needle.In this post, we will walk through a modern forecasting workflow on Google Cloud Platform (GCP). We will build five distinct forecasting models, spanning the spectrum from robust statistical methods to cutting-edge deep learning. The lineup includes TimesFM and ARIMAX (running directly in BigQuery), as well as TiDE, TFT, and AutoML (running in Vertex AI). We will race these models against each other to identify the top performer and, finally, determine if we can beat the single best model by combining them into a unified Ensemble.Why these models?We are not just throwing algorithms at a wall to see what sticks, but we are testing representatives from three distinct generations of forecasting developments.The Baseline Model (ARIMAX in BigQuery): We start with the gold standard ARIMAX for multi-variate forecasting with eXogenous factors. Running directly in BigQuery, this model will be our sanity check. It is fast, interpretable, and for many simple time series, surprisingly hard to beat. The hyperparameter tuning will also be handled automatically.The Foundation Model (TimesFM in BigQuery): Developed by Google Research team, this is a zero-shot model pre-trained on 100 billion real-world time points. It promises to do for time series what LLMs did for text, generalizing to new data without extensive training.The Deep Learning Models (Forecasting in Vertex AI): > TiDE (Time-series Dense Encoder) is a multi-layer perceptron (MLP) based encoder-decoder architecture that is optimised to run faster and often more accurate than complex Transformers since it uses simple, dense neural network layers and residual connections instead of complex attention mechanisms. > TFT (Temporal Fusion Transformer) is an attention-based deep learning model designed for interpretability that combines recurrent neural networks (RNNs) for local processing with self-attention mechanisms to capture long-range temporal dependencies and handle diverse input types. > AutoML is not a single model, but an automated workflow. Instead of manually selecting one algorithm, it runs a massive search experiment, testing dozens of different architectures (from simple linear models to complex neural networks and trees) in parallel. It handles the heavy lifting of feature engineering and hyperparameter tuning automatically, often combining the top performers into an ensemble. It can also be used as a benchmark model for what is possible with automated search.To make this practical, I have designed this guide to be reproducible. You can download the dataset from Kaggle (or swap in your own table) and follow the code snippets below to implement this workflow in your own project. The code snippets can also be found in this Colab notebook as a reference, ready to be downloaded. For an enterprise-ready application, you may run the code in your GCP project within Vertex AI Workbench.Google ColabNow, let’s start!The Kaggle dataset includes the hourly air pollution values with covariates like temperature, dew, snow, rain and wind. To start with, download the file (LSTM-Multivariate_pollution.csv) and upload it as a table to a BigQuery dataset.This dataset has a single time series. That will be a limitation to show the power of our deep learning algorithms but that’s ok, let’s keep it simple. In a real scenario, the dataset will have hundreds or thousands of series which will be labelled with the time-series ID and we will forecast all at once automatically. When we train with local models (e.g. statistical algorithms) the series are trained individually. In contrast, global models (e.g. deep learning algorithms) look at the entire population of data at once and train a single model on all data simultaneously. By training on multiple series, the model identifies shared patterns like how a promotion or holiday affects your entire inventory which provides better accuracy than looking at one item in isolation. This architecture also solves the cold start problem by using metadata (product attributes) even if a new item has no sales history, the model can generate a forecast based on how similar products have behaved in the past.We will add the time-series ID to our dataset even if there is only a single series. You can follow exactly the same flow when you have multiple series. We will also split the data into train and test for evaluation and limit the observations to the most recent. There are some dataset pre-requisites for training models in Vertex AI. See more details in the Colab notebook.# importing packagesfrom google.cloud import aiplatformfrom google.cloud import bigqueryfrom google.api_core.exceptions import GoogleAPICallErrorimport google.auth# getting the credentials and project idCREDS, PROJECT_ID = google.auth.default()print(f"Project ID: {PROJECT_ID}")# services locationLOCATION = "us-central1"# bigquery parameters for input tablesBQ_DATASET = "forecasting"BQ_TABLE = "pollution"CSV_FILE = "LSTM-Multivariate_pollution.csv"BQ_TABLE_RAW = f"{PROJECT_ID}.{BQ_DATASET}.{BQ_TABLE}"BQ_TABLE_TRAIN = f"{PROJECT_ID}.{BQ_DATASET}.{BQ_TABLE}_train"BQ_TABLE_TEST = f"{PROJECT_ID}.{BQ_DATASET}.{BQ_TABLE}_test"BQ_TABLE_INFERENCE = f"{PROJECT_ID}.{BQ_DATASET}.{BQ_TABLE}_inference"BQ_DATASET_PATH = BQ_TABLE_RAW.rsplit('.', 1)[0]# Initialize the BigQuery clientclient = bigquery.Client()The forecasting data with covariatesStep 2. Learn your Business: The AI Consultant for Domain ExpertiseEffective forecasting is not only a technical exercise, it requires a synergy between business teams to gain domain expertise and technical teams to use that expertise shaping the models. As a new approach, we will ask Gemini to act as a domain expert and give us advice on air pollution together with the reasoning. We can be as specific or broad as we want in our prompt.https://medium.com/media/ed01678c34480e75c41b8671cd308096/hrefBased on the recommendations from Gemini, we decide to set up the forecasting horizon as 48 hours considering the “diurnal cycle” and “actionability” and context window as 168 hours considering the impact of “human activity” and “pollutant cycles”.Domain specific recommendations from GeminiNow we configure the forecasting parameters.# Forecasting parametersID_TIMESTAMP = "date"ID_DATA = "area_id"TARGET = "pollution"FREQUENCY = "hourly"HORIZON = 48# 48 hr forecastsPREDICTION_ARIMAX = f"{PROJECT_ID}.{BQ_DATASET}.predictions_arimax_{HORIZON}"PREDICTION_TIMESFM = f"{PROJECT_ID}.{BQ_DATASET}.predictions_timesfm_{HORIZON}"PREDICTION_AUTOML = f"{PROJECT_ID}.{BQ_DATASET}.predictions_automl_{HORIZON}"PREDICTION_TIDE = f"{PROJECT_ID}.{BQ_DATASET}.predictions_tide_{HORIZON}"PREDICTION_TFT = f"{PROJECT_ID}.{BQ_DATASET}.predictions_tft_{HORIZON}"# Predictions output tableOUTPUT_PREDS_TABLE = f"{PROJECT_ID}.{BQ_DATASET}.predictions_all_{HORIZON}"Step 3. Forecasting in BigQuery: ARIMAX & TimesFMWe start forecasting with the “in-database” statistical model and the “pre-trained” foundational model in BigQuery. These models are very convenient to establish a strong baseline.ARIMAX (Multi-covariate Statistical Model)We train a traditional statistical model using a simple SQL code in BigQuery (CREATE OR REPLACE MODEL) with model type ARIMA_PLUS_XREG to account for our external features (rain, wind, temperature, etc.).# train an ARIMAX model in-database in BigQuery and register in Vertex AI.MODEL_NAME_ARIMAX = f"{PROJECT_ID}.{BQ_DATASET}.pollution_arimax_{HORIZON}"query = f"""CREATE OR REPLACE MODEL `{MODEL_NAME_ARIMAX}`OPTIONS( model_type = 'ARIMA_PLUS_XREG', TIME_SERIES_TIMESTAMP_COL = "{ID_TIMESTAMP}", TIME_SERIES_DATA_COL = "{TARGET}", TIME_SERIES_ID_COL = ["{ID_DATA}"], HORIZON = 48, DATA_FREQUENCY = "{FREQUENCY}", AUTO_ARIMA = TRUE, MODEL_REGISTRY = "VERTEX_AI") ASSELECT *FROM `{BQ_TABLE_TRAIN}`;"""query_job = client.query(query)print("Model training started.")try: # WAIT for the job to finish to see any errors query_job.result() print("Model training job completed successfully.")except Exception as e: # This captures the syntax errors from BigQuery print(f"Job failed with error: {e}")Once the model is trained (it takes a few minutes), we can then run the inference for the future values, either using ML.FORECAST or ML.EXPLAIN_FORECAST.# generate forecast values using the multi-variate ARIMAX model.query = f"""create or replace table `{PREDICTION_ARIMAX}` asSELECT *FROM ML.EXPLAIN_FORECAST(MODEL `{MODEL_NAME_ARIMAX}`, STRUCT({HORIZON} AS horizon, 0.95 AS confidence_level), (SELECT * FROM `{BQ_TABLE_INFERENCE}`))WHERE time_series_type = "forecast""""query_job = client.query(query)print("Model inference started.")try: # WAIT for the job to finish to see any errors query_job.result() print("Model inference job completed successfully.")except Exception as e: # This captures the syntax errors from BigQuery print(f"Job failed with error: {e}")TimesFM (Generative AI for Time Series)We run TimesFM model in BigQuery with AI.FORECAST as shown below to get the future predictions (no training needed). TimesFM is Google’s foundation model for univariate time series forecasting pre-trained on billions of real-world data points, meaning it predicts the future values based on patterns it learned elsewhere, without needing to be trained specifically on your data.# generate forecast values using univariate TimesFM model.query = f"""create or replace table `{PREDICTION_TIMESFM}` asSELECT *FROM AI.FORECAST( (SELECT * FROM {BQ_TABLE_TRAIN} ), horizon => {HORIZON}, confidence_level => 0.95, timestamp_col => "{ID_TIMESTAMP}", data_col => "{TARGET}");"""# Run the queryquery_job = client.query(query)print("Model inference started.")try: # WAIT for the job to finish to see any errors query_job.result() print("Model inference job completed successfully.")except Exception as e: # This captures the syntax errors from BigQuery print(f"Job failed with error: {e}")Step 4. Forecasting in Vertex AI: Deep LearningNext, we move to Vertex AI to train models with state-of-the-art deep learning architectures. Vertex AI supports model development through both the console UI and the Python SDK.Training advanced deep learning models with no-code in Vertex AIFor initial experimentation, the UI is often preferable for two key reasons:Error Reduction: The interface provides contextual documentation for complex parameters, simplifying the decision-making process and minimizing configuration errors.Prototyping to Production: Running a model in the UI first allows you to validate settings comfortably; once a “champion” configuration is identified, it can be easily replicated and automated via the Python SDK.https://medium.com/media/092c0b0bc9fa53fa14b475a8fc9d4014/hrefWhen the training is completed, we see the models listed under Model Registry in Vertex AI.Vertex AI and BigQuery models in Model RegistryThe next step is the inference. We use batch_predict method and create a Python function to submit batch prediction jobs for our AutoML, TiDE, and TFT models.# generate forecast values using Vertex AI models.def create_batch_prediction_job_bigquery_table( project: str, location: str, model_resource_name: str, job_display_name: str, bigquery_source: str, bigquery_destination_dataset: str, sync: bool = True,): aiplatform.init(project=project, location=location) #add bq:// for the full path bigquery_source_full = "bq://" + bigquery_source my_model = aiplatform.Model(model_resource_name) batch_prediction_job = my_model.batch_predict( job_display_name=job_display_name, bigquery_source=bigquery_source_full, bigquery_destination_prefix=bigquery_destination_dataset, sync=sync, ) batch_prediction_job.wait() print(f"Job State: {batch_prediction_job.state}") return batch_prediction_jobBatch_predict generates a table with forecasts and gives a random name to that table, using the below code we can rename the table to make it parametric in our workflow.# read and update the name of the table with forecasts generated.def rename_batch_prediction_table( project: str, batch_prediction_job, bigquery_destination_dataset: str, final_table_name: str): # Extract the Vertex Generated Table ID if not batch_prediction_job.output_info.bigquery_output_table: print("No BigQuery output table found.") return generated_table_id = batch_prediction_job.output_info.bigquery_output_table print(f"Vertex Generated: {generated_table_id}") # Construct Destination ID: project.dataset.table source_table_id = f"{bigquery_destination_dataset}.{generated_table_id}" destination_table_id = f"{bigquery_destination_dataset}.{final_table_name}" try: bq_client = bigquery.Client(project=project) print(f"Copying to: {destination_table_id} ...") # Copy (Metadata operation - Instant & Free) copy_job = bq_client.copy_table( source_table_id, destination_table_id, job_config=bigquery.CopyJobConfig(write_disposition="WRITE_TRUNCATE") ) copy_job.result() # Wait for completion print(f"Success! Data moved to: {destination_table_id}") # Cleanup bq_client.delete_table(source_table_id) print("Cleaned up temporary Vertex table.") except GoogleAPICallError as e: print(f"BigQuery Operation Failed: {e}")We then trigger predictions for all three models using their specific model IDs.# model IDs can found in Vertex AI Model Registry.MODEL_ID = "7031639642906558464" MODEL_TYPE = "AUTOML"bp_job = create_batch_prediction_job_bigquery_table(PROJECT_ID, LOCATION, MODEL_ID, f"fs_{MODEL_TYPE}_poll_{HORIZON}", BQ_TABLE_INFERENCE, BQ_DATASET_PATH, True)rename_batch_prediction_table(PROJECT_ID, bp_job, BQ_DATASET_PATH, f"PREDICTION_{MODEL_TYPE}")Step 5. What Really Matters: The EvaluationAfter running the forecasts for a 48-hour window (Dec 15th to Dec 17th), we compare the results against the actual pollution values. Ideally, for a real application in production, we would run the evaluation across multiple windows (better if different seasons) and also extract the probabilistic forecasts (predictions with likelihoods) to get better confidence. For the sake of simplicity, we run the evaluation for a single window in this post.To start with evalution, we collect all forecasting results in a single table.# Collect all forecasting results in one table. query = f"""create or replace table {OUTPUT_PREDS_TABLE} asSELECT t1.date, t1.pollution as actual, round(t2.forecast_value, 2) as pred_timesfm, round(t3.time_series_data, 2) as pred_arimax, round(t4.predicted_pollution.value, 2) as pred_automl, round(t5.predicted_pollution.value, 2) as pred_tide, round(t6.predicted_pollution.value, 2) as pred_tft, round(t3.prediction_interval_lower_bound, 2) as pred_lower_bound, round(t3.prediction_interval_upper_bound, 2) as pred_upper_bound, FROM `{BQ_TABLE_TEST}` AS t1LEFT JOIN {PREDICTION_TIMESFM} AS t2 ON t1.date = t2.forecast_timestampLEFT JOIN {PREDICTION_ARIMAX} AS t3 ON t1.date = t3.time_series_timestampLEFT JOIN {PREDICTION_AUTOML} AS t4 ON t1.date = cast(t4.date as timestamp)LEFT JOIN {PREDICTION_TIDE} AS t5 ON t1.date = cast(t5.date as timestamp)LEFT JOIN {PREDICTION_TFT} AS t6 ON t1.date = cast(t6.date as timestamp)order by date;"""query_job = client.query(query)try: query_job.result() print("Evaluation table created successfully.")except Exception as e: print(f"Job failed with error: {e}")Visual Inspection:Seeing the values on a chart helps to get an understanding of the big picture and how the models look like relatively.import pandas as pdimport matplotlib.pyplot as pltquery = f""" SELECT * FROM {OUTPUT_PREDS_TABLE} """query_job = client.query(query)df = query_job.to_dataframe()df = df.head(48)plt.figure(figsize=(14, 7))# Plot Actual Dataplt.plot(df['date'], df['actual'], label='Actual Pollution', color='black', linewidth=2.5)# Plot Forecastsplt.plot(df['date'], df['pred_automl'], label='AutoML', linestyle='--')plt.plot(df['date'], df['pred_tide'], label='Tide', linestyle='--')plt.plot(df['date'], df['pred_tft'], label='TFT', linestyle='--')plt.plot(df['date'], df['pred_timesfm'], label='TimesFM', linestyle='--')plt.plot(df['date'], df['pred_arimax'], label='ARIMAX', linestyle='--')# Formattingplt.title('Pollution Forecast Comparison with Future Covariates', fontsize=16)plt.xlabel('Date', fontsize=12)plt.ylabel('Pollution Value', fontsize=12)plt.legend(loc='upper right')plt.grid(True, alpha=0.3)plt.xticks(rotation=45)plt.tight_layout()plt.show()As you can see in the chart below, AutoML (dashed blue line) aligns with the actual pollution (solid black line) closely, especially during the initial and end phases of the 48 hour horizon. However, to establish statistical confidence and objectively rank the candidates, we move beyond qualitative observation to the computation of precise error metrics.The Statistical Metrics:We now transition from qualitative visual inspection to quantitative assessment and calculate some key performance metrics: Mean Absolute Error (MAE), Root Mean Squared Error (RMSE), and Weighted Average Percentage Error (WAPE). These are a few examples of the metrics that allow us to objectively benchmark the models by penalizing variance and quantifying the deviation between predicted values and the ground truth.# Compute metrics for each model in the output tablequery = f""" SELECT * FROM {OUTPUT_PREDS_TABLE} """query_job = client.query(query)df = query_job.to_dataframe()df = df.head(48)# List of your prediction column namesmodel_columns = [ 'pred_automl', 'pred_tide', 'pred_tft', 'pred_timesfm', 'pred_arimapl',]actual_col = 'actual'results = []for model in model_columns: # Extract columns y_true = df[actual_col] y_pred = df[model] # Append results results.append({ 'Model': model, 'MAE': round(calculate_mae(y_true, y_pred), 2), 'RMSE': round(calculate_rmse(y_true, y_pred), 2), 'WAPE (%)': round(calculate_wape(y_true, y_pred), 2), })# View Resultsresults_df = pd.DataFrame(results)print(results_df)Note: In this specific short-window test, AutoML, TFT and ARIMAX emerged as the clear frontrunners, outperforming the competition.Step 6. The Final Verdict: Comparison with EnsembleWhile AutoML is a strong individual porformer, we may want to see if we could squeeze out more accuracy by creating an Ensemble Model.We create two simple variations by averaging the results from the high performing models to uncorrelate the errors.Ensemble 1: A simple average of the three frontrunners: AutoML, TFT, and ARIMA+.Ensemble 2: A combination of the two leading deep learning architectures: AutoML and TFT.# creating ensemble models with AutoML, ARIMAX and TFT.query = f""" SELECT *, round((pred_automl + pred_tft + pred_arimax)/3, 2) as pred_ensemble1,round((pred_automl + pred_tft)/2, 2) as pred_ensemble2FROM {OUTPUT_PREDS_TABLE} """query_job = client.query(query)df = query_job.to_dataframe()df = df.head(48)See the visual inspection and metrics for the comparison of the ensemble models against the individual models for different horizons, 48-hour and 24-hour.Both ensemble models for 48-hour horizon slightly outperformed AutoML, delivering the lowest error rate for different metrics. If we focus on 24-hour horizon, then the ensemble of the three models is slightly better than AutoML.Why does a simple average of different predictions beat a complex model? By averaging different models, we increase the changes of smoothing out the variance as when one model over predicts, the other likely under predicts and we may create a more robust signal. On the other hand, the cost and complexity increases, so we may choose this approach if it’s worth the difference in evaluation. In a real scenario, we would run these evaluation tests on different time windows and seasons to get a robust outcome and make the final decision for the model to run in production.It is worth noting that model selection is rarely a pure accuracy contest. In regulated industries like finance or healthcare, interpretability often becomes more important than raw performance, stakeholders need to understand the why behind a prediction, not just the what. While this requirement might restrict your deployable options to white-box models, it shouldn’t stop you from testing advanced black-box algorithms. Using a complex deep learning model as a benchmark allows you to quantify exactly how much accuracy you are sacrificing for the sake of explainability, ensuring that the trade-off is a conscious business decision.Step 7. ConclusionModern tools have commoditized the construction of complex architectures for forecasting, making it easy to benchmark statistical baselines against cutting-edge deep learning and foundation models. This streamlined environment allows for rapid evaluation and ensembling of candidates, shifting the focus from manual tuning to strategic drivers that actually move the needle: domain expertise, data enrichment, and fast deployment.Why the race matters?The ROI of Accuracy- Quantifying the Business ImpactForecasting is a game of inches, where minor accuracy gains yield significant capital efficiency. In our benchmark, the Ensemble model achieved a 21.87% WAPE, outperforming the individual AutoML champion (22.84% WAPE) by nearly 1%. A mere 1% improvement in model accuracy might seem negligible on a dashboard, but at scale, it translates to massive capital efficiency. Consider the inventory management in grocery retail e.g. overstocking diary products leads to direct waste and degrading cash flow efficiency, while understocking leads to lost revenue and customer frustration. As an illustrative number, for a category with $10 million in annual Cost of Goods Sold (COGS), reducing the error by just 1% enables more precise procurement cycles. This shift recovers approximately $100,000 annually, capital previously lost to physical waste or tied up in safety stock. When multiplied across thousands of SKUs and locations, tightening that error margin by even a fraction can save millions in inventory costs and lost sales.Call to ActionReady to race these models on your own data? Let me know how you get on, and how your business value looks like. Good luck! 🍀The Modern Forecasting Stack: From ARIMA to Deep Learning and Foundation Models on Google Cloud was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.