File size: 18,839 Bytes
9b88b42
 
 
 
 
 
 
 
 
 
 
 
 
 
6752363
9b88b42
 
9f411df
 
 
 
 
 
9b88b42
 
 
 
 
 
 
 
 
 
18b9531
9b88b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
 
9b88b42
 
6752363
 
 
9b88b42
 
 
 
 
6752363
9b88b42
 
 
 
6752363
9b88b42
 
6752363
 
 
9b88b42
6752363
9b88b42
 
6752363
9b88b42
 
 
6752363
 
9b88b42
6752363
9b88b42
6752363
 
 
9b88b42
 
 
 
6752363
9b88b42
 
 
6752363
 
9b88b42
 
 
9f411df
 
 
 
 
9b88b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
 
9b88b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
 
9b88b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
 
9b88b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
 
9b88b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Financial Modeling Prep (FMP) MCP Server.

This MCP server provides company fundamentals, financial statements, and key metrics
using the Financial Modeling Prep API.

Free tier: 250 calls/day, 500MB/30 days
"""

import logging
from datetime import datetime
from typing import Dict, List, Optional, Any
from decimal import Decimal

import httpx
import yfinance as yf
from fastmcp import FastMCP
from pydantic import BaseModel, Field
from tenacity import (
    retry,
    stop_after_attempt,
    wait_exponential,
    retry_if_exception_type,
)

from backend.config import settings

logger = logging.getLogger(__name__)

# Initialize MCP server
mcp = FastMCP("financial-modeling-prep")

# API Configuration
BASE_URL = "https://financialmodelingprep.com/api/v3"
API_KEY = settings.fmp_api_key


class CompanyProfileRequest(BaseModel):
    """Request for company profile."""

    ticker: str


class CompanyProfile(BaseModel):
    """Company profile and fundamental data."""

    ticker: str
    company_name: Optional[str] = None
    sector: Optional[str] = None
    industry: Optional[str] = None
    website: Optional[str] = None
    description: Optional[str] = None
    ceo: Optional[str] = None
    employees: Optional[int] = None
    market_cap: Optional[Decimal] = None
    beta: Optional[Decimal] = None
    price: Optional[Decimal] = None
    volume_avg: Optional[int] = None
    exchange: Optional[str] = None
    ipo_date: Optional[str] = None
    country: Optional[str] = None


class FinancialStatementsRequest(BaseModel):
    """Request for financial statements."""

    ticker: str
    period: str = Field(default="annual", description="annual or quarter")
    limit: int = Field(default=5, ge=1, le=120)


class IncomeStatement(BaseModel):
    """Income statement data."""

    date: str
    revenue: Optional[Decimal] = None
    cost_of_revenue: Optional[Decimal] = None
    gross_profit: Optional[Decimal] = None
    operating_expenses: Optional[Decimal] = None
    operating_income: Optional[Decimal] = None
    ebitda: Optional[Decimal] = None
    net_income: Optional[Decimal] = None
    eps: Optional[Decimal] = None
    eps_diluted: Optional[Decimal] = None


class BalanceSheet(BaseModel):
    """Balance sheet data."""

    date: str
    total_assets: Optional[Decimal] = None
    total_current_assets: Optional[Decimal] = None
    cash_and_cash_equivalents: Optional[Decimal] = None
    total_liabilities: Optional[Decimal] = None
    total_current_liabilities: Optional[Decimal] = None
    total_debt: Optional[Decimal] = None
    total_stockholders_equity: Optional[Decimal] = None


class CashFlowStatement(BaseModel):
    """Cash flow statement data."""

    date: str
    operating_cash_flow: Optional[Decimal] = None
    capital_expenditure: Optional[Decimal] = None
    free_cash_flow: Optional[Decimal] = None
    net_cash_from_financing: Optional[Decimal] = None
    net_cash_from_investing: Optional[Decimal] = None
    net_change_in_cash: Optional[Decimal] = None


class FinancialRatiosRequest(BaseModel):
    """Request for financial ratios."""

    ticker: str
    ttm: bool = Field(default=True, description="Use trailing twelve months")


class FinancialRatios(BaseModel):
    """Key financial ratios."""

    ticker: str
    date: Optional[str] = None

    # Profitability
    net_profit_margin: Optional[Decimal] = None
    roe: Optional[Decimal] = None
    roa: Optional[Decimal] = None
    roic: Optional[Decimal] = None

    # Liquidity
    current_ratio: Optional[Decimal] = None
    quick_ratio: Optional[Decimal] = None
    cash_ratio: Optional[Decimal] = None

    # Efficiency
    asset_turnover: Optional[Decimal] = None
    inventory_turnover: Optional[Decimal] = None

    # Leverage
    debt_to_equity: Optional[Decimal] = None
    debt_to_assets: Optional[Decimal] = None
    interest_coverage: Optional[Decimal] = None


class KeyMetricsRequest(BaseModel):
    """Request for key metrics."""

    ticker: str
    ttm: bool = Field(default=True)


class KeyMetrics(BaseModel):
    """Key company metrics."""

    ticker: str
    date: Optional[str] = None
    market_cap: Optional[Decimal] = None
    pe_ratio: Optional[Decimal] = None
    price_to_book: Optional[Decimal] = None
    price_to_sales: Optional[Decimal] = None
    enterprise_value: Optional[Decimal] = None
    ev_to_ebitda: Optional[Decimal] = None
    revenue_per_share: Optional[Decimal] = None
    earnings_per_share: Optional[Decimal] = None
    book_value_per_share: Optional[Decimal] = None
    operating_cash_flow_per_share: Optional[Decimal] = None
    free_cash_flow_per_share: Optional[Decimal] = None


async def _make_request(endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """Make HTTP request to FMP API.

    Args:
        endpoint: API endpoint path
        params: Query parameters

    Returns:
        JSON response data

    Raises:
        httpx.HTTPError: On HTTP errors
    """
    if params is None:
        params = {}

    params["apikey"] = API_KEY

    url = f"{BASE_URL}/{endpoint}"

    async with httpx.AsyncClient() as client:
        response = await client.get(url, params=params, timeout=30.0)
        response.raise_for_status()
        return response.json()


@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type((TimeoutError, ConnectionError, httpx.HTTPStatusError)),
)
@mcp.tool()
async def get_company_profile(request: CompanyProfileRequest) -> CompanyProfile:
    """Get company profile using yfinance (free, no API key required).

    Replaces deprecated FMP v3/profile endpoint with yfinance as fallback.

    Args:
        request: Company profile request

    Returns:
        Company profile with name, sector, industry, market cap, description, etc.

    Example:
        >>> await get_company_profile(CompanyProfileRequest(ticker="AAPL"))
    """
    logger.info(f"Fetching company profile for {request.ticker} using yfinance")

    try:
        # Create ticker object
        stock = yf.Ticker(request.ticker)
        info = stock.info

        # Map yfinance data to CompanyProfile structure
        profile = CompanyProfile(
            ticker=request.ticker,
            company_name=info.get("longName") or info.get("shortName"),
            sector=info.get("sector"),
            industry=info.get("industry"),
            website=info.get("website"),
            description=info.get("longBusinessSummary"),
            ceo=info.get("companyOfficers", [{}])[0].get("name") if info.get("companyOfficers") else None,
            employees=info.get("fullTimeEmployees"),
            market_cap=Decimal(str(info["marketCap"])) if info.get("marketCap") else None,
            beta=Decimal(str(info["beta"])) if info.get("beta") else None,
            price=Decimal(str(info.get("currentPrice") or info.get("regularMarketPrice", 0))) if info.get("currentPrice") or info.get("regularMarketPrice") else None,
            volume_avg=info.get("averageVolume"),
            exchange=info.get("exchange"),
            ipo_date=info.get("ipoDate"),
            country=info.get("country"),
        )

        logger.info(f"Successfully fetched profile for {request.ticker} using yfinance: {profile.company_name}")
        return profile

    except Exception as e:
        logger.error(f"Error fetching company profile for {request.ticker} using yfinance: {e}")
        # Return minimal profile on error
        return CompanyProfile(ticker=request.ticker)


@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type((TimeoutError, ConnectionError, httpx.HTTPStatusError)),
)
@mcp.tool()
async def get_income_statement(request: FinancialStatementsRequest) -> List[IncomeStatement]:
    """Get income statement data.

    Args:
        request: Financial statements request

    Returns:
        List of income statements

    Example:
        >>> await get_income_statement(FinancialStatementsRequest(ticker="AAPL", period="annual", limit=5))
    """
    logger.info(f"Fetching income statement for {request.ticker}")

    try:
        data = await _make_request(
            f"income-statement/{request.ticker}",
            params={"period": request.period, "limit": request.limit}
        )

        statements = []
        for item in data:
            stmt = IncomeStatement(
                date=item.get("date", ""),
                revenue=Decimal(str(item["revenue"])) if item.get("revenue") else None,
                cost_of_revenue=Decimal(str(item["costOfRevenue"])) if item.get("costOfRevenue") else None,
                gross_profit=Decimal(str(item["grossProfit"])) if item.get("grossProfit") else None,
                operating_expenses=Decimal(str(item["operatingExpenses"])) if item.get("operatingExpenses") else None,
                operating_income=Decimal(str(item["operatingIncome"])) if item.get("operatingIncome") else None,
                ebitda=Decimal(str(item["ebitda"])) if item.get("ebitda") else None,
                net_income=Decimal(str(item["netIncome"])) if item.get("netIncome") else None,
                eps=Decimal(str(item["eps"])) if item.get("eps") else None,
                eps_diluted=Decimal(str(item["epsdiluted"])) if item.get("epsdiluted") else None,
            )
            statements.append(stmt)

        logger.info(f"Fetched {len(statements)} income statements for {request.ticker}")
        return statements

    except Exception as e:
        logger.error(f"Error fetching income statement for {request.ticker}: {e}")
        return []


@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type((TimeoutError, ConnectionError, httpx.HTTPStatusError)),
)
@mcp.tool()
async def get_balance_sheet(request: FinancialStatementsRequest) -> List[BalanceSheet]:
    """Get balance sheet data.

    Args:
        request: Financial statements request

    Returns:
        List of balance sheets

    Example:
        >>> await get_balance_sheet(FinancialStatementsRequest(ticker="AAPL", period="annual"))
    """
    logger.info(f"Fetching balance sheet for {request.ticker}")

    try:
        data = await _make_request(
            f"balance-sheet-statement/{request.ticker}",
            params={"period": request.period, "limit": request.limit}
        )

        sheets = []
        for item in data:
            sheet = BalanceSheet(
                date=item.get("date", ""),
                total_assets=Decimal(str(item["totalAssets"])) if item.get("totalAssets") else None,
                total_current_assets=Decimal(str(item["totalCurrentAssets"])) if item.get("totalCurrentAssets") else None,
                cash_and_cash_equivalents=Decimal(str(item["cashAndCashEquivalents"])) if item.get("cashAndCashEquivalents") else None,
                total_liabilities=Decimal(str(item["totalLiabilities"])) if item.get("totalLiabilities") else None,
                total_current_liabilities=Decimal(str(item["totalCurrentLiabilities"])) if item.get("totalCurrentLiabilities") else None,
                total_debt=Decimal(str(item["totalDebt"])) if item.get("totalDebt") else None,
                total_stockholders_equity=Decimal(str(item["totalStockholdersEquity"])) if item.get("totalStockholdersEquity") else None,
            )
            sheets.append(sheet)

        logger.info(f"Fetched {len(sheets)} balance sheets for {request.ticker}")
        return sheets

    except Exception as e:
        logger.error(f"Error fetching balance sheet for {request.ticker}: {e}")
        return []


@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type((TimeoutError, ConnectionError, httpx.HTTPStatusError)),
)
@mcp.tool()
async def get_cash_flow_statement(request: FinancialStatementsRequest) -> List[CashFlowStatement]:
    """Get cash flow statement data.

    Args:
        request: Financial statements request

    Returns:
        List of cash flow statements

    Example:
        >>> await get_cash_flow_statement(FinancialStatementsRequest(ticker="AAPL"))
    """
    logger.info(f"Fetching cash flow statement for {request.ticker}")

    try:
        data = await _make_request(
            f"cash-flow-statement/{request.ticker}",
            params={"period": request.period, "limit": request.limit}
        )

        statements = []
        for item in data:
            stmt = CashFlowStatement(
                date=item.get("date", ""),
                operating_cash_flow=Decimal(str(item["operatingCashFlow"])) if item.get("operatingCashFlow") else None,
                capital_expenditure=Decimal(str(item["capitalExpenditure"])) if item.get("capitalExpenditure") else None,
                free_cash_flow=Decimal(str(item["freeCashFlow"])) if item.get("freeCashFlow") else None,
                net_cash_from_financing=Decimal(str(item["netCashUsedProvidedByFinancingActivities"])) if item.get("netCashUsedProvidedByFinancingActivities") else None,
                net_cash_from_investing=Decimal(str(item["netCashUsedForInvestingActivites"])) if item.get("netCashUsedForInvestingActivites") else None,
                net_change_in_cash=Decimal(str(item["netChangeInCash"])) if item.get("netChangeInCash") else None,
            )
            statements.append(stmt)

        logger.info(f"Fetched {len(statements)} cash flow statements for {request.ticker}")
        return statements

    except Exception as e:
        logger.error(f"Error fetching cash flow statement for {request.ticker}: {e}")
        return []


@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type((TimeoutError, ConnectionError, httpx.HTTPStatusError)),
)
@mcp.tool()
async def get_financial_ratios(request: FinancialRatiosRequest) -> FinancialRatios:
    """Get key financial ratios.

    Args:
        request: Financial ratios request

    Returns:
        Financial ratios

    Example:
        >>> await get_financial_ratios(FinancialRatiosRequest(ticker="AAPL", ttm=True))
    """
    logger.info(f"Fetching financial ratios for {request.ticker}")

    try:
        endpoint = f"ratios-ttm/{request.ticker}" if request.ttm else f"ratios/{request.ticker}"
        data = await _make_request(endpoint)

        if not data or len(data) == 0:
            logger.warning(f"No ratios data found for {request.ticker}")
            return FinancialRatios(ticker=request.ticker)

        item = data[0] if isinstance(data, list) else data

        ratios = FinancialRatios(
            ticker=request.ticker,
            date=item.get("date"),
            net_profit_margin=Decimal(str(item["netProfitMargin"])) if item.get("netProfitMargin") else None,
            roe=Decimal(str(item["returnOnEquity"])) if item.get("returnOnEquity") else None,
            roa=Decimal(str(item["returnOnAssets"])) if item.get("returnOnAssets") else None,
            roic=Decimal(str(item["returnOnCapitalEmployed"])) if item.get("returnOnCapitalEmployed") else None,
            current_ratio=Decimal(str(item["currentRatio"])) if item.get("currentRatio") else None,
            quick_ratio=Decimal(str(item["quickRatio"])) if item.get("quickRatio") else None,
            cash_ratio=Decimal(str(item["cashRatio"])) if item.get("cashRatio") else None,
            asset_turnover=Decimal(str(item["assetTurnover"])) if item.get("assetTurnover") else None,
            inventory_turnover=Decimal(str(item["inventoryTurnover"])) if item.get("inventoryTurnover") else None,
            debt_to_equity=Decimal(str(item["debtEquityRatio"])) if item.get("debtEquityRatio") else None,
            debt_to_assets=Decimal(str(item["debtRatio"])) if item.get("debtRatio") else None,
            interest_coverage=Decimal(str(item["interestCoverage"])) if item.get("interestCoverage") else None,
        )

        logger.info(f"Successfully fetched ratios for {request.ticker}")
        return ratios

    except Exception as e:
        logger.error(f"Error fetching financial ratios for {request.ticker}: {e}")
        return FinancialRatios(ticker=request.ticker)


@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type((TimeoutError, ConnectionError, httpx.HTTPStatusError)),
)
@mcp.tool()
async def get_key_metrics(request: KeyMetricsRequest) -> KeyMetrics:
    """Get key company metrics.

    Args:
        request: Key metrics request

    Returns:
        Key metrics

    Example:
        >>> await get_key_metrics(KeyMetricsRequest(ticker="AAPL"))
    """
    logger.info(f"Fetching key metrics for {request.ticker}")

    try:
        endpoint = f"key-metrics-ttm/{request.ticker}" if request.ttm else f"key-metrics/{request.ticker}"
        data = await _make_request(endpoint)

        if not data or len(data) == 0:
            logger.warning(f"No key metrics found for {request.ticker}")
            return KeyMetrics(ticker=request.ticker)

        item = data[0] if isinstance(data, list) else data

        metrics = KeyMetrics(
            ticker=request.ticker,
            date=item.get("date"),
            market_cap=Decimal(str(item["marketCap"])) if item.get("marketCap") else None,
            pe_ratio=Decimal(str(item["peRatio"])) if item.get("peRatio") else None,
            price_to_book=Decimal(str(item["pbRatio"])) if item.get("pbRatio") else None,
            price_to_sales=Decimal(str(item["priceToSalesRatio"])) if item.get("priceToSalesRatio") else None,
            enterprise_value=Decimal(str(item["enterpriseValue"])) if item.get("enterpriseValue") else None,
            ev_to_ebitda=Decimal(str(item["evToEbitda"])) if item.get("evToEbitda") else None,
            revenue_per_share=Decimal(str(item["revenuePerShare"])) if item.get("revenuePerShare") else None,
            earnings_per_share=Decimal(str(item["netIncomePerShare"])) if item.get("netIncomePerShare") else None,
            book_value_per_share=Decimal(str(item["bookValuePerShare"])) if item.get("bookValuePerShare") else None,
            operating_cash_flow_per_share=Decimal(str(item["operatingCashFlowPerShare"])) if item.get("operatingCashFlowPerShare") else None,
            free_cash_flow_per_share=Decimal(str(item["freeCashFlowPerShare"])) if item.get("freeCashFlowPerShare") else None,
        )

        logger.info(f"Successfully fetched key metrics for {request.ticker}")
        return metrics

    except Exception as e:
        logger.error(f"Error fetching key metrics for {request.ticker}: {e}")
        return KeyMetrics(ticker=request.ticker)


# Export the MCP server
if __name__ == "__main__":
    mcp.run()