File size: 7,097 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
"""
Market data provider - unified interface for fetching financial data.

This module provides a high-level interface to the ResilientDataFetcher
for easier use in UI components.
"""

from __future__ import annotations

import logging
from datetime import datetime, timedelta
from typing import Optional

import pandas as pd

from quantlib_pro.data.fetcher import ResilientDataFetcher, DataFetchError
from quantlib_pro.data.providers import DataProvider

log = logging.getLogger(__name__)


class MarketDataProvider:
    """
    High-level market data provider with caching and fallback.
    
    This class wraps the ResilientDataFetcher to provide a simpler
    interface for UI components and analysis tools.
    
    Parameters
    ----------
    redis_client : optional
        Pre-built Redis client for caching (default: None)
    cache_ttl : int
        Cache time-to-live in seconds (default: 3600 = 1 hour)
    """
    
    def __init__(self, redis_client=None, cache_ttl=3600):
        self.fetcher = ResilientDataFetcher(
            redis_client=redis_client,
            cache_ttl=cache_ttl
        )
    
    def get_stock_data(
        self,
        ticker: str,
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        period: str = "1y"
    ) -> pd.DataFrame:
        """
        Fetch historical stock price data.
        
        Parameters
        ----------
        ticker : str
            Stock ticker symbol (e.g., 'AAPL', 'SPY')
        start_date : str, optional
            Start date in 'YYYY-MM-DD' format
        end_date : str, optional
            End date in 'YYYY-MM-DD' format
        period : str, optional
            Period string ('1y', '6mo', '3mo', etc.) if dates not specified
        
        Returns
        -------
        pd.DataFrame
            DataFrame with OHLCV columns and DatetimeIndex
        
        Raises
        ------
        DataFetchError
            If data cannot be fetched from any source
        """
        try:
            result = self.fetcher.fetch(
                ticker=ticker,
                start=start_date,
                end=end_date,
                period=period
            )
            return result.df
        except DataFetchError as e:
            log.error(f"Failed to fetch data for {ticker}: {e}")
            raise
    
    def get_multiple_stocks(
        self,
        tickers: list[str],
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        period: str = "1y"
    ) -> dict[str, pd.DataFrame]:
        """
        Fetch data for multiple stocks.
        
        Parameters
        ----------
        tickers : list[str]
            List of ticker symbols
        start_date, end_date, period : optional
            Same as get_stock_data()
        
        Returns
        -------
        dict[str, pd.DataFrame]
            Dictionary mapping ticker to DataFrame
        """
        results = {}
        for ticker in tickers:
            try:
                results[ticker] = self.get_stock_data(
                    ticker, start_date, end_date, period
                )
                log.info(f"Fetched data for {ticker}")
            except DataFetchError as e:
                log.warning(f"Skipping {ticker}: {e}")
        
        return results
    
    def get_returns(
        self,
        ticker: str,
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        period: str = "1y"
    ) -> pd.Series:
        """
        Fetch historical returns (percent change in adjusted close).
        
        Returns
        -------
        pd.Series
            Daily returns as decimal (e.g., 0.01 = 1% return)
        """
        data = self.get_stock_data(ticker, start_date, end_date, period)
        
        # Use Adj Close if available, otherwise Close
        price_col = 'Adj Close' if 'Adj Close' in data.columns else 'Close'
        returns = data[price_col].pct_change().dropna()
        
        return returns
    
    def get_correlation_matrix(
        self,
        tickers: list[str],
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        period: str = "1y"
    ) -> pd.DataFrame:
        """
        Calculate correlation matrix for a set of stocks.
        
        Parameters
        ----------
        tickers : list[str]
            List of ticker symbols
        start_date, end_date, period : optional
            Date range parameters
        
        Returns
        -------
        pd.DataFrame
            Correlation matrix (tickers x tickers)
        """
        # Fetch returns for all tickers
        returns_dict = {}
        for ticker in tickers:
            try:
                returns_dict[ticker] = self.get_returns(
                    ticker, start_date, end_date, period
                )
            except DataFetchError:
                log.warning(f"Skipping {ticker} in correlation calculation")
        
        if not returns_dict:
            raise DataFetchError("No data available for correlation matrix")
        
        # Combine into DataFrame and calculate correlation
        returns_df = pd.DataFrame(returns_dict)
        return returns_df.corr()
    
    def get_covariance_matrix(
        self,
        tickers: list[str],
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        period: str = "1y"
    ) -> pd.DataFrame:
        """
        Calculate covariance matrix for a set of stocks.
        
        Returns
        -------
        pd.DataFrame
            Covariance matrix (annualized)
        """
        returns_dict = {}
        for ticker in tickers:
            try:
                returns_dict[ticker] = self.get_returns(
                    ticker, start_date, end_date, period
                )
            except DataFetchError:
                log.warning(f"Skipping {ticker} in covariance calculation")
        
        if not returns_dict:
            raise DataFetchError("No data available for covariance matrix")
        
        returns_df = pd.DataFrame(returns_dict)
        # Annualize covariance (assuming daily data, 252 trading days)
        return returns_df.cov() * 252
    
    def get_expected_returns(
        self,
        tickers: list[str],
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        period: str = "1y"
    ) -> pd.Series:
        """
        Calculate expected returns (historical mean).
        
        Returns
        -------
        pd.Series
            Dictionary of expected annual returns
        """
        expected_returns = {}
        for ticker in tickers:
            try:
                returns = self.get_returns(ticker, start_date, end_date, period)
                # Annualize mean return (assuming 252 trading days)
                expected_returns[ticker] = returns.mean() * 252
            except DataFetchError:
                log.warning(f"Skipping {ticker} in expected returns calculation")
        
        return pd.Series(expected_returns)