utility-tariffs-lib 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. utility_tariffs_lib/README.md +41 -0
  2. utility_tariffs_lib/__init__.py +0 -0
  3. utility_tariffs_lib/py.typed +0 -0
  4. utility_tariffs_lib/tariff/__init__.py +164 -0
  5. utility_tariffs_lib/tariff/accumulator.py +195 -0
  6. utility_tariffs_lib/tariff/bands.py +124 -0
  7. utility_tariffs_lib/tariff/bill_days.py +73 -0
  8. utility_tariffs_lib/tariff/billing.py +28 -0
  9. utility_tariffs_lib/tariff/compile.py +124 -0
  10. utility_tariffs_lib/tariff/config.py +208 -0
  11. utility_tariffs_lib/tariff/defaults.py +16 -0
  12. utility_tariffs_lib/tariff/definition.py +321 -0
  13. utility_tariffs_lib/tariff/definition_parse.py +765 -0
  14. utility_tariffs_lib/tariff/definition_savings.py +116 -0
  15. utility_tariffs_lib/tariff/demand.py +44 -0
  16. utility_tariffs_lib/tariff/engine.py +284 -0
  17. utility_tariffs_lib/tariff/index.py +309 -0
  18. utility_tariffs_lib/tariff/period_bill.py +136 -0
  19. utility_tariffs_lib/tariff/periods.py +34 -0
  20. utility_tariffs_lib/tariff/price_curve.py +142 -0
  21. utility_tariffs_lib/tariff/price_series.py +137 -0
  22. utility_tariffs_lib/tariff/price_stats.py +194 -0
  23. utility_tariffs_lib/tariff/price_timeline.py +139 -0
  24. utility_tariffs_lib/tariff/reprice.py +106 -0
  25. utility_tariffs_lib/tariff/savings.py +118 -0
  26. utility_tariffs_lib/tariff/slot_history.py +128 -0
  27. utility_tariffs_lib/tariff/slots.py +266 -0
  28. utility_tariffs_lib/tariff/stored_energy.py +64 -0
  29. utility_tariffs_lib/tariff/windows.py +119 -0
  30. utility_tariffs_lib/tariffranking/__init__.py +39 -0
  31. utility_tariffs_lib/tariffranking/search.py +189 -0
  32. utility_tariffs_lib/tariffstore/__init__.py +13 -0
  33. utility_tariffs_lib/tariffstore/client.py +406 -0
  34. utility_tariffs_lib/tariffstore/compile.py +157 -0
  35. utility_tariffs_lib/tariffstore/index.py +188 -0
  36. utility_tariffs_lib/tariffstore/layout.py +39 -0
  37. utility_tariffs_lib/tariffstore/price_client.py +87 -0
  38. utility_tariffs_lib/tariffstore/prices.py +127 -0
  39. utility_tariffs_lib/tariffstore/schema.py +550 -0
  40. utility_tariffs_lib/timeutil/__init__.py +5 -0
  41. utility_tariffs_lib/timeutil/real_time.py +52 -0
  42. utility_tariffs_lib-0.1.0.dist-info/METADATA +61 -0
  43. utility_tariffs_lib-0.1.0.dist-info/RECORD +46 -0
  44. utility_tariffs_lib-0.1.0.dist-info/WHEEL +5 -0
  45. utility_tariffs_lib-0.1.0.dist-info/licenses/LICENSE +21 -0
  46. utility_tariffs_lib-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,137 @@
1
+ """price_series.py: a price for each interval of a run of days, and the cost of kWh against it.
2
+
3
+ A dynamic tariff has no band price, so the bill engine cannot price its energy from band totals.
4
+ This is the step before the engine: it looks up the price of each slot in a series (read from the
5
+ price day files in the store) and adds up kWh times price. The engine takes that total through a
6
+ `series_energy` node. A slot with no price in the series is refused, never priced as zero.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
12
+ from dataclasses import dataclass, fields, is_dataclass
13
+ from datetime import date, datetime, time, timedelta, timezone
14
+ from decimal import Decimal
15
+ from typing import Any
16
+ from zoneinfo import ZoneInfo
17
+
18
+ from .defaults import SLOT_SECONDS
19
+ from .definition import SeriesEnergy, TariffDefinition
20
+
21
+ _UTC = timezone.utc
22
+
23
+
24
+ class MissingPrice(ValueError):
25
+ """A slot falls outside the prices the series holds."""
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class PriceSeries:
30
+ """Prices of consecutive equal intervals from *start*, in the currency's major unit per kWh."""
31
+
32
+ start: datetime # aware
33
+ interval: timedelta
34
+ prices: tuple[Decimal, ...]
35
+
36
+ @property
37
+ def end(self) -> datetime:
38
+ return self.start + self.interval * len(self.prices)
39
+
40
+ def price_at(self, moment: datetime) -> Decimal:
41
+ """The price of the interval that holds *moment* (aware)."""
42
+ if not self.start <= moment < self.end:
43
+ raise MissingPrice(f"no price at {moment.isoformat()}, the series covers "
44
+ f"{self.start.isoformat()} to {self.end.isoformat()}")
45
+ return self.prices[(moment - self.start) // self.interval]
46
+
47
+
48
+ def _midnight(day: str, zone: str) -> datetime:
49
+ return datetime.combine(date.fromisoformat(day), time(0), ZoneInfo(zone)).astimezone(_UTC)
50
+
51
+
52
+ def series_from_days(days: Sequence[Mapping[str, Any]]) -> PriceSeries:
53
+ """One series from price day files (as read from JSON), which must follow one another.
54
+
55
+ Each day starts at its local midnight, so a clock change makes a day of 23 or 25 hours and the
56
+ next day still begins where this one ends. A gap, an overlap or a changed interval raises."""
57
+ if not days:
58
+ raise ValueError("a price series needs at least one day")
59
+ ordered = sorted(days, key=lambda d: str(d["date"]))
60
+ interval = timedelta(minutes=int(ordered[0]["interval_minutes"]))
61
+ start = _midnight(str(ordered[0]["date"]), str(ordered[0]["timezone"]))
62
+ prices: list[Decimal] = []
63
+ for doc in ordered:
64
+ if timedelta(minutes=int(doc["interval_minutes"])) != interval:
65
+ raise ValueError(f"{doc['date']}: the interval changes within the series")
66
+ if _midnight(str(doc["date"]), str(doc["timezone"])) != start + interval * len(prices):
67
+ raise ValueError(f"{doc['date']}: does not follow the day before it")
68
+ prices += [Decimal(p) for p in doc["prices"]]
69
+ return PriceSeries(start, interval, tuple(prices))
70
+
71
+
72
+ def _slot_price(series: PriceSeries, start: datetime, length: timedelta) -> Decimal:
73
+ """The price of a slot: each interval it touches, weighted by the time it covers."""
74
+ total, cursor, end = Decimal(0), start, start + length
75
+ while cursor < end:
76
+ offset = (cursor - series.start) // series.interval
77
+ edge = min(end, series.start + series.interval * (offset + 1))
78
+ total += series.price_at(cursor) * Decimal((edge - cursor).total_seconds())
79
+ cursor = edge
80
+ return total / Decimal(length.total_seconds())
81
+
82
+
83
+ def series_cost(
84
+ slots: Iterable[tuple[datetime, Decimal]],
85
+ series: PriceSeries,
86
+ slot_seconds: int = SLOT_SECONDS,
87
+ ) -> Decimal:
88
+ """kWh times price over *slots*, each given as (start, kWh imported).
89
+
90
+ A slot longer than the series interval takes the time-weighted average of the intervals it
91
+ covers. The total is not rounded: the bill node rounds it."""
92
+ length = timedelta(seconds=slot_seconds)
93
+ return sum((kwh * _slot_price(series, start, length) for start, kwh in slots), Decimal(0))
94
+
95
+
96
+ def feed_of(series: str) -> str:
97
+ """The feed id a series name stands for. A series name has underscores where the feed has
98
+ hyphens (`octopus_agile` is the feed `octopus-agile`), and the tariff's area key is the feed's
99
+ area."""
100
+ return series.replace("_", "-")
101
+
102
+
103
+ def _walk(value: object) -> Iterator[object]:
104
+ if is_dataclass(value) and not isinstance(value, type):
105
+ yield value
106
+ for item in fields(value):
107
+ yield from _walk(getattr(value, item.name))
108
+ elif isinstance(value, Mapping):
109
+ for child in value.values():
110
+ yield from _walk(child)
111
+ elif isinstance(value, tuple | list):
112
+ for child in value:
113
+ yield from _walk(child)
114
+
115
+
116
+ def series_names(definition: TariffDefinition) -> tuple[str, ...]:
117
+ """The price series the bill tree names, in the order they are found. Empty for a tariff with
118
+ fixed prices."""
119
+ found = [node.series for node in _walk(definition.total) if isinstance(node, SeriesEnergy)]
120
+ return tuple(dict.fromkeys(found))
121
+
122
+
123
+ def series_runs(days: Sequence[Mapping[str, Any]]) -> list[PriceSeries]:
124
+ """One series for each unbroken run of days, earliest first. A gap, or a day of another
125
+ interval, ends a run, so the days a feed has is still usable when one day is missing."""
126
+ runs: list[list[Mapping[str, Any]]] = []
127
+ for doc in sorted(days, key=lambda d: str(d["date"])):
128
+ if runs:
129
+ try:
130
+ series_from_days([*runs[-1], doc])
131
+ except ValueError:
132
+ runs.append([doc])
133
+ else:
134
+ runs[-1].append(doc)
135
+ else:
136
+ runs.append([doc])
137
+ return [series_from_days(run) for run in runs]
@@ -0,0 +1,194 @@
1
+ """price_stats.py: the lowest, highest and average price over a time range, and a rating.
2
+
3
+ The statistics read a price series from `price_curve`, so every tax and discount is already in.
4
+ The average is weighted by time, because slots can be of any length. A range the series does not
5
+ cover in full still gets statistics from the part it does cover, and says so in `complete`.
6
+
7
+ The rating places a price inside the range's own lowest to highest span, in five equal steps.
8
+ That makes it comparable across tariffs and countries: it says how a price compares with the
9
+ rest of the day, not whether it is cheap in money. A range with one price has no span, so every
10
+ price in it rates as normal.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Sequence
16
+ from dataclasses import dataclass
17
+ from datetime import datetime, timedelta
18
+ from decimal import Decimal
19
+ from typing import Literal
20
+
21
+ from .price_curve import PriceSlot
22
+
23
+ POINTS = (10, 50, 90) # the percentiles that say what low, middle and high look like
24
+ MIN_WINDOW = timedelta(hours=6) # least prices a window needs before its percentiles show
25
+ MIN_PERCENT, MAX_PERCENT = 1, 99 # the percentiles a caller may ask for
26
+ MIN_HISTORY_DAYS = 7 # least past days the same time of day needs before its percentiles show
27
+ HISTORY_DAYS = 28
28
+ PART_OF_DAY = timedelta(hours=4) # the stretch of each past day that is compared
29
+ LEVELS = ("low", "mid", "high")
30
+ RATINGS = ("very_low", "low", "normal", "high", "very_high")
31
+ type Rating = Literal["very_low", "low", "normal", "high", "very_high"]
32
+ type Level = Literal["low", "mid", "high"]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class PriceStats:
37
+ """The prices over a range, per kWh."""
38
+
39
+ lowest: Decimal
40
+ highest: Decimal
41
+ average: Decimal # weighted by the time each price is in force
42
+ complete: bool # False when the series does not cover the whole range
43
+
44
+
45
+ def price_stats(
46
+ slots: Sequence[PriceSlot],
47
+ start: datetime,
48
+ end: datetime,
49
+ flow: Literal["import", "export"] = "import",
50
+ ) -> PriceStats | None:
51
+ """The statistics of *flow* prices from *start* to *end*, or None when none are held."""
52
+ if end <= start:
53
+ raise ValueError("end must be after start")
54
+ prices: list[tuple[Decimal, Decimal]] = [] # (price, seconds in force)
55
+ for slot in slots:
56
+ seconds = (min(slot.end, end) - max(slot.start, start)).total_seconds()
57
+ if seconds > 0:
58
+ price = slot.import_price if flow == "import" else slot.export_price
59
+ prices.append((price, Decimal(str(seconds))))
60
+ if not prices:
61
+ return None
62
+ covered = sum((seconds for _, seconds in prices), Decimal(0))
63
+ weighted = sum((price * seconds for price, seconds in prices), Decimal(0))
64
+ return PriceStats(
65
+ lowest=min(price for price, _ in prices),
66
+ highest=max(price for price, _ in prices),
67
+ average=weighted / covered,
68
+ complete=covered == Decimal(str((end - start).total_seconds())),
69
+ )
70
+
71
+
72
+ def price_rating(price: Decimal, stats: PriceStats) -> Rating:
73
+ """Where *price* sits between the lowest and highest price of *stats*, in five steps."""
74
+ span = stats.highest - stats.lowest
75
+ if span <= 0:
76
+ return "normal"
77
+ position = (price - stats.lowest) / span
78
+ step = min(int(position * len(RATINGS)), len(RATINGS) - 1)
79
+ return RATINGS[max(step, 0)] # type: ignore[return-value]
80
+
81
+
82
+ def _weighted(
83
+ slots: Sequence[PriceSlot], start: datetime, end: datetime, flow: str,
84
+ ) -> list[tuple[Decimal, Decimal]]:
85
+ """(price, seconds in force) for each slot part inside the range."""
86
+ found: list[tuple[Decimal, Decimal]] = []
87
+ for slot in slots:
88
+ seconds = (min(slot.end, end) - max(slot.start, start)).total_seconds()
89
+ if seconds > 0:
90
+ price = slot.import_price if flow == "import" else slot.export_price
91
+ found.append((price, Decimal(str(seconds))))
92
+ return found
93
+
94
+
95
+ def _percentiles(
96
+ weighted: list[tuple[Decimal, Decimal]], points: Sequence[int],
97
+ ) -> dict[int, Decimal]:
98
+ """The price at each percentile by time: the lowest price for which at least that share of
99
+ the time is at or below it (nearest rank)."""
100
+ ordered = sorted(weighted)
101
+ total = sum((seconds for _, seconds in ordered), Decimal(0))
102
+ result: dict[int, Decimal] = {}
103
+ for point in points:
104
+ wanted, running = total * Decimal(point) / Decimal(100), Decimal(0)
105
+ for price, seconds in ordered:
106
+ running += seconds
107
+ if running >= wanted:
108
+ result[point] = price
109
+ break
110
+ return result
111
+
112
+
113
+ def price_percentiles( # noqa: PLR0913
114
+ slots: Sequence[PriceSlot],
115
+ start: datetime,
116
+ end: datetime,
117
+ flow: Literal["import", "export"] = "import",
118
+ points: Sequence[int] = POINTS,
119
+ ) -> dict[int, Decimal] | None:
120
+ """The percentiles of *flow* prices over a range, weighted by time, or None when the slots
121
+ cover less than `MIN_WINDOW` of it. A long price counts for as long as it is in force."""
122
+ if end <= start:
123
+ raise ValueError("end must be after start")
124
+ weighted = _weighted(slots, start, end, flow)
125
+ if sum((seconds for _, seconds in weighted), Decimal(0)) < Decimal(
126
+ str(MIN_WINDOW.total_seconds())):
127
+ return None
128
+ return _percentiles(weighted, points)
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class HistoryPercentiles:
133
+ """The percentiles of the same part of the day over past days, and how many days they use."""
134
+
135
+ points: dict[int, Decimal]
136
+ days: int
137
+
138
+
139
+ def history_percentiles( # noqa: PLR0913
140
+ slots: Sequence[PriceSlot],
141
+ moment: datetime,
142
+ flow: Literal["import", "export"] = "import",
143
+ look_back: int = HISTORY_DAYS,
144
+ points: Sequence[int] = POINTS,
145
+ ) -> HistoryPercentiles | None:
146
+ """The percentiles of the `PART_OF_DAY` around *moment*'s local time of day, over each of the
147
+ last *look_back* days that the slots cover in full. None when fewer than `MIN_HISTORY_DAYS`
148
+ days qualify.
149
+
150
+ Days are counted on the local calendar, so a clock change does not move the time of day."""
151
+ local = moment.astimezone(slots[0].start.tzinfo) if slots else moment
152
+ weighted: list[tuple[Decimal, Decimal]] = []
153
+ days = 0
154
+ for back in range(1, look_back + 1):
155
+ centre = datetime.combine(
156
+ local.date() - timedelta(days=back), local.time(), local.tzinfo)
157
+ part = _weighted(slots, centre - PART_OF_DAY / 2, centre + PART_OF_DAY / 2, flow)
158
+ covered = sum((seconds for _, seconds in part), Decimal(0))
159
+ if covered == Decimal(str(PART_OF_DAY.total_seconds())):
160
+ weighted += part
161
+ days += 1
162
+ if days < MIN_HISTORY_DAYS:
163
+ return None
164
+ return HistoryPercentiles(_percentiles(weighted, points), days)
165
+
166
+
167
+ def price_level(price: Decimal, points: dict[int, Decimal], low: int = 10, high: int = 90) -> Level:
168
+ """Low at or below the *low* percentile, high at or above the *high* one, else mid. When the
169
+ two are the same price there is no spread, so the level is mid. A percentile that is not in
170
+ *points* gives mid."""
171
+ floor, ceiling = points.get(low), points.get(high)
172
+ if floor is None or ceiling is None or floor == ceiling:
173
+ return "mid"
174
+ if price <= floor:
175
+ return "low"
176
+ return "high" if price >= ceiling else "mid"
177
+
178
+
179
+ def next_at_or_below(
180
+ slots: Sequence[PriceSlot],
181
+ moment: datetime,
182
+ threshold: Decimal,
183
+ flow: Literal["import", "export"] = "import",
184
+ ) -> PriceSlot | None:
185
+ """The slot in force at *moment*, or else the first one after it, whose price is at or below
186
+ *threshold*. It is how a percentile becomes "the next cheap time". None when none is held.
187
+
188
+ A slot that meets the one before it at the same side of the threshold is not joined, so the
189
+ caller reads the start of a cheap stretch from the first slot it gets back."""
190
+ for slot in sorted(slots, key=lambda item: item.start):
191
+ price = slot.import_price if flow == "import" else slot.export_price
192
+ if slot.end > moment and price <= threshold:
193
+ return slot
194
+ return None
@@ -0,0 +1,139 @@
1
+ """price_timeline.py: the prices over a range that crosses a revision or follows a price feed.
2
+
3
+ `price_curve` prices one definition. Two things need more. A revision that starts later in the
4
+ range has its own definition, so the range is cut where each revision starts and each part is
5
+ priced with the definition in force there. And a tariff on a price series (`series_energy`) has no
6
+ band price: its slots come from the published prices, so they stop where the series stops. Nothing
7
+ is extrapolated and nothing is priced as zero. The caller reads `known_until` to see how far the
8
+ prices are known.
9
+
10
+ The price of a series slot is the series price taken through the bill, so a tax or a discount
11
+ after the energy line is in the price, as it is for a band price.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Callable, Mapping, Sequence
17
+ from dataclasses import dataclass
18
+ from datetime import date, datetime
19
+ from decimal import Decimal
20
+
21
+ from .bands import band_at, export_band_at, no_holidays
22
+ from .definition import TariffDefinition
23
+ from .engine import BillInputs, price_bill
24
+ from .price_curve import _STEP, MarginalPrices, PriceSlot, marginal_prices, price_curve
25
+ from .price_series import PriceSeries, series_names
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Revision:
30
+ """A definition and the first local day it applies."""
31
+
32
+ first_day: date
33
+ definition: TariffDefinition
34
+
35
+
36
+ def _start_of(revision: Revision) -> datetime:
37
+ return datetime.combine(revision.first_day, datetime.min.time(), revision.definition.timezone)
38
+
39
+
40
+ def series_factor(definition: TariffDefinition, name: str) -> Decimal:
41
+ """What one unit of a series price becomes in the bill: 1 when nothing follows the energy
42
+ line, and for example 1.05 when VAT is added after it."""
43
+ names = {other: Decimal(0) for other in series_names(definition)}
44
+ base = price_bill(definition, BillInputs(30, 30, {}, Decimal(0), import_cost_by_series=names))
45
+ names[name] = _STEP
46
+ more = price_bill(definition, BillInputs(30, 30, {}, Decimal(0), import_cost_by_series=names))
47
+ return (more.total - base.total) / _STEP
48
+
49
+
50
+ def series_curve( # noqa: PLR0913
51
+ definition: TariffDefinition,
52
+ series: PriceSeries,
53
+ start: datetime,
54
+ end: datetime,
55
+ is_holiday: Callable[[date], bool] = no_holidays,
56
+ ) -> tuple[PriceSlot, ...]:
57
+ """The slots of a one-series tariff from *start* to *end*, as far as *series* covers them.
58
+ Export prices come from the document, as for any tariff."""
59
+ (name,) = series_names(definition)
60
+ factor = series_factor(definition, name)
61
+ marginal = marginal_prices(definition)
62
+ slots: list[PriceSlot] = []
63
+ cursor = max(start, series.start)
64
+ while cursor < min(end, series.end):
65
+ offset = (cursor - series.start) // series.interval
66
+ edge = min(end, series.end, series.start + series.interval * (offset + 1))
67
+ slot = _published(definition, marginal, cursor, edge, series.price_at(cursor) * factor,
68
+ is_holiday)
69
+ if slots and slots[-1].end == slot.start and slots[-1].import_price == slot.import_price \
70
+ and slots[-1].export_band == slot.export_band:
71
+ slot = PriceSlot(slots.pop().start, slot.end, slot.import_band, slot.export_band,
72
+ slot.import_price, slot.export_price, slot.source)
73
+ slots.append(slot)
74
+ cursor = edge
75
+ return tuple(slots)
76
+
77
+
78
+ def _published( # noqa: PLR0913
79
+ definition: TariffDefinition, marginal: MarginalPrices, start: datetime, end: datetime,
80
+ price: Decimal, is_holiday: Callable[[date], bool],
81
+ ) -> PriceSlot:
82
+ in_band = band_at(definition, start, is_holiday)
83
+ out_band = export_band_at(definition, start, is_holiday)
84
+ return PriceSlot(start, end, in_band, out_band, price, marginal.export_prices[out_band],
85
+ "published")
86
+
87
+
88
+ def price_timeline( # noqa: PLR0913
89
+ revisions: Sequence[Revision],
90
+ start: datetime,
91
+ end: datetime,
92
+ series: Mapping[str, Sequence[PriceSeries]] | None = None,
93
+ is_holiday: Callable[[date], bool] = no_holidays,
94
+ ) -> tuple[PriceSlot, ...]:
95
+ """The prices from *start* to *end* (aware times) over one or more revisions.
96
+
97
+ *revisions* are in date order. The first applies from *start*, whatever its first day, and each
98
+ later one from its first day at local midnight. *series* holds, for the name of each series a
99
+ definition uses, the runs of published prices (`series_runs`). A series tariff with no run
100
+ that covers part of the range gives no slots for that part."""
101
+ if not revisions:
102
+ raise ValueError("a timeline needs at least one revision")
103
+ if end <= start:
104
+ raise ValueError("end must be after start")
105
+ slots: list[PriceSlot] = []
106
+ for position, revision in enumerate(revisions):
107
+ part_start = start if position == 0 else max(start, _start_of(revision))
108
+ part_end = end if position + 1 == len(revisions) else min(end, _start_of(
109
+ revisions[position + 1]))
110
+ if part_start >= part_end:
111
+ continue
112
+ slots += _part(revision.definition, part_start, part_end, series or {}, is_holiday)
113
+ return tuple(slots)
114
+
115
+
116
+ def _part( # noqa: PLR0913
117
+ definition: TariffDefinition, start: datetime, end: datetime,
118
+ series: Mapping[str, Sequence[PriceSeries]], is_holiday: Callable[[date], bool],
119
+ ) -> list[PriceSlot]:
120
+ names = series_names(definition)
121
+ if not names:
122
+ return list(price_curve(definition, start, end, is_holiday))
123
+ if len(names) > 1:
124
+ raise ValueError("a tariff on more than one price series has no single price")
125
+ found: list[PriceSlot] = []
126
+ for run in series.get(names[0], ()):
127
+ found += series_curve(definition, run, start, end, is_holiday)
128
+ return sorted(found, key=lambda slot: slot.start)
129
+
130
+
131
+ def known_until(slots: Sequence[PriceSlot], start: datetime) -> datetime | None:
132
+ """The end of the unbroken run of slots that begins at *start*, or None when none does."""
133
+ reached: datetime | None = None
134
+ for slot in slots:
135
+ if reached is None and slot.start <= start < slot.end:
136
+ reached = slot.end
137
+ elif reached is not None and slot.start == reached:
138
+ reached = slot.end
139
+ return reached
@@ -0,0 +1,106 @@
1
+ """reprice.py: price the half-hourly history under a tariff, and build the bill from it.
2
+
3
+ The history (slots.py) holds energy, never a price, so any tariff can be applied to any days.
4
+ Each slot's import is priced at the rate in force when the slot starts, so a rate window that
5
+ starts or ends inside a half hour is priced as if it began at the slot start. The usual windows
6
+ begin on the hour or half hour and are priced exactly.
7
+
8
+ A supplier bill takes the meter's kWh for each rate band, prices each band and rounds each line
9
+ to the cent. Pricing slot by slot and rounding once is a cent or two out for the same energy.
10
+ Rounding.PER_BAND does what the bill does. Rounding.TOTAL is the figure the cost sensors add up.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Sequence
16
+ from dataclasses import dataclass
17
+ from datetime import timedelta
18
+ from enum import Enum
19
+
20
+ from ..timeutil import shift_real
21
+ from .billing import BillBreakdown, money
22
+ from .config import TariffConfig
23
+ from .defaults import SLOT_SECONDS
24
+ from .periods import RatePeriod
25
+ from .slots import SlotDay
26
+
27
+
28
+ class Rounding(Enum):
29
+ """How the energy lines are rounded before the rest of the bill is worked out."""
30
+
31
+ TOTAL = "total" # add the band costs, round once
32
+ PER_BAND = "per_band" # round each band's cost to the cent first, as a supplier bill does
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class BillPeriod:
37
+ """The length of the bill: the days it covers and the days of the whole period.
38
+
39
+ *period_days* sets the share of the monthly levy charged. None means an average month.
40
+ """
41
+
42
+ days: int
43
+ period_days: int | None = None
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Repriced:
48
+ """Slots priced under one tariff."""
49
+
50
+ import_kwh_by_band: dict[str, float] # kWh imported in each rate band, in first-seen order
51
+ export_kwh: float
52
+ energy_cost: float # the bands' cost before the discount and VAT
53
+ export_credit: float
54
+ bill: BillBreakdown
55
+ coverage: float # share of the days' time that was observed, 0 to 1
56
+
57
+
58
+ def import_by_band(days: Sequence[SlotDay], tariff: TariffConfig) -> dict[str, float]:
59
+ """kWh imported in each rate band, the band taken from each slot's start."""
60
+ bands: dict[str, float] = {}
61
+ for day in days:
62
+ for index, kwh in enumerate(day.flows["import"]):
63
+ if kwh:
64
+ band = _band_at(day, index, tariff).name
65
+ bands[band] = bands.get(band, 0.0) + kwh
66
+ return bands
67
+
68
+
69
+ def import_rates(day: SlotDay, tariff: TariffConfig) -> list[float]:
70
+ """The import rate in force at the start of each slot, before the discount and VAT."""
71
+ rates = _band_rates(tariff)
72
+ return [rates[_band_at(day, index, tariff).name] for index in range(day.slot_count)]
73
+
74
+
75
+ def reprice(
76
+ days: Sequence[SlotDay],
77
+ tariff: TariffConfig,
78
+ period: BillPeriod,
79
+ rounding: Rounding = Rounding.TOTAL,
80
+ ) -> Repriced:
81
+ """The bill for *days* under *tariff*. The days are the bill period, in any order."""
82
+ bands = import_by_band(days, tariff)
83
+ rates = _band_rates(tariff)
84
+ costs = [kwh * rates[name] for name, kwh in bands.items()]
85
+ if rounding is Rounding.PER_BAND:
86
+ costs = [money(c) for c in costs]
87
+ energy_cost = sum(costs)
88
+ export_kwh = sum(day.total("export") for day in days)
89
+ export_credit = tariff.calculate_export_earnings(export_kwh)
90
+ bill = tariff.calculate_bill(energy_cost, period.days, period.period_days, export_credit)
91
+ return Repriced(bands, export_kwh, energy_cost, export_credit, bill, _coverage(days))
92
+
93
+
94
+ def _band_at(day: SlotDay, index: int, tariff: TariffConfig) -> RatePeriod:
95
+ start = shift_real(day.start, timedelta(seconds=index * SLOT_SECONDS))
96
+ return tariff.get_current_rate(start.astimezone(day.tz))
97
+
98
+
99
+ def _band_rates(tariff: TariffConfig) -> dict[str, float]:
100
+ rates = {period.name: period.rate for period in tariff.rate_periods}
101
+ rates[tariff.base_rate_name] = tariff.base_rate
102
+ return rates
103
+
104
+
105
+ def _coverage(days: Sequence[SlotDay]) -> float:
106
+ return sum(day.coverage for day in days) / len(days) if days else 0.0