File size: 26,573 Bytes
559c2ff
 
 
 
 
 
 
 
 
 
466043f
559c2ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ecd145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466043f
3ecd145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466043f
 
3ecd145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
559c2ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ecd145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
559c2ff
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
"""analysis/textdiff.py β€” verbatim text delta signals for the Analyst Edge layer.

Pure Python + sentence-transformers, zero LLM calls.
Compares the most recent filing period against the prior period for a ticker
and surfaces verbatim before→after fragments for the most material changes:

  1. risk_reworded / risk_added / risk_removed  β€” risk-factor diffs
  2. term_frequency                             β€” analyst-lexicon count deltas
  3. guidance_language_shift                   β€” hedge/modal word shifts in MD&A
  4. kpi_dropped                               β€” metric mentioned prior, absent now
  5. compute_lexicon_trend               β€” multi-quarter lexicon term trend (n-quarter monotone run)

Usage:
    from analysis.textdiff import compute
    signals = compute("NVDA")
"""
from __future__ import annotations

import re
from typing import Optional

import numpy as np

from analysis.signals import QuarterDelta
from storage.sections_db import get_section, get_periods_for_ticker

# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

_REWORD_THRESHOLD = 0.70    # cosine similarity: current & prior considered "same risk"
_NEW_RISK_THRESHOLD = 0.40  # below this β†’ new risk (added)
_IDENTICAL_THRESHOLD = 0.93 # above this β†’ unchanged, skip

_MIN_ITEM_WORDS = 25        # minimum words for a text chunk to be considered

# Analyst / macro lexicon to track frequency across periods
_LEXICON: list[tuple[str, str]] = [
    # (term, display_label)
    (r"\btariff\b",          "tariff"),
    (r"\bexport control\b",  "export control"),
    (r"\bheadwind\b",        "headwind"),
    (r"\buncertainty\b",     "uncertainty"),
    (r"\bsoftness\b",        "softness"),
    (r"\bslowing\b",         "slowing"),
    (r"\bdecelerat\w*",      "deceleration"),
    (r"\bcautious\b",        "cautious"),
    (r"\bpressure\b",        "pressure"),
    (r"\bai\b",              "AI"),
    (r"\bbuyback\b",         "buyback"),
    (r"\blayoff\b",          "layoff"),
    (r"\brestructur\w*",     "restructuring"),
    (r"\bimpairment\b",      "impairment"),
    (r"\blitigation\b",      "litigation"),
    (r"\bchinese? market\b", "China market"),
    (r"\bsanction\b",        "sanction"),
    (r"\brecession\b",       "recession"),
]

# Frequency swing that triggers a signal (Γ—2 or more, and absolute diff β‰₯ 2)
_FREQ_RATIO_THRESHOLD = 2.0
_FREQ_ABS_THRESHOLD = 2

# KPI labels that, if absent from the current MD&A, signal a dropped KPI
_KPI_PATTERNS: list[tuple[str, str]] = [
    (r"\b(?:gross\s+)?margins?\b",                          "gross margin"),
    (r"\b(?:operating\s+)?margins?\b",                      "operating margin"),
    (r"\bfree\s+cash\s+flow\b",                             "free cash flow"),
    (r"\bdays?\s+sales?\s+outstanding\b|\bdso\b",           "DSO"),
    (r"\bdays?\s+inventory\s+outstanding\b|\bdio\b",        "DIO"),
    (r"\bdays?\s+payable\s+outstanding\b|\bdpo\b",          "DPO"),
    (r"\bshare\s+(?:repurchase|buyback)\b",                 "share repurchase"),
    (r"\bdividend\b",                                       "dividend"),
    (r"\bguidance\b",                                       "guidance"),
    (r"\bbacklog\b",                                        "backlog"),
    (r"\bdeferred\s+revenue\b",                             "deferred revenue"),
    (r"\bnet\s+retention\s+rate\b",                         "net retention rate"),
]

# Guidance hedge / modality words
_HEDGE_WORDS = [
    "expect to grow", "expect growth", "expects to grow", "expects growth",
    "anticipate", "plan to", "target", "forecast",
    "moderate", "soften", "decline", "reduce", "headwind", "challenge",
    "cautious", "uncertain", "volatile",
]

# ---------------------------------------------------------------------------
# Model (lazy singleton)
# ---------------------------------------------------------------------------

_encoder = None


def _get_encoder():
    global _encoder
    if _encoder is None:
        from sentence_transformers import SentenceTransformer
        _encoder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
    return _encoder


def _embed(texts: list[str]) -> np.ndarray:
    enc = _get_encoder()
    vecs = enc.encode(texts, convert_to_numpy=True, show_progress_bar=False)
    # Normalise rows
    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    norms = np.where(norms < 1e-8, 1.0, norms)
    return vecs / norms


def _cosine(a: np.ndarray, b: np.ndarray) -> float:
    return float(np.dot(a, b))


# ---------------------------------------------------------------------------
# Text splitters
# ---------------------------------------------------------------------------

def _split_into_items(text: str, min_words: int = _MIN_ITEM_WORDS) -> list[str]:
    """Split a section text into logical chunks (risk items / paragraphs).

    Uses double-newline paragraph boundaries. Merges short lines (headers)
    with the following paragraph. Returns only chunks >= min_words.
    """
    raw = re.split(r"\n{2,}", text.strip())
    items: list[str] = []
    buffer = ""
    for para in raw:
        para = para.strip()
        if not para:
            continue
        word_count = len(para.split())
        if word_count < 8:
            # Likely a heading β€” prepend to next paragraph
            buffer = para + " "
        else:
            combined = (buffer + para).strip()
            buffer = ""
            if len(combined.split()) >= min_words:
                items.append(combined)
    if buffer.strip() and len(buffer.split()) >= min_words:
        items.append(buffer.strip())
    return items


def _split_sentences(text: str) -> list[str]:
    """Simple sentence splitter (no NLTK dependency)."""
    sentences = re.split(r"(?<=[.!?])\s+", text)
    return [s.strip() for s in sentences if len(s.split()) >= 5]


# ---------------------------------------------------------------------------
# Greedy one-to-one item alignment
# ---------------------------------------------------------------------------

def _align_items(
    current_items: list[str],
    prior_items: list[str],
    current_vecs: np.ndarray,
    prior_vecs: np.ndarray,
) -> tuple[dict[int, int], dict[int, float]]:
    """Greedy one-to-one alignment: each current item β†’ best prior item.

    Returns:
        matches: {current_idx: prior_idx}
        scores:  {current_idx: cosine_similarity}
    """
    if len(current_items) == 0 or len(prior_items) == 0:
        return {}, {}

    # pairwise similarities: (n_current Γ— n_prior)
    sim_matrix = current_vecs @ prior_vecs.T  # shape (n_cur, n_pri)

    matches: dict[int, int] = {}
    scores: dict[int, float] = {}
    used_prior: set[int] = set()

    # Process current items in order; assign best available prior match
    for ci in range(len(current_items)):
        row = sim_matrix[ci]
        # mask already-used prior indices
        masked = [(row[pi], pi) for pi in range(len(prior_items)) if pi not in used_prior]
        if not masked:
            break
        best_score, best_pi = max(masked)
        matches[ci] = best_pi
        scores[ci] = best_score
        if best_score >= _NEW_RISK_THRESHOLD:
            used_prior.add(best_pi)

    return matches, scores


# ---------------------------------------------------------------------------
# Risk factor diff
# ---------------------------------------------------------------------------

def compute_risk_deltas(
    current_text: str,
    prior_text: str,
    period_from: str,
    period_to: str,
    form_type: str,
) -> list[QuarterDelta]:
    """Align risk-factor items across two periods and classify changes."""
    if not current_text or not prior_text:
        return []

    current_items = _split_into_items(current_text)
    prior_items = _split_into_items(prior_text)
    if not current_items or not prior_items:
        return []

    current_vecs = _embed(current_items)
    prior_vecs = _embed(prior_items)

    matches, scores = _align_items(current_items, prior_items, current_vecs, prior_vecs)

    matched_prior_indices: set[int] = set()
    deltas: list[QuarterDelta] = []
    source_lit = "10-K" if "10-K" in form_type.upper() else "10-Q"

    for ci, item in enumerate(current_items):
        pi = matches.get(ci)
        score = scores.get(ci, 0.0)

        if pi is not None and score >= _NEW_RISK_THRESHOLD:
            matched_prior_indices.add(pi)
            if score >= _IDENTICAL_THRESHOLD:
                continue  # unchanged β€” not interesting

            # Reworded: significant textual change
            before = _truncate(prior_items[pi], 120)
            after = _truncate(item, 120)
            sig = "HIGH" if score < 0.80 else "MEDIUM"
            deltas.append(QuarterDelta(
                kind="risk_reworded",
                period_from=period_from,
                period_to=period_to,
                before_text=before,
                after_text=after,
                computed_metric=f"similarity {score:.2f}",
                source=source_lit,
                significance=sig,
                term="",
            ))
        else:
            # New risk β€” not matched in prior
            after = _truncate(item, 120)
            deltas.append(QuarterDelta(
                kind="risk_added",
                period_from=period_from,
                period_to=period_to,
                before_text="",
                after_text=after,
                computed_metric="",
                source=source_lit,
                significance="HIGH",
                term="",
            ))

    # Removed: prior items not matched by any current item
    for pi, item in enumerate(prior_items):
        if pi not in matched_prior_indices:
            before = _truncate(item, 120)
            deltas.append(QuarterDelta(
                kind="risk_removed",
                period_from=period_from,
                period_to=period_to,
                before_text=before,
                after_text="",
                computed_metric="",
                source=source_lit,
                significance="MEDIUM",
                term="",
            ))

    # Keep at most 6 highest-significance deltas to avoid flooding the prompt
    order = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
    deltas.sort(key=lambda d: (order[d.significance], d.kind))
    return deltas[:6]


# ---------------------------------------------------------------------------
# Analyst-lexicon frequency deltas
# ---------------------------------------------------------------------------

def compute_lexicon_deltas(
    current_text: str,
    prior_text: str,
    period_from: str,
    period_to: str,
    form_type: str,
) -> list[QuarterDelta]:
    """Count analyst-lexicon term occurrences and flag large swings."""
    if not current_text or not prior_text:
        return []

    source_lit = "10-K" if "10-K" in form_type.upper() else "10-Q"
    cur_lower = current_text.lower()
    pri_lower = prior_text.lower()

    deltas: list[QuarterDelta] = []

    for pattern, label in _LEXICON:
        cur_count = len(re.findall(pattern, cur_lower, re.IGNORECASE))
        pri_count = len(re.findall(pattern, pri_lower, re.IGNORECASE))

        if cur_count == 0 and pri_count == 0:
            continue

        abs_diff = abs(cur_count - pri_count)
        if abs_diff < _FREQ_ABS_THRESHOLD:
            continue

        # Require at least Γ—2 change in either direction
        max_count = max(cur_count, pri_count)
        min_count = min(cur_count, pri_count) or 0.5  # avoid div-by-zero
        ratio = max_count / min_count
        if ratio < _FREQ_RATIO_THRESHOLD:
            continue

        direction = "up" if cur_count > pri_count else "down"
        pct = (cur_count - pri_count) / (pri_count or 1) * 100
        metric = f"{pri_count}β†’{cur_count} occurrences ({pct:+.0f}%)"

        # Significance: HIGH if ratio β‰₯ 3 or abs_diff β‰₯ 5
        sig = "HIGH" if (ratio >= 3.0 or abs_diff >= 5) else "MEDIUM"

        # Extract a context sentence for the term (from current or prior)
        after_ctx = _find_context_sentence(current_text, pattern) if cur_count > 0 else ""
        before_ctx = _find_context_sentence(prior_text, pattern) if pri_count > 0 else ""

        deltas.append(QuarterDelta(
            kind="term_frequency",
            period_from=period_from,
            period_to=period_to,
            before_text=before_ctx,
            after_text=after_ctx,
            computed_metric=metric,
            source=source_lit,
            significance=sig,
            term=label,
        ))

    deltas.sort(key=lambda d: {"HIGH": 0, "MEDIUM": 1}.get(d.significance, 2))
    return deltas[:5]


def _find_context_sentence(text: str, pattern: str) -> str:
    """Return the first sentence containing a match for `pattern`."""
    sentences = _split_sentences(text)
    for sent in sentences:
        if re.search(pattern, sent, re.IGNORECASE):
            return _truncate(sent, 100)
    return ""


# ---------------------------------------------------------------------------
# Multi-quarter lexicon trend detection
# ---------------------------------------------------------------------------

def _detect_trend(counts: list[int]) -> str | None:
    """Detect the longest strictly monotone run at the tail of a count series.

    Args:
        counts: term occurrence counts in **chronological order** (oldest first).

    Returns:
        ``"rising N quarters"`` if the last Nβ‰₯3 values are strictly increasing,
        ``"falling N quarters"`` if the last Nβ‰₯3 values are strictly decreasing,
        ``None`` otherwise.

    Examples:
        >>> _detect_trend([1, 3, 5, 8])
        'rising 4 quarters'
        >>> _detect_trend([8, 5, 3, 1])
        'falling 4 quarters'
        >>> _detect_trend([1, 5, 2, 4, 6])
        'rising 3 quarters'
        >>> _detect_trend([1, 2, 2, 4])  # plateau breaks strict run
        >>> _detect_trend([1, 3])  # only 2 values
    """
    if len(counts) < 3:
        return None

    # Walk backwards from the end to find the longest tail run
    # We track whether the tail is rising or falling from the last step
    n = len(counts)

    # Determine direction of the final step
    if counts[-1] > counts[-2]:
        direction = "rising"
    elif counts[-1] < counts[-2]:
        direction = "falling"
    else:
        return None  # last step is flat β†’ no strict run

    # Extend the run backwards as far as the same strict direction holds
    run_length = 2  # we already know the last pair qualifies
    for i in range(n - 2, 0, -1):
        if direction == "rising" and counts[i] > counts[i - 1]:
            run_length += 1
        elif direction == "falling" and counts[i] < counts[i - 1]:
            run_length += 1
        else:
            break  # run ends here

    if run_length < 3:
        return None

    return f"{direction} {run_length} quarters"


def compute_lexicon_trend(ticker: str, n: int = 4) -> list[QuarterDelta]:
    """Detect multi-quarter monotone trends for each analyst-lexicon term.

    Looks back up to *n* 10-Q periods and surfaces terms whose occurrence
    count has been strictly rising or falling for 3+ consecutive quarters β€”
    a more durable signal than a single quarter-over-quarter spike.

    Args:
        ticker: uppercase ticker symbol.
        n: maximum number of recent 10-Q periods to examine (default 4).

    Returns:
        Up to 5 ``QuarterDelta`` objects (HIGH-significance first), one per
        term that shows a multi-quarter trend.  Returns ``[]`` if fewer than
        3 periods are available or no trends are detected.
    """
    ticker = ticker.upper()
    periods = get_periods_for_ticker(ticker, form_type="10-Q")
    if len(periods) < 3:
        return []

    n = min(n, len(periods))
    # periods[:n] is newest-first; reverse for chronological order
    selected = list(reversed(periods[:n]))  # [oldest, ..., newest]

    # Pre-load section text for each period
    period_texts: list[str] = []
    for period in selected:
        mda = get_section(ticker, period, "mda") or ""
        risk = get_section(ticker, period, "risk_factors") or ""
        period_texts.append((mda + "\n\n" + risk).strip())

    deltas: list[QuarterDelta] = []

    for pattern, label in _LEXICON:
        counts = [
            len(re.findall(pattern, text, re.IGNORECASE))
            for text in period_texts
        ]

        trend = _detect_trend(counts)
        if trend is None:
            continue

        # Build the QuarterDelta
        oldest_period = selected[0]   # oldest of the n selected (chronological)
        newest_period = selected[-1]  # newest of the n selected (chronological)

        first_count = counts[0]
        last_count = counts[-1]
        metric = (
            f"{first_count}β†’{last_count} occurrences over "
            f"{oldest_period}β†’{newest_period} ({trend})"
        )

        oldest_text = period_texts[0]
        newest_text = period_texts[-1]
        before_ctx = _find_context_sentence(oldest_text, pattern) if first_count > 0 else ""
        after_ctx = _find_context_sentence(newest_text, pattern) if last_count > 0 else ""

        # Significance: HIGH for runs of 4+, MEDIUM for 3
        run_quarters = int(trend.split()[1])
        sig = "HIGH" if run_quarters >= 4 else "MEDIUM"

        deltas.append(QuarterDelta(
            kind="term_frequency",
            period_from=oldest_period,
            period_to=newest_period,
            before_text=before_ctx,
            after_text=after_ctx,
            computed_metric=metric,
            source="10-Q",
            significance=sig,
            term=label,
        ))

    # HIGH first, then MEDIUM; cap at 5
    deltas.sort(key=lambda d: {"HIGH": 0, "MEDIUM": 1}.get(d.significance, 2))
    return deltas[:5]


# ---------------------------------------------------------------------------
# Guidance / MD&A language shift
# ---------------------------------------------------------------------------

def compute_guidance_shifts(
    current_mda: str,
    prior_mda: str,
    period_from: str,
    period_to: str,
    form_type: str,
) -> list[QuarterDelta]:
    """Detect forward-looking language becoming more cautious or more bullish."""
    if not current_mda or not prior_mda:
        return []

    source_lit = "10-K" if "10-K" in form_type.upper() else "10-Q"

    # Extract sentences that contain guidance / forward-looking language
    cur_fwd = _forward_looking_sentences(current_mda)
    pri_fwd = _forward_looking_sentences(prior_mda)

    if not cur_fwd or not pri_fwd:
        return []

    # Count hedge words in guidance sentences
    cur_hedge = _count_hedge(cur_fwd)
    pri_hedge = _count_hedge(pri_fwd)

    abs_diff = abs(cur_hedge - pri_hedge)
    if abs_diff < 2:
        return []

    direction = "more cautious" if cur_hedge > pri_hedge else "more confident"
    pct = (cur_hedge - pri_hedge) / (pri_hedge or 1) * 100
    metric = f"{pri_hedge}β†’{cur_hedge} hedge-word occurrences ({pct:+.0f}%) β†’ {direction}"

    # Pick most representative sentence from each period
    before_sent = _pick_representative(pri_fwd, prior_mda)
    after_sent = _pick_representative(cur_fwd, current_mda)

    sig = "HIGH" if abs_diff >= 5 else "MEDIUM"

    return [QuarterDelta(
        kind="guidance_language_shift",
        period_from=period_from,
        period_to=period_to,
        before_text=before_sent,
        after_text=after_sent,
        computed_metric=metric,
        source=source_lit,
        significance=sig,
        term="guidance tone",
    )]


_FWD_PATTERNS = re.compile(
    r"\b(expect|anticipate|forecast|guidance|outlook|project|target|plan\s+to|"
    r"will\s+(?:grow|increase|decrease|decline|moderate)|believe\s+(?:we|our))\b",
    re.IGNORECASE,
)


def _forward_looking_sentences(text: str) -> list[str]:
    sentences = _split_sentences(text)
    return [s for s in sentences if _FWD_PATTERNS.search(s)]


def _count_hedge(sentences: list[str]) -> int:
    joined = " ".join(sentences).lower()
    return sum(1 for w in _HEDGE_WORDS if w in joined)


def _pick_representative(sentences: list[str], full_text: str) -> str:
    """Return the shortest guidance sentence (most quotable) that contains a hedge word."""
    hedge_sents = [
        s for s in sentences
        if any(h in s.lower() for h in _HEDGE_WORDS)
    ]
    pool = hedge_sents if hedge_sents else sentences
    pool_sorted = sorted(pool, key=lambda s: len(s.split()))
    if pool_sorted:
        return _truncate(pool_sorted[0], 100)
    return _truncate(sentences[0], 100) if sentences else ""


# ---------------------------------------------------------------------------
# Dropped KPI detection
# ---------------------------------------------------------------------------

def compute_kpi_drops(
    current_mda: str,
    prior_mda: str,
    period_from: str,
    period_to: str,
    form_type: str,
) -> list[QuarterDelta]:
    """Flag a KPI / metric label that appears in prior MD&A but not in current."""
    if not current_mda or not prior_mda:
        return []

    source_lit = "10-K" if "10-K" in form_type.upper() else "10-Q"
    cur_lower = current_mda.lower()
    pri_lower = prior_mda.lower()

    deltas: list[QuarterDelta] = []
    for pattern, label in _KPI_PATTERNS:
        in_current = bool(re.search(pattern, cur_lower, re.IGNORECASE))
        in_prior = bool(re.search(pattern, pri_lower, re.IGNORECASE))

        if in_prior and not in_current:
            ctx = _find_context_sentence(prior_mda, pattern)
            deltas.append(QuarterDelta(
                kind="kpi_dropped",
                period_from=period_from,
                period_to=period_to,
                before_text=ctx,
                after_text="",
                computed_metric=f"'{label}' mentioned in {period_from} MD&A, absent from {period_to}",
                source=source_lit,
                significance="MEDIUM",
                term=label,
            ))

    return deltas[:3]


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _truncate(text: str, max_words: int) -> str:
    words = text.split()
    if len(words) <= max_words:
        return text
    return " ".join(words[:max_words]) + "…"


# ---------------------------------------------------------------------------
# Main entry point
# ---------------------------------------------------------------------------

def compute(ticker: str, current_period: Optional[str] = None) -> list[QuarterDelta]:
    """Compute all text delta signals for a ticker.

    Compares the current period (latest ingested 10-Q) against the prior
    period (previous 10-Q). Returns an empty list if sections are missing
    or an error occurs β€” never raises.

    Args:
        ticker: uppercase ticker symbol.
        current_period: override the current period (default: latest in DB).
    """
    try:
        return _compute_inner(ticker, current_period)
    except Exception as exc:
        import sys
        print(f"[textdiff] Error computing deltas for {ticker}: {exc}", file=sys.stderr)
        return []


def _compute_inner(ticker: str, current_period: Optional[str]) -> list[QuarterDelta]:
    ticker = ticker.upper()

    # Determine current and prior periods (10-Q only for QoQ comparison)
    periods = get_periods_for_ticker(ticker, form_type="10-Q")
    if len(periods) < 2:
        return []

    period_to = current_period if current_period else periods[0]
    # Find the prior period (the one just before period_to in the list)
    if period_to in periods:
        idx = periods.index(period_to)
        if idx + 1 >= len(periods):
            return []
        period_from = periods[idx + 1]
    else:
        period_from = periods[1]

    # Determine form_type for the current period (need it for source label)
    # Look for any section stored for this period to infer form_type
    # Default to 10-Q since we filtered above
    form_type = "10-Q"

    # Load sections
    cur_risk = get_section(ticker, period_to, "risk_factors") or ""
    pri_risk = get_section(ticker, period_from, "risk_factors") or ""
    cur_mda = get_section(ticker, period_to, "mda") or ""
    pri_mda = get_section(ticker, period_from, "mda") or ""

    if not cur_risk and not cur_mda:
        return []

    all_deltas: list[QuarterDelta] = []

    # 1. Risk factors diff
    if cur_risk and pri_risk:
        all_deltas.extend(compute_risk_deltas(cur_risk, pri_risk, period_from, period_to, form_type))

    # 2. Lexicon frequency deltas (combined mda + risk text for broader coverage)
    cur_full = (cur_mda + "\n\n" + cur_risk).strip()
    pri_full = (pri_mda + "\n\n" + pri_risk).strip()
    if cur_full and pri_full:
        all_deltas.extend(compute_lexicon_deltas(cur_full, pri_full, period_from, period_to, form_type))

    # 3. Guidance language shift (MD&A only)
    if cur_mda and pri_mda:
        all_deltas.extend(compute_guidance_shifts(cur_mda, pri_mda, period_from, period_to, form_type))

    # 4. Dropped KPIs
    if cur_mda and pri_mda:
        all_deltas.extend(compute_kpi_drops(cur_mda, pri_mda, period_from, period_to, form_type))

    # 5. Multi-quarter lexicon trends (ticker-level, not period-pair)
    trend_deltas = compute_lexicon_trend(ticker)
    all_deltas.extend(trend_deltas)

    # Prefer trend signals over QoQ signals for the same term:
    # collect terms that have a multi-quarter trend signal and remove any
    # plain QoQ term_frequency delta for the same term.
    trend_terms: set[str] = {
        d.term
        for d in trend_deltas
        if d.kind == "term_frequency" and "quarters" in (d.computed_metric or "")
    }
    if trend_terms:
        all_deltas = [
            d for d in all_deltas
            if not (
                d.kind == "term_frequency"
                and d.term in trend_terms
                and "quarters" not in (d.computed_metric or "")
            )
        ]

    # Deduplicate and sort: HIGH first, then MEDIUM, then LOW
    seen: set[str] = set()
    deduped: list[QuarterDelta] = []
    for d in all_deltas:
        key = f"{d.kind}:{d.term}:{d.before_text[:40]}"
        if key not in seen:
            seen.add(key)
            deduped.append(d)

    order = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
    deduped.sort(key=lambda d: (order[d.significance], d.kind))
    return deduped