File size: 1,725 Bytes
3f43e82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import os
from dotenv import load_dotenv
from typing import List, Dict, Any
import logging


load_dotenv()

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


FMP_API_KEY = os.getenv("FMP_API_KEY")
if not FMP_API_KEY:
    logger.warning("FMP_API_KEY not found. FMP calls will fail.")


FMP_BASE_URL = "https://financialmodelingprep.com/api/v3"


class FMPError(Exception):
    """Custom exception for FMP API errors."""

    pass


def get_earnings_surprises(ticker: str) -> List[Dict[str, Any]]:
    """
    Fetches earnings surprise data for a single ticker from Financial Modeling Prep.
    Returns a list of earnings surprise records.
    Raises FMPError on API-specific issues.
    Raises requests.RequestException on network issues.
    """
    if not FMP_API_KEY:
        raise FMPError("FMP API Key not configured.")

    endpoint = f"{FMP_BASE_URL}/earning_surprise/{ticker}"
    params = {"apikey": FMP_API_KEY}

    logger.info(f"Fetching earnings surprise data for {ticker} from FMP.")
    response = requests.get(endpoint, params=params, timeout=30)
    response.raise_for_status()
    data = response.json()

    if isinstance(data, list):
        return data
    else:

        logger.error(f"Unexpected FMP response structure for {ticker}: {data}")

        if isinstance(data, dict) and data.get("error"):
            raise FMPError(f"FMP API returned error for {ticker}: {data['error']}")

        if isinstance(data, dict) and not data:
            logger.warning(
                f"FMP API returned empty response for {ticker}, potentially no data."
            )
            return []
        raise FMPError(f"Unexpected API response structure for {ticker}.")