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,41 @@
1
+ # lib/
2
+
3
+ The store library and the bill engine. This repository is where both are written and tested, and
4
+ it is the source of truth for all tariff and billing code and calculations. They use only the
5
+ standard library, so any script, skill or integration can import or copy them.
6
+
7
+ | Folder | What it holds |
8
+ | --- | --- |
9
+ | `tariff/` | The tariff definition reader, the bill engine, band assignment, half-hourly slots and repricing. `tariff/README.md` lists the public names |
10
+ | `tariffstore/` | The store's own code: validator, checksum, index build, compile step and the client (`Store`) |
11
+ | `tariffranking/` | Prices every plan over the same measured usage and ranks them, with the current plan's rank. Imports `tariff/` only |
12
+ | `timeutil/` | Clock helpers that `tariff/` imports (`shift_real`, `elapsed_seconds`, `local_time_on`) |
13
+
14
+ ## Using it from another project
15
+
16
+ Copy the folders as they stand and do not edit the copy. Record the commit copied, so a
17
+ later copy can be compared. The Home Assistant integration `macuistin/givenergy_inverter_manager`
18
+ does this with a script, a weekly workflow that opens a pull request, and a release check. Change
19
+ the code here, with its tests, and let the copy follow.
20
+
21
+ `tariff/` and `timeutil/` began in that integration and moved here on 2026-11-11, unchanged from
22
+ its commit `68ec1923ac68817032dfaa51cc3c82817d2ce115`.
23
+
24
+ The code uses Python 3.14 syntax (for example `except A, B:`), so it needs Python 3.14 or newer.
25
+
26
+ ## Known gaps between the tariff files and the engine
27
+
28
+ Found by `tests/test_tariffs_through_lib.py`. A tariff file is not what the engine reads. The
29
+ compile step (`lib/tariffstore/compile.py`) builds the library's definition from a tariff file and its
30
+ country block, and closes most gaps itself. What remains is work in `lib/tariff`.
31
+
32
+ 1. The library accepts only ISO 3166-2 region codes. Our area `region` codes (`GSP-A`,
33
+ `OFGEM-EASTERN`) are not, so compile leaves the region null. A customer's region is chosen by the
34
+ area key.
35
+ 2. Closed. The library prices an export by time of day (export
36
+ `zones`), so Prime Outgoing's 16:00 to 19:00 rate is credited by band.
37
+ 3. The library requires an `export` price in every definition. With no export file paired, compile
38
+ supplies 0 and adds no export line, so an unpaired tariff credits nothing. The library cannot say
39
+ "unknown".
40
+ 4. A bill period is a whole number of calendar months. The library has no period of a fixed
41
+ number of days, and no volume tiers, demand charges or dynamic prices. `docs/design.md` lists what each would need.
File without changes
File without changes
@@ -0,0 +1,164 @@
1
+ """Tariff model, energy and cost accumulation, and bill maths. No knowledge of Home Assistant."""
2
+
3
+ from .accumulator import CounterMemory, EnergyAccumulator
4
+ from .bands import band_at, export_band_at, export_by_band, no_holidays
5
+ from .billing import BillBreakdown, money
6
+ from .compile import Locale, definition_from_config
7
+ from .config import TariffConfig, cheapest_period
8
+ from .definition import SCHEMA_VERSION, DefinitionError, TariffDefinition
9
+ from .definition_parse import load_definition, parse_definition
10
+ from .definition_savings import DefinitionSavings, SavingsOptions, definition_savings
11
+ from .demand import peak_kw_by_window
12
+ from .engine import (
13
+ BillInputs,
14
+ CheckFailed,
15
+ Line,
16
+ MissingPeak,
17
+ MissingSeries,
18
+ PricedBill,
19
+ price_bill,
20
+ verify_checks,
21
+ )
22
+ from .index import (
23
+ ChecksumMismatch,
24
+ StaticSource,
25
+ TariffIndex,
26
+ TariffSource,
27
+ build_index,
28
+ checksum_of,
29
+ find_tariff,
30
+ load_revision,
31
+ parse_index,
32
+ revision_in_force,
33
+ )
34
+ from .period_bill import (
35
+ PeriodBill,
36
+ PeriodRules,
37
+ bill_period_bounds,
38
+ months_of,
39
+ price_period,
40
+ start_day_of,
41
+ start_month_of,
42
+ )
43
+ from .periods import RatePeriod
44
+ from .price_curve import MarginalPrices, PriceSlot, marginal_prices, price_curve
45
+ from .price_series import (
46
+ MissingPrice,
47
+ PriceSeries,
48
+ feed_of,
49
+ series_cost,
50
+ series_from_days,
51
+ series_names,
52
+ series_runs,
53
+ )
54
+ from .price_stats import (
55
+ HistoryPercentiles,
56
+ PriceStats,
57
+ history_percentiles,
58
+ next_at_or_below,
59
+ price_level,
60
+ price_percentiles,
61
+ price_rating,
62
+ price_stats,
63
+ )
64
+ from .price_timeline import Revision, known_until, price_timeline, series_curve, series_factor
65
+ from .reprice import BillPeriod, Repriced, Rounding, import_by_band, reprice
66
+ from .savings import Battery, Savings, savings
67
+ from .slot_history import SlotHistory
68
+ from .slots import DEFAULT_LOADS, FLOWS, SlotDay, SlotEnergy, StoredSlotDay
69
+ from .stored_energy import StoredEnergy, stored_energy_change, value_per_stored_kwh
70
+ from .windows import Window, WindowSearch, find_window
71
+
72
+ __all__ = [
73
+ "SCHEMA_VERSION",
74
+ "ChecksumMismatch",
75
+ "StaticSource",
76
+ "TariffIndex",
77
+ "TariffSource",
78
+ "build_index",
79
+ "checksum_of",
80
+ "find_tariff",
81
+ "load_revision",
82
+ "parse_index",
83
+ "revision_in_force",
84
+ "Locale",
85
+ "definition_from_config",
86
+ "band_at",
87
+ "export_band_at",
88
+ "export_by_band",
89
+ "no_holidays",
90
+ "DefinitionSavings",
91
+ "SavingsOptions",
92
+ "definition_savings",
93
+ "PeriodBill",
94
+ "PeriodRules",
95
+ "bill_period_bounds",
96
+ "price_period",
97
+ "start_day_of",
98
+ "months_of",
99
+ "start_month_of",
100
+ "BillInputs",
101
+ "CheckFailed",
102
+ "Line",
103
+ "MissingPeak",
104
+ "MissingPrice",
105
+ "MissingSeries",
106
+ "PriceSeries",
107
+ "series_cost",
108
+ "series_from_days",
109
+ "PricedBill",
110
+ "peak_kw_by_window",
111
+ "price_bill",
112
+ "verify_checks",
113
+ "BillPeriod",
114
+ "DefinitionError",
115
+ "TariffDefinition",
116
+ "load_definition",
117
+ "parse_definition",
118
+ "MarginalPrices",
119
+ "PriceSlot",
120
+ "marginal_prices",
121
+ "price_curve",
122
+ "HistoryPercentiles",
123
+ "Revision",
124
+ "feed_of",
125
+ "history_percentiles",
126
+ "known_until",
127
+ "next_at_or_below",
128
+ "price_level",
129
+ "price_percentiles",
130
+ "price_timeline",
131
+ "series_curve",
132
+ "series_factor",
133
+ "series_names",
134
+ "series_runs",
135
+ "PriceStats",
136
+ "price_rating",
137
+ "price_stats",
138
+ "Battery",
139
+ "Savings",
140
+ "savings",
141
+ "Window",
142
+ "WindowSearch",
143
+ "find_window",
144
+ "Repriced",
145
+ "Rounding",
146
+ "import_by_band",
147
+ "reprice",
148
+ "BillBreakdown",
149
+ "CounterMemory",
150
+ "EnergyAccumulator",
151
+ "DEFAULT_LOADS",
152
+ "FLOWS",
153
+ "RatePeriod",
154
+ "SlotDay",
155
+ "SlotEnergy",
156
+ "SlotHistory",
157
+ "StoredSlotDay",
158
+ "StoredEnergy",
159
+ "TariffConfig",
160
+ "cheapest_period",
161
+ "money",
162
+ "stored_energy_change",
163
+ "value_per_stored_kwh",
164
+ ]
@@ -0,0 +1,195 @@
1
+ """accumulator.py: running energy and cost totals for a billing period."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+
8
+
9
+ @dataclass
10
+ class CounterMemory:
11
+ """The last reading of each inverter daily counter, and which ones to stop trusting.
12
+
13
+ A daily counter drops to zero at midnight. The memory outlives the midnight reset so a
14
+ stale reading just after it is not added a second time. lib/guards/counter.py judges each
15
+ reading against this memory.
16
+
17
+ Only the AC charge baseline is saved. The other readings, their times and the list of
18
+ counters that jumped live in memory, so a restart starts them fresh.
19
+ """
20
+
21
+ ac_charge_kwh: float = 0.0
22
+ readings: dict[str, tuple[float, datetime]] = field(
23
+ default_factory=dict, compare=False, repr=False
24
+ )
25
+ distrusted: set[str] = field(default_factory=set, compare=False, repr=False)
26
+ # The last reading of each counter that passed, to recognise a counter coming back.
27
+ last_trusted: dict[str, tuple[float, datetime]] = field(
28
+ default_factory=dict, compare=False, repr=False
29
+ )
30
+ # The AC charge rise the last screening allowed. It is the only rise that is booked.
31
+ ac_charge_rise_kwh: float = field(default=0.0, compare=False, repr=False)
32
+
33
+
34
+ @dataclass
35
+ class EnergyAccumulator:
36
+ """
37
+ Tracks energy and cost accumulation over a billing period (resets at midnight).
38
+
39
+ Fields are grouped by what they enable:
40
+ Basic flows — solar, import, export, house, zappi, immersion
41
+ Rate breakdown — import split by cheap (timed) vs peak (base) rate
42
+ Cost attribution — cost per load type and per rate tier
43
+ Savings — value delivered by the integration
44
+ Battery health — throughput for cycle and depreciation tracking
45
+ """
46
+
47
+ # ── Basic energy flows ────────────────────────────────────────────────────
48
+ import_kwh: float = 0.0
49
+ export_kwh: float = 0.0
50
+ solar_kwh: float = 0.0
51
+ battery_discharge_kwh: float = 0.0
52
+ battery_charge_kwh: float = 0.0
53
+ zappi_kwh: float = 0.0
54
+ immersion_kwh: float = 0.0
55
+ house_kwh: float = 0.0
56
+ # The part of import_kwh that went into the battery (the inverter's AC charge counter). It is
57
+ # stored, not used, so it does not count as the grid supplying the house.
58
+ grid_to_battery_kwh: float = 0.0
59
+ # What the grid energy that went into the battery cost, and the kWh that cost covers. Both
60
+ # are kept by the integration from the moment it prices the AC charge counter, so
61
+ # grid_to_battery_priced_kwh can be less than grid_to_battery_kwh on the day it is
62
+ # first installed. Today's accumulator only. See core/stored_energy.py.
63
+ grid_to_battery_cost: float = 0.0
64
+ grid_to_battery_priced_kwh: float = 0.0
65
+ # The battery's state of charge at the start of the period, None until the first reading.
66
+ # A bookmark, not an accumulated figure, so it is left out of equality: a period with
67
+ # nothing else on it still counts as empty.
68
+ soc_at_start_pct: float | None = field(default=None, compare=False)
69
+
70
+ # ── Rate-tier import breakdown ────────────────────────────────────────────
71
+ # "cheap" = any timed rate period active (Night, Nightboost, etc.)
72
+ # "peak" = base/day rate (no timed period active)
73
+ import_kwh_cheap: float = 0.0 # kWh imported at timed cheap rate
74
+ import_kwh_peak: float = 0.0 # kWh imported at base/peak rate
75
+ import_cost_cheap: float = 0.0 # cost at cheap rate
76
+ import_cost_peak: float = 0.0 # cost at peak rate
77
+
78
+ # ── Cost attribution per rate period and load ─────────────────────────────
79
+ import_cost_by_period: dict[str, float] = field(default_factory=dict)
80
+ # kWh imported, and kWh the house used, in each rate period. They are what the bill audit
81
+ # lists beside the cost, and are empty on a period that began before they were kept.
82
+ import_kwh_by_period: dict[str, float] = field(default_factory=dict)
83
+ house_kwh_by_period: dict[str, float] = field(default_factory=dict)
84
+ export_earnings: float = 0.0
85
+ zappi_cost: float = 0.0
86
+ immersion_cost: float = 0.0 # import cost attributable to immersion heater
87
+ house_cost: float = 0.0 # import cost attributable to rest-of-house load
88
+
89
+ # ── Counterfactual ────────────────────────────────────────────────────────
90
+ # What the house load would have cost bought from the grid at the rate in force
91
+ # when it ran. The saving from solar and battery is this minus what was paid.
92
+ grid_equivalent_load_cost: float = 0.0
93
+
94
+ # ── Integration savings ───────────────────────────────────────────────────
95
+ # immersion_solar_kwh: solar kWh diverted to immersion that would otherwise
96
+ # have been exported at the lower export rate.
97
+ # immersion_savings: (import_rate - export_rate) × immersion_solar_kwh
98
+ immersion_solar_kwh: float = 0.0
99
+ immersion_savings: float = 0.0
100
+
101
+ # ── Battery throughput ────────────────────────────────────────────────────
102
+ # Total kWh cycled through the battery (in + out). Divide by 2 × capacity
103
+ # to get fractional cycles. Multiply by (replacement_cost / rated_cycles)
104
+ # to estimate depreciation cost.
105
+ battery_throughput_kwh: float = 0.0
106
+
107
+ # ── Missed solar (self-consumption opportunity) ───────────────────────────
108
+ # kWh exported while battery is full, solar generating, and no flex load
109
+ # active — represents solar that could have been self-consumed.
110
+ missed_solar_kwh: float = 0.0
111
+
112
+ # ── Inverter derating ──────────────────────────────────────────────────────
113
+ # Minutes the inverter spent above the derating temperature threshold today.
114
+ inverter_derating_minutes: float = 0.0
115
+
116
+ @property
117
+ def total_import_cost(self) -> float:
118
+ return sum(self.import_cost_by_period.values())
119
+
120
+ @property
121
+ def total_cost(self) -> float:
122
+ """Total import cost today (standing charges tracked separately in accrued_bill)."""
123
+ return self.total_import_cost
124
+
125
+ @property
126
+ def net_position(self) -> float:
127
+ """Negative = net cost, positive = net earnings."""
128
+ return self.export_earnings - self.total_cost
129
+
130
+ @property
131
+ def peak_import_fraction(self) -> float:
132
+ """Fraction of import that occurred at peak (base) rate. 0–1."""
133
+ total = self.import_kwh
134
+ return (self.import_kwh_peak / total) if total > 0 else 0.0
135
+
136
+ @property
137
+ def cheap_import_fraction(self) -> float:
138
+ """Fraction of import that occurred at cheap (timed) rate. 0–1."""
139
+ total = self.import_kwh
140
+ return (self.import_kwh_cheap / total) if total > 0 else 0.0
141
+
142
+ @property
143
+ def grid_to_house_kwh(self) -> float:
144
+ """Import that went to the house, not into the battery. Never negative.
145
+
146
+ Without a grid-to-battery reading the figure is the whole import.
147
+ """
148
+ return max(0.0, self.import_kwh - self.grid_to_battery_kwh)
149
+
150
+ @property
151
+ def supplied_without_grid_kwh(self) -> float:
152
+ """The house load not drawn from the grid at the time: solar, and battery discharge."""
153
+ return max(0.0, self.house_kwh - self.grid_to_house_kwh)
154
+
155
+ @property
156
+ def self_sufficiency_pct(self) -> float:
157
+ """Percentage of the house's consumption that did not have to be drawn from the grid.
158
+
159
+ house_kwh is the whole load, EV and immersion included, so they are not added again.
160
+ Grid energy the battery stored (grid_to_battery_kwh) is not counted against it.
161
+ Later discharge of that stored energy counts as supplied from storage. EV and
162
+ immersion energy bought from the grid is in house_kwh, so it still counts as grid.
163
+ With no grid-to-battery reading, all import counts, as it did before the reading
164
+ existed.
165
+ """
166
+ if self.house_kwh <= 0:
167
+ return 100.0
168
+ return max(0.0, min(100.0, (1 - self.grid_to_house_kwh / self.house_kwh) * 100))
169
+
170
+ @property
171
+ def solar_share_pct(self) -> float:
172
+ """Percentage of the house's consumption met by solar generated and kept on site.
173
+
174
+ Solar kept on site is generation less export. It includes solar stored in the
175
+ battery, which counts when it is generated, not when it is later discharged.
176
+ It does not count battery discharge, so energy the battery took from the grid
177
+ never raises the figure. It ignores grid import, so buying cheap energy does not
178
+ lower it. Compare self_sufficiency_pct, which counts all the house did not draw from the
179
+ grid.
180
+
181
+ house_kwh is the whole load, EV and immersion included, so they are not added again.
182
+ With no consumption the share is 0, not 100 as for self-sufficiency: no solar was
183
+ used, and a day with nothing to power should not read as fully solar powered.
184
+ """
185
+ if self.house_kwh <= 0:
186
+ return 0.0
187
+ solar_kept_kwh = max(0.0, self.solar_kwh - self.export_kwh)
188
+ return min(100.0, solar_kept_kwh / self.house_kwh * 100)
189
+
190
+ @property
191
+ def self_consumption_pct(self) -> float:
192
+ """Percentage of solar generation consumed on-site."""
193
+ if self.solar_kwh == 0:
194
+ return 0.0
195
+ return min(100.0, (1 - self.export_kwh / self.solar_kwh) * 100)
@@ -0,0 +1,124 @@
1
+ """bands.py: which price band each half-hour slot falls in, under a tariff definition.
2
+
3
+ Import and export each have their own bands. A slot belongs to the band in force at its start,
4
+ read on the clock of the definition's time zone. The slots are real elapsed time, so on a
5
+ clock-change day a skipped hour has no slots and a repeated hour is matched twice by the same
6
+ clock times.
7
+
8
+ A zone that runs past midnight belongs to the day it starts, so a Friday 23:00 to 08:00 zone
9
+ still applies at 01:00 on Saturday. When a public holiday counts as a weekend day, it matches a
10
+ zone that lists a weekend day and no zone that lists only weekdays. A zone with no days applies on
11
+ every day. Whether a date is a public holiday is not known here, so the caller passes that in.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Callable, Sequence
17
+ from datetime import date, datetime, time, timedelta
18
+ from decimal import Decimal
19
+
20
+ from ..timeutil import shift_real
21
+ from .defaults import SLOT_SECONDS
22
+ from .definition import ExportPrices, ImportPrices, TariffDefinition, Zone
23
+ from .slots import SlotDay
24
+
25
+ _WEEKEND = frozenset({5, 6})
26
+
27
+
28
+ def no_holidays(_day: date) -> bool:
29
+ return False
30
+
31
+
32
+ def band_at(
33
+ definition: TariffDefinition,
34
+ moment: datetime,
35
+ is_holiday: Callable[[date], bool] = no_holidays,
36
+ ) -> str:
37
+ """The name of the import band in force at *moment*: the applicable zone of highest
38
+ priority, or the base band."""
39
+ return _band_of(definition.import_prices, moment.astimezone(definition.timezone), is_holiday)
40
+
41
+
42
+ def export_band_at(
43
+ definition: TariffDefinition,
44
+ moment: datetime,
45
+ is_holiday: Callable[[date], bool] = no_holidays,
46
+ ) -> str:
47
+ """The name of the export band in force at *moment*, by the same rule as `band_at`."""
48
+ return _band_of(definition.export_prices, moment.astimezone(definition.timezone), is_holiday)
49
+
50
+
51
+ def _band_of(
52
+ prices: ImportPrices | ExportPrices, local: datetime, is_holiday: Callable[[date], bool]
53
+ ) -> str:
54
+ for zone in sorted(prices.zones, key=lambda zone: -zone.priority):
55
+ if _applies(zone, local, is_holiday):
56
+ return zone.name
57
+ return prices.base.name
58
+
59
+
60
+ def import_by_band(
61
+ days: Sequence[SlotDay],
62
+ definition: TariffDefinition,
63
+ is_holiday: Callable[[date], bool] = no_holidays,
64
+ ) -> dict[str, Decimal]:
65
+ """kWh imported in each band over *days*, in the order the bands are first met."""
66
+ return _by_band(days, "import", definition, is_holiday)
67
+
68
+
69
+ def export_by_band(
70
+ days: Sequence[SlotDay],
71
+ definition: TariffDefinition,
72
+ is_holiday: Callable[[date], bool] = no_holidays,
73
+ ) -> dict[str, Decimal]:
74
+ """kWh exported in each export band over *days*, in the order the bands are first met."""
75
+ return _by_band(days, "export", definition, is_holiday)
76
+
77
+
78
+ def _by_band(
79
+ days: Sequence[SlotDay],
80
+ flow: str,
81
+ definition: TariffDefinition,
82
+ is_holiday: Callable[[date], bool],
83
+ ) -> dict[str, Decimal]:
84
+ prices = definition.export_prices if flow == "export" else definition.import_prices
85
+ totals: dict[str, float] = {}
86
+ for day in days:
87
+ for index, kwh in enumerate(day.flows[flow]):
88
+ if kwh:
89
+ start = shift_real(day.start, timedelta(seconds=index * SLOT_SECONDS))
90
+ band = _band_of(prices, start.astimezone(definition.timezone), is_holiday)
91
+ totals[band] = totals.get(band, 0.0) + kwh
92
+ return {band: Decimal(repr(round(kwh, 6))) for band, kwh in totals.items()}
93
+
94
+
95
+ def zone_applies(zone: Zone, local: datetime, is_holiday: Callable[[date], bool]) -> bool:
96
+ """Whether *zone* is in force at the local time *local*. A zone whose start equals its end
97
+ covers the whole day."""
98
+ return _applies(zone, local, is_holiday)
99
+
100
+
101
+ def _applies(zone: Zone, local: datetime, is_holiday: Callable[[date], bool]) -> bool:
102
+ if not _in_hours(zone, local.time()):
103
+ return False
104
+ # A zone past midnight belongs to the day it began.
105
+ began = local.date()
106
+ if zone.start > zone.end and local.time() < zone.end:
107
+ began = began - timedelta(days=1)
108
+ if zone.months and began.month not in zone.months:
109
+ return False
110
+ return _on_day(zone, began, is_holiday)
111
+
112
+
113
+ def _in_hours(zone: Zone, clock: time) -> bool:
114
+ if zone.start < zone.end:
115
+ return zone.start <= clock < zone.end
116
+ return clock >= zone.start or clock < zone.end
117
+
118
+
119
+ def _on_day(zone: Zone, day: date, is_holiday: Callable[[date], bool]) -> bool:
120
+ if not zone.days:
121
+ return True
122
+ if zone.holidays_as_weekend and is_holiday(day):
123
+ return bool(zone.days & _WEEKEND)
124
+ return day.weekday() in zone.days
@@ -0,0 +1,73 @@
1
+ """
2
+ bill_days.py: one stored row for each finished day of the bill period.
3
+
4
+ At midnight the day that ended is added to the bill period's list. When the period ends the list
5
+ goes into that period's snapshot and the next period starts empty, so the store never holds more
6
+ than the current period and the periods already archived.
7
+
8
+ A row holds what the day imported, used and exported in each rate period. The first row of a
9
+ period also holds the tariff in force that day, and a later row holds it only when it differs
10
+ from the one before, so a tariff that changes mid-bill is recorded on the day it changed and
11
+ an archived period keeps the rates it was billed at. The tariff is plain data the host supplies.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Mapping, Sequence
17
+ from datetime import date
18
+ from typing import Any
19
+
20
+ from .accumulator import EnergyAccumulator
21
+
22
+ _DECIMALS = 4
23
+
24
+
25
+ def _by_period(values: Mapping[str, float]) -> dict[str, float]:
26
+ return {name: round(kwh, _DECIMALS) for name, kwh in values.items() if kwh}
27
+
28
+
29
+ def day_row(acc: EnergyAccumulator, day: date) -> dict[str, Any]:
30
+ """The row for a finished day, from that day's accumulator."""
31
+ return {
32
+ "date": day.isoformat(),
33
+ "import_kwh": round(acc.import_kwh, _DECIMALS),
34
+ "export_kwh": round(acc.export_kwh, _DECIMALS),
35
+ "solar_kwh": round(acc.solar_kwh, _DECIMALS),
36
+ "house_kwh": round(acc.house_kwh, _DECIMALS),
37
+ "battery_charge_kwh": round(acc.battery_charge_kwh, _DECIMALS),
38
+ "battery_discharge_kwh": round(acc.battery_discharge_kwh, _DECIMALS),
39
+ "import_kwh_by_period": _by_period(acc.import_kwh_by_period),
40
+ "import_cost_by_period": _by_period(acc.import_cost_by_period),
41
+ "house_kwh_by_period": _by_period(acc.house_kwh_by_period),
42
+ "load_cost": round(acc.grid_equivalent_load_cost, _DECIMALS),
43
+ "export_credit": round(acc.export_earnings, _DECIMALS),
44
+ }
45
+
46
+
47
+ def tariff_in_effect(days: Sequence[Mapping[str, Any]]) -> dict[str, Any] | None:
48
+ """The tariff of the newest row that records one, or None when no row does."""
49
+ for row in reversed(days):
50
+ if isinstance(row.get("tariff"), dict):
51
+ tariff: dict[str, Any] = row["tariff"]
52
+ return tariff
53
+ return None
54
+
55
+
56
+ def with_day(
57
+ days: Sequence[Mapping[str, Any]], row: dict[str, Any], tariff: dict[str, Any]
58
+ ) -> list[dict[str, Any]]:
59
+ """The list with *row* added, carrying *tariff* when it is the first or differs from before."""
60
+ stored = dict(row)
61
+ if tariff_in_effect(days) != tariff:
62
+ stored["tariff"] = tariff
63
+ return [dict(existing) for existing in days] + [stored]
64
+
65
+
66
+ def tariff_for_day(days: Sequence[Mapping[str, Any]], index: int) -> dict[str, Any] | None:
67
+ """The tariff that applied on the row at *index*: the newest one recorded up to it."""
68
+ return tariff_in_effect(days[: index + 1])
69
+
70
+
71
+ def tariff_changes(days: Sequence[Mapping[str, Any]]) -> list[str]:
72
+ """The dates, after the first row, on which the tariff differs from the day before."""
73
+ return [str(row["date"]) for row in days[1:] if "tariff" in row]
@@ -0,0 +1,28 @@
1
+ """billing.py: rounding the way a supplier bill rounds, and one bill line by line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from decimal import ROUND_HALF_UP, Decimal
7
+
8
+
9
+ def money(value: float) -> float:
10
+ """Round to whole cents, halves upward, the way a supplier bill rounds each line."""
11
+ return float(Decimal(repr(round(value, 8))).quantize(Decimal("0.01"), ROUND_HALF_UP))
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class BillBreakdown:
16
+ """One bill, line by line. Every figure is rounded to cents as a bill rounds it."""
17
+
18
+ energy: float
19
+ supplier_saving: float
20
+ standing_charge: float
21
+ pso_levy: float
22
+ vat: float
23
+ export_credit: float
24
+ total: float
25
+
26
+ @property
27
+ def before_vat(self) -> float:
28
+ return money(self.energy - self.supplier_saving + self.standing_charge + self.pso_levy)