from __future__ import annotations from datetime import datetime, time import pandas as pd MARKET_OPEN = time(9, 15) MARKET_CLOSE = time(15, 30) HOUR_MARKS = [time(9,15), time(10,15), time(11,15), time(12,15), time(13,15), time(14,15), time(15,15), time(15,30)] def hour_passed(t: datetime) -> int: order = [time(10,15), time(11,15), time(12,15), time(13,15), time(14,15), time(15,15)] return order.index(t.time()) + 1 if t.time() in order else 0 def filter_timerange(df: pd.DataFrame, col: str, start: datetime, end: datetime) -> pd.DataFrame: mask = (df[col] >= start) & (df[col] < end) return df.loc[mask].copy() def ohlc_day(df: pd.DataFrame, dt_col: str, day: datetime) -> tuple[float,float,float,float]: d = df[df[dt_col].dt.date == day.date()] if d.empty: raise ValueError(f"No data for {day.date()}") o = float(d.iloc[0]["open"]) h = float(d["high"].max()) l = float(d["low"].min()) c = float(d.iloc[-1]["close"]) return o, h, l, c def ohlc_at(df: pd.DataFrame, dt_col: str, ts: datetime) -> tuple[float,float,float,float]: row = df.loc[df[dt_col] == ts] if row.empty: raise ValueError(f"No bar at {ts}") r = row.iloc[0] return float(r["open"]), float(r["high"]), float(r["low"]), float(r["close"]) def hourly_ohlc_dict(df: pd.DataFrame, dt_col: str, now: datetime) -> dict: """Return a nested dict of each completed hour's OHLC up to `now`.""" hours = [h for h in HOUR_MARKS if h < now.time()] out = {} names = ["first_hour","second_hour","third_hour","fourth_hour","fifth_hour","sixth_hour","last_15_minutes"] for i, h in enumerate(hours): try: o,hhi,llo,c = ohlc_at(df, dt_col, datetime.combine(now.date(), h)) out[names[i]] = {"open": o, "high": hhi, "low": llo, "close": c} except Exception: pass return out