Real-time strategies (Belgian implicit balancing)¶
This page explains the money-making layer that runs on top of the real-time engine (docs/realtime_engine.md):
how each strategy decides, how to run the evidence backtest on Elia Open Data, and how to add a strategy. The
results themselves live in reports/realtime_belgium.md, regenerated by scripts/research/realtime_backtest.py.
The setting: a battery deviates from its nomination minute by minute; Elia settles every quarter-hour at the single
imbalance price. Discharging (power > 0) makes the BRP long and is paid the price; charging pays it. A decision for
minute t may only use data published by t (see the information model in docs/realtime_engine.md).
Strategies¶
| Strategy | Module | Idea | Tradable |
|---|---|---|---|
IdleStrategy |
strategies/base.py |
never trades (zero baseline) | yes |
ThresholdStrategy(mode="price") |
strategies/threshold.py |
act when the running quarter-hour price leaves quantile bands of recent final prices | yes |
ThresholdStrategy(mode="si") |
strategies/threshold.py |
act on the running system imbalance (formula-independent) | yes |
ForecastMPCStrategy |
strategies/forecast_mpc.py |
rolling stochastic MPC on forecast price distributions | yes |
PrismStrategy (SCALES-L) |
strategies/prism.py |
same MPC core, prices from a mechanism-aware state forecast | yes |
RLStrategy |
strategies/rl.py |
double DQN on discretised power (baseline from the RL literature) | yes |
OracleQHStrategy |
strategies/oracle.py |
perfect-foresight LP on final prices (upper bound only) | no |
Forecasting layer (realtime/forecasting)¶
build_features(market, publication, FeatureConfig(...))returns one row per decision minute built only from visible data: running quarter-hour-to-date SI/price/MIP/MDP/alpha/aFRR price (ODS133/ODS165, cumulative), instantaneous SI and activations (ODS126), a projected final SI and the mechanism applied to it, the previous quarter-hour's last visible values, Elia's SI forecasts and probability bins (ODS136/ODS147), day-ahead price, recent published final prices and calendar. Feature groups:INVARIANT_GROUPS(mechanism-invariant state),current_mech,new_mech. Field names are fixed by the config, so a missing input is an all-NaN column.monthly_folds(...),single_fold(...),training_rows(...): walk-forward splits; a fold trains at the start of its test month and drops training rows whose target was not yet published (embargo).PriceForecaster: gradient-boosting heads (quantiles 10/25/50/75/90 %, mean, P(SI < 0)) for the current and the next quarter-hour. Heads learn the residual to the running estimate (CURRENT_PRICE_BASELINE).PrismForecaster: P(SI < 0) x regime-conditional component distributions, priced by the mechanism operator (regime_components):current= MIP + alpha / MDP - alpha;new2026= volume-weighted main components, either published (ODS212) or reconstructed from current-design state (components="reconstructed", zero new-formula price history).forecast_skill(...): pinball loss, CRPS, MAE (mean / median / running estimate / last final), 80 % coverage and Brier score per minute-in-quarter-hour.
scikit-learn is the optional extra ml and is imported only when a model is fitted.
Forecast MPC¶
ForecastMPCStrategy(forecaster, MPCConfig(...)):
resetasks the forecaster for per-minute price distributions of the current and next quarter-hour (computed from the decision context's market, so the audit perturbs them too).- A stochastic dynamic programme on a state-of-charge grid gives the value of stored energy at the start of the
next quarter-hour: stage 1 uses the model's next-quarter-hour distribution (re-planned at
replan_minutes), stages 2..horizon_qhuse 28-day same-time-of-day quantiles of published prices, and the energy left at the horizon is valued at the trailing 7-day mean price. Two fractional transitions represent exactly full power, and a per-quarter-hour discount (discount_per_qh=0.995) makes the policy act now when expected prices are equal. - Every minute
remaining_qh_energysolves the energy of the rest of the current quarter-hour in closed form against that value function (SOC limits, efficiencies, degradation) and spreads it over the remaining minutes.risk="neutral"trades on the forecast mean;risk="quantile"discharges on therisk_quantilequantile and charges on1 - risk_quantile(a trade filter);risk="cvar"blends the mean with tail means. - By default it never pays to inject (
allow_negative_price_discharge=False): at hugely negative prices a rolling plan can keep paying to "make room for the next quarter-hour" without ever charging that room (seen on 6 April 2026, five quarter-hours at -15,000 EUR/MWh).
Performance: the DP is vectorised over all quarter-hours in reset; a decision is a few microseconds, so 2.4 years
of minutes take about a minute per strategy.
SCALES-L (mechanism-aware strategy)¶
SCALES-L is the control layer of the SCALES framework (State, Code/mechanism, Agent impact, Lag-aware control,
Equilibrium, Structured contracts). The module and class names keep the earlier working name PRISM
(strategies/prism.py, PrismStrategy, PrismForecaster).
PrismStrategy(PrismForecaster(...)) is the mechanism-decoupled strategy: forecast the state, not the price. Both
Elia formulas map the final SI regime and regime components to the price, so the forecaster learns P(SI < 0)
(identical under both formulas) and the component distributions, and the price distribution is the operator
applied to the forecast state. It refuses to run under a mechanism whose operator it does not implement. With
components="reconstructed" a new-formula strategy is trained before any new-formula price exists; see the
natural experiment in reports/realtime_belgium.md.
RL baseline¶
train_dqn(market, battery, train=..., validation=..., config=DQNConfig(...)) trains a double DQN (five power
levels, 26 causal market features + SOC + energy already delivered in the quarter-hour, reward = realised price x
energy - degradation) on a vectorised environment of parallel days, keeps the checkpoint that is best on the
validation days and stops at max_minutes. torch is the optional extra rl (device mps when available). The
policy is exported to numpy (DQNPolicy.save/load), and RLStrategy(policy) needs no torch at inference.
Live running-price fusion¶
RunningEstimateFusion(forecaster, running_field, error_variance) (forecasting/fusion.py) combines a forecaster's
current-quarter-hour distribution with the live running quarter-hour-to-date price by precision weighting. The
observation variance per visible minute is estimated with running_error_variance(...) on a training window of
the formula then in force; applied to the new formula's running price it lets a zero-history SCALES-L forecaster use
the strongest late-quarter-hour signal from the first day after the switch.
Live (paper) trading¶
The strategies plug into realtime.live (euroflex live run --strategy <name>):
- Re-planning. The live engine calls
refresh(ctx)before every decision on a window whose arrays are filled in place.ForecastMPCStrategy.refresh(and therefore SCALES-L) recomputes the forecasts at the current minute and at the re-plan minutes of the current quarter-hour, plus that quarter-hour's value-to-go (MPCPlan.update);RLStrategy.refreshrebuilds the observations but keeps the energy already delivered in the quarter-hour.tests/test_rt_strategy_live_refresh.pyreplays a window minute by minute and requires the live decisions to equal the backtest decisions. - Factories.
LIVE_STRATEGIESinforecast_mpc.py(forecast-mpc),prism.py(prism,scales-l;mechanism="auto"switches from the current operator to the zero-history new operator plus live fusion when the settlement rule changes, viaMechanismSwitchStrategy) andrl.py(rl-dqn). - Deployment fold.
python scripts/research/realtime_backtest.py --stages deployfits the forecasters on the latest six months with a test window that starts at the last available day (forecasting.deploy). The pickled models go to$EUROFLEX_MODELS_DIR(default~/.cache/euroflex_bess_lab/realtime_backtest/models); the RL policy is also committed asreports/ledgers/realtime_rl_policy.npz. Re-run the stage after refreshingdata/public.
Running the backtest¶
python scripts/research/realtime_backtest.py # semantics, train, rl, simulate, audit, report
python scripts/research/realtime_backtest.py --stages report # rebuild the report from cached results
python scripts/research/realtime_backtest.py --quick --out /tmp/realtime_quick # smoke test, short periods
Stages cache their outputs outside the checkout ($EUROFLEX_CACHE_DIR/realtime_backtest, default
~/.cache/euroflex_bess_lab/realtime_backtest; override with --cache) and can be resumed; --force recomputes.
Periods: (A) 2024-06-01..2026-01-01 current formula, (B) 2026-01-01..2026-08-01 both formulas on the same days,
(C) 2026-08-01..latest data. Batteries 1 MW / 2 MWh and 1 MW / 1 MWh, efficiencies 0.95/0.95, degradation 8 EUR per
MWh discharged, 1-minute publication lag (sensitivity 0-3), final prices 5 minutes after the quarter-hour.
Quarter-hour ledgers for the valuation layer are written to reports/ledgers/realtime_<strategy>_<mechanism>_<period>.parquet
with JSON sidecars.
A single run in Python:
from euroflex_bess_lab.realtime import BatteryParams, MarketData, check_no_lookahead, simulate
from euroflex_bess_lab.realtime.forecasting import PriceForecaster, monthly_folds
from euroflex_bess_lab.realtime.strategies.forecast_mpc import CachedForecaster, ForecastMPCStrategy, MPCConfig
market = MarketData.from_public("2025-01-01T00:00:00Z", "2025-05-01T00:00:00Z")
folds = monthly_folds("2025-04-01", "2025-05-01", data_start="2025-01-01", train_months=3)
forecaster = CachedForecaster(PriceForecaster().fit(market, folds))
battery = BatteryParams(power_mw=1.0, energy_mwh=2.0)
april = market.slice("2025-04-01T00:00:00Z", "2025-05-01T00:00:00Z")
result = simulate(april, ForecastMPCStrategy(forecaster, MPCConfig(risk="quantile")), battery)
print(result.summary())
print(
check_no_lookahead(
lambda: ForecastMPCStrategy(forecaster.forecaster),
april.slice("2025-04-10T00:00:00Z", "2025-04-12T00:00:00Z"),
battery,
cut_minute=1503,
)
)
Adding a strategy¶
- Subclass
BaseStrategy(or implement theStrategyprotocol):name,reset(ctx),decide(ctx) -> float(MW for the next minute, + = discharge). The simulator clips to power and SOC limits. - Only use visible information: the
DecisionContexthelpers (latest,latest_in_current_qh,minute_window,settlement_window,da_price, ...) or arrays derived inresetfromctx.marketwhere rowtuses only rows belowctx.visible_minute_end/ctx.visible_qh_end. Never read data from outsidectx.market(a look-ahead audit cannot see it). - Prove it:
check_no_lookahead(lambda: MyStrategy(...), market, battery, cut_minute=...)must pass on synthetic data (realtime.forecasting.synthetic.synthetic_market) and on a real-data slice, at several cut minutes. For strategies with precomputed plans, also compare the plan arrays under perturbation (seetests/test_rt_strategy_prism.py::test_white_box_plan_is_causal). - Fit anything learnable on a training window that ends before the test window (walk-forward), fix
hyper-parameters before looking at test results, and add the strategy to
MAIN_STRATEGIESinscripts/research/realtime_backtest.pyto include it in the report.