summaryrefslogtreecommitdiff
path: root/backend/tests/test_api.py
blob: b136f23993ac2b9bffdbf7f6779fb89ff7b89c22 (plain)
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
import pandas as pd
import pytest
from fastapi import HTTPException

from app import main
from app.services import data_service


def clear_service_caches() -> None:
    data_service.INFO_CACHE.clear()
    data_service.FAST_INFO_CACHE.clear()
    data_service.PRICE_CACHE.clear()
    data_service.HISTORY_CACHE.clear()
    data_service.STATEMENT_CACHE.clear()
    data_service.SHARES_CACHE.clear()
    data_service.RATIO_CACHE.clear()
    data_service.BETA_CACHE.clear()
    data_service.SHORT_CACHE.clear()


def quarterly_frame(rows: dict[str, list[float]]) -> pd.DataFrame:
    columns = pd.to_datetime(["2025-12-31", "2025-09-30", "2025-06-30", "2025-03-31"])
    return pd.DataFrame(rows, index=columns).T


def test_health() -> None:
    assert main.health() == {"status": "ok"}


def test_search_smoke(monkeypatch) -> None:
    monkeypatch.setattr(main.data_service, "search_tickers", lambda q: [{"symbol": "AAPL", "name": "Apple Inc.", "exchange": "NASDAQ"}])
    assert main.search("apple")[0]["symbol"] == "AAPL"


def test_watchlist_smoke(tmp_path, monkeypatch) -> None:
    monkeypatch.setattr(main, "DB_PATH", tmp_path / "prism.db")
    monkeypatch.setattr(main.data_service, "get_company_info", lambda symbol: {"currentPrice": 100.0, "previousClose": 95.0})
    res = main.add_watchlist_symbol("aapl")
    assert res["items"][0]["symbol"] == "AAPL"


def test_mocked_ticker_overview(monkeypatch) -> None:
    monkeypatch.setattr(
        main.data_service,
        "get_ticker_overview",
        lambda symbol: {
            "profile": {"symbol": "AAPL", "name": "Apple Inc.", "sector": None, "industry": None, "exchange": "NASDAQ", "website": None, "summary": None},
            "quote": {"price": 100.0, "prev_close": 98.0, "change": 2.0, "change_pct": 0.0204},
            "signals": [],
            "stats": {"market_cap": None, "trailing_pe": None, "trailing_eps": None, "volume": None, "average_volume": None, "beta": None},
            "ratios": {
                "price_to_book": None,
                "price_to_sales": None,
                "ev_to_sales": None,
                "ev_to_ebitda": None,
                "gross_margin_ttm": None,
                "operating_margin_ttm": None,
                "net_margin_ttm": None,
                "roe_ttm": None,
                "roa_ttm": None,
                "roic_ttm": None,
                "debt_to_equity": None,
                "current_ratio": None,
                "dividend_yield_ttm": None,
                "dividend_payout_ratio_ttm": None,
            },
            "range_52w": {"low": None, "high": None, "price": 100.0},
            "short_interest": {"short_percent_of_float": None, "short_ratio": None, "shares_short": None, "shares_short_prior_month": None, "shares_short_delta_pct": None},
            "meta": {"status": "partial", "is_partial": True, "field_availability": {}, "sources": {}},
        },
    )
    assert main.ticker_overview("AAPL")["profile"]["symbol"] == "AAPL"


def test_service_overview_prefers_info_fields(monkeypatch) -> None:
    clear_service_caches()
    monkeypatch.setattr(
        data_service,
        "get_company_info",
        lambda symbol: {
            "longName": "Apple Inc.",
            "exchange": "NMS",
            "currentPrice": 190.0,
            "previousClose": 188.0,
            "marketCap": 2_900_000_000_000,
            "trailingPE": 31.2,
            "trailingEps": 6.08,
            "volume": 50_000_000,
            "averageVolume": 60_000_000,
            "beta": 1.18,
            "fiftyTwoWeekHigh": 199.0,
            "fiftyTwoWeekLow": 164.0,
        },
    )
    monkeypatch.setattr(data_service, "get_fast_info", lambda symbol: {"lastPrice": 1.0, "exchange": "NYQ"})
    monkeypatch.setattr(data_service, "get_price_history", lambda symbol, period="1m": [])
    monkeypatch.setattr(data_service, "_pick_search_match", lambda symbol: {"symbol": "AAPL", "name": "Wrong", "exchange": "NYSE"})
    monkeypatch.setattr(data_service, "get_profile_enrichment", lambda symbol: {})

    overview = data_service.get_ticker_overview("AAPL")
    assert overview is not None
    assert overview["profile"]["name"] == "Apple Inc."
    assert overview["profile"]["exchange"] == "NASDAQ"
    assert overview["quote"]["price"] == 190.0
    assert overview["stats"]["market_cap"] == 2_900_000_000_000
    assert overview["meta"]["sources"]["profile.name"] == "info"
    assert overview["meta"]["sources"]["quote.price"] == "info"


def test_service_overview_falls_back_to_fast_info(monkeypatch) -> None:
    clear_service_caches()
    monkeypatch.setattr(data_service, "get_company_info", lambda symbol: {})
    monkeypatch.setattr(
        data_service,
        "get_fast_info",
        lambda symbol: {
            "lastPrice": 100.0,
            "previousClose": 98.0,
            "marketCap": 2_000_000_000,
            "lastVolume": 1_500_000,
            "threeMonthAverageVolume": 1_250_000,
            "yearHigh": 130.0,
            "yearLow": 90.0,
            "exchange": "NMS",
        },
    )
    monkeypatch.setattr(data_service, "get_price_history", lambda symbol, period="1m": [])
    monkeypatch.setattr(data_service, "_pick_search_match", lambda symbol: {"symbol": "AAPL", "name": "Apple Inc.", "exchange": "NASDAQ"})
    monkeypatch.setattr(data_service, "get_profile_enrichment", lambda symbol: {})

    overview = data_service.get_ticker_overview("AAPL")
    assert overview is not None
    assert overview["quote"]["price"] == 100.0
    assert overview["quote"]["prev_close"] == 98.0
    assert overview["stats"]["average_volume"] == 1_250_000
    assert overview["meta"]["sources"]["quote.price"] == "fast_info"
    assert overview["meta"]["sources"]["range_52w.high"] == "fast_info"


def test_service_overview_falls_back_to_search_and_history(monkeypatch) -> None:
    clear_service_caches()
    month_history = [
        {"date": "2026-01-01", "close": 98.0, "volume": 1000.0},
        {"date": "2026-01-02", "close": 100.0, "volume": 1200.0},
    ]
    year_history = month_history + [{"date": "2026-04-02", "close": 120.0, "volume": 900.0}]
    monkeypatch.setattr(data_service, "get_company_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_fast_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "_pick_search_match", lambda symbol: {"symbol": "AAPL", "name": "Apple Inc.", "exchange": "NMS"})
    monkeypatch.setattr(data_service, "get_profile_enrichment", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_price_history", lambda symbol, period="1m": month_history if period == "1m" else year_history)

    overview = data_service.get_ticker_overview("AAPL")
    assert overview is not None
    assert overview["profile"]["name"] == "Apple Inc."
    assert overview["quote"]["price"] == 100.0
    assert overview["range_52w"]["high"] == 120.0
    assert overview["meta"]["sources"]["profile.name"] == "search"
    assert overview["meta"]["sources"]["quote.price"] == "history_recent"


def test_service_overview_invalid_symbol(monkeypatch) -> None:
    clear_service_caches()
    monkeypatch.setattr(data_service, "get_company_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_fast_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "_pick_search_match", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_profile_enrichment", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_price_history", lambda symbol, period="1m": [])
    assert data_service.get_ticker_overview("BAD") is None


def test_ticker_overview_404(monkeypatch) -> None:
    monkeypatch.setattr(main.data_service, "get_ticker_overview", lambda symbol: None)
    with pytest.raises(HTTPException) as exc:
        main.ticker_overview("INVALID")
    assert exc.value.status_code == 404
    assert exc.value.detail == "ticker data unavailable"


def test_ticker_overview_partial_response(monkeypatch) -> None:
    monkeypatch.setattr(
        main.data_service,
        "get_ticker_overview",
        lambda symbol: {
            "profile": {"symbol": "AAPL", "name": "Apple Inc.", "exchange": "NASDAQ", "sector": None, "industry": None, "website": None, "summary": None},
            "quote": {"price": 100.0, "prev_close": 98.0, "change": 2.0, "change_pct": 0.0204},
            "signals": [],
            "stats": {"market_cap": None, "trailing_pe": None, "trailing_eps": None, "volume": 1000.0, "average_volume": None, "beta": None},
            "ratios": {
                "price_to_book": None,
                "price_to_sales": None,
                "ev_to_sales": None,
                "ev_to_ebitda": None,
                "gross_margin_ttm": None,
                "operating_margin_ttm": None,
                "net_margin_ttm": None,
                "roe_ttm": None,
                "roa_ttm": None,
                "roic_ttm": None,
                "debt_to_equity": None,
                "current_ratio": None,
                "dividend_yield_ttm": None,
                "dividend_payout_ratio_ttm": None,
            },
            "range_52w": {"low": None, "high": None, "price": 100.0},
            "short_interest": {"short_percent_of_float": None, "short_ratio": None, "shares_short": None, "shares_short_prior_month": None, "shares_short_delta_pct": None},
            "meta": {"status": "partial", "is_partial": True, "field_availability": {"stats.market_cap": False}, "sources": {"profile.name": "search"}},
        },
    )
    body = main.ticker_overview("AAPL")
    assert body["meta"]["is_partial"] is True
    assert body["profile"]["name"] == "Apple Inc."


def test_ticker_history_period_mapping(monkeypatch) -> None:
    data_service.HISTORY_CACHE.clear()
    captured: list[str] = []

    class DummyTicker:
        def __init__(self, symbol: str) -> None:
            self.symbol = symbol

        def history(self, period: str):
            captured.append(period)
            return pd.DataFrame(
                [{"Open": 1.0, "High": 1.0, "Low": 1.0, "Close": 1.0, "Volume": 1.0}],
                index=[pd.Timestamp("2026-01-01")],
            )

    monkeypatch.setattr(data_service.yf, "Ticker", DummyTicker)
    assert len(data_service.get_price_history("AAPL", period="1m")) == 1
    assert len(data_service.get_price_history("AAPL", period="3m")) == 1
    assert len(data_service.get_price_history("AAPL", period="6m")) == 1
    assert captured == ["1mo", "3mo", "6mo"]


def test_compute_ttm_ratios_populates_overlapping_stats(monkeypatch) -> None:
    clear_service_caches()
    monkeypatch.setattr(data_service, "get_company_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_fast_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_latest_price", lambda symbol: 50.0)
    monkeypatch.setattr(data_service, "get_shares_outstanding", lambda symbol: 100.0)
    monkeypatch.setattr(
        data_service,
        "get_income_statement",
        lambda symbol, quarterly=False: quarterly_frame(
            {
                "Total Revenue": [1_000.0, 1_000.0, 1_000.0, 1_000.0],
                "Gross Profit": [500.0, 500.0, 500.0, 500.0],
                "Operating Income": [250.0, 250.0, 250.0, 250.0],
                "Net Income": [100.0, 100.0, 100.0, 100.0],
                "EBIT": [150.0, 150.0, 150.0, 150.0],
                "EBITDA": [200.0, 200.0, 200.0, 200.0],
                "Tax Provision": [20.0, 20.0, 20.0, 20.0],
                "Pretax Income": [120.0, 120.0, 120.0, 120.0],
            }
        ),
    )
    monkeypatch.setattr(
        data_service,
        "get_balance_sheet",
        lambda symbol, quarterly=False: quarterly_frame(
            {
                "Stockholders Equity": [500.0, 0.0, 0.0, 0.0],
                "Total Assets": [1_200.0, 0.0, 0.0, 0.0],
                "Total Debt": [150.0, 0.0, 0.0, 0.0],
                "Current Assets": [300.0, 0.0, 0.0, 0.0],
                "Current Liabilities": [100.0, 0.0, 0.0, 0.0],
                "Cash And Cash Equivalents": [50.0, 0.0, 0.0, 0.0],
            }
        ),
    )
    monkeypatch.setattr(
        data_service,
        "get_cash_flow",
        lambda symbol, quarterly=False: quarterly_frame({"Cash Dividends Paid": [-10.0, -10.0, -10.0, -10.0]}),
    )

    ratios = data_service.compute_ttm_ratios("AAPL")
    assert ratios["market_cap"] == 5_000.0
    assert ratios["trailing_eps"] == 4.0
    assert ratios["trailing_pe"] == 12.5
    assert ratios["price_to_book"] == 10.0
    assert ratios["price_to_sales"] == 1.25
    assert ratios["ev_to_sales"] == 1.275
    assert ratios["gross_margin_ttm"] == 0.5
    assert ratios["operating_margin_ttm"] == 0.25
    assert ratios["net_margin_ttm"] == 0.1
    assert ratios["roe_ttm"] == 0.8
    assert round(ratios["roic_ttm"], 6) == round((600.0 * (1 - (80.0 / 480.0))) / 600.0, 6)
    assert ratios["debt_to_equity"] == 0.3
    assert ratios["current_ratio"] == 3.0
    assert ratios["dividend_yield_ttm"] == 0.008
    assert ratios["dividend_payout_ratio_ttm"] == 0.1


def test_compute_ttm_ratios_guardrails_suppress_outliers(monkeypatch) -> None:
    clear_service_caches()
    monkeypatch.setattr(data_service, "get_company_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_fast_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_latest_price", lambda symbol: 1_000.0)
    monkeypatch.setattr(data_service, "get_shares_outstanding", lambda symbol: 100.0)
    monkeypatch.setattr(
        data_service,
        "get_income_statement",
        lambda symbol, quarterly=False: quarterly_frame(
            {
                "Total Revenue": [1.0, 1.0, 1.0, 1.0],
                "Net Income": [1.0, 1.0, 1.0, 1.0],
                "EBIT": [1.0, 1.0, 1.0, 1.0],
                "EBITDA": [100_000.0, 100_000.0, 100_000.0, 100_000.0],
                "Tax Provision": [0.0, 0.0, 0.0, 0.0],
                "Pretax Income": [1.0, 1.0, 1.0, 1.0],
            }
        ),
    )
    monkeypatch.setattr(
        data_service,
        "get_balance_sheet",
        lambda symbol, quarterly=False: quarterly_frame(
            {
                "Stockholders Equity": [1.0, 0.0, 0.0, 0.0],
                "Total Assets": [10.0, 0.0, 0.0, 0.0],
                "Total Debt": [1_000.0, 0.0, 0.0, 0.0],
                "Cash And Cash Equivalents": [0.0, 0.0, 0.0, 0.0],
            }
        ),
    )
    monkeypatch.setattr(data_service, "get_cash_flow", lambda symbol, quarterly=False: pd.DataFrame())

    ratios = data_service.compute_ttm_ratios("AAPL")
    assert ratios["trailing_pe"] == 25_000.0
    assert "price_to_book" not in ratios
    assert "price_to_sales" not in ratios
    assert "ev_to_sales" not in ratios
    assert "ev_to_ebitda" not in ratios


def test_overview_uses_computed_sources_and_ratios(monkeypatch) -> None:
    clear_service_caches()
    monkeypatch.setattr(
        data_service,
        "get_company_info",
        lambda symbol: {
            "longName": "Apple Inc.",
            "exchange": "NMS",
            "currentPrice": 120.0,
            "previousClose": 118.0,
        },
    )
    monkeypatch.setattr(data_service, "get_fast_info", lambda symbol: {})
    monkeypatch.setattr(data_service, "get_price_history", lambda symbol, period="1m": [])
    monkeypatch.setattr(data_service, "_pick_search_match", lambda symbol: {"symbol": "AAPL", "name": "Apple Inc.", "exchange": "NASDAQ"})
    monkeypatch.setattr(data_service, "get_profile_enrichment", lambda symbol: {})
    monkeypatch.setattr(
        data_service,
        "compute_ttm_ratios",
        lambda symbol: {
            "market_cap": 1_500_000_000.0,
            "trailing_pe": 24.5,
            "trailing_eps": 4.9,
            "price_to_book": 8.0,
            "price_to_sales": 6.2,
            "ev_to_sales": 6.8,
            "ev_to_ebitda": 22.1,
            "gross_margin_ttm": 0.44,
            "operating_margin_ttm": 0.27,
            "net_margin_ttm": 0.18,
            "roe_ttm": 0.31,
            "roa_ttm": 0.12,
            "roic_ttm": 0.19,
            "debt_to_equity": 0.42,
            "current_ratio": 1.8,
            "dividend_yield_ttm": 0.005,
            "dividend_payout_ratio_ttm": 0.12,
        },
    )

    overview = data_service.get_ticker_overview("AAPL")
    assert overview is not None
    assert overview["stats"]["trailing_pe"] == 24.5
    assert overview["stats"]["market_cap"] == 1_500_000_000.0
    assert overview["ratios"]["price_to_book"] == 8.0
    assert overview["meta"]["sources"]["stats.trailing_pe"] == "computed"
    assert overview["meta"]["sources"]["stats.market_cap"] == "computed"
    assert overview["meta"]["sources"]["ratios.price_to_book"] == "computed"
    assert overview["meta"]["field_availability"]["ratios.ev_to_ebitda"] is True
    assert any(signal["key"] == "Valuation" and "24.5x" in signal["value"] for signal in overview["signals"])


def test_financials_route_returns_structure(monkeypatch) -> None:
    monkeypatch.setattr(
        main.data_service,
        "get_financials",
        lambda symbol, period="annual": {
            "period": "annual",
            "income": {"columns": ["FY 2024", "TTM"], "rows": [
                {"label": "Total Revenue", "indent": 0, "is_total": True,
                 "is_section": False, "is_margin": False, "values": [391_000.0, 394_500.0]},
            ]},
            "balance": {"columns": [], "rows": []},
            "cash_flow": {"columns": [], "rows": []},
        },
    )
    result = main.ticker_financials("AAPL", period="annual")
    assert result["period"] == "annual"
    assert result["income"]["columns"][0] == "FY 2024"
    assert result["income"]["rows"][0]["label"] == "Total Revenue"


def test_financials_route_period_param(monkeypatch) -> None:
    captured: list[str] = []

    def mock_get_financials(symbol, period="annual"):
        captured.append(period)
        return {
            "period": period,
            "income": {"columns": [], "rows": []},
            "balance": {"columns": [], "rows": []},
            "cash_flow": {"columns": [], "rows": []},
        }

    monkeypatch.setattr(main.data_service, "get_financials", mock_get_financials)
    main.ticker_financials("AAPL", period="quarterly")
    assert captured == ["quarterly"]