For AI agents: the complete documentation index is available at https://docs.ovhcloud.com/pl/llms.txt, the full documentation bundle is available at https://docs.ovhcloud.com/pl/llms-full.txt, and this page is available as Markdown at https://docs.ovhcloud.com/pl/guides/public-cloud/data-platform/tutorials-eco2mix-forecast-production.md.
Przejdź do treści

Forecast the electricity consumption of each region every day with PySpark

Pokaż jako Markdown

Find out how to train with PySpark a forecast model of electricity consumption per region, run it every morning and follow its accuracy

Objective

This guide walks you through building a daily forecast of regional electricity consumption with PySpark. You explore the regional consumption and train one forecast model per region in a notebook, then export the job to a Custom PySpark action with the Data Platform Extension and run it every morning to forecast the consumption of each region for every hour of tomorrow. Along the way you read its logs in Logs Explorer, follow its run in the Spark History Server, declare its lineage, go back in time with Time Travel and measure its accuracy with SQL.

It is the second part of Collect the daily electricity consumption of French regions.

By the end you will have the table regional_forecasts, filled every morning with 288 forecasts (12 regions × 24 hours) by a scheduled job that alerts you if it fails, and a view that compares each forecast with the consumption measured the next day.

Requirements

To follow this guide you need:

  • the tables eco2mix_regional_history and eco2mix_regional_realtime, the view regional_consumption_hourly and the scheduled workflow Daily realtime collection, built in Collect the daily electricity consumption of French regions. The job needs a collection from the day it runs: run the workflow if it has not run yet today.
  • the two files below.
FileDownload
Exploration notebookeco2mix_regional_exploration.ipynb
Production notebookeco2mix_regional_production.ipynb

This guide assumes you are comfortable with Python and the basics of PySpark.

What you will build

StageComponentResult
1. Prepare the output tableLakehouse Manager tablesregional_forecasts, empty, with five attributes
2. Explore and model in a notebookNotebooksOne model per region, tested on 2024
3. Export the jobData Platform Extension and Custom PySpark actionregional_forecast, the production notebook as an action
4. Run the job and read its logsLogs Explorer288 forecasts for tomorrow
5. Follow the runSpark History ServerThe jobs, stages and executors of the run
6. Schedule the forecastWorkflow and alertOne forecast every morning at 06:37 UTC, an alert if it fails
7. Check the lineagelineage_run and LineageThe job between its inputs and its output
8. Go back in timeTime TravelA past version of the real-time data, next to today's
9. Follow the forecast qualityLakehouse Manager viewsError and bias, day by day and region by region

Instructions

Step 1: Preparing the output table

The production notebook and the job write their forecasts to regional_forecasts. Create it in Lakehouse Manager, before the first run.

  1. Open Lakehouse Manager > Tables and click New table > Create an empty table.

  2. Name the table regional_forecasts, keep the dataset default_dataset and click Create.

  3. Open the table, then its Schema tab. For each attribute below, click New attribute, fill in its name and data type, then click Save:

    AttributeData typeContent
    forecast_hourDatetimeThe forecast hour, UTC
    region_codeNumber, numeric type IntegerThe INSEE code of the region
    region_nameStringThe name of the region
    predicted_mwNumber, numeric type DoubleThe forecast, in MW
    run_atDatetimeWhen the job ran, UTC
    The New attribute window for region_code, data type Number and numeric type Integer
  4. Click Build.

    The Schema tab of regional_forecasts with forecast_hour, predicted_mw, region_code, region_name and run_at
Info

Best practice: create the output tables of a job in Lakehouse Manager, as here. Lakehouse Manager, Trino and Spark all see them, and the SDK method insert_dataframe, which the job uses, writes into them.

Step 2: Exploring and modelling in a notebook

Creating the notebook server

  1. Open Data Processing Engine > Notebooks and click New notebook.
  2. Select the image PySpark notebook and click Select.
  3. Name the notebook server regional-forecast.
  4. In its Preferences tab, in the Dependencies section, click Add, keep the type Python and enter holidays and scikit-learn, pressing Enter after each one. Click Add.
  5. Click Create: the server starts.
The Preferences tab of regional-forecast with the Python dependencies holidays and scikit-learn

The server installs the two packages, ready for the notebook: holidays provides the French public holidays, scikit-learn the regression trained in each region.

Running the exploration notebook

  1. Once the server has started, click Open in Jupyter.
  2. In JupyterLab, click Upload Files in the file browser and select eco2mix_regional_exploration.ipynb.
  3. Open the notebook, with the kernel Python 3 (ipykernel), and run its cells in order.
SectionWhat it doesWhat you get
1. Set upConnects to default_dataset with connect("dwh/default_dataset/") and uses its Spark session, source.spark, set to UTCSpark 4.1.2 and the catalog of your project
2. LoadReads the view regional_consumption_hourly, adds Paris time columns and caches the resultAbout 1.45 million region-hours
3.1 CoverageCounts the measured hours per region and per year8,759 hours a year, 8,783 in leap years
3.2 and 3.3Compares the size of the regions, their daily profile and January with JulyThe same daily shape everywhere, a different sensitivity to cold
4. FeaturesAdds public holidays, hour of day crossed with the type of day, month, and the consumption 48 and 168 hours beforeA check on Christmas 2024
5. One model per regionTrains one regression per region with groupBy("region_code").applyInPandas(...) on 2022 and 2023, tests it on 2024An error from 3.67 % (Provence-Alpes-Côte d'Azur) to 6.55 % (Centre-Val de Loire), about a third below "same hour one week before"
6. Add up the regionsAdds up the 12 forecasts hour by hour and draws the week of 8 January 2024A chart of the actual and forecast consumption
Notebook section 3.1: measured hours per region and year, from 2013 to 2025 Notebook section 5: the 2024 error of each regional model next to the week-before forecast Notebook section 6: actual consumption and summed regional forecasts, week of 8 January 2024

The choices behind the model:

  • A short lag of 48 hours, not 24. The job runs on the morning of day D to forecast day D+1: day D is not over, so the latest complete day is D-1.
  • Lags by join on region and time, not with lag(): a missing hour would shift the rows.
  • A missing hour takes the value of the hour before. The dataset follows Paris time: on the day clocks go back in autumn, one UTC hour is missing, 00:00 UTC on 25 October 2026. Without this fallback, the forecasts of 27 October and 1 November, which need that hour as their 48- and 168-hour lags, could not be computed.
  • Public holidays count as Sundays, and the type of day is crossed with the hour: each type of day keeps its own shape.
  • One model per region, with applyInPandas: Spark sends the rows of each region to a Python worker, and the regions train side by side. That is what Spark brings here. The volume itself, about 1.45 million region-hours, stays modest.

Step 3: Exporting the production notebook as a Custom PySpark action

The exploration notebook is for exploring. The job lives in a second notebook, eco2mix_regional_production.ipynb, which holds only what the job needs. The Data Platform extension turns it into a Custom PySpark action, without copying code around.

Running the production notebook

  1. In JupyterLab, upload eco2mix_regional_production.ipynb with Upload Files and open it, with the kernel Python 3 (ipykernel).
  2. Run its cells in order. The last one writes tomorrow's 288 forecasts to regional_forecasts, and a second run replaces them.
SectionWhat it does
1. Set upImports, logging, the connection to default_dataset and its Spark session, in UTC
2. FeaturesParis time, public holidays and the consumption 48 and 168 hours before, with the hour before as a fallback
3. One model per regionfit_and_forecast, which applyInPandas runs once per region
4. Forecast tomorrow and write itRetrains each region on its most recent 730 days, forecasts every hour of tomorrow and replaces the forecasts of that day
5. RunDeclares the lineage, names the Spark jobs and logs the result

The notebook is written to run as a job:

  • Only the job: the export keeps every code cell and drops the text cells. The notebook holds no exploration, and the query that checks the result sits in a text cell.
  • connect() first, then SparkSession.builder.getOrCreate(): in the notebook, connect() creates the Spark session with the settings of the lakehouse, without which Spark cannot read the view regional_consumption_hourly. In the action, the session already exists. getOrCreate() then returns that session in both cases.
  • logging instead of print: the messages show under each cell in the notebook, and in Logs Explorer with their level once the code runs as an action.
  • lineage_run and setJobDescription: declare the lineage (Step 7) and name the Spark jobs in the Spark History Server (Step 5).
  • Training window cached, spark.sql.shuffle.partitions set to 12, latest measured hour read from the real-time table: keep the run short, see Step 5.

Exporting the notebook

  1. Save the notebook: the export reads the file on disk.
  2. In the left sidebar of JupyterLab, open the Data Platform panel and click Actions.
  3. Fill in the form, then click Preview:
    • Notebook: eco2mix_regional_production.ipynb;
    • Repository and Version: keep Default and the deployed version;
    • Create a new custom action, named regional_forecast, of type Custom PySpark.
  4. Check the summary, then click Create action. The entry function is customfunc: the code is wrapped in def customfunc(event): and the text cells are ignored. Dependencies lists holidays and scikit-learn: the export adds the Python dependencies of the notebook server to the action, so there is nothing to install by hand.
Exporting the production notebook as the Custom PySpark action regional_forecast from the Data Platform panel

Configuring the action

  1. Open Data Processing Engine > Actions, then regional_forecast.

  2. Check the Configuration tab: Python requirements lists holidays and scikit-learn, brought by the export, and PySpark version is the same as in the notebook (here 4.1.2). Each action has its own PySpark version: check it too when you copy an action.

    The Configuration tab of regional_forecast with its Python requirements and PySpark version 4.1.2
  3. In the Preferences tab, set the resources and options:

SettingValue
Executors3
Executor size1, which makes 3 DPU, plus 1 DPU for the driver
Logs Levelinfo

Depending on your capacity, you can raise the number of executors or their size. What matters is to keep several executors: Spark trains the regions on them in parallel.

The Preferences tab of regional_forecast: 3 executors and 1 driver of size 1, 4 DPU

When you are done with the notebooks, stop the notebook server to free its DPU.

Step 4: Running the job and reading its logs

  1. Click Run. The first run builds an image with the Python requirements, which takes about 5 minutes. The next runs reuse it.
  2. In Jobs, open the run, then click Drill-down in Logs Explorer.

The lines written by the job:

[INFO] Spark 4.1.2, catalog db_<id>_default_dataset
[INFO] Latest measured hour: 2026-11-24 10:00:00
[INFO] Forecast 2026-11-24 23:00:00 to 2026-11-25 23:00:00 (UTC): 288 region-hours
[INFO] Auvergne-Rhône-Alpes: trained on 17517 hours
[INFO] Bourgogne-Franche-Comté: trained on 17517 hours
[INFO] Bretagne: trained on 17518 hours
...
[INFO] Insert into table regional_forecasts completed
[INFO] regional_forecasts written
Logs Explorer for regional_forecast: training hours per region, insert into regional_forecasts, action completed in 82.4 seconds

In the Serverless execution mode, Data Platform allocates the resources for each run and releases them afterwards, so you only pay for the run. For a job that must start immediately, the Always-up execution mode (beta) keeps reserved instances.

To read the logs:

  • Times are in UTC in the logs, and in the time zone of your browser in the interface.
  • The states of the driver and executors are logged every 30 seconds.
  • A line Spark UI available at: https://<project>.eu.dataplatform.ovh.net/spark-ui-<id> gives the address of the live Spark interface, available while the run lasts.

In the Explorer, check what the job wrote:

SELECT run_at, count(*) AS forecasts
FROM regional_forecasts
GROUP BY run_at
ORDER BY run_at

You get one line of 288 forecasts per forecast day. The job first deletes the forecasts of the day it forecasts, then writes the new ones: this run replaced the forecasts that the production notebook wrote for the same day.

Step 5: Following the run in the Spark History Server

If the Spark History Server is stopped, start it first: see Spark History Server. Then, in Jobs, open the run and click Open on Spark History Server.

TabWhat it shows
JobsThe Spark jobs grouped under Train one model per region and forecast tomorrow, then Write regional_forecasts: these are the descriptions set by setJobDescription
Stages12 tasks for the training and the write stages, one per shuffle partition
ExecutorsThe driver and 3 executors with one core each: an executor is an instance of the action, and its size sets its memory
The Jobs tab of the Spark History Server with the training and write jobs The Spark History Server Stages tab: training and write stages of 12 tasks each The Executors tab of the Spark History Server with the driver and three executors of one core, which ran 28, 20 and 299 of the 347 tasks

What the run teaches, and what the production notebook does about it:

  • Without a cache, Spark computes the joins again for every Spark action. The job caches the training window.
  • spark.sql.shuffle.partitions is 200 by default. On 12 regions, a first version of the job ran 200 tasks to train and write, 188 of them empty. The job sets it to 12.
  • Reading a view for a single maximum computes its whole aggregation. The job reads the latest measured hour from the real-time table, the smallest one.
  • The duration of the first Spark job includes the wait for the executors.
  • At this volume, one executor runs most of the tasks: 299 of the 347 in this run. 12 regions are a small workload, and the same code spreads more evenly over the executors as the data grows.

The Spark History Server follows the runs of actions and workflows: this is why the parallel training is observed on the job rather than in the notebook.

Step 6: Scheduling the forecast

Spark actions get a workflow of their own: the forecast runs 20 minutes after the collection.

  1. Open Data Processing Engine > Workflows, click New workflow and name it Daily regional forecast.

  2. In the workflow builder, click Add your first action and select regional_forecast, then click Create.

  3. In the Preferences tab, in the Triggers section, click Add and fill in the trigger: name Every morning, type Cron, mode Advanced, expression 37 6 * * *. Click Confirm.

  4. In the same tab, set the resources and the Spark version of the workflow. The preferences of a workflow replace those of the actions it runs, so give it the settings of the action:

SettingValue
Executors3
Executor size1
Driver size1
Force workflow language version, in the Development language sectionOn, with Spark 4.1.2, the version the job was written for

Leave the Parallelization options turned off: two runs at the same time would both delete and write the forecasts of the same day.

The Preferences tab of the workflow Daily regional forecast with its resources and Spark 4.1.2

The job protects itself: if the morning collection is missing, tomorrow's lags are missing too, and the job raises an error instead of writing a wrong forecast. A single missing hour, such as the one at the autumn time change, does not stop the job: the missing hour takes the value of the hour before.

Getting an alert when it fails

  1. In the Alerts tab of the workflow, click New alert.
  2. Select the metric Status: the value is set to Failed. Click Next.
  3. Check the subscribers: your account is listed. Click Next.
  4. Name the alert Regional forecast failed and click Confirm.
The last step of the alert creation window, with the name Regional forecast failed

See Configure a job execution alert for the other conditions and options.

Step 7: Checking the lineage

Lineage is recorded automatically for the Load and Aggregate actions. A Custom action declares its own, with the SDK helper lineage_run. The last section of the production notebook already does it:

from forepaas.dwh.lineage import lineage_run

with lineage_run(
    "regional_forecast",
    inputs=[
        "default_dataset/eco2mix_regional_history",
        "default_dataset/eco2mix_regional_realtime",
    ],
    outputs=["default_dataset/regional_forecasts"],
    connector=source,
):
    ...

lineage_run sends a START event, then a COMPLETE or FAIL event, and never makes the action fail. connector= adds the schemas of the tables.

Open Lakehouse Manager > Lineage, select regional_forecasts, turn on Full Graph and set the Depth to 3. The graph shows three paths:

  • the Parquet file, through Load data (LHM · load), to eco2mix_regional_history: the first load done by Lakehouse Manager when it created the table;
  • regional.json, through the Load action (DPE · load), to eco2mix_regional_realtime;
  • both tables, through regional_forecast (SDK · custom), to regional_forecasts.
Full lineage graph of regional_forecasts at depth 3, from the Parquet file and regional.json

The graph follows the data from table to table, through the loads and the job. The actions that work inside a table, such as the SQL and Deduplicate actions, are not part of it.

Step 8: Going back in time with Time Travel

Open Lakehouse Manager > Tables > eco2mix_regional_realtime, then its Time Travel tab. Each collection leaves four versions: Data inserted by the Load action, Data updated by the SQL action, then Data deleted and Data inserted by the Deduplicate action. Snapshots are kept for 14 days by default.

The Time Travel tab of eco2mix_regional_realtime with the four versions of the last collection

Compare the morning of a day as the collection of that day saw it with the same morning today:

  1. Copy the Snapshot ID of the last version of a past day: it is the state of the table after the collection of that morning.

  2. In the Explorer, run the query below, with that ID and that day:

    SELECT date_heure, consommation, collected_at
    FROM eco2mix_regional_realtime FOR VERSION AS OF <snapshot ID>
    WHERE code_insee_region = 11
      AND date_heure BETWEEN TIMESTAMP '<day> 05:00:00' AND TIMESTAMP '<day> 08:00:00'
    ORDER BY date_heure
  3. Run it again without FOR VERSION AS OF <snapshot ID>.

In Île-de-France (region 11), the quarter hours measured before the collection, up to about 06:00 UTC, have the same consumption in both versions. The later ones are empty in the past version and filled in the current one, with the collected_at of a later collection: the Deduplicate action keeps the most recent value of each quarter hour.

The Explorer with the current version of the morning of 22 November 2026 in Île-de-France, every quarter hour filled and collected on 23 November

Step 9: Following the forecast quality

Comparing each forecast with the measurement

In Lakehouse Manager > Views, click New View and create the view regional_forecast_vs_actual in default_dataset, with table names only:

SELECT
    f.region_code,
    f.region_name,
    f.forecast_hour AS hour_utc,
    CAST(with_timezone(f.forecast_hour, 'UTC') AT TIME ZONE 'Europe/Paris' AS timestamp(6)) AS hour_paris,
    f.predicted_mw,
    a.consumption_mw AS actual_mw,
    abs(f.predicted_mw - a.consumption_mw) / a.consumption_mw AS ape,
    f.run_at
FROM regional_forecasts f
LEFT JOIN regional_consumption_hourly a
  ON a.region_code = f.region_code
 AND a.hour_utc = f.forecast_hour

Only Trino reads this view, so it can use the time zone functions of Trino to give the Paris time. ape is the absolute percentage error of each forecast: its average is the MAPE.

The Create a new view window with regional_forecast_vs_actual and its SQL definition

A forecast day is measured the next day: run the queries below once the job has run for a few days. Your figures depend on the days you run them. Those below cover 29 October to 5 November 2026.

Error day by day

SELECT CAST(hour_paris AS date)    AS day,
       count(*)                    AS forecasts,
       count(actual_mw)            AS measured,
       round(100 * avg(ape), 2)    AS mape_pct
FROM default_dataset.regional_forecast_vs_actual
GROUP BY CAST(hour_paris AS date)
ORDER BY day
Explorer: error per forecast day, from 3.84 % to 5.50 %, 29 October to 5 November

Bias: which way the forecast is wrong

SELECT CAST(hour_paris AS date)                                         AS day,
       round(100 * avg((predicted_mw - actual_mw) / actual_mw), 2)      AS bias_pct,
       count_if(predicted_mw > actual_mw)                                AS over_forecasts,
       count_if(predicted_mw < actual_mw)                                AS under_forecasts
FROM default_dataset.regional_forecast_vs_actual
WHERE actual_mw IS NOT NULL
GROUP BY CAST(hour_paris AS date)
ORDER BY day
Explorer: bias per forecast day, negative from 29 October to 5 November except 1 November
DayMAPEBiasOver / under forecasts
Thursday 29 October5.50 %-4.45 %56 / 232
Friday 30 October4.72 %-3.71 %75 / 213
Saturday 31 October3.84 %-2.29 %81 / 207
Sunday 1 November4.17 %+2.64 %200 / 88
Monday 2 November4.23 %-0.99 %103 / 185
Tuesday 3 November4.60 %-2.42 %81 / 207
Wednesday 4 November4.82 %-3.78 %60 / 228
Thursday 5 November4.77 %-1.23 %107 / 181

On Sunday 1 November, a public holiday, the errors lean the other way. On the other seven days, the model forecasts too low. In autumn, consumption rises from one week to the next as heating starts, and the model, which relies on the consumption 48 and 168 hours earlier, stays below it. A bias on the same side several days in a row is the signal to watch.

Error by region

SELECT region_name,
       count(actual_mw)            AS measured,
       round(100 * avg(ape), 2)    AS mape_pct
FROM default_dataset.regional_forecast_vs_actual
WHERE actual_mw IS NOT NULL
GROUP BY region_name
ORDER BY mape_pct
Explorer: error per region over the measured forecasts, from 3.85 % in Provence-Alpes-Côte d'Azur

Read this ranking over several weeks: over a few days, it changes a lot.

Good to know

  • Each run replaces the forecasts for its target day. The job deletes tomorrow's forecasts before it writes the new ones: you can run it again the same day.
  • The workflow's preferences override those of the action. When you change the resources or the Spark version of regional_forecast, change them in the workflow too.

What the weather would add

An error of 4 to 5 % already beats the forecast "same hour one week before" by about a third, with the calendar and the past consumption alone. What the model misses most is the weather. Heating makes consumption depend on the temperature: the first cold days of autumn raise it faster than the lags of 48 and 168 hours can follow, which is the bias of Step 9. Section 3.3 of the notebook also shows that each region reacts to the cold in its own way.

With a temperature forecast for each region among its features, each regional model could estimate the heating of the next day instead of inferring it from past days, and its error would drop markedly.

What you have built

You have a forecast of tomorrow's consumption for the 12 regions of mainland France, written every morning by a Custom PySpark job that runs the code of your notebook, alerts you when it fails and declares its lineage. You can follow each run in Logs Explorer and in the Spark History Server, and a view measures the forecast accuracy day after day.

From here, you can add a temperature forecast to the features, or build a dashboard on regional_forecast_vs_actual with Apache Superset.

Go further

For training or technical assistance implementing our solutions, contact your sales representative or visit our Professional Services page to request a quote and have your project analysed by our experts.

Ask questions, give your feedback and interact directly with the team building the Data Platform on the dedicated Discord channel.

If you need support with your OVHcloud services, create a request in our Help Centre.

Join our community of users.

Czy ta strona była pomocna?