Spaces:
Sleeping

File size: 26,435 Bytes
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d4d0bb
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d4d0bb
3e964dd
8d4d0bb
3e964dd
 
8d4d0bb
 
 
 
3e964dd
8d4d0bb
 
 
7d0c890
 
 
 
 
 
 
 
 
 
8d4d0bb
 
3e964dd
 
 
7d0c890
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
 
8d4d0bb
 
 
 
 
 
3e964dd
 
 
8d4d0bb
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d4d0bb
3e964dd
 
8d4d0bb
3e964dd
 
 
8d4d0bb
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
8d4d0bb
3e964dd
8d4d0bb
3e964dd
8d4d0bb
 
 
 
 
 
3e964dd
8d4d0bb
3e964dd
 
8d4d0bb
 
3e964dd
8d4d0bb
3e964dd
 
 
 
 
 
 
8d4d0bb
3e964dd
 
8d4d0bb
3e964dd
 
 
 
 
 
 
 
 
8d4d0bb
 
3e964dd
 
 
7d0c890
8d4d0bb
 
 
 
 
7d0c890
8d4d0bb
3e964dd
7d0c890
8d4d0bb
3e964dd
 
 
 
 
 
 
 
 
 
 
8d4d0bb
 
 
3e964dd
8d4d0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d0c890
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
8d4d0bb
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
7d0c890
 
 
 
 
 
 
 
45994d6
 
7d0c890
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d4d0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Unified Yahoo Finance client using curl_cffi Chrome TLS impersonation.

Replaces yfinance library for all data fetching. Works for all exchanges
(US, NSE India .NS, BSE .BO, LSE .L, etc.) without IP blocks.

Session is a module-level singleton β€” one Chrome TLS session shared across
all requests. Cookie/crumb lifecycle managed automatically.
"""
from __future__ import annotations

import os
import time
from functools import lru_cache

import pandas as pd
import structlog

import threading
_crumb_lock = threading.Lock()

log = structlog.get_logger()

try:
    from curl_cffi import requests as cffi_requests
    _session = cffi_requests.Session(impersonate="chrome124")
    _AVAILABLE = True
except ImportError:
    _session = None
    _AVAILABLE = False
    log.error("curl_cffi_missing", fix="pip install curl_cffi")

_BASE1 = "https://query1.finance.yahoo.com"
_BASE2 = "https://query2.finance.yahoo.com"

_crumb: str | None = None
_crumb_ts: float = 0.0
_CRUMB_TTL = 3600  # seconds


def _safe_raw(obj: dict, key: str):
    """Extract .raw from Yahoo Finance nested value objects."""
    val = obj.get(key, {})
    if isinstance(val, dict):
        return val.get("raw")
    return None


def _stmt_val(obj: dict, key: str) -> float | None:
    """Like _safe_raw but treats 0 as unavailable (Yahoo returns 0 for missing financial fields)."""
    raw = _safe_raw(obj, key)
    if raw is None or raw == 0:
        return None
    return raw


def _get_valid_crumb(ticker: str) -> str:
    global _crumb, _crumb_ts

    if _crumb and time.time() - _crumb_ts < _CRUMB_TTL:
        return _crumb

    with _crumb_lock:
        # double-check inside lock
        if _crumb and time.time() - _crumb_ts < _CRUMB_TTL:
            return _crumb

        _warm_session(ticker)

        for base in (_BASE2, _BASE1):
            try:
                r = _session.get(f"{base}/v1/test/getcrumb", timeout=10)
                if r.status_code == 200 and r.text.strip():
                    _crumb = r.text.strip()
                    _crumb_ts = time.time()
                    log.info("crumb_acquired", base=base)
                    return _crumb
            except Exception as exc:
                log.warning("crumb_fetch_failed", base=base, error=str(exc))

    raise RuntimeError("Failed to obtain Yahoo crumb")


def _warm_session(ticker: str) -> None:
    """Visit fc.yahoo.com for cookie consent, then chart to prime session."""
    try:
        _session.get("https://fc.yahoo.com", timeout=8)
    except Exception:
        pass
    try:
        _session.get(
            f"{_BASE1}/v8/finance/chart/{ticker}",
            params={"range": "5d", "interval": "1d"},
            timeout=10,
        )
    except Exception:
        pass


# ── OHLCV ──────────────────────────────────────────────────────────────────

def fetch_ohlcv(
    ticker: str,
    years: int = 20,
    interval: str = "1wk",
    days: int | None = None,
    range_str: str | None = None,
) -> pd.DataFrame:
    """OHLCV for any ticker. Pass range_str (e.g. '1mo','3mo','1y') or days for intraday."""
    if not _AVAILABLE:
        return pd.DataFrame()

    url = f"{_BASE1}/v8/finance/chart/{ticker}"
    if not range_str:
        range_str = f"{days}d" if days else f"{min(years, 20)}y"
    params = {
        "range": range_str,
        "interval": interval,
        "includePrePost": "false",
        "events": "history",
    }
    try:
        r = _session.get(url, params=params, timeout=20)
        if r.status_code != 200:
            log.warning("ohlcv_http_error", ticker=ticker, status=r.status_code)
            return pd.DataFrame()

        data = r.json()
        chart_result = data.get("chart", {}).get("result", [])
        if not chart_result:
            return pd.DataFrame()

        chart = chart_result[0]
        timestamps = chart.get("timestamp", [])
        if not timestamps:
            return pd.DataFrame()

        quote = chart.get("indicators", {}).get("quote", [{}])[0]
        adj_list = chart.get("indicators", {}).get("adjclose", [{}])
        adjclose = adj_list[0].get("adjclose", []) if adj_list else []

        rows = []
        for i, ts in enumerate(timestamps):
            close_val = (
                adjclose[i] if i < len(adjclose) and adjclose[i]
                else (quote.get("close") or [None])[i] if i < len(quote.get("close") or []) else None
            )
            if close_val is None:
                continue
            rows.append({
                "Open": (quote.get("open") or [None])[i] if i < len(quote.get("open") or []) else None,
                "High": (quote.get("high") or [None])[i] if i < len(quote.get("high") or []) else None,
                "Low": (quote.get("low") or [None])[i] if i < len(quote.get("low") or []) else None,
                "Close": close_val,
                "Volume": (quote.get("volume") or [0])[i] or 0,
            })

        if not rows:
            return pd.DataFrame()

        idx = pd.to_datetime(timestamps[: len(rows)], unit="s", utc=True).tz_localize(None)
        return pd.DataFrame(rows, index=idx).dropna(subset=["Close"])

    except Exception as exc:
        log.warning("ohlcv_fetch_failed", ticker=ticker, error=str(exc))
        return pd.DataFrame()


# ── Real-time quote ────────────────────────────────────────────────────────

def fetch_quote(ticker: str) -> dict:
    """Real-time price, change, volume from v8 chart (1d/2m interval)."""
    if not _AVAILABLE:
        return {"ticker": ticker, "error": "curl_cffi unavailable"}

    try:
        r = _session.get(
            f"{_BASE1}/v8/finance/chart/{ticker}",
            params={"range": "1d", "interval": "2m", "includePrePost": "false"},
            timeout=15,
        )
        data = r.json()
        chart_result = data.get("chart", {}).get("result", [])
        if not chart_result:
            return {"ticker": ticker, "price": None}

        meta = chart_result[0].get("meta", {})
        price = meta.get("regularMarketPrice")
        # regularMarketPreviousClose is always yesterday's official close regardless
        # of chart range. chartPreviousClose reflects the chart's start date and can
        # be 30d ago when Yahoo returns 1mo metadata for a 1d range request.
        prev_close = (
            meta.get("regularMarketPreviousClose")
            or meta.get("chartPreviousClose")
            or meta.get("previousClose")
        )
        if price is not None and prev_close is not None:
            change = round(price - prev_close, 4)
            pct_change = round(change / prev_close * 100, 2)
        else:
            change = None
            pct_change = None

        # Intraday OHLC from timestamps
        quote = chart_result[0].get("indicators", {}).get("quote", [{}])[0]
        opens = [v for v in (quote.get("open") or []) if v is not None]
        highs = [v for v in (quote.get("high") or []) if v is not None]
        lows = [v for v in (quote.get("low") or []) if v is not None]
        volumes = [v for v in (quote.get("volume") or []) if v is not None]

        return {
            "ticker": ticker,
            "price": price,
            "prev_close": prev_close,
            "change": change,
            "pct_change": pct_change,
            "volume": sum(volumes) if volumes else meta.get("regularMarketVolume"),
            "avg_volume_3m": meta.get("averageDailyVolume3Month"),
            "market_cap": meta.get("marketCap"),
            "open": opens[0] if opens else None,
            "high": max(highs) if highs else None,
            "low": min(lows) if lows else None,
            "currency": meta.get("currency", "USD"),
            "exchange": meta.get("exchangeName"),
            "timestamp": meta.get("regularMarketTime"),
        }
    except Exception as exc:
        log.warning("quote_fetch_failed", ticker=ticker, error=str(exc))
        return {"ticker": ticker, "error": str(exc)}


# ── Live news ─────────────────────────────────────────────────────────────

def fetch_news(ticker: str, count: int = 8) -> list[dict]:
    """
    Live news for a ticker via Google News RSS (no API key needed).
    Handles both Indian (.NS / .BO) and US/global tickers.
    """
    if not _AVAILABLE:
        return []

    try:
        import xml.etree.ElementTree as _ET
        from email.utils import parsedate_to_datetime

        is_india = ticker.endswith((".NS", ".BO"))
        base = ticker.replace(".NS", "").replace(".BO", "")

        if is_india:
            query = f"{base} NSE stock India"
            params = {"q": query, "hl": "en-IN", "gl": "IN", "ceid": "IN:en"}
        else:
            query = f"{base} stock"
            params = {"q": query, "hl": "en-US", "gl": "US", "ceid": "US:en"}

        r = _session.get("https://news.google.com/rss/search", params=params, timeout=10)
        if r.status_code != 200:
            log.warning("news_rss_error", ticker=ticker, status=r.status_code)
            return []

        root = _ET.fromstring(r.content)
        items = root.findall(".//item")[:count]

        results: list[dict] = []

        for item in items:
            title = item.findtext("title", "") or ""
            link = item.findtext("link", "") or ""
            source = item.findtext("source", "Google News") or "Google News"
            pub_date = item.findtext("pubDate", "") or ""
            description = item.findtext("description", "") or ""

            try:
                dt = parsedate_to_datetime(pub_date)
                date_str = dt.strftime("%Y-%m-%d")
            except Exception:
                date_str = pub_date[:10] if pub_date else None

            results.append({
                "text": f"{title}. {description}".strip(". "),
                "url": link,
                "title": title,
                "source": source,
                "published_at": date_str,
                "ticker": ticker,
                "live": True,
            })

        log.info("news_rss_ok", ticker=ticker, count=len(results))
        return results

    except Exception as exc:
        log.warning("news_fetch_failed", ticker=ticker, error=str(exc))
        return []


# ── Fundamentals ───────────────────────────────────────────────────────────

def fetch_fundamentals(ticker: str) -> dict:
    """PE, EPS, margins, analyst consensus via quoteSummary API."""
    global _crumb

    if not _AVAILABLE:
        return {"ticker": ticker, "error": "curl_cffi unavailable"}

    crumb = None
    for attempt in range(2):
        try:
            crumb = _get_valid_crumb(ticker)
            break
        except Exception as exc:
            log.warning("crumb_retry", ticker=ticker, attempt=attempt, error=str(exc))
            _crumb = None

    # proceed even with crumb=None β€” quoteSummary sometimes works without it
    modules = "summaryDetail,financialData,defaultKeyStatistics,recommendationTrend,assetProfile,summaryProfile,price,quoteType"
    params: dict = {"modules": modules}
    if crumb:
        params["crumb"] = crumb

    try:
        r = _session.get(
            f"{_BASE1}/v10/finance/quoteSummary/{ticker}",
            params=params,
            timeout=15,
        )
        data = r.json()
        result = (data.get("quoteSummary") or {}).get("result") or []
        result = [r for r in result if r]

        if not result:
            log.warning("empty_fundamentals", ticker=ticker)

            _crumb = None
            _warm_session(ticker)

            try:
                crumb = _get_valid_crumb(ticker)
                params["crumb"] = crumb

                r = _session.get(
                    f"{_BASE1}/v10/finance/quoteSummary/{ticker}",
                    params=params,
                    timeout=15,
                )
                data = r.json()
                result = data.get("quoteSummary", {}).get("result", [])
            except Exception as exc:
                log.warning("fundamentals_retry_failed", ticker=ticker, error=str(exc))
                return {"ticker": ticker, "error": "retry failed"}

            if not result:
                return {"ticker": ticker, "error": "no data after retry"}

        item = result[0]
        sd = item.get("summaryDetail", {})
        fd = item.get("financialData", {})
        ks = item.get("defaultKeyStatistics", {})
        recs = item.get("recommendationTrend", {}).get("trend", [])

        buy = hold = sell = 0
        if recs:
            r0 = recs[0]
            buy = r0.get("strongBuy", 0) + r0.get("buy", 0)
            hold = r0.get("hold", 0)
            sell = r0.get("sell", 0) + r0.get("strongSell", 0)

        def _raw(d: dict, key: str):
            v = d.get(key)
            if isinstance(v, dict):
                return v.get("raw")
            return v

        return {
            "ticker": ticker,
            "pe": _raw(sd, "trailingPE"),
            "forward_pe": _raw(sd, "forwardPE"),
            "eps": _raw(ks, "trailingEps"),
            "revenue": _raw(fd, "totalRevenue"),
            "revenue_growth": _raw(fd, "revenueGrowth"),
            "gross_margin": _raw(fd, "grossMargins"),
            "operating_margin": _raw(fd, "operatingMargins"),
            "net_margin": _raw(fd, "profitMargins"),
            "debt_to_equity": _raw(fd, "debtToEquity"),
            "current_ratio": _raw(fd, "currentRatio"),
            "roe": _raw(fd, "returnOnEquity"),
            "market_cap": _raw(sd, "marketCap"),
            "avg_volume_3m": _raw(sd, "averageVolume"),
            "dividend_yield": _raw(sd, "dividendYield"),
            "beta": _raw(sd, "beta"),
            "week_52_high": _raw(sd, "fiftyTwoWeekHigh"),
            "week_52_low": _raw(sd, "fiftyTwoWeekLow"),
            "analyst_consensus": {"buy": buy, "hold": hold, "sell": sell,
                                   "avg_target": _raw(fd, "targetMeanPrice")},
        }
    except Exception as exc:
        log.warning("fundamentals_fetch_failed", ticker=ticker, error=str(exc))
        return {"ticker": ticker, "error": str(exc)}


def fetch_company_info(ticker: str) -> dict:
    """Company profile: business summary, industry, country, employees, website."""
    if not _AVAILABLE:
        return {}
    try:
        _warm_session(ticker)
        crumb = None
        try:
            crumb = _get_valid_crumb(ticker)
        except Exception as exc:
            log.warning("company_info_crumb_failed", ticker=ticker, error=str(exc))
        params: dict = {"modules": "assetProfile"}
        if crumb:
            params["crumb"] = crumb
        r = _session.get(
            f"{_BASE1}/v10/finance/quoteSummary/{ticker}",
            params=params,
            timeout=12,
        )
        data = r.json()
        result = data.get("quoteSummary", {}).get("result", [])
        if not result:
            return {}
        ap = (
            result[0].get("assetProfile")
            or result[0].get("summaryProfile")
            or {}
        )
        if not ap:
            return {}
        return {
            "industry": ap.get("industry"),
            "country": ap.get("country"),
            "city": ap.get("city"),
            "website": ap.get("website"),
            "full_time_employees": ap.get("fullTimeEmployees"),
            "business_summary": ap.get("longBusinessSummary"),
        }
    except Exception as exc:
        log.warning("company_info_fetch_failed", ticker=ticker, error=str(exc))
        return {}


# ── Financial Statements ──────────────────────────────────────────────────

def _quotesummary(ticker: str, module: str) -> dict:
    """Shared quoteSummary call with crumb auth. Returns result[0] or {}."""
    if not _AVAILABLE:
        return {}
    try:
        crumb = None
        try:
            crumb = _get_valid_crumb(ticker)
        except Exception as exc:
            log.warning("quotesummary_crumb_failed", ticker=ticker, module=module, error=str(exc))
        params: dict = {"modules": module}
        if crumb:
            params["crumb"] = crumb
        r = _session.get(
            f"{_BASE1}/v10/finance/quoteSummary/{ticker}",
            params=params,
            timeout=15,
        )
        if r.status_code != 200:
            return {}
        result = r.json().get("quoteSummary", {}).get("result") or []
        return result[0] if result else {}
    except Exception as exc:
        log.warning("quotesummary_failed", ticker=ticker, module=module, error=str(exc))
        return {}


def _fetch_timeseries(ticker: str, types: list[str]) -> dict[str, dict[str, float | None]]:
    """
    Fetch financial metrics via Yahoo Finance fundamentals-timeseries API.
    This is the API Yahoo Finance website uses for financial statements β€” unlike
    quoteSummary, it returns complete income/balance/cashflow data for all stocks.

    Returns {period_date: {ts_field_name: raw_value}} dict, newest date first.
    """
    if not _AVAILABLE:
        return {}
    try:
        import time as _time
        crumb = _get_valid_crumb(ticker)
        now = int(_time.time())
        region = "IN" if ticker.endswith((".NS", ".BO")) else "US"
        r = _session.get(
            f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}",
            params={
                "type": ",".join(types),
                "period1": str(now - 6 * 365 * 24 * 3600),
                "period2": str(now),
                "crumb": crumb,
                "lang": "en-US",
                "region": region,
                "corsDomain": "finance.yahoo.com",
            },
            timeout=15,
        )
        if r.status_code != 200:
            return {}
        result = r.json().get("timeseries", {}).get("result") or []
        by_period: dict[str, dict[str, float | None]] = {}
        for item in result:
            field = (item.get("meta") or {}).get("type", [""])[0]
            if not field:
                continue
            for entry in item.get(field, []):
                date = entry.get("asOfDate")
                if not date:
                    continue
                raw = (entry.get("reportedValue") or {}).get("raw")
                by_period.setdefault(date, {})[field] = raw if raw else None
        # Newest period first
        return dict(sorted(by_period.items(), reverse=True))
    except Exception as exc:
        log.warning("timeseries_fetch_failed", ticker=ticker, error=str(exc))
        return {}


def fetch_income_stmt(ticker: str, quarterly: bool = False) -> list[dict]:
    """
    Annual or quarterly income statements via Yahoo Finance timeseries API.
    Returns list of periods, newest first. Works for US and Indian (.NS/.BO) tickers.
    """
    prefix = "quarterly" if quarterly else "annual"
    types = [
        f"{prefix}TotalRevenue",
        f"{prefix}GrossProfit",
        f"{prefix}EBIT",
        f"{prefix}NetIncome",
        f"{prefix}NormalizedEBITDA",
        f"{prefix}TotalExpenses",   # works for both US and Indian stocks
    ]
    by_period = _fetch_timeseries(ticker, types)
    out = []
    for date, vals in by_period.items():
        out.append({
            "period": date,
            "period_type": "quarterly" if quarterly else "annual",
            "revenue": vals.get(f"{prefix}TotalRevenue"),
            "gross_profit": vals.get(f"{prefix}GrossProfit"),
            "operating_income": vals.get(f"{prefix}EBIT"),
            "net_income": vals.get(f"{prefix}NetIncome"),
            "total_expenses": vals.get(f"{prefix}TotalExpenses"),
            "ebitda": vals.get(f"{prefix}NormalizedEBITDA"),
        })
    return out


def fetch_balance_sheet(ticker: str) -> list[dict]:
    """Annual balance sheets via Yahoo Finance timeseries API. Newest first."""
    types = [
        "annualTotalAssets",
        "annualTotalLiabilitiesNetMinorityInterest",
        "annualStockholdersEquity",
        "annualCurrentAssets",
        "annualCurrentLiabilities",
        "annualLongTermDebt",
        "annualCashCashEquivalentsAndShortTermInvestments",  # US + non-bank Indian
        "annualCashAndCashEquivalents",                      # Indian banks fallback
    ]
    by_period = _fetch_timeseries(ticker, types)
    out = []
    for date, vals in by_period.items():
        # Indian banks use annualCashAndCashEquivalents; US/non-bank use the longer field
        cash = (
            vals.get("annualCashCashEquivalentsAndShortTermInvestments")
            or vals.get("annualCashAndCashEquivalents")
        )
        stmt = {
            "period": date,
            "period_type": "annual",
            "total_assets": vals.get("annualTotalAssets"),
            "total_liabilities": vals.get("annualTotalLiabilitiesNetMinorityInterest"),
            "total_equity": vals.get("annualStockholdersEquity"),
            "current_assets": vals.get("annualCurrentAssets"),
            "current_liabilities": vals.get("annualCurrentLiabilities"),
            "long_term_debt": vals.get("annualLongTermDebt"),
            "cash": cash,
        }
        financial_keys = [k for k in stmt if k not in ("period", "period_type")]
        if any(stmt[k] is not None for k in financial_keys):
            out.append(stmt)
    return out


def fetch_cashflow(ticker: str) -> list[dict]:
    """Annual cash flow statements via Yahoo Finance timeseries API. Newest first."""
    types = [
        "annualOperatingCashFlow",
        "annualCapitalExpenditure",
        "annualInvestingCashFlow",
        "annualFinancingCashFlow",
        "annualFreeCashFlow",
        "annualChangesInCash",      # true net change in cash balance
    ]
    by_period = _fetch_timeseries(ticker, types)
    out = []
    for date, vals in by_period.items():
        stmt = {
            "period": date,
            "period_type": "annual",
            "operating_cashflow": vals.get("annualOperatingCashFlow"),
            "capex": vals.get("annualCapitalExpenditure"),
            "investing_cashflow": vals.get("annualInvestingCashFlow"),
            "financing_cashflow": vals.get("annualFinancingCashFlow"),
            "free_cashflow": vals.get("annualFreeCashFlow"),
            "net_change_in_cash": vals.get("annualChangesInCash"),
        }
        financial_keys = [k for k in stmt if k not in ("period", "period_type")]
        if any(stmt[k] is not None for k in financial_keys):
            out.append(stmt)
    return out


# ── Sector ETF performance ─────────────────────────────────────────────────

_SECTOR_ETFS: list[tuple[str, str]] = [
    ("XLK",  "Technology"),
    ("XLV",  "Healthcare"),
    ("XLF",  "Financials"),
    ("XLE",  "Energy"),
    ("XLY",  "Consumer Disc."),
    ("XLP",  "Consumer Staples"),
    ("XLB",  "Materials"),
    ("XLI",  "Industrials"),
    ("XLU",  "Utilities"),
    ("XLRE", "Real Estate"),
    ("XLC",  "Comm. Services"),
    ("SOXX", "Semiconductors"),
]


def fetch_sector_etfs() -> list[dict]:
    """
    Fetch daily % change for 12 US sector ETFs.
    Returns [{sector, etf, return_pct, price}].
    """
    results = []
    for etf, label in _SECTOR_ETFS:
        try:
            q = fetch_quote(etf)
            pct = q.get("pct_change")
            price = q.get("price")
            if pct is not None:
                results.append({
                    "sector": label,
                    "etf": etf,
                    "return_pct": round(float(pct), 2),
                    "price": round(float(price), 2) if price else None,
                })
        except Exception:
            continue
    return results


# ── SEC Filings (EDGAR) ────────────────────────────────────────────────

def fetch_filings(ticker: str, count: int = 10) -> list[dict]:
    """
    Fetch latest SEC filings (10-K, 10-Q, 8-K etc.) from EDGAR for a ticker.
    Works via company CIK lookup β†’ filings feed.
    """

    if not _AVAILABLE:
        return []

    try:
        import json
        import xml.etree.ElementTree as ET

        headers = {
            "User-Agent": "FinoraAI/1.0 (contact: support@finora.ai)"
        }

        # 1. Get ticker β†’ CIK mapping
        mapping_url = "https://www.sec.gov/files/company_tickers.json"
        r = _session.get(mapping_url, headers=headers, timeout=15)

        if r.status_code != 200:
            return []

        data = r.json()

        cik = None
        ticker = ticker.upper()

        for _, v in data.items():
            if v.get("ticker", "").upper() == ticker:
                cik = str(v.get("cik_str")).zfill(10)
                break

        if not cik:
            return []

        # 2. Pull filings feed
        feed_url = f"https://data.sec.gov/submissions/CIK{cik}.json"
        r = _session.get(feed_url, headers=headers, timeout=15)

        if r.status_code != 200:
            return []

        filings = r.json().get("filings", {}).get("recent", {})

        forms = filings.get("form", [])
        dates = filings.get("filingDate", [])
        accession = filings.get("accessionNumber", [])
        primary_docs = filings.get("primaryDocument", [])

        results = []

        for i in range(min(count, len(forms))):
            results.append({
                "ticker": ticker,
                "form": forms[i],
                "filing_date": dates[i],
                "accession_number": accession[i],
                "document": primary_docs[i],
                "url": f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{accession[i].replace('-', '')}/{primary_docs[i]}",
            })

        return results

    except Exception as exc:
        log.warning("filings_fetch_failed", ticker=ticker, error=str(exc))
        return []