ckharche commited on
Commit
bfda30f
·
verified ·
1 Parent(s): 29c6f86

Update trade_analysis/data.py

Browse files
Files changed (1) hide show
  1. trade_analysis/data.py +36 -40
trade_analysis/data.py CHANGED
@@ -54,52 +54,48 @@ class UnifiedDataProvider:
54
  return data
55
  return None
56
 
 
57
  async def fetch_multi_timeframe_stock_data(self, symbol: str) -> dict:
58
  """
59
- Fetches OHLCV data from Finnhub for multiple timeframes.
60
- This completely replaces the unreliable yfinance implementation.
61
  """
62
- print(f"Fetching Finnhub OHLCV for {symbol}...")
63
  dfs = {}
64
-
65
- # Mapping from our names to Finnhub's resolution codes and time periods
66
- timeframes = {
67
- "daily": ("D", 90), # Daily data for the last year
68
- # "hourly": ("60", 28), # Hourly data for the last 2 years
69
- # "15m": ("15", 7), # 15-minute data for the last 60 days
70
- # "5m": ("5", 2),
71
- }
72
-
73
- base_url = "https://finnhub.io/api/v1/stock/candle"
74
-
75
- for name, (resolution, days_back) in timeframes.items():
76
- end_ts = int(datetime.now().timestamp())
77
- start_ts = int((datetime.now() - timedelta(days=days_back)).timestamp())
78
-
79
- params = {
80
- "symbol": symbol,
81
- "resolution": resolution,
82
- "from": start_ts,
83
- "to": end_ts,
84
- "token": config.FINNHUB_KEY
85
- }
86
-
87
- try:
88
- res = await self.client.get(base_url, params=params)
89
- res.raise_for_status()
90
- data = res.json()
91
- processed_df = _process_finnhub_data(data, symbol)
92
 
93
- if not processed_df.empty:
94
- print(f" - Fetched and processed {len(processed_df)} points for {name} interval from Finnhub.")
95
- dfs[name] = processed_df
96
- else:
97
- dfs[name] = pd.DataFrame()
98
- except (httpx.RequestError, httpx.HTTPStatusError) as e:
99
- print(f"ERROR: Finnhub OHLCV request failed for {symbol} ({name}): {e}")
100
- dfs[name] = pd.DataFrame()
 
 
 
101
  return dfs
102
-
103
  async def fetch_news(self, symbol: str, days: int = 3) -> tuple:
104
  """Fetches news from Finnhub, with local file fallback."""
105
  local_data = self._load_local_data(symbol)
 
54
  return data
55
  return None
56
 
57
+
58
  async def fetch_multi_timeframe_stock_data(self, symbol: str) -> dict:
59
  """
60
+ REWRITTEN FOR FREE TIER: Fetches the current day's quote data from Finnhub.
61
+ Historical candle data is a premium feature.
62
  """
63
+ print(f"Fetching Finnhub REAL-TIME QUOTE for {symbol}...")
64
  dfs = {}
65
+ base_url = "https://finnhub.io/api/v1/quote"
66
+ params = {"symbol": symbol, "token": config.FINNHUB_KEY}
67
+
68
+ try:
69
+ res = await self.client.get(base_url, params=params)
70
+ res.raise_for_status()
71
+ data = res.json()
72
+
73
+ if data and 'c' in data and data['c'] != 0:
74
+ # Create a single-row DataFrame
75
+ df = pd.DataFrame([{
76
+ 'Open': data['o'],
77
+ 'High': data['h'],
78
+ 'Low': data['l'],
79
+ 'Close': data['c'],
80
+ # Volume is not in the quote endpoint, so we put a placeholder
81
+ 'Volume': 0
82
+ }])
83
+ # Use the current time for the index
84
+ df.index = pd.to_datetime([datetime.now(tz=pytz.UTC)])
 
 
 
 
 
 
 
 
85
 
86
+ # Since we only have one row, we can't do multi-timeframe.
87
+ # We will return this single row for the 'daily' key.
88
+ dfs["daily"] = df
89
+ print(f" - Fetched real-time quote for {symbol} from Finnhub.")
90
+ else:
91
+ dfs["daily"] = pd.DataFrame()
92
+
93
+ except (httpx.RequestError, httpx.HTTPStatusError) as e:
94
+ print(f"ERROR: Finnhub Quote request failed for {symbol}: {e}")
95
+ dfs["daily"] = pd.DataFrame()
96
+
97
  return dfs
98
+
99
  async def fetch_news(self, symbol: str, days: int = 3) -> tuple:
100
  """Fetches news from Finnhub, with local file fallback."""
101
  local_data = self._load_local_data(symbol)