value-semantics-core 2.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.
@@ -0,0 +1,223 @@
1
+ """Exact dated enterprise-value arithmetic.
2
+
3
+ The primitive deliberately owns only arithmetic and operand identity. Source,
4
+ currency, date, share-basis, split, and component-classification authority stay
5
+ with the calling product contract.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import Counter
11
+ from collections.abc import Sequence
12
+ from dataclasses import dataclass, field
13
+ from decimal import Decimal, localcontext
14
+ from typing import Literal, TypeAlias
15
+
16
+
17
+ EnterpriseValueUnavailableReason: TypeAlias = Literal[
18
+ "duplicate_component_id",
19
+ "non_positive_price",
20
+ "non_positive_shares",
21
+ ]
22
+
23
+
24
+ def _require_finite_decimal(value: Decimal, *, field_name: str) -> None:
25
+ if not isinstance(value, Decimal):
26
+ raise TypeError(f"{field_name} must be Decimal")
27
+ if not value.is_finite():
28
+ raise ValueError(f"{field_name} must be finite")
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class EnterpriseValueComponent:
33
+ """One already-signed enterprise-value component."""
34
+
35
+ component_id: str
36
+ value: Decimal
37
+
38
+ def __post_init__(self) -> None:
39
+ if not isinstance(self.component_id, str) or not self.component_id.strip():
40
+ raise ValueError("component_id must be a non-empty str")
41
+ if self.component_id != self.component_id.strip():
42
+ raise ValueError("component_id must not have surrounding whitespace")
43
+ _require_finite_decimal(self.value, field_name="component value")
44
+
45
+
46
+ def _component_tuple(
47
+ values: Sequence[EnterpriseValueComponent],
48
+ ) -> tuple[EnterpriseValueComponent, ...]:
49
+ if isinstance(values, (str, bytes)) or not isinstance(values, Sequence):
50
+ raise TypeError("components must be a sequence")
51
+ result = tuple(values)
52
+ if any(not isinstance(value, EnterpriseValueComponent) for value in result):
53
+ raise TypeError("components must contain EnterpriseValueComponent values")
54
+ return result
55
+
56
+
57
+ def _exact_sum(values: Sequence[Decimal]) -> Decimal:
58
+ minimum_exponent = min(int(value.as_tuple().exponent) for value in values)
59
+ maximum_adjusted = max(value.adjusted() for value in values)
60
+ with localcontext() as context:
61
+ context.prec = max(
62
+ 28,
63
+ maximum_adjusted - minimum_exponent + len(str(len(values))) + 2,
64
+ )
65
+ return sum(values, start=Decimal(0))
66
+
67
+
68
+ def _exact_product(left: Decimal, right: Decimal) -> Decimal:
69
+ with localcontext() as context:
70
+ context.prec = max(
71
+ 28,
72
+ len(left.as_tuple().digits) + len(right.as_tuple().digits) + 2,
73
+ )
74
+ return left * right
75
+
76
+
77
+ def _duplicate_ids(
78
+ components: Sequence[EnterpriseValueComponent],
79
+ ) -> tuple[str, ...]:
80
+ counts = Counter(value.component_id for value in components)
81
+ return tuple(
82
+ dict.fromkeys(
83
+ value.component_id for value in components if counts[value.component_id] > 1
84
+ )
85
+ )
86
+
87
+
88
+ def _validate_result(
89
+ *,
90
+ price_per_share: Decimal,
91
+ split_adjusted_shares: Decimal,
92
+ equity_value: Decimal,
93
+ components: tuple[EnterpriseValueComponent, ...],
94
+ enterprise_value: Decimal,
95
+ ) -> None:
96
+ for field_name, value in (
97
+ ("price_per_share", price_per_share),
98
+ ("split_adjusted_shares", split_adjusted_shares),
99
+ ("equity_value", equity_value),
100
+ ("enterprise_value", enterprise_value),
101
+ ):
102
+ _require_finite_decimal(value, field_name=field_name)
103
+ if type(components) is not tuple or any(
104
+ not isinstance(value, EnterpriseValueComponent) for value in components
105
+ ):
106
+ raise TypeError("components must be a tuple of EnterpriseValueComponent values")
107
+ expected_equity = _exact_product(price_per_share, split_adjusted_shares)
108
+ expected_enterprise = _exact_sum(
109
+ (expected_equity, *(value.value for value in components))
110
+ )
111
+ if equity_value != expected_equity:
112
+ raise ValueError("equity_value must equal exact price times shares")
113
+ if enterprise_value != expected_enterprise:
114
+ raise ValueError("enterprise_value must equal equity value plus signed components")
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class DatedEnterpriseValueAvailable:
119
+ price_per_share: Decimal
120
+ split_adjusted_shares: Decimal
121
+ equity_value: Decimal
122
+ components: tuple[EnterpriseValueComponent, ...]
123
+ enterprise_value: Decimal
124
+ status: Literal["available"] = field(default="available", init=False)
125
+
126
+ def __post_init__(self) -> None:
127
+ _validate_result(
128
+ price_per_share=self.price_per_share,
129
+ split_adjusted_shares=self.split_adjusted_shares,
130
+ equity_value=self.equity_value,
131
+ components=self.components,
132
+ enterprise_value=self.enterprise_value,
133
+ )
134
+ if self.price_per_share <= 0 or self.split_adjusted_shares <= 0:
135
+ raise ValueError("available enterprise value requires positive price and shares")
136
+ if _duplicate_ids(self.components):
137
+ raise ValueError("available enterprise-value component IDs must be unique")
138
+
139
+
140
+ @dataclass(frozen=True, slots=True)
141
+ class DatedEnterpriseValueUnavailable:
142
+ reason: EnterpriseValueUnavailableReason
143
+ price_per_share: Decimal
144
+ split_adjusted_shares: Decimal
145
+ components: tuple[EnterpriseValueComponent, ...]
146
+ status: Literal["unavailable"] = field(default="unavailable", init=False)
147
+
148
+ def __post_init__(self) -> None:
149
+ if self.reason not in {
150
+ "duplicate_component_id",
151
+ "non_positive_price",
152
+ "non_positive_shares",
153
+ }:
154
+ raise ValueError("unsupported enterprise-value unavailable reason")
155
+ _require_finite_decimal(self.price_per_share, field_name="price_per_share")
156
+ _require_finite_decimal(
157
+ self.split_adjusted_shares,
158
+ field_name="split_adjusted_shares",
159
+ )
160
+ if type(self.components) is not tuple or any(
161
+ not isinstance(value, EnterpriseValueComponent) for value in self.components
162
+ ):
163
+ raise TypeError("components must be a tuple of EnterpriseValueComponent values")
164
+
165
+
166
+ DatedEnterpriseValueResult: TypeAlias = (
167
+ DatedEnterpriseValueAvailable | DatedEnterpriseValueUnavailable
168
+ )
169
+
170
+
171
+ def derive_dated_enterprise_value(
172
+ *,
173
+ price_per_share: Decimal,
174
+ split_adjusted_shares: Decimal,
175
+ components: Sequence[EnterpriseValueComponent],
176
+ ) -> DatedEnterpriseValueResult:
177
+ """Derive exact EV from already-normalized, already-signed operands."""
178
+
179
+ _require_finite_decimal(price_per_share, field_name="price_per_share")
180
+ _require_finite_decimal(split_adjusted_shares, field_name="split_adjusted_shares")
181
+ component_rows = _component_tuple(components)
182
+ if _duplicate_ids(component_rows):
183
+ return DatedEnterpriseValueUnavailable(
184
+ reason="duplicate_component_id",
185
+ price_per_share=price_per_share,
186
+ split_adjusted_shares=split_adjusted_shares,
187
+ components=component_rows,
188
+ )
189
+ if price_per_share <= 0:
190
+ return DatedEnterpriseValueUnavailable(
191
+ reason="non_positive_price",
192
+ price_per_share=price_per_share,
193
+ split_adjusted_shares=split_adjusted_shares,
194
+ components=component_rows,
195
+ )
196
+ if split_adjusted_shares <= 0:
197
+ return DatedEnterpriseValueUnavailable(
198
+ reason="non_positive_shares",
199
+ price_per_share=price_per_share,
200
+ split_adjusted_shares=split_adjusted_shares,
201
+ components=component_rows,
202
+ )
203
+ equity_value = _exact_product(price_per_share, split_adjusted_shares)
204
+ enterprise_value = _exact_sum(
205
+ (equity_value, *(value.value for value in component_rows))
206
+ )
207
+ return DatedEnterpriseValueAvailable(
208
+ price_per_share=price_per_share,
209
+ split_adjusted_shares=split_adjusted_shares,
210
+ equity_value=equity_value,
211
+ components=component_rows,
212
+ enterprise_value=enterprise_value,
213
+ )
214
+
215
+
216
+ __all__ = [
217
+ "DatedEnterpriseValueAvailable",
218
+ "DatedEnterpriseValueResult",
219
+ "DatedEnterpriseValueUnavailable",
220
+ "EnterpriseValueComponent",
221
+ "EnterpriseValueUnavailableReason",
222
+ "derive_dated_enterprise_value",
223
+ ]
@@ -0,0 +1,220 @@
1
+ """Deterministic formatting for the shared numeric-display contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime
6
+ from decimal import Decimal, InvalidOperation
7
+ from typing import Any
8
+
9
+ from .numeric_display import NumericDisplaySpec
10
+
11
+
12
+ def format_numeric(value: Any, display: NumericDisplaySpec) -> str:
13
+ if display.numeric_kind == "date":
14
+ return _iso_date(value)
15
+
16
+ number = _decimal(value)
17
+ if number is None:
18
+ raise ValueError(f"numeric display received non-numeric value: {value!r}")
19
+
20
+ prefix, suffix = _numeric_affixes(display)
21
+ if display.numeric_kind == "currency":
22
+ return f"{prefix}{number:,.{display.precision}f}{suffix}"
23
+ if display.numeric_kind == "percentage":
24
+ return f"{number * 100:,.{display.precision}f}{suffix}"
25
+ if display.numeric_kind == "basis_points":
26
+ return f"{number * 10000:,.{display.precision}f}{suffix}"
27
+ if display.numeric_kind in {"multiple", "count", "ratio", "index", "duration"}:
28
+ return f"{number:,.{display.precision}f}{suffix}"
29
+ if display.numeric_kind == "per_share":
30
+ return f"{prefix}{number:,.{display.precision}f}"
31
+ if display.numeric_kind == "weight":
32
+ return f"{number * 100:,.{display.precision}f}{suffix}"
33
+
34
+ raise ValueError(f"unsupported numeric display kind: {display.numeric_kind!r}")
35
+
36
+
37
+ def numeric_unit_tag(display: NumericDisplaySpec) -> str:
38
+ """Return the exact non-numeric affixes emitted by ``format_numeric``."""
39
+
40
+ prefix, suffix = _numeric_affixes(display)
41
+ return f"{prefix}{suffix}"
42
+
43
+
44
+ def normalize_declared_numeric(
45
+ value: Any,
46
+ *,
47
+ unit: str,
48
+ currency: str | None = None,
49
+ precision: int = 1,
50
+ ) -> tuple[Any, dict[str, Any]]:
51
+ """Canonicalize one explicitly declared producer unit at its boundary."""
52
+
53
+ normalized_unit = unit.strip().lower()
54
+ currency_code = currency.upper() if currency else None
55
+ if currency_code:
56
+ scales = {
57
+ "currency": "unit",
58
+ "money": "unit",
59
+ "ones": "unit",
60
+ "usd": "unit",
61
+ "thousands": "thousands",
62
+ "usd_thousands": "thousands",
63
+ "millions": "millions",
64
+ "million": "millions",
65
+ "usd_millions": "millions",
66
+ "billions": "billions",
67
+ "billion": "billions",
68
+ "usd_billions": "billions",
69
+ }
70
+ if normalized_unit in {"per_share", "usd/share", "usd_per_share"}:
71
+ return value, {
72
+ "numeric_kind": "per_share",
73
+ "currency": currency_code,
74
+ "precision": precision,
75
+ }
76
+ if normalized_unit not in scales:
77
+ raise ValueError(f"unsupported monetary unit: {unit!r}")
78
+ return value, {
79
+ "numeric_kind": "currency",
80
+ "scale": scales[normalized_unit],
81
+ "currency": currency_code,
82
+ "precision": precision,
83
+ }
84
+
85
+ if normalized_unit in {
86
+ "%",
87
+ "percent",
88
+ "percentage",
89
+ "percentage_points",
90
+ "percent floor",
91
+ 'percent floor ("in excess of")',
92
+ }:
93
+ return _scale_value(value, Decimal("0.01")), {
94
+ "numeric_kind": "percentage",
95
+ "precision": precision,
96
+ }
97
+ if normalized_unit in {"decimal_pct", "decimal_percent", "decimal"}:
98
+ return value, {"numeric_kind": "percentage", "precision": precision}
99
+ if normalized_unit in {"x", "multiple"}:
100
+ return value, {"numeric_kind": "multiple", "precision": precision}
101
+ if normalized_unit == "ratio":
102
+ return value, {"numeric_kind": "ratio", "precision": precision}
103
+ if normalized_unit == "index":
104
+ return value, {"numeric_kind": "index", "precision": precision}
105
+ if normalized_unit in {"bps", "basis_points"}:
106
+ return _scale_value(value, Decimal("0.0001")), {
107
+ "numeric_kind": "basis_points",
108
+ "precision": max(precision, 2),
109
+ }
110
+ if normalized_unit in {
111
+ "clients",
112
+ "customers",
113
+ "employees",
114
+ "patients",
115
+ "seats",
116
+ "stores",
117
+ "users",
118
+ "wells",
119
+ }:
120
+ return value, {
121
+ "numeric_kind": "count",
122
+ "precision": 0,
123
+ "unit_label": normalized_unit,
124
+ }
125
+ if normalized_unit == "count":
126
+ return value, {"numeric_kind": "count", "precision": 0}
127
+ raise ValueError(f"unsupported declared numeric unit: {unit!r}")
128
+
129
+
130
+ def _scale_value(value: Any, multiplier: Decimal) -> Any:
131
+ if isinstance(value, dict) and "value" in value:
132
+ return {**value, "value": _scale_value(value["value"], multiplier)}
133
+ number = _decimal(value)
134
+ if number is None:
135
+ raise ValueError(f"numeric normalization received non-numeric value: {value!r}")
136
+ return number * multiplier
137
+
138
+
139
+ def _unit_suffix(display: NumericDisplaySpec) -> str:
140
+ suffix = {
141
+ "unit": "",
142
+ "thousands": "k",
143
+ "millions": "m",
144
+ "billions": "bn",
145
+ }[display.scale]
146
+ if display.unit_label:
147
+ suffix = f"{suffix} {display.unit_label}" if suffix else f" {display.unit_label}"
148
+ return suffix
149
+
150
+
151
+ def _numeric_affixes(display: NumericDisplaySpec) -> tuple[str, str]:
152
+ kind = display.numeric_kind
153
+ if kind == "currency":
154
+ prefix = "$" if display.currency == "USD" else f"{display.currency or ''} "
155
+ return prefix, _unit_suffix(display)
156
+ if kind == "percentage":
157
+ return "", "%"
158
+ if kind == "basis_points":
159
+ return "", " bp"
160
+ if kind == "multiple":
161
+ return "", "×"
162
+ if kind == "count":
163
+ return "", _unit_suffix(display)
164
+ if kind == "per_share":
165
+ prefix = "$" if display.currency == "USD" else f"{display.currency or ''} "
166
+ return prefix, ""
167
+ if kind in {"ratio", "index", "duration"}:
168
+ return "", _unit_suffix(display)
169
+ if kind == "date":
170
+ return "", ""
171
+ if kind == "weight":
172
+ denominator = display.denominator_basis
173
+ if denominator is None:
174
+ raise ValueError("weight display requires denominator_basis")
175
+ try:
176
+ denominator_label = _DENOMINATOR_LABELS[denominator]
177
+ except KeyError as exc:
178
+ raise ValueError(
179
+ f"unsupported weight denominator basis: {denominator!r}"
180
+ ) from exc
181
+ return "", f"% of {denominator_label}"
182
+ raise ValueError(f"unsupported numeric display kind: {kind!r}")
183
+
184
+
185
+ def _iso_date(value: Any) -> str:
186
+ if isinstance(value, datetime):
187
+ raise ValueError(f"date display requires an ISO calendar date: {value!r}")
188
+ if isinstance(value, date):
189
+ return value.isoformat()
190
+ if not isinstance(value, str):
191
+ raise ValueError(f"date display requires an ISO calendar date: {value!r}")
192
+ try:
193
+ parsed = date.fromisoformat(value)
194
+ except ValueError as exc:
195
+ raise ValueError(f"date display requires an ISO calendar date: {value!r}") from exc
196
+ if parsed.isoformat() != value:
197
+ raise ValueError(f"date display requires an ISO calendar date: {value!r}")
198
+ return value
199
+
200
+
201
+ def _decimal(value: Any) -> Decimal | None:
202
+ try:
203
+ result = Decimal(str(value))
204
+ except (InvalidOperation, TypeError, ValueError):
205
+ return None
206
+ return result if result.is_finite() else None
207
+
208
+
209
+ _DENOMINATOR_LABELS = {
210
+ "nav": "NAV",
211
+ "gross_exposure": "gross exposure",
212
+ "net_exposure": "net exposure",
213
+ "portfolio_value": "portfolio value",
214
+ "total_market_value": "total market value",
215
+ "benchmark_total": "benchmark total",
216
+ "fund_total": "fund total",
217
+ }
218
+
219
+
220
+ __all__ = ["format_numeric", "normalize_declared_numeric", "numeric_unit_tag"]