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,751 @@
1
+ """Deterministic forward-P/E value semantics.
2
+
3
+ The derivation in this module is deliberately provider-neutral and effect-free.
4
+ Callers supply the exact period mapping, price, estimates, and display quantum;
5
+ the functions never consult a clock or fetch data.
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 datetime import date, timedelta
14
+ from decimal import Decimal, ROUND_HALF_EVEN, localcontext
15
+ from typing import Literal, TypeAlias
16
+
17
+
18
+ ForwardPeUnavailableReason: TypeAlias = Literal[
19
+ "missing_fiscal_anchor",
20
+ "invalid_price",
21
+ "missing_future_estimate",
22
+ "duplicate_future_period",
23
+ "non_positive_eps",
24
+ ]
25
+
26
+ Fy1ForwardPeriodUnavailableReason: TypeAlias = Literal[
27
+ "missing_fiscal_anchor",
28
+ "missing_future_estimate",
29
+ "duplicate_future_period",
30
+ ]
31
+
32
+ NtmForwardPeUnavailableReason: TypeAlias = Literal[
33
+ "missing_fiscal_anchor",
34
+ "missing_close_date",
35
+ "fiscal_anchor_postdates_close",
36
+ "invalid_price",
37
+ "insufficient_future_quarters",
38
+ "duplicate_future_period",
39
+ "overlapping_future_periods",
40
+ "gapped_future_periods",
41
+ "non_quarterly_period_cadence",
42
+ "non_positive_aggregate_eps",
43
+ ]
44
+
45
+ _UNAVAILABLE_REASONS = frozenset(
46
+ {
47
+ "missing_fiscal_anchor",
48
+ "invalid_price",
49
+ "missing_future_estimate",
50
+ "duplicate_future_period",
51
+ "non_positive_eps",
52
+ }
53
+ )
54
+
55
+ _NTM_UNAVAILABLE_REASONS = frozenset(
56
+ {
57
+ "missing_fiscal_anchor",
58
+ "missing_close_date",
59
+ "fiscal_anchor_postdates_close",
60
+ "invalid_price",
61
+ "insufficient_future_quarters",
62
+ "duplicate_future_period",
63
+ "overlapping_future_periods",
64
+ "gapped_future_periods",
65
+ "non_quarterly_period_cadence",
66
+ "non_positive_aggregate_eps",
67
+ }
68
+ )
69
+
70
+ _MIN_INCLUSIVE_QUARTER_DAYS = 70
71
+ _MAX_INCLUSIVE_QUARTER_DAYS = 105
72
+ _MIN_FOUR_QUARTER_HORIZON_DAYS = 350
73
+ _MAX_FOUR_QUARTER_HORIZON_DAYS = 385
74
+
75
+
76
+ def _require_date(value: date, *, field_name: str) -> None:
77
+ if type(value) is not date:
78
+ raise TypeError(f"{field_name} must be date")
79
+
80
+
81
+ def _require_finite_decimal(value: Decimal, *, field_name: str) -> None:
82
+ if not isinstance(value, Decimal):
83
+ raise TypeError(f"{field_name} must be Decimal")
84
+ if not value.is_finite():
85
+ raise ValueError(f"{field_name} must be finite")
86
+
87
+
88
+ def _require_analyst_count(value: int | None) -> None:
89
+ if value is None:
90
+ return
91
+ if type(value) is not int or value < 0:
92
+ raise ValueError("analyst_count must be a non-negative int or None")
93
+
94
+
95
+ @dataclass(frozen=True, slots=True)
96
+ class ForwardEpsEstimate:
97
+ """One annual consensus-EPS estimate for an exact fiscal period end."""
98
+
99
+ period_end: date
100
+ eps: Decimal
101
+ analyst_count: int | None = None
102
+
103
+ def __post_init__(self) -> None:
104
+ _require_date(self.period_end, field_name="period_end")
105
+ _require_finite_decimal(self.eps, field_name="eps")
106
+ _require_analyst_count(self.analyst_count)
107
+
108
+
109
+ @dataclass(frozen=True, slots=True)
110
+ class Fy1ForwardPeriodAvailable:
111
+ """The earliest unique annual target period strictly after an anchor."""
112
+
113
+ period_end: date
114
+ status: Literal["available"] = field(default="available", init=False)
115
+
116
+ def __post_init__(self) -> None:
117
+ _require_date(self.period_end, field_name="period_end")
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class Fy1ForwardPeriodUnavailable:
122
+ """A closed reason why an FY1 target period cannot be selected."""
123
+
124
+ reason: Fy1ForwardPeriodUnavailableReason
125
+ period_end: date | None = None
126
+ status: Literal["unavailable"] = field(default="unavailable", init=False)
127
+
128
+ def __post_init__(self) -> None:
129
+ if self.reason not in {
130
+ "missing_fiscal_anchor",
131
+ "missing_future_estimate",
132
+ "duplicate_future_period",
133
+ }:
134
+ raise ValueError(f"unsupported FY1 period reason: {self.reason!r}")
135
+ if self.period_end is not None:
136
+ _require_date(self.period_end, field_name="period_end")
137
+
138
+
139
+ Fy1ForwardPeriodResult: TypeAlias = (
140
+ Fy1ForwardPeriodAvailable | Fy1ForwardPeriodUnavailable
141
+ )
142
+
143
+
144
+ @dataclass(frozen=True, slots=True)
145
+ class QuarterlyForwardEpsEstimate:
146
+ """One sourced quarterly EPS estimate with exact inclusive boundaries."""
147
+
148
+ fact_id: str
149
+ period_start: date
150
+ period_end: date
151
+ eps: Decimal
152
+ analyst_count: int | None = None
153
+
154
+ def __post_init__(self) -> None:
155
+ if not isinstance(self.fact_id, str) or not self.fact_id.strip():
156
+ raise ValueError("fact_id must be a non-empty str")
157
+ if self.fact_id != self.fact_id.strip():
158
+ raise ValueError("fact_id must not have surrounding whitespace")
159
+ _require_date(self.period_start, field_name="period_start")
160
+ _require_date(self.period_end, field_name="period_end")
161
+ if self.period_start >= self.period_end:
162
+ raise ValueError("quarter period requires period_start < period_end")
163
+ _require_finite_decimal(self.eps, field_name="eps")
164
+ _require_analyst_count(self.analyst_count)
165
+
166
+
167
+ def _ambiguous_quarter_estimates(
168
+ estimates: Sequence[QuarterlyForwardEpsEstimate],
169
+ *,
170
+ selected: Sequence[QuarterlyForwardEpsEstimate],
171
+ ) -> tuple[QuarterlyForwardEpsEstimate, ...]:
172
+ """Return facts that conflict with a selected horizon dimension."""
173
+
174
+ fact_id_counts = Counter(estimate.fact_id for estimate in estimates)
175
+ period_start_counts = Counter(estimate.period_start for estimate in estimates)
176
+ period_end_counts = Counter(estimate.period_end for estimate in estimates)
177
+ ambiguous_fact_ids = {
178
+ estimate.fact_id
179
+ for estimate in selected
180
+ if fact_id_counts[estimate.fact_id] > 1
181
+ }
182
+ ambiguous_period_starts = {
183
+ estimate.period_start
184
+ for estimate in selected
185
+ if period_start_counts[estimate.period_start] > 1
186
+ }
187
+ ambiguous_period_ends = {
188
+ estimate.period_end
189
+ for estimate in selected
190
+ if period_end_counts[estimate.period_end] > 1
191
+ }
192
+ return tuple(
193
+ estimate
194
+ for estimate in sorted(
195
+ estimates,
196
+ key=lambda candidate: (
197
+ candidate.period_start,
198
+ candidate.period_end,
199
+ candidate.fact_id,
200
+ ),
201
+ )
202
+ if estimate.fact_id in ambiguous_fact_ids
203
+ or estimate.period_start in ambiguous_period_starts
204
+ or estimate.period_end in ambiguous_period_ends
205
+ )
206
+
207
+
208
+ def _has_bounded_quarterly_cadence(
209
+ estimates: Sequence[QuarterlyForwardEpsEstimate],
210
+ ) -> bool:
211
+ """Admit conventional calendar and 52/53-week issuer quarter cadence.
212
+
213
+ The deliberately conservative 10..15-week per-period and 50..55-week
214
+ aggregate bounds fail closed for skipped, stub, or multi-quarter periods
215
+ without consulting an issuer calendar or ambient service.
216
+ """
217
+
218
+ if len(estimates) != 4:
219
+ return False
220
+ inclusive_period_days = tuple(
221
+ (estimate.period_end - estimate.period_start).days + 1 for estimate in estimates
222
+ )
223
+ if any(
224
+ not _MIN_INCLUSIVE_QUARTER_DAYS <= period_days <= _MAX_INCLUSIVE_QUARTER_DAYS
225
+ for period_days in inclusive_period_days
226
+ ):
227
+ return False
228
+ covered_days = (estimates[-1].period_end - estimates[0].period_start).days + 1
229
+ return (
230
+ _MIN_FOUR_QUARTER_HORIZON_DAYS <= covered_days <= _MAX_FOUR_QUARTER_HORIZON_DAYS
231
+ )
232
+
233
+
234
+ @dataclass(frozen=True, slots=True)
235
+ class ForwardPeAvailable:
236
+ """A reproducible forward P/E and the exact operands selected for it."""
237
+
238
+ multiple: Decimal
239
+ price: Decimal
240
+ eps: Decimal
241
+ estimate_period_end: date
242
+ analyst_count: int | None
243
+ status: Literal["available"] = field(default="available", init=False)
244
+
245
+ def __post_init__(self) -> None:
246
+ _require_finite_decimal(self.multiple, field_name="multiple")
247
+ _require_finite_decimal(self.price, field_name="price")
248
+ _require_finite_decimal(self.eps, field_name="eps")
249
+ _require_date(self.estimate_period_end, field_name="estimate_period_end")
250
+ _require_analyst_count(self.analyst_count)
251
+ if self.price <= 0:
252
+ raise ValueError("price must be positive")
253
+ if self.eps <= 0:
254
+ raise ValueError("eps must be positive")
255
+ if self.multiple < 0:
256
+ raise ValueError("multiple must be non-negative")
257
+
258
+
259
+ @dataclass(frozen=True, slots=True)
260
+ class ForwardPeUnavailable:
261
+ """A closed, domain-level reason that forward P/E cannot be derived."""
262
+
263
+ reason: ForwardPeUnavailableReason
264
+ estimate_period_end: date | None = None
265
+ eps: Decimal | None = None
266
+ status: Literal["unavailable"] = field(default="unavailable", init=False)
267
+
268
+ def __post_init__(self) -> None:
269
+ if self.reason not in _UNAVAILABLE_REASONS:
270
+ raise ValueError(
271
+ f"unsupported forward P/E unavailable reason: {self.reason!r}"
272
+ )
273
+ if self.estimate_period_end is not None:
274
+ _require_date(
275
+ self.estimate_period_end,
276
+ field_name="estimate_period_end",
277
+ )
278
+ if self.eps is not None:
279
+ _require_finite_decimal(self.eps, field_name="eps")
280
+
281
+
282
+ ForwardPeResult: TypeAlias = ForwardPeAvailable | ForwardPeUnavailable
283
+
284
+
285
+ @dataclass(frozen=True, slots=True)
286
+ class NtmForwardPeAvailable:
287
+ """Exact next-four-quarter P/E with its complete operand set."""
288
+
289
+ multiple: Decimal
290
+ price: Decimal
291
+ eps: Decimal
292
+ close_date: date
293
+ last_reported_period_end: date
294
+ covered_period_start: date
295
+ covered_period_end: date
296
+ covered_days: int
297
+ quarters: tuple[QuarterlyForwardEpsEstimate, ...]
298
+ status: Literal["available"] = field(default="available", init=False)
299
+
300
+ def __post_init__(self) -> None:
301
+ _require_finite_decimal(self.multiple, field_name="multiple")
302
+ _require_finite_decimal(self.price, field_name="price")
303
+ _require_finite_decimal(self.eps, field_name="eps")
304
+ _require_date(self.close_date, field_name="close_date")
305
+ _require_date(
306
+ self.last_reported_period_end,
307
+ field_name="last_reported_period_end",
308
+ )
309
+ _require_date(self.covered_period_start, field_name="covered_period_start")
310
+ _require_date(self.covered_period_end, field_name="covered_period_end")
311
+ if self.last_reported_period_end > self.close_date:
312
+ raise ValueError("last_reported_period_end must not postdate close_date")
313
+ if self.price <= 0:
314
+ raise ValueError("price must be positive")
315
+ if self.eps <= 0:
316
+ raise ValueError("eps must be positive")
317
+ if self.multiple < 0:
318
+ raise ValueError("multiple must be non-negative")
319
+ if type(self.quarters) is not tuple or any(
320
+ not isinstance(quarter, QuarterlyForwardEpsEstimate)
321
+ for quarter in self.quarters
322
+ ):
323
+ raise TypeError(
324
+ "quarters must be a tuple of QuarterlyForwardEpsEstimate values"
325
+ )
326
+ if len(self.quarters) != 4:
327
+ raise ValueError("quarters must contain exactly four estimates")
328
+ if _ambiguous_quarter_estimates(self.quarters, selected=self.quarters):
329
+ raise ValueError(
330
+ "quarter fact IDs, period starts, and period ends must be unique"
331
+ )
332
+ if type(self.covered_days) is not int or self.covered_days <= 0:
333
+ raise ValueError("covered_days must be a positive int")
334
+ if self.covered_period_start != self.quarters[0].period_start:
335
+ raise ValueError("covered_period_start must match the first quarter")
336
+ if self.covered_period_end != self.quarters[-1].period_end:
337
+ raise ValueError("covered_period_end must match the last quarter")
338
+ expected_days = (self.covered_period_end - self.covered_period_start).days + 1
339
+ if self.covered_days != expected_days:
340
+ raise ValueError("covered_days must match the inclusive covered period")
341
+ if self.covered_period_start != self.last_reported_period_end + timedelta(
342
+ days=1
343
+ ):
344
+ raise ValueError(
345
+ "covered period must begin immediately after the fiscal anchor"
346
+ )
347
+ for previous, current in zip(self.quarters, self.quarters[1:]):
348
+ if current.period_start != previous.period_end + timedelta(days=1):
349
+ raise ValueError("quarters must be contiguous and non-overlapping")
350
+ if not _has_bounded_quarterly_cadence(self.quarters):
351
+ raise ValueError("quarters must have bounded quarterly period cadence")
352
+ if self.eps != _sum_eps(self.quarters):
353
+ raise ValueError(
354
+ "eps must equal the exact sum of the four quarter estimates"
355
+ )
356
+
357
+ @property
358
+ def fact_ids(self) -> tuple[str, ...]:
359
+ """Return the exact source-fact identities included in the derivation."""
360
+
361
+ return tuple(quarter.fact_id for quarter in self.quarters)
362
+
363
+
364
+ @dataclass(frozen=True, slots=True)
365
+ class NtmForwardPeUnavailable:
366
+ """A closed reason exact next-four-quarter P/E cannot be derived."""
367
+
368
+ reason: NtmForwardPeUnavailableReason
369
+ close_date: date | None = None
370
+ last_reported_period_end: date | None = None
371
+ eps: Decimal | None = None
372
+ quarters: tuple[QuarterlyForwardEpsEstimate, ...] = ()
373
+ status: Literal["unavailable"] = field(default="unavailable", init=False)
374
+
375
+ def __post_init__(self) -> None:
376
+ if self.reason not in _NTM_UNAVAILABLE_REASONS:
377
+ raise ValueError(f"unsupported NTM P/E unavailable reason: {self.reason!r}")
378
+ if self.close_date is not None:
379
+ _require_date(self.close_date, field_name="close_date")
380
+ if self.last_reported_period_end is not None:
381
+ _require_date(
382
+ self.last_reported_period_end,
383
+ field_name="last_reported_period_end",
384
+ )
385
+ if self.eps is not None:
386
+ _require_finite_decimal(self.eps, field_name="eps")
387
+ if type(self.quarters) is not tuple or any(
388
+ not isinstance(quarter, QuarterlyForwardEpsEstimate)
389
+ for quarter in self.quarters
390
+ ):
391
+ raise TypeError(
392
+ "quarters must be a tuple of QuarterlyForwardEpsEstimate values"
393
+ )
394
+
395
+ @property
396
+ def fact_ids(self) -> tuple[str, ...]:
397
+ """Return source-fact identities retained on a failed derivation."""
398
+
399
+ return tuple(quarter.fact_id for quarter in self.quarters)
400
+
401
+
402
+ NtmForwardPeResult: TypeAlias = NtmForwardPeAvailable | NtmForwardPeUnavailable
403
+
404
+
405
+ def _quantization_precision(
406
+ price: Decimal,
407
+ eps: Decimal,
408
+ quantum: Decimal,
409
+ ) -> int:
410
+ """Choose sufficient local precision without mutating global Decimal state."""
411
+
412
+ quotient_integer_digits = max(1, price.adjusted() - eps.adjusted() + 2)
413
+ quantum_fractional_digits = max(0, -int(quantum.as_tuple().exponent))
414
+ operand_digits = len(price.as_tuple().digits) + len(eps.as_tuple().digits)
415
+ return max(
416
+ 28,
417
+ quotient_integer_digits + quantum_fractional_digits + operand_digits + 8,
418
+ )
419
+
420
+
421
+ def _require_quantum(quantum: Decimal) -> None:
422
+ _require_finite_decimal(quantum, field_name="quantum")
423
+ if quantum <= 0:
424
+ raise ValueError("quantum must be positive")
425
+
426
+
427
+ def _derive_pe_multiple(
428
+ *,
429
+ price: Decimal,
430
+ eps: Decimal,
431
+ quantum: Decimal,
432
+ ) -> Decimal:
433
+ """Divide positive Decimal operands using one canonical rounding path."""
434
+
435
+ with localcontext() as context:
436
+ context.prec = _quantization_precision(price, eps, quantum)
437
+ return (price / eps).quantize(quantum, rounding=ROUND_HALF_EVEN)
438
+
439
+
440
+ def _sum_eps(estimates: Sequence[QuarterlyForwardEpsEstimate]) -> Decimal:
441
+ """Sum finite Decimal EPS operands exactly under an isolated context."""
442
+
443
+ values = tuple(estimate.eps for estimate in estimates)
444
+ if not values:
445
+ return Decimal(0)
446
+ minimum_exponent = min(int(value.as_tuple().exponent) for value in values)
447
+ maximum_adjusted = max(value.adjusted() for value in values)
448
+ carry_digits = len(str(len(values)))
449
+ with localcontext() as context:
450
+ context.prec = max(
451
+ 28,
452
+ maximum_adjusted - minimum_exponent + carry_digits + 2,
453
+ )
454
+ return sum(values, start=Decimal(0))
455
+
456
+
457
+ def derive_forward_pe(
458
+ *,
459
+ price: Decimal | None,
460
+ estimate: ForwardEpsEstimate,
461
+ quantum: Decimal,
462
+ ) -> ForwardPeResult:
463
+ """Derive forward P/E for one already-mapped exact annual period."""
464
+
465
+ _require_quantum(quantum)
466
+
467
+ if not isinstance(price, Decimal) or not price.is_finite() or price <= 0:
468
+ return ForwardPeUnavailable(reason="invalid_price")
469
+ if estimate.eps <= 0:
470
+ return ForwardPeUnavailable(
471
+ reason="non_positive_eps",
472
+ estimate_period_end=estimate.period_end,
473
+ eps=estimate.eps,
474
+ )
475
+
476
+ return ForwardPeAvailable(
477
+ multiple=_derive_pe_multiple(
478
+ price=price,
479
+ eps=estimate.eps,
480
+ quantum=quantum,
481
+ ),
482
+ price=price,
483
+ eps=estimate.eps,
484
+ estimate_period_end=estimate.period_end,
485
+ analyst_count=estimate.analyst_count,
486
+ )
487
+
488
+
489
+ def select_fy1_forward_period(
490
+ *,
491
+ period_ends: Sequence[date],
492
+ last_reported_period_end: date | None,
493
+ ) -> Fy1ForwardPeriodResult:
494
+ """Select the earliest unique annual period strictly after an anchor."""
495
+
496
+ if last_reported_period_end is None:
497
+ return Fy1ForwardPeriodUnavailable(reason="missing_fiscal_anchor")
498
+ _require_date(last_reported_period_end, field_name="last_reported_period_end")
499
+ normalized_period_ends = tuple(period_ends)
500
+ for period_end in normalized_period_ends:
501
+ _require_date(period_end, field_name="period_end")
502
+ future_period_ends = tuple(
503
+ period_end
504
+ for period_end in normalized_period_ends
505
+ if period_end > last_reported_period_end
506
+ )
507
+ if not future_period_ends:
508
+ return Fy1ForwardPeriodUnavailable(reason="missing_future_estimate")
509
+ earliest_period_end = min(future_period_ends)
510
+ if future_period_ends.count(earliest_period_end) != 1:
511
+ return Fy1ForwardPeriodUnavailable(
512
+ reason="duplicate_future_period",
513
+ period_end=earliest_period_end,
514
+ )
515
+ return Fy1ForwardPeriodAvailable(period_end=earliest_period_end)
516
+
517
+
518
+ def derive_fy1_forward_pe(
519
+ *,
520
+ price: Decimal | None,
521
+ estimates: Sequence[ForwardEpsEstimate],
522
+ last_reported_period_end: date | None,
523
+ quantum: Decimal,
524
+ ) -> ForwardPeResult:
525
+ """Derive FY1 P/E from the earliest unambiguous period after the anchor.
526
+
527
+ The earliest future period is authoritative for this derivation. A duplicate
528
+ or non-positive estimate at that period makes the result unavailable; a later
529
+ estimate is never used to conceal the ambiguity or non-positive earnings.
530
+ """
531
+
532
+ selection = select_fy1_forward_period(
533
+ period_ends=tuple(estimate.period_end for estimate in estimates),
534
+ last_reported_period_end=last_reported_period_end,
535
+ )
536
+ if isinstance(selection, Fy1ForwardPeriodUnavailable):
537
+ return ForwardPeUnavailable(
538
+ reason=selection.reason,
539
+ estimate_period_end=selection.period_end,
540
+ )
541
+ estimate = next(
542
+ estimate
543
+ for estimate in estimates
544
+ if estimate.period_end == selection.period_end
545
+ )
546
+ return derive_forward_pe(
547
+ price=price,
548
+ estimate=estimate,
549
+ quantum=quantum,
550
+ )
551
+
552
+
553
+ def derive_ntm_forward_pe(
554
+ *,
555
+ price: Decimal | None,
556
+ close_date: date | None,
557
+ estimates: Sequence[QuarterlyForwardEpsEstimate],
558
+ last_reported_period_end: date | None,
559
+ quantum: Decimal,
560
+ ) -> NtmForwardPeResult:
561
+ """Derive P/E from the earliest four complete quarters after an anchor.
562
+
563
+ A selected quarter is never replaced to conceal a duplicate, overlap, gap,
564
+ or non-positive aggregate. The supplied close date is retained so an outer
565
+ peer policy can require one common close across independently derived issuers.
566
+ """
567
+
568
+ _require_quantum(quantum)
569
+ if last_reported_period_end is None:
570
+ return NtmForwardPeUnavailable(reason="missing_fiscal_anchor")
571
+ _require_date(last_reported_period_end, field_name="last_reported_period_end")
572
+ if close_date is None:
573
+ return NtmForwardPeUnavailable(
574
+ reason="missing_close_date",
575
+ last_reported_period_end=last_reported_period_end,
576
+ )
577
+ _require_date(close_date, field_name="close_date")
578
+ if last_reported_period_end > close_date:
579
+ return NtmForwardPeUnavailable(
580
+ reason="fiscal_anchor_postdates_close",
581
+ close_date=close_date,
582
+ last_reported_period_end=last_reported_period_end,
583
+ )
584
+ if not isinstance(price, Decimal) or not price.is_finite() or price <= 0:
585
+ return NtmForwardPeUnavailable(
586
+ reason="invalid_price",
587
+ close_date=close_date,
588
+ last_reported_period_end=last_reported_period_end,
589
+ )
590
+
591
+ normalized_estimates = tuple(estimates)
592
+ if any(
593
+ not isinstance(estimate, QuarterlyForwardEpsEstimate)
594
+ for estimate in normalized_estimates
595
+ ):
596
+ raise TypeError("estimates must contain QuarterlyForwardEpsEstimate values")
597
+
598
+ future_estimates = tuple(
599
+ estimate
600
+ for estimate in normalized_estimates
601
+ if estimate.period_end > last_reported_period_end
602
+ )
603
+ estimates_by_period: dict[
604
+ tuple[date, date],
605
+ list[QuarterlyForwardEpsEstimate],
606
+ ] = {}
607
+ for estimate in future_estimates:
608
+ estimates_by_period.setdefault(
609
+ (estimate.period_start, estimate.period_end),
610
+ [],
611
+ ).append(estimate)
612
+ ordered_periods = sorted(estimates_by_period)
613
+ selected_periods = ordered_periods[:4]
614
+ selected_scope = tuple(
615
+ estimate
616
+ for period in selected_periods
617
+ for estimate in estimates_by_period[period]
618
+ )
619
+ ambiguous_estimates = _ambiguous_quarter_estimates(
620
+ future_estimates,
621
+ selected=selected_scope,
622
+ )
623
+ if ambiguous_estimates:
624
+ return NtmForwardPeUnavailable(
625
+ reason="duplicate_future_period",
626
+ close_date=close_date,
627
+ last_reported_period_end=last_reported_period_end,
628
+ quarters=ambiguous_estimates,
629
+ )
630
+ crossing_anchor = tuple(
631
+ estimate
632
+ for estimate in future_estimates
633
+ if estimate.period_start <= last_reported_period_end
634
+ )
635
+ if crossing_anchor:
636
+ return NtmForwardPeUnavailable(
637
+ reason="overlapping_future_periods",
638
+ close_date=close_date,
639
+ last_reported_period_end=last_reported_period_end,
640
+ quarters=tuple(
641
+ sorted(
642
+ crossing_anchor,
643
+ key=lambda estimate: (
644
+ estimate.period_start,
645
+ estimate.period_end,
646
+ estimate.fact_id,
647
+ ),
648
+ )
649
+ ),
650
+ )
651
+
652
+ if len(selected_periods) < 4:
653
+ return NtmForwardPeUnavailable(
654
+ reason="insufficient_future_quarters",
655
+ close_date=close_date,
656
+ last_reported_period_end=last_reported_period_end,
657
+ quarters=tuple(
658
+ estimates_by_period[period][0] for period in selected_periods
659
+ ),
660
+ )
661
+
662
+ selected = tuple(estimates_by_period[period][0] for period in selected_periods)
663
+ expected_first_start = last_reported_period_end + timedelta(days=1)
664
+ if selected[0].period_start > expected_first_start:
665
+ return NtmForwardPeUnavailable(
666
+ reason="gapped_future_periods",
667
+ close_date=close_date,
668
+ last_reported_period_end=last_reported_period_end,
669
+ quarters=selected,
670
+ )
671
+ if selected[0].period_start < expected_first_start:
672
+ return NtmForwardPeUnavailable(
673
+ reason="overlapping_future_periods",
674
+ close_date=close_date,
675
+ last_reported_period_end=last_reported_period_end,
676
+ quarters=selected,
677
+ )
678
+ for previous, current in zip(selected, selected[1:]):
679
+ expected_start = previous.period_end + timedelta(days=1)
680
+ if current.period_start < expected_start:
681
+ return NtmForwardPeUnavailable(
682
+ reason="overlapping_future_periods",
683
+ close_date=close_date,
684
+ last_reported_period_end=last_reported_period_end,
685
+ quarters=selected,
686
+ )
687
+ if current.period_start > expected_start:
688
+ return NtmForwardPeUnavailable(
689
+ reason="gapped_future_periods",
690
+ close_date=close_date,
691
+ last_reported_period_end=last_reported_period_end,
692
+ quarters=selected,
693
+ )
694
+
695
+ if not _has_bounded_quarterly_cadence(selected):
696
+ return NtmForwardPeUnavailable(
697
+ reason="non_quarterly_period_cadence",
698
+ close_date=close_date,
699
+ last_reported_period_end=last_reported_period_end,
700
+ quarters=selected,
701
+ )
702
+
703
+ aggregate_eps = _sum_eps(selected)
704
+ if aggregate_eps <= 0:
705
+ return NtmForwardPeUnavailable(
706
+ reason="non_positive_aggregate_eps",
707
+ close_date=close_date,
708
+ last_reported_period_end=last_reported_period_end,
709
+ eps=aggregate_eps,
710
+ quarters=selected,
711
+ )
712
+
713
+ covered_period_start = selected[0].period_start
714
+ covered_period_end = selected[-1].period_end
715
+ return NtmForwardPeAvailable(
716
+ multiple=_derive_pe_multiple(
717
+ price=price,
718
+ eps=aggregate_eps,
719
+ quantum=quantum,
720
+ ),
721
+ price=price,
722
+ eps=aggregate_eps,
723
+ close_date=close_date,
724
+ last_reported_period_end=last_reported_period_end,
725
+ covered_period_start=covered_period_start,
726
+ covered_period_end=covered_period_end,
727
+ covered_days=(covered_period_end - covered_period_start).days + 1,
728
+ quarters=selected,
729
+ )
730
+
731
+
732
+ __all__ = [
733
+ "ForwardEpsEstimate",
734
+ "ForwardPeAvailable",
735
+ "ForwardPeResult",
736
+ "ForwardPeUnavailable",
737
+ "ForwardPeUnavailableReason",
738
+ "Fy1ForwardPeriodAvailable",
739
+ "Fy1ForwardPeriodResult",
740
+ "Fy1ForwardPeriodUnavailable",
741
+ "Fy1ForwardPeriodUnavailableReason",
742
+ "NtmForwardPeAvailable",
743
+ "NtmForwardPeResult",
744
+ "NtmForwardPeUnavailable",
745
+ "NtmForwardPeUnavailableReason",
746
+ "QuarterlyForwardEpsEstimate",
747
+ "derive_forward_pe",
748
+ "derive_fy1_forward_pe",
749
+ "derive_ntm_forward_pe",
750
+ "select_fy1_forward_period",
751
+ ]