File size: 10,923 Bytes
72fc0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
FRED (Federal Reserve Economic Data) API Client

Provides access to economic indicators from the St. Louis Federal Reserve:
- GDP, unemployment, inflation data
- Interest rates and yield curves  
- Manufacturing indicators (PMI)
- Consumer sentiment and confidence

API Documentation: https://fred.stlouisfed.org/docs/api/
"""

import logging
import os
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple

import pandas as pd
import requests

from quantlib_pro.utils.validation import require_positive

log = logging.getLogger(__name__)


class FREDError(Exception):
    """Raised when FRED API returns an error."""


class FREDClient:
    """
    FRED (Federal Reserve Economic Data) API client.
    
    Features:
    - 30+ key economic indicators
    - Historical time series data
    - Automatic caching and rate limiting
    - Data validation and cleaning
    
    Parameters
    ----------
    api_key : str, optional
        FRED API key. If None, reads from FRED_API_KEY env var.
    base_url : str
        API base URL (default: https://api.stlouisfed.org/fred)
    timeout : int
        Request timeout in seconds (default: 30)
    
    Examples
    --------
    >>> client = FREDClient()
    >>> gdp = client.get_gdp_growth()
    >>> unemployment = client.get_unemployment_rate()
    >>> rates = client.get_interest_rates()
    """
    
    BASE_URL = "https://api.stlouisfed.org/fred"
    
    # Key Economic Series IDs
    SERIES_MAP = {
        # Growth Indicators
        'gdp': 'GDP',                           # Gross Domestic Product
        'gdp_growth': 'A191RL1Q225SBEA',        # Real GDP Growth Rate
        'industrial_production': 'INDPRO',      # Industrial Production Index
        
        # Employment
        'unemployment': 'UNRATE',               # Unemployment Rate
        'employment': 'PAYEMS',                 # Nonfarm Payrolls
        'labor_force': 'CIVPART',               # Labor Force Participation Rate
        
        # Inflation  
        'cpi': 'CPIAUCSL',                      # Consumer Price Index
        'cpi_core': 'CPILFESL',                 # Core CPI (ex food & energy)
        'ppi': 'PPIACO',                        # Producer Price Index
        'pce': 'PCE',                           # Personal Consumption Expenditures
        
        # Interest Rates
        'fed_funds': 'FEDFUNDS',                # Federal Funds Rate
        'treasury_10y': 'GS10',                 # 10-Year Treasury
        'treasury_2y': 'GS2',                   # 2-Year Treasury
        'treasury_3m': 'GS3M',                  # 3-Month Treasury
        
        # Financial Indicators
        'vix': 'VIXCLS',                        # VIX Volatility Index
        'sp500': 'SP500',                       # S&P 500 Index
        'dollar_index': 'DTWEXBGS',             # Trade Weighted US Dollar Index
        
        # Manufacturing & Business
        'ism_pmi': 'NAPM',                      # ISM Manufacturing PMI
        'capacity_utilization': 'TCU',          # Capacity Utilization
        
        # Consumer & Housing
        'consumer_sentiment': 'UMCSENT',        # University of Michigan Consumer Sentiment
        'consumer_confidence': 'CSCICP03USM665S', # Consumer Confidence Index  
        'housing_starts': 'HOUST',              # Housing Starts
        'existing_home_sales': 'EXHOSLUSM495S', # Existing Home Sales
    }
    
    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = None,
        timeout: int = 30,
    ):
        self.api_key = api_key or os.getenv("FRED_API_KEY")
        if not self.api_key:
            raise ValueError(
                "FRED API key required. Set FRED_API_KEY environment variable "
                "or pass api_key parameter. Get key: https://fred.stlouisfed.org/docs/api/api_key.html"
            )
        
        self.base_url = (base_url or self.BASE_URL).rstrip("/")
        self.timeout = timeout
        
        # Session for connection pooling
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'QuantLib-Pro-FRED-Client/1.0'
        })
    
    def _make_request(self, endpoint: str, params: Dict) -> Dict:
        """Make authenticated request to FRED API."""
        params['api_key'] = self.api_key
        params['file_type'] = 'json'
        
        url = f"{self.base_url}/{endpoint}"
        
        try:
            response = self.session.get(url, params=params, timeout=self.timeout)
            response.raise_for_status()
            data = response.json()
            
            # Check for FRED API errors
            if 'error_message' in data:
                raise FREDError(f"FRED API error: {data['error_message']}")
            
            return data
            
        except requests.RequestException as e:
            log.error(f"FRED API request failed: {e}")
            raise FREDError(f"Request failed: {e}")
    
    def get_series(
        self,
        series_id: str,
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        limit: int = 1000,
    ) -> pd.DataFrame:
        """
        Get time series data for a FRED series.
        
        Parameters
        ----------
        series_id : str
            FRED series identifier (e.g., 'GDP', 'UNRATE')
        start_date : str, optional
            Start date in YYYY-MM-DD format
        end_date : str, optional  
            End date in YYYY-MM-DD format
        limit : int
            Maximum number of observations
        
        Returns
        -------
        pd.DataFrame
            Time series with date index and value column
        """
        params = {
            'series_id': series_id,
            'limit': limit,
            'sort_order': 'desc',
        }
        
        if start_date:
            params['start_date'] = start_date
        if end_date:
            params['end_date'] = end_date
        
        data = self._make_request('series/observations', params)
        
        if 'observations' not in data or not data['observations']:
            log.warning(f"No data returned for series {series_id}")
            return pd.DataFrame()
        
        # Convert to DataFrame
        df = pd.DataFrame(data['observations'])
        
        # Clean and convert data
        df['date'] = pd.to_datetime(df['date'])
        df['value'] = pd.to_numeric(df['value'], errors='coerce')
        
        # Filter out missing values
        df = df.dropna(subset=['value'])
        
        # Set date as index and sort
        df = df.set_index('date').sort_index()
        
        return df[['value']]
    
    def get_latest_value(self, series_id: str) -> Tuple[float, str]:
        """
        Get the latest value for a FRED series.
        
        Returns
        -------
        tuple
            (latest_value, date_string)
        """
        df = self.get_series(series_id, limit=1)
        if df.empty:
            raise FREDError(f"No data available for series {series_id}")
        
        latest_value = df.iloc[-1]['value']
        latest_date = df.index[-1].strftime('%Y-%m-%d')
        
        return latest_value, latest_date
    
    def get_gdp_growth(self, periods: int = 8) -> pd.DataFrame:
        """Get quarterly GDP growth rate (last 2 years)."""
        return self.get_series('A191RL1Q225SBEA', limit=periods)
    
    def get_unemployment_rate(self, periods: int = 24) -> pd.DataFrame:
        """Get monthly unemployment rate (last 2 years)."""
        return self.get_series('UNRATE', limit=periods)
    
    def get_inflation_rate(self, periods: int = 24) -> pd.DataFrame:
        """Get monthly CPI inflation rate (last 2 years)."""
        return self.get_series('CPIAUCSL', limit=periods)
    
    def get_interest_rates(self, periods: int = 60) -> pd.DataFrame:
        """Get key interest rates (last 5 years)."""
        rates_data = {}
        
        for name, series_id in [
            ('fed_funds', 'FEDFUNDS'),
            ('treasury_10y', 'GS10'), 
            ('treasury_2y', 'GS2'),
            ('treasury_3m', 'GS3M'),
        ]:
            try:
                df = self.get_series(series_id, limit=periods)
                if not df.empty:
                    rates_data[name] = df['value']
            except Exception as e:
                log.warning(f"Failed to fetch {name}: {e}")
        
        return pd.DataFrame(rates_data)
    
    def get_manufacturing_pmi(self, periods: int = 24) -> pd.DataFrame:
        """Get ISM Manufacturing PMI (last 2 years)."""
        return self.get_series('NAPM', limit=periods)
    
    def get_consumer_sentiment(self, periods: int = 24) -> pd.DataFrame:
        """Get University of Michigan Consumer Sentiment (last 2 years)."""
        return self.get_series('UMCSENT', limit=periods)
    
    def get_macro_snapshot(self) -> Dict[str, float]:
        """
        Get current snapshot of key macro indicators.
        
        Returns
        -------
        dict
            Latest values for key economic indicators
        """
        snapshot = {}
        
        indicators = [
            ('gdp_growth', 'A191RL1Q225SBEA'),
            ('unemployment', 'UNRATE'),
            ('inflation', 'CPIAUCSL'),
            ('fed_funds_rate', 'FEDFUNDS'),
            ('treasury_10y', 'GS10'),
            ('pmi', 'NAPM'),
            ('consumer_sentiment', 'UMCSENT'),
        ]
        
        for name, series_id in indicators:
            try:
                value, date = self.get_latest_value(series_id)
                snapshot[name] = value
                snapshot[f'{name}_date'] = date
            except Exception as e:
                log.warning(f"Failed to fetch {name}: {e}")
                snapshot[name] = None
        
        return snapshot
    
    def get_yield_curve(self) -> pd.DataFrame:
        """
        Get current yield curve (3M, 2Y, 5Y, 10Y, 30Y).
        
        Returns
        -------
        pd.DataFrame
            Current yield curve rates
        """
        curve_series = {
            '3M': 'GS3M',
            '2Y': 'GS2', 
            '5Y': 'GS5',
            '10Y': 'GS10',
            '30Y': 'GS30',
        }
        
        rates = {}
        for maturity, series_id in curve_series.items():
            try:
                value, _ = self.get_latest_value(series_id)
                rates[maturity] = value
            except Exception as e:
                log.warning(f"Failed to fetch {maturity} rate: {e}")
        
        return pd.DataFrame([rates], index=['Current'])
    
    def __repr__(self):
        return f"FREDClient(base_url='{self.base_url}')"


# Convenience function for creating client
def create_fred_client(api_key: Optional[str] = None) -> FREDClient:
    """Create FRED client with optional API key."""
    return FREDClient(api_key=api_key)