ifieryarrows commited on
Commit
8da8a14
·
verified ·
1 Parent(s): 7919961

Sync from GitHub (tests passed)

Browse files
deep_learning/data/feature_store.py CHANGED
@@ -249,18 +249,25 @@ def _build_daily_embedding_features(
249
  def build_tft_dataframe(
250
  session,
251
  cfg: Optional[TFTASROConfig] = None,
 
 
252
  ) -> tuple[pd.DataFrame, list[str], list[str], list[str], float]:
253
  """
254
  Build the master DataFrame for TFT training / inference.
255
 
256
  Returns:
257
- (df, time_varying_unknown_reals, time_varying_known_reals, target_cols)
258
 
259
  The returned df has:
260
  - "time_idx" : integer time index (required by pytorch_forecasting)
261
  - "group_id" : constant "copper" (single series)
262
  - "target" : next-day simple return
263
  - columns for all three TFT feature categories
 
 
 
 
 
264
  """
265
  if cfg is None:
266
  cfg = get_tft_config()
@@ -369,8 +376,11 @@ def build_tft_dataframe(
369
  master = pd.concat(parts, axis=1)
370
  master = master.loc[target_index]
371
 
372
- valid_mask = master["target"].notna()
373
- master = master[valid_mask].copy()
 
 
 
374
 
375
  master = master.fillna(0.0)
376
 
 
249
  def build_tft_dataframe(
250
  session,
251
  cfg: Optional[TFTASROConfig] = None,
252
+ *,
253
+ drop_missing_target: bool = True,
254
  ) -> tuple[pd.DataFrame, list[str], list[str], list[str], float]:
255
  """
256
  Build the master DataFrame for TFT training / inference.
257
 
258
  Returns:
259
+ (df, time_varying_unknown_reals, time_varying_known_reals, target_cols, last_close)
260
 
261
  The returned df has:
262
  - "time_idx" : integer time index (required by pytorch_forecasting)
263
  - "group_id" : constant "copper" (single series)
264
  - "target" : next-day simple return
265
  - columns for all three TFT feature categories
266
+
267
+ Training and validation need complete next-day targets, so the default
268
+ drops rows where ``target`` is missing. Live inference needs the latest
269
+ observed bar as the forecast anchor, so callers can keep that final row
270
+ and let the missing target be filled with a neutral dummy value.
271
  """
272
  if cfg is None:
273
  cfg = get_tft_config()
 
376
  master = pd.concat(parts, axis=1)
377
  master = master.loc[target_index]
378
 
379
+ if drop_missing_target:
380
+ valid_mask = master["target"].notna()
381
+ master = master[valid_mask].copy()
382
+ else:
383
+ master = master.copy()
384
 
385
  master = master.fillna(0.0)
386
 
deep_learning/inference/predictor.py CHANGED
@@ -136,28 +136,44 @@ class TFTPredictor:
136
  - baseline_staleness_days (int, 0 = fresh)
137
  """
138
  from deep_learning.data.feature_store import build_tft_dataframe
139
- from deep_learning.data.dataset import build_datasets, create_dataloaders
140
  from deep_learning.models.tft_copper import format_prediction
141
  from pytorch_forecasting import TimeSeriesDataSet
142
 
143
  # 1. Pre-flight: check PriceBar freshness and lazy-ingest if stale
144
  staleness_days, ingest_triggered = self._check_price_freshness(session, symbol)
145
 
146
- master_df, tv_unknown, tv_known, target_cols, last_known_price = build_tft_dataframe(session, self.cfg)
 
 
 
 
147
 
148
- # Extract the date of the baseline price so the frontend can show
149
- # "% change relative to <date> close" unambiguously.
150
- reference_price_date: Optional[str] = None
 
151
  try:
152
  if hasattr(master_df.index, "max"):
153
  last_date = master_df.index.max()
154
- reference_price_date = str(last_date)[:10] if last_date is not None else None
155
  except Exception:
156
- reference_price_date = None
 
 
 
 
 
 
 
157
 
158
  logger.info(
159
- "TFT predict: baseline_price=%.4f (date=%s) for %s",
160
- last_known_price, reference_price_date, symbol,
 
 
 
 
 
161
  )
162
 
163
  encoder_length = self.cfg.model.max_encoder_length
@@ -222,7 +238,7 @@ class TFTPredictor:
222
  result = format_prediction(
223
  pred_for_format,
224
  quantiles=self.cfg.model.quantiles,
225
- baseline_price=last_known_price,
226
  reference_price_date=reference_price_date,
227
  )
228
 
@@ -274,6 +290,57 @@ class TFTPredictor:
274
  {"symbol": symbol, "kind": "unknown", "name": symbol, "note": ""},
275
  )
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  def _check_price_freshness(self, session, symbol: str) -> tuple[int, bool]:
278
  """
279
  Compute staleness in calendar days for the target symbol and, when
 
136
  - baseline_staleness_days (int, 0 = fresh)
137
  """
138
  from deep_learning.data.feature_store import build_tft_dataframe
 
139
  from deep_learning.models.tft_copper import format_prediction
140
  from pytorch_forecasting import TimeSeriesDataSet
141
 
142
  # 1. Pre-flight: check PriceBar freshness and lazy-ingest if stale
143
  staleness_days, ingest_triggered = self._check_price_freshness(session, symbol)
144
 
145
+ master_df, tv_unknown, tv_known, target_cols, last_known_price = build_tft_dataframe(
146
+ session,
147
+ self.cfg,
148
+ drop_missing_target=False,
149
+ )
150
 
151
+ # Track feature freshness separately from the baseline close. In live
152
+ # inference the feature frame keeps the final bar with a dummy target,
153
+ # while training still drops it.
154
+ feature_last_date: Optional[str] = None
155
  try:
156
  if hasattr(master_df.index, "max"):
157
  last_date = master_df.index.max()
158
+ feature_last_date = self._date_label(last_date)
159
  except Exception:
160
+ feature_last_date = None
161
+
162
+ baseline_price, reference_price_date = self._latest_price_baseline(
163
+ session,
164
+ symbol,
165
+ fallback_price=last_known_price,
166
+ fallback_date=feature_last_date,
167
+ )
168
 
169
  logger.info(
170
+ "TFT predict: baseline_price=%.4f reference_price_date=%s "
171
+ "feature_last_date=%s baseline_staleness_days=%s for %s",
172
+ baseline_price,
173
+ reference_price_date,
174
+ feature_last_date,
175
+ staleness_days,
176
+ symbol,
177
  )
178
 
179
  encoder_length = self.cfg.model.max_encoder_length
 
238
  result = format_prediction(
239
  pred_for_format,
240
  quantiles=self.cfg.model.quantiles,
241
+ baseline_price=baseline_price,
242
  reference_price_date=reference_price_date,
243
  )
244
 
 
290
  {"symbol": symbol, "kind": "unknown", "name": symbol, "note": ""},
291
  )
292
 
293
+ @staticmethod
294
+ def _date_label(value: Any) -> Optional[str]:
295
+ """Format a date-like value as YYYY-MM-DD for API/log fields."""
296
+ if value is None:
297
+ return None
298
+ try:
299
+ return value.date().isoformat()
300
+ except AttributeError:
301
+ return str(value)[:10]
302
+ except Exception:
303
+ return None
304
+
305
+ def _latest_price_baseline(
306
+ self,
307
+ session,
308
+ symbol: str,
309
+ *,
310
+ fallback_price: float,
311
+ fallback_date: Optional[str],
312
+ ) -> tuple[float, Optional[str]]:
313
+ """
314
+ Return the latest close and date from PriceBar.
315
+
316
+ The feature frame may drop or dummy-fill the final target depending on
317
+ training vs inference mode. Baseline reporting must therefore come from
318
+ the canonical price table, not from the post-target-filter frame.
319
+ """
320
+ baseline_price = fallback_price
321
+ reference_price_date = fallback_date
322
+
323
+ try:
324
+ from app.models import PriceBar
325
+
326
+ latest_bar = (
327
+ session.query(PriceBar)
328
+ .filter(PriceBar.symbol == symbol)
329
+ .order_by(PriceBar.date.desc())
330
+ .first()
331
+ )
332
+ if latest_bar is not None and latest_bar.close is not None:
333
+ baseline_price = float(latest_bar.close)
334
+ reference_price_date = self._date_label(latest_bar.date)
335
+ except Exception as exc:
336
+ logger.warning(
337
+ "Latest PriceBar baseline lookup failed for %s; using feature fallback: %s",
338
+ symbol,
339
+ exc,
340
+ )
341
+
342
+ return baseline_price, reference_price_date
343
+
344
  def _check_price_freshness(self, session, symbol: str) -> tuple[int, bool]:
345
  """
346
  Compute staleness in calendar days for the target symbol and, when