Upload runtime.py
Browse files181 unmodified lines1821831841851861871108 unmodified lines12961297129812991300130113023 unmodified lines130613071308130913101311131213131314131513161317131813193 unmodified lines1323132413251326132713281329133013311332119 unmodified lines1452145314541455145614571458181 unmodified linesreturn pd.Timestamp(schedule.index[-1]).date()class ProbabilityBlend:def __init__(self, models: list[Any], weights: np.ndarray):self.models = models1108 unmodified linesdef build_prediction_track_record(daily: pd.DataFrame,sessions: int = 10,) -> list[dict[str, Any]]:"""Rolling last-N Tomorrow simulation: predict each session, score vs prior close."""3 unmodified linesfallback_prob = float(summary.get("latest_forecast_prob_up", 0.49900560447008563))forecaster_by_target = _load_forecaster_predictions_by_target()daily_rows = daily.copy()daily_rows["date"] = pd.to_datetime(daily_rows["date"], errors="coerce").dt.normalize()daily_rows = daily_rows.dropna(subset=["date"]).sort_values("date")daily_rows = daily_rows[daily_rows["close"].map(lambda value: np.isfinite(float(value)) if pd.notna(value) else False)].copy()completed_day = expected_completed_daily_date()daily_rows = daily_rows[daily_rows["date"].dt.date <= completed_day]if daily_rows.empty:return []3 unmodified linesif pd.notna(row["close"]) and np.isfinite(float(row["close"]))}records: list[dict[str, Any]] = []for _, row in daily_rows.tail(sessions).iterrows():target_day = row["date"].date()day_close = float(row["close"])actual_move, actual_direction = _tomorrow_actual_outcome(target_day, day_close, closes_by_date)if actual_direction is None:continue119 unmodified lines"total_test_days": int(tomorrow_summary.get("n_test") or len(tomorrow_test) or 0),"models": model_metrics,}track_record = build_prediction_track_record(daily, sessions=10)return {"latest": t5_latest,"tomorrow_latest": tomorrow_latest,181 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112121108 unmodified lines1321132213231324132513263 unmodified lines133013311332133313341335133613371338133913401341134213431344134513461347134813493 unmodified lines1353135413551356135713581359136013611362136313641365119 unmodified lines1485148614871488148914901491181 unmodified linesreturn pd.Timestamp(schedule.index[-1]).date()def last_n_trading_sessions(end_day: date, count: int) -> list[date]:"""Return the last ``count`` NSE sessions ending on (or before) ``end_day``."""sessions: list[date] = []cursor = end_dayguard = 0while len(sessions) < count and guard < count * 12:guard += 1if is_trading_day(cursor):sessions.append(cursor)if len(sessions) >= count:breakcursor = previous_trading_day(cursor - timedelta(days=1))sessions.reverse()return sessionsdef _track_record_end_session(now: datetime | None = None) -> date:"""Latest session the track record should score (today after the close refresh window)."""now = now or datetime.now(IST)today = now.date()if is_trading_day(today) and now.time() >= CLOSE_REFRESH_READY:return todayreturn expected_completed_daily_date(now)class ProbabilityBlend:def __init__(self, models: list[Any], weights: np.ndarray):self.models = models1108 unmodified linesdef build_prediction_track_record(sessions: int = 10,) -> list[dict[str, Any]]:"""Rolling last-N Tomorrow simulation: predict each session, score vs prior close."""3 unmodified linesfallback_prob = float(summary.get("latest_forecast_prob_up", 0.49900560447008563))forecaster_by_target = _load_forecaster_predictions_by_target()end_session = _track_record_end_session()latest_daily = latest_parquet_date(NIFTY_1D_PATH)if latest_daily is None or latest_daily < end_session:try:refresh_daily_data()except Exception:passdaily_rows = pd.read_parquet(NIFTY_1D_PATH)daily_rows["date"] = pd.to_datetime(daily_rows["date"], errors="coerce").dt.normalize()daily_rows = daily_rows.dropna(subset=["date"]).sort_values("date")daily_rows = daily_rows[daily_rows["close"].map(lambda value: np.isfinite(float(value)) if pd.notna(value) else False)].copy()if daily_rows.empty:return []3 unmodified linesif pd.notna(row["close"]) and np.isfinite(float(row["close"]))}session_dates = last_n_trading_sessions(end_session, sessions)records: list[dict[str, Any]] = []for target_day in session_dates:day_close = closes_by_date.get(target_day)if day_close is None:continueactual_move, actual_direction = _tomorrow_actual_outcome(target_day, day_close, closes_by_date)if actual_direction is None:continue119 unmodified lines"total_test_days": int(tomorrow_summary.get("n_test") or len(tomorrow_test) or 0),"models": model_metrics,}track_record = build_prediction_track_record(sessions=10)return {"latest": t5_latest,"tomorrow_latest": tomorrow_latest,
runtime.py+41-8