Forecast the electricity consumption of each region every day with PySpark
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_historyandeco2mix_regional_realtime, the viewregional_consumption_hourlyand the scheduled workflowDaily 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.
This guide assumes you are comfortable with Python and the basics of PySpark.
What you will build
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.
-
Open Lakehouse Manager > Tables and click New table > Create an empty table.
-
Name the table
regional_forecasts, keep the datasetdefault_datasetand click Create. -
Open the table, then its Schema tab. For each attribute below, click New attribute, fill in its name and data type, then click Save:
-
Click Build.
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
- Open Data Processing Engine > Notebooks and click New notebook.
- Select the image PySpark notebook and click Select.
- Name the notebook server
regional-forecast. - In its Preferences tab, in the Dependencies section, click Add, keep the type Python and enter
holidaysandscikit-learn, pressing Enter after each one. Click Add. - Click Create: the server starts.
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
- Once the server has started, click Open in Jupyter.
- In JupyterLab, click Upload Files in the file browser and select
eco2mix_regional_exploration.ipynb. - Open the notebook, with the kernel Python 3 (ipykernel), and run its cells in order.
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
- In JupyterLab, upload
eco2mix_regional_production.ipynbwith Upload Files and open it, with the kernel Python 3 (ipykernel). - Run its cells in order. The last one writes tomorrow's 288 forecasts to
regional_forecasts, and a second run replaces them.
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, thenSparkSession.builder.getOrCreate(): in the notebook,connect()creates the Spark session with the settings of the lakehouse, without which Spark cannot read the viewregional_consumption_hourly. In the action, the session already exists.getOrCreate()then returns that session in both cases.logginginstead ofprint: the messages show under each cell in the notebook, and in Logs Explorer with their level once the code runs as an action.lineage_runandsetJobDescription: declare the lineage (Step 7) and name the Spark jobs in the Spark History Server (Step 5).- Training window cached,
spark.sql.shuffle.partitionsset to 12, latest measured hour read from the real-time table: keep the run short, see Step 5.
Exporting the notebook
- Save the notebook: the export reads the file on disk.
- In the left sidebar of JupyterLab, open the Data Platform panel and click Actions.
- 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.
- Notebook:
- Check the summary, then click Create action. The entry function is
customfunc: the code is wrapped indef customfunc(event):and the text cells are ignored. Dependencies listsholidaysandscikit-learn: the export adds the Python dependencies of the notebook server to the action, so there is nothing to install by hand.
Configuring the action
-
Open Data Processing Engine > Actions, then
regional_forecast. -
Check the Configuration tab: Python requirements lists
holidaysandscikit-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.
-
In the Preferences tab, set the resources and options:
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.
When you are done with the notebooks, stop the notebook server to free its DPU.
Step 4: Running the job and reading its logs
- Click Run. The first run builds an image with the Python requirements, which takes about 5 minutes. The next runs reuse it.
- In Jobs, open the run, then click Drill-down in Logs Explorer.
The lines written by the job:
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:
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.
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.partitionsis 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.
-
Open Data Processing Engine > Workflows, click New workflow and name it
Daily regional forecast. -
In the workflow builder, click Add your first action and select
regional_forecast, then click Create. -
In the Preferences tab, in the Triggers section, click Add and fill in the trigger: name
Every morning, type Cron, mode Advanced, expression37 6 * * *. Click Confirm. -
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:
Leave the Parallelization options turned off: two runs at the same time would both delete and write the forecasts of the same day.
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
- In the Alerts tab of the workflow, click New alert.
- Select the metric Status: the value is set to Failed. Click Next.
- Check the subscribers: your account is listed. Click Next.
- Name the alert
Regional forecast failedand click Confirm.
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:
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), toeco2mix_regional_realtime;- both tables, through
regional_forecast(SDK · custom), toregional_forecasts.
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.
Compare the morning of a day as the collection of that day saw it with the same morning today:
-
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.
-
In the Explorer, run the query below, with that ID and that day:
-
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.
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:
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.
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
Bias: which way the forecast is wrong
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
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.