Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.de.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Diese Integration ist Open Source, weil ich daran glaube, der Community, die Hom

### Stromtarife & -netz
- **Tarif-Integration** - Unterstützung für Tibber, Awattar, Nordpool, Octopus Energy und generische Preissensoren.
- **Externe Preisprognosen** - Ein optionaler [Prognosesensor](docs/price-forecast-input.de.md) übernimmt Vorhersagen eines eigenständigen Modells zur Diagnose. Veröffentlichte Tarifpreise bleiben die Grundlage der Steuerung.
- **Externe Preisprognosen** - Ein optionaler [Prognosesensor](docs/price-forecast-input.de.md) übernimmt Vorhersagen eines eigenständigen Modells zur Diagnose, einschließlich Punktschätzungen ohne Preisband in Version 2. Veröffentlichte Tarifpreise bleiben die Grundlage der Steuerung.
- **Einspeiselimit-Management** - Absorbieren potenziell abgeregelter Leistung möglich, z.B. wenn Einspeisebegrenzungen gelten.
- **Netzsupplementierung** - Möglichkeit, eine bestimmte Menge an Netzstrom zu erlauben, um Geräte zusätzlich zu supplementieren.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ The [0.4.0rc1 candidate notes](docs/release-candidate.md) explain migration and

### Tariffs & Grid
- **Tariff Integration** - Support for Tibber, Awattar, Nordpool, Octopus Energy, and generic price sensors.
- **External Price Forecasts** - An optional [forecast sensor](docs/price-forecast-input.md) accepts predictions from a separate model for diagnostics. Published tariffs remain the basis for control.
- **External Price Forecasts** - An optional [forecast sensor](docs/price-forecast-input.md) accepts predictions from a separate model for diagnostics, including version 2 point estimates without a price band. Published tariffs remain the basis for control.
- **Export Limit Management** - Absorb would-be-curtailed power when feed-in caps apply.
- **Grid Supplementation** - Allow a small amount of grid power to top up appliances.

Expand Down
50 changes: 35 additions & 15 deletions custom_components/pv_excess_control/price_forecast.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Validate external electricity price forecasts without Home Assistant access.

Version 1 is an observation contract. Its empirical bounds are not calibrated
probabilities and no accepted snapshot grants permission to control a device.
Versions 1 and 2 are observation contracts. Version 2 also represents point
forecasts with explicitly absent bounds. Accepted snapshots never grant device
control, and supplied bounds are not calibrated probabilities.
"""

from __future__ import annotations
Expand All @@ -19,23 +20,27 @@ class PriceForecastError(ValueError):

@dataclass(frozen=True)
class PriceForecastInterval:
"""One immutable interval with empirical price bounds in EUR/kWh."""
"""One immutable interval with optional explicit bounds in EUR/kWh."""

start: datetime
end: datetime
price: float
lower: float
upper: float
lower: float | None
upper: float | None
source: str | None = None

def as_dict(self) -> dict[str, Any]:
def as_dict(self, *, include_source: bool = True) -> dict[str, Any]:
"""Return an independent JSON-compatible representation."""
return {
result = {
"start": self.start.isoformat(),
"end": self.end.isoformat(),
"price": self.price,
"lower": self.lower,
"upper": self.upper,
}
if include_source and self.source is not None:
result["source"] = self.source
return result


@dataclass(frozen=True)
Expand All @@ -47,19 +52,20 @@ class PriceForecastSnapshot:
model: str
price_basis: str
intervals: tuple[PriceForecastInterval, ...]
schema_version: int = 1

def as_dict(self) -> dict[str, Any]:
"""Return only validated contract fields, without source-owned objects."""
return {
"schema_version": 1,
"schema_version": self.schema_version,
"market": "DE-LU",
"unit": "EUR/kWh",
"price_basis": self.price_basis,
"generated_at": self.generated_at.isoformat(),
"expires_at": self.expires_at.isoformat(),
"model": self.model,
"quality": {"status": "experimental", "automation_eligible": False},
"intervals": [row.as_dict() for row in self.intervals],
"intervals": [row.as_dict(include_source=self.schema_version == 2) for row in self.intervals],
}


Expand Down Expand Up @@ -99,7 +105,8 @@ def parse_price_forecast(payload: Any, *, now: datetime) -> PriceForecastSnapsho
now = now.astimezone(timezone.utc)
if not isinstance(payload, Mapping):
raise PriceForecastError("invalid_payload")
if type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:
version = payload.get("schema_version")
if type(version) is not int or version not in (1, 2):
raise PriceForecastError("unsupported_schema")
if payload.get("market") != "DE-LU" or payload.get("unit") != "EUR/kWh":
raise PriceForecastError("unsupported_market_or_unit")
Expand Down Expand Up @@ -138,11 +145,24 @@ def parse_price_forecast(payload: Any, *, now: datetime) -> PriceForecastSnapsho
raise PriceForecastError("noncontiguous_intervals")
if end - generated > timedelta(days=7):
raise PriceForecastError("horizon_too_long")
price, lower, upper = (_number(row.get(key)) for key in ("price", "lower", "upper"))
if not lower <= price <= upper:
raise PriceForecastError("invalid_bounds")
intervals.append(PriceForecastInterval(start, end, price, lower, upper))
price = _number(row.get("price"))
source = None
if version == 2:
source = row.get("source")
if not isinstance(source, str) or not source.strip() or len(source) > 128:
raise PriceForecastError("invalid_source")
if "lower" not in row or "upper" not in row:
raise PriceForecastError("invalid_bounds")
if (row["lower"] is None) != (row["upper"] is None):
raise PriceForecastError("invalid_bounds")
if version == 2 and row["lower"] is None and row["upper"] is None:
lower = upper = None
else:
lower, upper = (_number(row.get(key)) for key in ("lower", "upper"))
if not lower <= price <= upper:
raise PriceForecastError("invalid_bounds")
intervals.append(PriceForecastInterval(start, end, price, lower, upper, source))
previous_end = end
if intervals[-1].end <= now:
raise PriceForecastError("no_future_intervals")
return PriceForecastSnapshot(generated, expires, model, payload["price_basis"], tuple(intervals))
return PriceForecastSnapshot(generated, expires, model, payload["price_basis"], tuple(intervals), version)
42 changes: 36 additions & 6 deletions docs/price-forecast-input.de.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Home-Assistant-Sensor unter **Konfigurieren → Strompreise → Strompreis-Progn
Die Angabe ist optional und unabhängig vom Tarifanbieter. Zum Entfernen die
Auswahl leeren. Nach Abschluss der Optionen wird der Eintrag neu geladen.

Version 1 dient der Beobachtung und Auswertung. Sie erstellt einen Diagnosesensor
Versionen 1 und 2 dienen der Beobachtung und Auswertung. Sie liefern einen Diagnosesensor
**Price Forecast** mit Quelle, Modell, Zeitstempeln und angenommenen Intervallen.
`available` bedeutet, dass Struktur und Datenfrische geprüft wurden; es bestätigt
keine Prognosegenauigkeit. Prognosen ersetzen keine bestätigten Tarifintervalle,
Expand Down Expand Up @@ -40,7 +40,7 @@ keine aktuelle Prognose.
}
```

- `schema_version` ist die ganze Zahl `1`, der Markt `DE-LU`, die Einheit
- `schema_version` ist die ganze Zahl `1` oder `2`, der Markt `DE-LU`, die Einheit
`EUR/kWh`.
- `price_basis` ist `wholesale` oder `retail`. Großhandelspreise enthalten keine
Gebühren und Steuern des Haushaltstarifs; dieser Eingang rechnet sie nicht um.
Expand All @@ -52,9 +52,15 @@ keine aktuelle Prognose.
jeweils 15, 30 oder 60 Minuten Dauer. Jedes Ende liegt höchstens sieben
tatsächlich vergangene Tage nach der Erstellung. Mindestens ein Intervall
reicht noch in die Zukunft. UTC-Vergleiche erhalten Zeitumstellungen korrekt.
- Preise und Grenzen sind endliche JSON-Zahlen mit `lower <= price <= upper`.
Null und negative Preise sind gültig. Fehlende Zahlen, Wahrheitswerte, NaN und
Unendlich werden abgewiesen; fehlende Daten werden niemals zu null.
- Preise sind endliche JSON-Zahlen; der Zahlenwert `0` und negative Preise sind gültig.
Version 1 benötigt endliche Grenzen mit `lower <= price <= upper`. Version 2
erlaubt entweder solche Grenzen oder ausdrücklich `lower: null` und
`upper: null` gemeinsam. Beide Schlüssel bleiben Pflicht. Fehlende Preise,
Wahrheitswerte, NaN und Unendlich werden abgewiesen.
- Jedes Intervall der Version 2 benötigt zusätzlich eine nichtleere Zeichenkette
`source` mit höchstens 128 Zeichen. Diese Anbieterkennung wird unverändert in
die Diagnose übernommen; die Integration interpretiert sie nicht und leitet
daraus keine Steuerungsfreigabe ab.
- `model` ist eine nichtleere Zeichenkette mit höchstens 128 Zeichen. Unterstützt
wird `experimental` mit dem booleschen Wert `automation_eligible: false`.
Grenzen beschreiben empirische Streuung und keine nachgewiesene
Expand All @@ -66,12 +72,36 @@ Ein unabhängiger Anbieter kann dieses JSON über einen Home-Assistant-REST- ode
MQTT-Sensor bereitstellen. Anbieter können dasselbe Format liefern, ohne
Modellabhängigkeiten in dieser Integration zu installieren.

## Punktprognosen in Version 2

Die übrigen Angaben bleiben gleich. Setze `schema_version` auf `2` und ergänze
`source` in jedem Intervall. Ein Intervall ohne angegebenes Unsicherheitsband
sieht so aus:

```json
{
"start": "2026-11-01T13:00:00+00:00",
"end": "2026-11-01T14:00:00+00:00",
"price": 0.08,
"lower": null,
"upper": null,
"source": "external-provider"
}
```

Dieser Preis wird ohne Band dargestellt. Die Integration erhält beide `null`-
Werte und die Anbieterkennung. Ein Datensatz der Version 2 darf Punktprognosen
und Intervalle mit Grenzen kombinieren; eine einzelne `null`-Grenze zusammen mit
einer Zahl ist ungültig. Version 1 behält ihre verpflichtenden numerischen
Grenzen und ihr Ausgabeformat. Für beide Versionen gelten dieselben Regeln für
Frische, zeitliche Abdeckung und reine Beobachtung.

## Diagnose und Historie

Der Diagnosesensor meldet `not_configured`, `missing_sensor`, `unavailable`,
`expired`, `no_future_intervals` oder einen Prüfgrund wie `unsupported_schema`,
`unsupported_market_or_unit`, `unsupported_quality`, `future_generation`,
`invalid_price`, `invalid_bounds` oder `noncontiguous_intervals`. Abgewiesene Daten
`invalid_price`, `invalid_bounds`, `invalid_source` oder `noncontiguous_intervals`. Abgewiesene Daten
entfernen den angenommenen Datensatz bei der nächsten Koordinatoraktualisierung;
eine frühere erfolgreiche Prognose wird nicht als aktuell weitergeführt.

Expand Down
38 changes: 32 additions & 6 deletions docs/price-forecast-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Assistant sensor in **Configure → Energy Pricing → Electricity price forecas
sensor**. This setting is optional and independent of the tariff provider. Clear
the selector to remove the input. Completing the options flow reloads the entry.

Version 1 is for observation and evaluation. It creates a **Price Forecast**
Versions 1 and 2 are for observation and evaluation. They provide a **Price Forecast**
diagnostic sensor with source, model, timestamps and accepted intervals. A status
of `available` means that the input passed structural and freshness validation;
it does not certify prediction accuracy. Forecasts never replace confirmed tariff
Expand Down Expand Up @@ -39,7 +39,7 @@ rejected. Values below illustrate the format, not a current forecast.
}
```

- `schema_version` is the integer `1`, market `DE-LU`, unit `EUR/kWh`.
- `schema_version` is the integer `1` or `2`, market `DE-LU`, unit `EUR/kWh`.
- `price_basis` is `wholesale` or `retail`. Wholesale prices exclude the household
tariff's fees and taxes; the input does not perform that conversion.
- Every timestamp includes a timezone offset. UTC is recommended. Generation
Expand All @@ -49,9 +49,13 @@ rejected. Values below illustrate the format, not a current forecast.
minutes. Each end is at most seven elapsed days after generation. At least one
interval must still extend into the future. UTC comparisons preserve daylight
saving transitions.
- Prices and bounds are finite JSON numbers with `lower <= price <= upper`.
Zero and negative prices are valid. Missing numbers, booleans, NaN and infinity
are rejected; missing data never becomes zero.
- Prices are finite JSON numbers; zero and negative prices are valid. Version 1
requires finite bounds with `lower <= price <= upper`. Version 2 allows either
those bounds or explicit `lower: null` and `upper: null` together. Both bound
keys remain required. Missing prices, booleans, NaN and infinity are rejected.
- Every version 2 interval also requires a nonempty `source` string of at most
128 characters. This is an opaque producer label copied into diagnostics;
the integration does not interpret it or use it to authorize control.
- `model` is a nonempty string of at most 128 characters. The supported quality
is `experimental` with boolean `automation_eligible: false`. Bounds describe
empirical spread, not demonstrated probability coverage.
Expand All @@ -61,12 +65,34 @@ An independent producer can expose this JSON through a Home Assistant REST or
MQTT sensor. Producers can implement the same contract without adding forecasting
dependencies to this integration.

## Point forecasts in version 2

Keep the same envelope, set `schema_version` to `2`, and provide `source` on every
interval. An interval without a supplied uncertainty band looks like this:

```json
{
"start": "2026-11-01T13:00:00+00:00",
"end": "2026-11-01T14:00:00+00:00",
"price": 0.08,
"lower": null,
"upper": null,
"source": "external-provider"
}
```

Display this price without a band. The integration preserves both nulls and the
source label. A version 2 payload may combine point and bounded intervals; one
null bound paired with a numeric bound is invalid. Version 1 keeps its existing
required numeric bounds and output shape. The same freshness, coverage and
observation-only rules apply to both versions.

## Diagnostics and history

The diagnostic sensor reports `not_configured`, `missing_sensor`, `unavailable`,
`expired`, `no_future_intervals` or a validation reason such as
`unsupported_schema`, `unsupported_market_or_unit`, `unsupported_quality`,
`future_generation`, `invalid_price`, `invalid_bounds`, or
`future_generation`, `invalid_price`, `invalid_bounds`, `invalid_source`, or
`noncontiguous_intervals`. Rejected input clears the accepted snapshot on the next
coordinator update; an old successful forecast is not retained as current.

Expand Down
2 changes: 1 addition & 1 deletion tests/test_price_forecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_zero_and_negative_prices_are_preserved_and_input_is_not_mutated():


@pytest.mark.parametrize("field,value", [
("schema_version", True), ("schema_version", 1.0), ("schema_version", 2),
("schema_version", True), ("schema_version", 1.0), ("schema_version", 3),
("unit", "ct/kWh"), ("market", "FR"), ("price_basis", "unknown"),
("model", ""), ("generated_at", "2026-11-01T12:00:00"),
("generated_at", (NOW + timedelta(seconds=1)).isoformat()),
Expand Down
Loading