Spaces:
Sleeping

File size: 5,136 Bytes
3e964dd
 
 
 
 
 
 
 
 
45994d6
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
3e964dd
45994d6
 
 
3e964dd
45994d6
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fundamentals node — Yahoo Finance quoteSummary via curl_cffi."""
from __future__ import annotations

import asyncio
import time

import structlog

from backend.graph.state import FiNoraState
from backend.rag.yahoo_client import fetch_balance_sheet, fetch_cashflow, fetch_fundamentals, fetch_income_stmt, fetch_sector_etfs

log = structlog.get_logger()

_FUNDAMENTALS_CACHE: dict[str, tuple[dict, float]] = {}
_SECTOR_CACHE: tuple[list[dict], float] | None = None
_CACHE_TTL = 300.0  # 5 minutes


def _get_cached_fundamentals(yf_ticker: str) -> dict | None:
    entry = _FUNDAMENTALS_CACHE.get(yf_ticker)
    if entry and (time.monotonic() - entry[1]) < _CACHE_TTL:
        return entry[0]
    return None


def _set_cached_fundamentals(yf_ticker: str, data: dict) -> None:
    _FUNDAMENTALS_CACHE[yf_ticker] = (data, time.monotonic())


def _get_similar_stocks(ticker: str, sector: str | None) -> list[dict]:
    if not sector:
        return []
    try:
        from backend.rag.ingestion.universe import universe
        all_stocks = universe.search("", limit=10000)
        similar = [
            {"ticker": s["ticker"], "name": s["name"],
             "sector": s.get("sector", ""), "exchange": s.get("exchange", ""),
             "currency": s.get("currency", "USD")}
            for s in all_stocks
            if s.get("sector", "").lower() == sector.lower() and s["ticker"] != ticker
        ]
        return similar[:8]
    except Exception:
        return []


def _fetch_sector_context(ticker: str, sector: str | None) -> dict:
    global _SECTOR_CACHE
    now = time.monotonic()

    etfs: list[dict] = []
    if _SECTOR_CACHE and (now - _SECTOR_CACHE[1]) < _CACHE_TTL:
        etfs = _SECTOR_CACHE[0]
    else:
        try:
            etfs = fetch_sector_etfs()
            _SECTOR_CACHE = (etfs, now)
        except Exception:
            etfs = []

    similar = _get_similar_stocks(ticker, sector)

    # Find the ETF for this stock's sector
    sector_etf: dict | None = None
    if sector:
        for etf in etfs:
            if etf.get("sector", "").lower() == sector.lower():
                sector_etf = etf
                break

    return {
        "sector": sector,
        "sector_etf": sector_etf,
        "all_sector_etfs": etfs,
        "similar_stocks": similar,
    }


async def fundamentals_node(state: FiNoraState) -> dict:
    intents = state.get("intents", [])
    has_fundamental = "fundamental" in intents
    has_comparative = "comparative" in intents

    if not has_fundamental and not has_comparative:
        return {"fundamental_data": None, "sector_context": None}

    ticker = state.get("ticker", "")
    yf_ticker = state.get("yf_ticker", ticker)
    if not ticker:
        return {"fundamental_data": None, "sector_context": None}

    result: dict = {"fundamental_data": None, "sector_context": None}

    # Fetch fundamentals if needed
    if has_fundamental:
        cached = _get_cached_fundamentals(yf_ticker)
        if cached:
            log.debug("fundamentals_cache_hit", ticker=ticker)
            result["fundamental_data"] = cached
        else:
            loop = asyncio.get_running_loop()
            data, annual_income, annual_cashflow, annual_balance = await asyncio.gather(
                loop.run_in_executor(None, fetch_fundamentals, yf_ticker),
                loop.run_in_executor(None, fetch_income_stmt, yf_ticker),
                loop.run_in_executor(None, fetch_cashflow, yf_ticker),
                loop.run_in_executor(None, fetch_balance_sheet, yf_ticker),
            )
            data["ticker"] = ticker
            data["annual_income"] = annual_income
            data["annual_cashflow"] = annual_cashflow
            data["annual_balance"] = annual_balance
            _set_cached_fundamentals(yf_ticker, data)
            log.info("fundamentals_node_done", ticker=ticker, yf_ticker=yf_ticker,
                     pe=data.get("pe"), income_periods=len(annual_income),
                     cashflow_periods=len(annual_cashflow),
                     balance_periods=len(annual_balance))
            result["fundamental_data"] = data

    # Fetch sector context if comparative intent present
    if has_comparative:
        # Get sector from fundamentals data or state
        fd = result.get("fundamental_data") or {}
        sector = fd.get("sector") or state.get("sector")

        # If no fundamentals fetched yet, get sector from universe
        if not sector:
            try:
                from backend.rag.ingestion.universe import universe
                entry = universe.get_by_ticker(ticker)
                sector = (entry or {}).get("sector")
            except Exception:
                sector = None

        loop = asyncio.get_running_loop()
        sector_ctx = await loop.run_in_executor(None, _fetch_sector_context, ticker, sector)
        result["sector_context"] = sector_ctx
        log.info("sector_context_fetched", ticker=ticker, sector=sector,
                 similar_count=len(sector_ctx.get("similar_stocks", [])),
                 etfs_count=len(sector_ctx.get("all_sector_etfs", [])))

    return result