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,119 @@
1
+ """windows.py: the cheapest or dearest stretch of a given length in a price series.
2
+
3
+ The prices are constant inside a slot, so the best window always starts either where a slot starts
4
+ or ends exactly when a slot ends. Trying only those starts finds the exact best for any duration
5
+ and any slot length, with no rounding to a slot. A window costs the load's power, times the time
6
+ spent in each slot, times that slot's all-in price from `price_curve`.
7
+
8
+ A window is only offered where the series has a price for every moment of it. When the series ends
9
+ before the latest end asked for, the result says so and does not guess the rest.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Sequence
15
+ from dataclasses import dataclass
16
+ from datetime import datetime, timedelta
17
+ from decimal import Decimal
18
+ from typing import Literal
19
+
20
+ from .price_curve import PriceSlot
21
+
22
+ _HOUR = Decimal(3600)
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class WindowSearch:
27
+ """What to look for. Times are aware. A range left out is the whole series."""
28
+
29
+ duration: timedelta
30
+ flow: Literal["import", "export"] = "import"
31
+ highest: bool = False # the dearest window, not the cheapest
32
+ latest: bool = False # on a tie, the latest start, not the earliest
33
+ power_kw: Decimal = Decimal(1)
34
+ earliest_start: datetime | None = None
35
+ latest_end: datetime | None = None # a "finish by" time
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Window:
40
+ """The window found, and what it costs against starting as early as allowed."""
41
+
42
+ start: datetime
43
+ end: datetime
44
+ cost: Decimal # the load's cost over the window, in the currency of the prices
45
+ average_price: Decimal # per kWh
46
+ reference_cost: Decimal | None # the same load starting at the earliest start
47
+ complete: bool # False when the series ends before the latest end asked for
48
+
49
+ @property
50
+ def saving(self) -> Decimal | None:
51
+ """The reference cost less this cost. Negative when a dearest window was asked for."""
52
+ return None if self.reference_cost is None else self.reference_cost - self.cost
53
+
54
+
55
+ def find_window(slots: Sequence[PriceSlot], search: WindowSearch) -> Window | None:
56
+ """The best window under *search*, or None when no window fits inside the priced time."""
57
+ if search.duration <= timedelta(0) or search.power_kw <= 0:
58
+ raise ValueError("duration and power must be above zero")
59
+ if not slots:
60
+ return None
61
+ first, last = _range(slots, search)
62
+ costs = {
63
+ start: cost
64
+ for start in _starts(slots, search.duration, first, last)
65
+ if (cost := _cost(slots, search, start)) is not None
66
+ }
67
+ if not costs:
68
+ return None
69
+ best = min(costs, key=lambda start: _rank(search, start, costs[start]))
70
+ hours = Decimal(search.duration.total_seconds()) / _HOUR
71
+ return Window(
72
+ start=best,
73
+ end=best + search.duration,
74
+ cost=costs[best],
75
+ average_price=costs[best] / (hours * search.power_kw),
76
+ reference_cost=_cost(slots, search, first),
77
+ complete=search.latest_end is None or search.latest_end <= slots[-1].end,
78
+ )
79
+
80
+
81
+ def _rank(search: WindowSearch, start: datetime, cost: Decimal) -> tuple[Decimal, float]:
82
+ """Smaller is better: cost (negated for the dearest), then start (negated for the latest)."""
83
+ when = start.timestamp()
84
+ return (-cost if search.highest else cost, -when if search.latest else when)
85
+
86
+
87
+ def _range(slots: Sequence[PriceSlot], search: WindowSearch) -> tuple[datetime, datetime]:
88
+ """The part of the priced time the search may use."""
89
+ first, last = slots[0].start, slots[-1].end
90
+ if search.earliest_start is not None:
91
+ first = max(first, search.earliest_start)
92
+ if search.latest_end is not None:
93
+ last = min(last, search.latest_end)
94
+ return first, last
95
+
96
+
97
+ def _starts(
98
+ slots: Sequence[PriceSlot], duration: timedelta, first: datetime, last: datetime
99
+ ) -> list[datetime]:
100
+ edges = {first, last - duration}
101
+ for slot in slots:
102
+ edges.update((slot.start, slot.end - duration))
103
+ return sorted(s for s in edges if s >= first and s + duration <= last)
104
+
105
+
106
+ def _cost(slots: Sequence[PriceSlot], search: WindowSearch, start: datetime) -> Decimal | None:
107
+ end = start + search.duration
108
+ seconds = Decimal(0)
109
+ total = Decimal(0)
110
+ for slot in slots:
111
+ overlap = min(slot.end, end).timestamp() - max(slot.start, start).timestamp()
112
+ if overlap <= 0:
113
+ continue
114
+ price = slot.import_price if search.flow == "import" else slot.export_price
115
+ seconds += Decimal(overlap)
116
+ total += price * Decimal(overlap)
117
+ if seconds != Decimal(search.duration.total_seconds()):
118
+ return None
119
+ return total * search.power_kw / _HOUR
@@ -0,0 +1,39 @@
1
+ """Rank every plan of a store against the current one over past usage."""
2
+
3
+ from .search import (
4
+ MAX_BILLS,
5
+ MAX_WEEKS,
6
+ TOP,
7
+ Candidate,
8
+ DayRange,
9
+ Ranked,
10
+ SearchResult,
11
+ Unit,
12
+ Usage,
13
+ Window,
14
+ needs_export_rate,
15
+ price_ranges,
16
+ ranges,
17
+ rank_sentence,
18
+ search,
19
+ with_export_rate,
20
+ )
21
+
22
+ __all__ = [
23
+ "MAX_BILLS",
24
+ "MAX_WEEKS",
25
+ "TOP",
26
+ "Candidate",
27
+ "DayRange",
28
+ "Ranked",
29
+ "SearchResult",
30
+ "Unit",
31
+ "Usage",
32
+ "Window",
33
+ "needs_export_rate",
34
+ "price_ranges",
35
+ "rank_sentence",
36
+ "ranges",
37
+ "search",
38
+ "with_export_rate",
39
+ ]
@@ -0,0 +1,189 @@
1
+ """
2
+ search.py: rank every plan of a store against the current one over past usage.
3
+
4
+ The history holds energy and no price, so each plan is priced over the same days by the same bill
5
+ engine. The window is a number of weeks, or a number of whole bills of the current tariff. A
6
+ re-pricing of measured usage, never a forecast, and it never writes: this module imports only the
7
+ tariff library.
8
+
9
+ A plan on a price feed is left out, since the history holds no feed prices. A plan with no
10
+ export price is priced with the export rate the user gave for it, or is left out
11
+ when none was given (`needs_export_rate`). The current plan is always priced as saved, since an
12
+ export rate of 0 is a real choice for it.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Callable, Sequence
18
+ from dataclasses import dataclass, replace
19
+ from datetime import date, timedelta
20
+ from decimal import Decimal
21
+ from enum import Enum
22
+
23
+ from ..tariff import BillInputs, SlotHistory, TariffDefinition, price_bill, series_names
24
+ from ..tariff.bands import export_by_band, import_by_band, no_holidays
25
+ from ..tariff.period_bill import bill_period_bounds
26
+
27
+ MAX_WEEKS = 104
28
+ MAX_BILLS = 24
29
+ AVERAGE_MONTH_DAYS = 30 # the period a weeks window shares the monthly levy over
30
+ TOP = 3
31
+
32
+
33
+ class Unit(Enum):
34
+ WEEKS = "weeks"
35
+ BILLS = "bills"
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Window:
40
+ unit: Unit
41
+ count: int
42
+
43
+ def __post_init__(self) -> None:
44
+ limit = MAX_WEEKS if self.unit is Unit.WEEKS else MAX_BILLS
45
+ if not 1 <= self.count <= limit:
46
+ raise ValueError(f"the window must be 1 to {limit} {self.unit.value}")
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class DayRange:
51
+ first: date
52
+ last: date # included
53
+ period_days: int # days the monthly charges are shared over
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Candidate:
58
+ key: str
59
+ label: str
60
+ definition: TariffDefinition
61
+ export_rate: Decimal | None = None # typed by the user for a plan with no export price
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Ranked:
66
+ key: str
67
+ label: str
68
+ total: float
69
+ difference: float # this plan less the current one: negative is cheaper
70
+ rank: int
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class SearchResult:
75
+ ranked: tuple[Ranked, ...]
76
+ current_rank: int
77
+ first_day: date
78
+ last_day: date
79
+ days: int
80
+ days_recorded: int
81
+ data_from: date | None
82
+ skipped: int # plans left out
83
+
84
+ @property
85
+ def compared(self) -> int:
86
+ return len(self.ranked)
87
+
88
+
89
+ def ranges(window: Window, through: date, start_day: int, months: int = 1) -> list[DayRange]:
90
+ """The day ranges to price, ending with the day *through* (weeks) or the last whole bill."""
91
+ if window.unit is Unit.WEEKS:
92
+ first = through - timedelta(days=window.count * 7 - 1)
93
+ return [DayRange(first, through, AVERAGE_MONTH_DAYS)]
94
+ first_of_open, _ = bill_period_bounds(start_day, through, months)
95
+ found: list[DayRange] = []
96
+ cursor = first_of_open
97
+ for _ in range(window.count):
98
+ first, following = bill_period_bounds(start_day, cursor - timedelta(days=1), months)
99
+ found.append(DayRange(first, following - timedelta(days=1), (following - first).days))
100
+ cursor = first
101
+ return sorted(found, key=lambda r: r.first)
102
+
103
+
104
+ def needs_export_rate(definition: TariffDefinition) -> bool:
105
+ """True when the plan lists no export price, so the user's own rate is needed to price it."""
106
+ prices = definition.export_prices
107
+ return not (prices.base.price > 0 or prices.zones)
108
+
109
+
110
+ def with_export_rate(definition: TariffDefinition, rate: Decimal) -> TariffDefinition:
111
+ """*definition* paying *rate* for export, when it lists none."""
112
+ if not needs_export_rate(definition):
113
+ return definition
114
+ base = replace(definition.export_prices.base, price=rate)
115
+ return replace(definition, export_prices=replace(definition.export_prices, base=base))
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class Usage:
120
+ """The measured usage to price: the history, the day ranges and the holiday calendar."""
121
+
122
+ history: SlotHistory
123
+ spans: Sequence[DayRange]
124
+ is_holiday: Callable[[date], bool] = no_holidays
125
+
126
+
127
+ def price_ranges(usage: Usage, definition: TariffDefinition) -> Decimal:
128
+ """The total of the bills for the usage's spans priced under *definition*."""
129
+ is_holiday = usage.is_holiday
130
+ total = Decimal(0)
131
+ for span in usage.spans:
132
+ days = usage.history.between(span.first, span.last)
133
+ export: Decimal | dict[str, Decimal]
134
+ if definition.export_prices.zones:
135
+ export = export_by_band(days, definition, is_holiday)
136
+ else:
137
+ export = Decimal(repr(round(sum(d.total("export") for d in days), 6)))
138
+ length = (span.last - span.first).days + 1
139
+ inputs = BillInputs(
140
+ length, span.period_days, import_by_band(days, definition, is_holiday), export
141
+ )
142
+ total += price_bill(definition, inputs).total
143
+ return total
144
+
145
+
146
+ def search(usage: Usage, current: Candidate, others: Sequence[Candidate]) -> SearchResult:
147
+ """Price *current* and every candidate over the usage and rank them, cheapest first."""
148
+ spans = usage.spans
149
+ skipped = 0
150
+ priced: list[tuple[Candidate, Decimal]] = []
151
+ for candidate in [current, *others]:
152
+ definition = candidate.definition
153
+ if series_names(definition) and candidate.key != current.key:
154
+ skipped += 1 # a price feed has no band prices, and its cost needs the published prices
155
+ continue
156
+ if needs_export_rate(definition) and candidate.key != current.key:
157
+ if candidate.export_rate is None:
158
+ skipped += 1
159
+ continue
160
+ definition = with_export_rate(definition, candidate.export_rate)
161
+ priced.append((candidate, price_ranges(usage, definition)))
162
+ priced.sort(key=lambda item: (item[1], item[0].key != current.key, item[0].label))
163
+ base = next(total for cand, total in priced if cand.key == current.key)
164
+ ranked = tuple(
165
+ Ranked(c.key, c.label, float(t), float(t - base), index)
166
+ for index, (c, t) in enumerate(priced, start=1)
167
+ )
168
+ days = usage.history.between(spans[0].first, spans[-1].last)
169
+ return SearchResult(
170
+ ranked=ranked,
171
+ current_rank=next(r.rank for r in ranked if r.key == current.key),
172
+ first_day=spans[0].first,
173
+ last_day=spans[-1].last,
174
+ days=(spans[-1].last - spans[0].first).days + 1,
175
+ days_recorded=len(days),
176
+ data_from=days[0].day if days else None,
177
+ skipped=skipped,
178
+ )
179
+
180
+
181
+ def rank_sentence(result: SearchResult) -> str:
182
+ """Where the current plan stands, in words."""
183
+ rank, total = result.current_rank, result.compared
184
+ if rank == 1:
185
+ return f"Your plan is the cheapest of the {total} compared."
186
+ if rank <= TOP:
187
+ return f"Your plan is number {rank} of the {total} compared, in the top {TOP}."
188
+ gap = result.ranked[rank - 1].total - result.ranked[0].total
189
+ return f"Your plan is number {rank} of the {total} compared, {gap:.2f} above the cheapest."
@@ -0,0 +1,13 @@
1
+ """The stored tariff format: its validator, its index, the compile step and a client.
2
+
3
+ Standard library only, and no import from `lib.tariff`, so the sync scripts, the checks and any
4
+ client share exactly one definition of the format.
5
+ """
6
+ from .client import FolderCache, MemoryCache, Store, StoreError, folder_reader, url_reader
7
+ from .compile import CompileError, compile_area
8
+ from .price_client import PriceStore
9
+ from .schema import checksum, validate_country, validate_tariff
10
+
11
+ __all__ = ["CompileError", "FolderCache", "MemoryCache", "PriceStore", "Store", "StoreError",
12
+ "checksum", "compile_area", "folder_reader", "url_reader", "validate_country",
13
+ "validate_tariff"]