File size: 11,701 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
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
import requests
import os
from dotenv import load_dotenv
from typing import Dict, List, Optional, Any
import logging

load_dotenv()

logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

FMP_API_KEY = os.getenv("FMP_API_KEY")
ALPHAVANTAGE_API_KEY = os.getenv("ALPHAVANTAGE_API_KEY")

FMP_BASE_URL = "https://financialmodelingprep.com/api/v3"
ALPHAVANTAGE_BASE_URL = "https://www.alphavantage.co/query"


class DataIngestionError(Exception):
    """Custom exception for data ingestion API errors."""

    pass


class FMPFetchError(DataIngestionError):
    """Specific error for FMP fetching issues."""

    pass


class AVFetchError(DataIngestionError):
    """Specific error for AlphaVantage fetching issues."""

    pass


def _fetch_from_fmp(ticker: str, api_key: str) -> Dict[str, Dict[str, Any]]:
    """Internal function to fetch data from FMP. Uses /historical-price-full/ as recommended."""

    endpoint = f"{FMP_BASE_URL}/historical-price-full/{ticker}"
    params = {"apikey": api_key}
    logger.info(
        f"Fetching historical daily data for {ticker} from FMP (using /historical-price-full/)."
    )
    try:
        response = requests.get(endpoint, params=params, timeout=30)
        response.raise_for_status()
        data = response.json()

        if isinstance(data, dict):

            if "Error Message" in data:
                raise FMPFetchError(
                    f"FMP API returned error for {ticker}: {data['Error Message']}"
                )
            if data.get("symbol") and "historical" in data:
                historical_data_list = data.get("historical")

                if isinstance(historical_data_list, list):
                    if not historical_data_list:
                        logger.warning(
                            f"FMP API returned empty historical data list for {ticker} (from /historical-price-full/)."
                        )
                        return {}

                    prices_dict: Dict[str, Dict[str, Any]] = {}
                    for record in historical_data_list:
                        if isinstance(record, dict) and "date" in record:
                            prices_dict[record["date"]] = record
                        else:
                            logger.warning(
                                f"Skipping invalid FMP record format for {ticker}: {record}"
                            )
                    logger.info(
                        f"Successfully fetched and formatted {len(prices_dict)} historical records for {ticker} from FMP."
                    )
                    return prices_dict
                else:
                    raise FMPFetchError(
                        f"FMP API historical data for {ticker} has unexpected 'historical' type: {type(historical_data_list)}"
                    )
            else:
                raise FMPFetchError(
                    f"FMP API response for {ticker} (from /historical-price-full/) missing expected structure (symbol/historical keys). Response: {str(data)[:200]}"
                )

        elif isinstance(data, list):
            if not data:
                logger.warning(
                    f"FMP API returned empty list for {ticker} (from /historical-price-full/)."
                )
                return {}
            if isinstance(data[0], dict) and (
                "Error Message" in data[0] or "error" in data[0]
            ):
                error_msg = data[0].get(
                    "Error Message", data[0].get("error", "Unknown error in list")
                )
                raise FMPFetchError(
                    f"FMP API returned error list for {ticker}: {error_msg}"
                )
            else:
                raise FMPFetchError(
                    f"FMP API returned unexpected top-level list structure for {ticker} (from /historical-price-full/). Response: {str(data)[:200]}"
                )
        else:
            raise FMPFetchError(
                f"FMP API returned unexpected response type for {ticker} (from /historical-price-full/): {type(data)}. Response: {str(data)[:200]}"
            )

    except requests.exceptions.RequestException as e:
        raise FMPFetchError(f"FMP data fetch (network) failed for {ticker}: {e}")
    except Exception as e:
        raise FMPFetchError(
            f"FMP data fetch (processing) failed for {ticker}: {e}. Response: {str(locals().get('data', 'N/A'))[:200]}"
        )


def _fetch_from_alphavantage(ticker: str, api_key: str) -> Dict[str, Dict[str, Any]]:
    """Internal function to fetch data from AlphaVantage."""
    endpoint = f"{ALPHAVANTAGE_BASE_URL}/query"
    params = {
        "function": "TIME_SERIES_DAILY_ADJUSTED",
        "symbol": ticker,
        "apikey": api_key,
        "outputsize": "compact",
    }
    logger.info(f"Fetching historical daily data for {ticker} from AlphaVantage.")
    try:
        response = requests.get(endpoint, params=params, timeout=30)
        response.raise_for_status()
        data = response.json()

        if not isinstance(data, dict):
            raise AVFetchError(
                f"AlphaVantage API returned unexpected response type for {ticker}: {type(data)}. Expected dict. Response: {str(data)[:200]}"
            )

        if "Error Message" in data:
            raise AVFetchError(
                f"AlphaVantage API returned error for {ticker}: {data['Error Message']}"
            )
        if "Note" in data:
            logger.warning(
                f"AlphaVantage API returned note for {ticker}: {data['Note']} - treating as no data."
            )

            return {}

        time_series_data = data.get("Time Series (Daily)")

        if time_series_data is None:

            if not data:
                logger.warning(
                    f"AlphaVantage API returned an empty dictionary for {ticker}."
                )
                return {}
            else:
                raise AVFetchError(
                    f"AlphaVantage API response for {ticker} missing 'Time Series (Daily)' key. Response: {str(data)[:200]}"
                )

        if not isinstance(time_series_data, dict):
            raise AVFetchError(
                f"AlphaVantage API 'Time Series (Daily)' for {ticker} is not a dictionary. Type: {type(time_series_data)}. Response: {str(data)[:200]}"
            )

        if not time_series_data:
            logger.warning(
                f"AlphaVantage API returned empty time series data for {ticker}."
            )
            return {}

        prices_dict: Dict[str, Dict[str, Any]] = {}
        for date_str, values_dict in time_series_data.items():
            if isinstance(values_dict, dict):
                cleaned_values: Dict[str, Any] = {}
                if "1. open" in values_dict:
                    cleaned_values["open"] = values_dict["1. open"]
                if "2. high" in values_dict:
                    cleaned_values["high"] = values_dict["2. high"]
                if "3. low" in values_dict:
                    cleaned_values["low"] = values_dict["3. low"]
                if "4. close" in values_dict:
                    cleaned_values["close"] = values_dict["4. close"]
                if "5. adjusted close" in values_dict:
                    cleaned_values["adjClose"] = values_dict["5. adjusted close"]
                if "6. volume" in values_dict:
                    cleaned_values["volume"] = values_dict["6. volume"]

                if cleaned_values:
                    prices_dict[date_str] = cleaned_values
                else:
                    logger.warning(
                        f"AlphaVantage data for {ticker} on {date_str} missing expected price keys within daily record."
                    )
            else:
                logger.warning(
                    f"Skipping invalid AlphaVantage daily record (not a dict) for {ticker} on {date_str}: {values_dict}"
                )
        logger.info(
            f"Successfully fetched and formatted {len(prices_dict)} historical records for {ticker} from AlphaVantage."
        )
        return prices_dict

    except requests.exceptions.RequestException as e:
        raise AVFetchError(
            f"AlphaVantage data fetch (network) failed for {ticker}: {e}"
        )
    except Exception as e:
        raise AVFetchError(
            f"AlphaVantage data fetch (processing) failed for {ticker}: {e}. Response: {str(locals().get('data', 'N/A'))[:200]}"
        )


def get_daily_adjusted_prices(ticker: str) -> Dict[str, Dict[str, Any]]:
    """
    Fetches historical daily adjusted prices for a single ticker.
    Tries FMP first if key is available. If FMP fails, tries AlphaVantage if key is available.
    Returns a dictionary mapping date strings to price dictionaries.
    Raises DataIngestionError if no keys are configured or if both APIs fail.
    """
    fmp_key_available = bool(FMP_API_KEY)
    av_key_available = bool(ALPHAVANTAGE_API_KEY)

    if not fmp_key_available and not av_key_available:
        raise DataIngestionError(
            "No API keys configured for historical price data (FMP, AlphaVantage)."
        )

    fmp_error_detail = None
    av_error_detail = None
    data_from_fmp = {}
    data_from_av = {}

    if fmp_key_available:
        try:
            data_from_fmp = _fetch_from_fmp(ticker, FMP_API_KEY)
            if data_from_fmp:
                return data_from_fmp
            else:

                fmp_error_detail = f"FMP API returned no data for {ticker}."
                logger.warning(fmp_error_detail)
        except FMPFetchError as e:
            fmp_error_detail = str(e)
            logger.error(f"FMPFetchError for {ticker}: {fmp_error_detail}")
        except Exception as e:
            fmp_error_detail = (
                f"An unexpected error occurred during FMP fetch for {ticker}: {e}"
            )
            logger.error(fmp_error_detail)

    if av_key_available:
        try:
            data_from_av = _fetch_from_alphavantage(ticker, ALPHAVANTAGE_API_KEY)
            if data_from_av:
                return data_from_av
            else:

                av_error_detail = f"AlphaVantage API returned no data for {ticker}."
                logger.warning(av_error_detail)
        except AVFetchError as e:
            av_error_detail = str(e)
            logger.error(f"AVFetchError for {ticker}: {av_error_detail}")
        except Exception as e:
            av_error_detail = f"An unexpected error occurred during AlphaVantage fetch for {ticker}: {e}"
            logger.error(av_error_detail)

    error_messages = []
    if fmp_key_available:
        if fmp_error_detail:
            error_messages.append(f"FMP: {fmp_error_detail}")
        elif not data_from_fmp:
            error_messages.append(f"FMP: Returned no data for {ticker}.")

    if av_key_available:
        if av_error_detail:
            error_messages.append(f"AlphaVantage: {av_error_detail}")
        elif not data_from_av:
            error_messages.append(f"AlphaVantage: Returned no data for {ticker}.")

    providers_tried = []
    if fmp_key_available:
        providers_tried.append("FMP")
    if av_key_available:
        providers_tried.append("AlphaVantage")

    final_message = f"Failed to fetch historical data for {ticker} after trying {', '.join(providers_tried) if providers_tried else 'available providers'}."
    if error_messages:
        final_message += " Details: " + "; ".join(error_messages)
    else:
        final_message += " No data was returned from any attempted source."

    raise DataIngestionError(final_message)