feat: electricity fee provider framework and generic providers (#1235)

Add new provider class for electricity fees providers.

Add the generic providers:
- ElecFeeFixed
- ElecFeeImport

The providers provide predictions for:

- elecfee_consumption_amt_wh:
  Total fixed fee for consumed energy per Wh [amount/Wh]. This is the accumulation of all
  fixed per-Wh fees payable on "consumed energy - such as network charge, concession fee,
  and electricity charge - into a single amount.
- elecfee_consumption_percent_amt:
  Total fixed surcharge on consumed energy, given as a percentage of the monetary amount
  already charged for that energy [%]. This is the accumulation of all percentage-based
  surcharges payable on top of the consumed-energy fee - such as VAT - into a single
  percentage. This is a percentage of the fee amount, not a per-Wh rate.
- elecfee_feedin_amt_wh:
  Total fixed deduction from feed-in energy per Wh [amount/Wh]. This is the accumulation of
  all fixed per-Wh charges deducted from feed-in energy - such as metering fees or
  grid-operator handling "charges - into a single amount. Applied after the percentage-based
  deduction, i.e. it reduces the price by a flat amount per Wh rather than by a share of the
  raw price.
- elecfee_feedin_percent_amt:
  Total percentage deducted from the raw feed-in price (spot price) [%]. This is the
  accumulation of all percentage-based deductions payable on the feed-in tariff - such as a
  marketing or balancing fee retained by the aggregator - into a single percentage. It is
  applied as `raw_price * (100 - percent) / 100`, i.e. it scales down the raw price rather
  than adding a surcharge to it.

A new _apply_fee() method is added to the base class for ElecPrice and FeedInTariff to be used to
add the fees in a consistent way. Fees are taken from the active ElecFee provider and applied
to the raw prices given to the _apply_fee() method.

The optional application of fees is added to:

- ElecPriceAkkudoktor
- ElecPriceFixed
- ElecPriceEnergyCharts
- ElecPriceSMARD
- FeedInTariffEnergyCharts
- FeedInTariffFixed
- FeedInTariffSMARD

The import providers ElecPriceImport and FeedInTariffImport do not apply fees by intentention.

The following providers currently do not handle fees defined by ElecFee:

- ElecPriceTibber
- FeedInTariffAkkudoktor
- FeedInTariffDvhubOnline
- FeedInTariffTibber

The tests for this feature are either added or existing tests are extended.

The documentation was extended for the electricity fee provider settings.

Besides this feature further improvements are added:

* feat: add SMARD quarter-hour electricty price and feed-in tariff provider

* feat: to_series method for TimeWindows and ValueTimeWindows

  Additional to to_array the time window sequence can now also produce a pandas series.
  Test have been extended to cover the series generation.

* feat: use time windows in fixed feedin tariff provider

  Feedin tariff can now be configured by time windows - not a single value.

* feat: EOSdash select for PVLib inverters and modules

  Provide PVLib inverter and module names in config selection.

* feat: EOSdash lazy select for big option sets

  Add a new form for lazy selection of big option sets. Filtering and
  generation of the option set is done server-side.

* fix: use raw data for ETS/ median prediction

  Use to raw time series data for ETS/ median prediction to avoid interference
  by e.g. dynamic grid charges.

* fix: EOSdash config drops by type only on details resolve

  Drop configuration by type and path. Prevents dropping of configuration items
  with same type and level but different path.

* fix: EOSdash configuration section closes on update

  Open section if searching or if last update touched this category — including
  updates on deeply nested sub-fields.

* chore: make elecfeefixed, elecpricefixed and feedintarifffixed warn about no windows and default to 0

  Missining configuration creates default 0 value and a warning instead of an exception.

* fix: test setup for providers

  Reset db state on each test run.

* chore: improve config option naming for elecpricefixed.

* chore: adapt elecpricefixed test to changed time_windows naming

* chore: factorized common price provider helpers to priceabc.py

  Factorized common price provider helpers to priceabc.py. Add tests for these helpers.
  Reduce/ change testing of elecpriceabc.py and feedintariffabc.py to cover
  only specifics. Rest of testing is already covered by test_priceabc.py.

* chore: update version

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
This commit is contained in:
Bobby Noelte
2026-08-23 02:26:16 +02:00
committed by GitHub
parent 6849b731b0
commit ba76087db9
71 changed files with 6584 additions and 1191 deletions
+6 -1
View File
@@ -43,6 +43,7 @@ from akkudoktoreos.core.version import __version__
from akkudoktoreos.devices.devices import DevicesCommonSettings
from akkudoktoreos.measurement.measurement import MeasurementCommonSettings
from akkudoktoreos.optimization.optimization import OptimizationCommonSettings
from akkudoktoreos.prediction.elecfee import ElecFeeCommonSettings
from akkudoktoreos.prediction.elecprice import ElecPriceCommonSettings
from akkudoktoreos.prediction.feedintariff import FeedInTariffCommonSettings
from akkudoktoreos.prediction.load import LoadCommonSettings
@@ -264,6 +265,9 @@ class SettingsEOS(pydantic_settings.BaseSettings, PydanticModelNestedValueMixin)
prediction: Optional[PredictionCommonSettings] = Field(
default=None, json_schema_extra={"description": "Prediction Settings"}
)
elecfee: Optional[ElecFeeCommonSettings] = Field(
default=None, json_schema_extra={"description": "Electricity Fee Settings"}
)
elecprice: Optional[ElecPriceCommonSettings] = Field(
default=None, json_schema_extra={"description": "Electricity Price Settings"}
)
@@ -312,6 +316,7 @@ class SettingsEOSDefaults(SettingsEOS):
measurement: MeasurementCommonSettings = Field(default_factory=MeasurementCommonSettings)
optimization: OptimizationCommonSettings = Field(default_factory=OptimizationCommonSettings)
prediction: PredictionCommonSettings = Field(default_factory=PredictionCommonSettings)
elecfee: ElecFeeCommonSettings = Field(default_factory=ElecFeeCommonSettings)
elecprice: ElecPriceCommonSettings = Field(default_factory=ElecPriceCommonSettings)
feedintariff: FeedInTariffCommonSettings = Field(default_factory=FeedInTariffCommonSettings)
load: LoadCommonSettings = Field(default_factory=LoadCommonSettings)
@@ -621,6 +626,7 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
# This should not happen
raise RuntimeError("Config file path not set.")
settings = {}
try:
backup_file = config_file.with_suffix(f".{to_datetime(as_string='YYYYMMDDHHmmss')}")
if migrate_config_file(config_file, backup_file):
@@ -632,7 +638,6 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
logger.error(
f"Error reading config file '{config_file}' (falling back to default config): {ex}"
)
settings = {}
return settings
+170
View File
@@ -7,6 +7,7 @@ from enum import StrEnum
from typing import Any, ClassVar, Iterator, Optional, Union
import numpy as np
import pandas as pd
import pendulum
from babel.dates import get_day_names
from pydantic import Field, field_serializer, field_validator, model_validator
@@ -668,6 +669,76 @@ class TimeWindowSequence(SettingsBaseModel):
return np.array(result, dtype=np.float64)
def to_series(
self,
start_datetime: DateTime,
end_datetime: DateTime,
interval: Duration,
dropna: bool = True,
boundary: str = "context",
align_to_interval: bool = True,
) -> pd.Series:
"""Return a pandas Series indicating window coverage over a time grid.
The time grid is constructed from ``start_datetime`` to ``end_datetime``
(exclusive) in steps of ``interval``. Each element is ``1.0`` when the
corresponding step falls inside any window in this sequence, and ``0.0``
otherwise.
Args:
start_datetime: First step of the time grid (inclusive).
end_datetime: Upper bound of the time grid (exclusive).
interval: Fixed step size between consecutive grid points.
dropna: Unused for ``TimeWindowSequence`` (no NaN values are
produced). Accepted for signature compatibility.
boundary: Controls range enforcement. Only ``"context"`` is
currently supported.
align_to_interval: When ``True``, ``start_datetime`` is floored to
the nearest interval boundary in wall-clock time before
generating the grid. The timezone (or naivety) of
``start_datetime`` is preserved exactly.
Returns:
``pd.Series`` with a ``DatetimeIndex`` and ``float64`` values.
``1.0`` means the timestamp is inside a window; ``0.0`` means it
is not.
Raises:
ValueError: If ``boundary`` is not ``"context"``.
"""
if boundary != "context":
raise ValueError(f"Unsupported boundary {boundary!r}. Only 'context' is supported.")
interval_s = interval.total_seconds()
if align_to_interval and interval_s > 0:
# Floor purely in wall-clock seconds so the timezone (or naivety)
# of start_datetime is never touched and no UTC conversion occurs.
wall_s = (
start_datetime.hour * 3600
+ start_datetime.minute * 60
+ start_datetime.second
+ start_datetime.microsecond / 1_000_000
)
remainder_s = wall_s % interval_s
if remainder_s:
start_datetime = start_datetime.subtract(seconds=remainder_s)
timestamps: list[DateTime] = []
values: list[float] = []
current = start_datetime
while current < end_datetime:
timestamps.append(current)
values.append(1.0 if self.contains(current) else 0.0)
current = current.add(seconds=interval_s)
return pd.Series(
values,
index=pd.DatetimeIndex(timestamps),
dtype=np.float64,
)
def add_window(self, window: TimeWindow) -> None:
"""Add a new time window to the sequence.
@@ -861,3 +932,102 @@ class ValueTimeWindowSequence(TimeWindowSequence):
current = current.add(seconds=interval_s)
return np.array(result, dtype=np.float64)
def to_series(
self,
start_datetime: DateTime,
end_datetime: DateTime,
interval: Duration,
dropna: bool = True,
boundary: str = "context",
align_to_interval: bool = True,
) -> pd.Series:
"""Return a pandas Series of window values over a time grid.
The time grid is constructed from ``start_datetime`` to ``end_datetime``
(exclusive) in steps of ``interval``, matching the ``key_to_series``
signature used by the prediction store. Each element holds the
``value`` of the first matching window at that step, ``0.0`` when no
window matches, or ``NaN`` when the matching window has ``value=None``
and ``dropna=False``.
When ``dropna=True``, steps whose matching window has ``value=None`` are
omitted from the resulting Series entirely, including their timestamps.
Args:
start_datetime: First step of the time grid (inclusive).
end_datetime: Upper bound of the time grid (exclusive).
interval: Fixed step size between consecutive grid points.
dropna: When ``True``, steps whose matching window carries
``value=None`` are dropped from the Series. When ``False``,
those steps emit ``NaN``.
boundary: Controls range enforcement. Only ``"context"`` is
currently supported; the output is always clipped to
``[start_datetime, end_datetime)``.
align_to_interval: When ``True``, ``start_datetime`` is floored to
the nearest interval boundary in wall-clock time before
generating the grid. The timezone (or naivety) of
``start_datetime`` is preserved exactly — no UTC conversion
is performed. When ``False``, ``start_datetime`` is used as-is.
Returns:
``pd.Series`` with a ``DatetimeIndex`` and ``float64`` values.
Positive values are window values; ``0.0`` means no window matched;
``NaN`` means a window matched but its value was ``None`` (only when
``dropna=False``).
Raises:
ValueError: If ``boundary`` is not ``"context"``.
"""
if boundary != "context":
raise ValueError(f"Unsupported boundary {boundary!r}. Only 'context' is supported.")
interval_s = interval.total_seconds()
if align_to_interval and interval_s > 0:
# Floor purely in wall-clock seconds so the timezone (or naivety)
# of start_datetime is never touched and no UTC conversion occurs.
# This is correct regardless of the machine's local timezone.
wall_s = (
start_datetime.hour * 3600
+ start_datetime.minute * 60
+ start_datetime.second
+ start_datetime.microsecond / 1_000_000
)
remainder_s = wall_s % interval_s
if remainder_s:
start_datetime = start_datetime.subtract(seconds=remainder_s)
timestamps: list[DateTime] = []
result: list[float] = []
current = start_datetime
while current < end_datetime:
step_value: Optional[float] = None
matched = False
for window in self.windows:
if window.contains(current):
step_value = window.value
matched = True
break
if not matched:
timestamps.append(current)
result.append(0.0)
elif step_value is None:
if not dropna:
timestamps.append(current)
result.append(float("nan"))
# else: omit this step and its timestamp
else:
timestamps.append(current)
result.append(step_value)
current = current.add(seconds=interval_s)
return pd.Series(
result,
index=pd.DatetimeIndex(timestamps),
dtype=np.float64,
)
+23 -1
View File
@@ -62,11 +62,18 @@ MIGRATION_MAP: Dict[
"devices/batteries/0/initial_soc_percentage": None,
# - electric_vehicles
"devices/electric_vehicles/0/initial_soc_percentage": None,
# elecfee
# =======
# - ElecFeeFixed
# - ElecFeeImport
# elecprice
# =========
"elecprice/charges_kwh": None,
"elecprice/vat_rate": None,
# - ElecPriceAkkudoktor
# - ElecPriceEnergyCharts
# - ElecPriceFixed
"elecprice/elecpricefixed/time_windows": "elecprice/elecpricefixed/elecprice_marketprice_amt_kwh",
# - ElecPriceImport
"elecprice/provider_settings/ElecPriceImport/import_file_path": "elecprice/elecpriceimport/import_file_path",
"elecprice/provider_settings/ElecPriceImport/import_json": "elecprice/elecpriceimport/import_json",
@@ -75,7 +82,22 @@ MIGRATION_MAP: Dict[
# feedintariff
# ============
# - FeedInTariffFixed
"feedintariff/provider_settings/FeedInTariffFixed/feed_in_tariff_kwh": "feedintariff/feedintarifffixed/feed_in_tariff_kwh",
"feedintariff/feedintarifffixed/feed_in_tariff_kwh": (
"feedintariff/feedintarifffixed/feed_in_tariff_amt_kwh",
lambda v: {
"windows": [
{"start_time": "00:00", "duration": "24 hours", "value": float(v)},
],
},
),
"feedintariff/provider_settings/FeedInTariffFixed/feed_in_tariff_kwh": (
"feedintariff/feedintarifffixed/feed_in_tariff_amt_kwh",
lambda v: {
"windows": [
{"start_time": "00:00", "duration": "24 hours", "value": float(v)},
],
},
),
# - FeedInTariffImport
"feedintariff/provider_settings/FeedInTariffImport/import_file_path": "feedintariff/feedintariffimport/import_file_path",
"feedintariff/provider_settings/FeedInTariffImport/import_json": "feedintariff/feedintariffimport/import_json",