from __future__ import annotations import pandas as pd from datetime import datetime, timedelta from typing import Optional, Dict, Any, List, Literal, Hashable, cast from .models import PositionState, TradePlan, SummaryBankNifty, DecisionOutput from .llm import LLMClient from .prompts import ( USER_MORNING, USER_DECIDE_TRADE, USER_INTRAHOUR_UPDATE, USER_INTRAHOUR_UPDATE_2, USER_CLOSING, ) from .utils import hour_passed, hourly_ohlc_dict from .simulator import simulate_trade_from_signal, slice_intraday from .news import summaries_between from .writer import to_excel_safely from .checkpoint import CheckpointManager class Engine: def __init__(self, *, llm: LLMClient, logger, bundle, out_dir, checkpoint: CheckpointManager): self.llm = llm self.log = logger self.bundle = bundle self.out_dir = out_dir self.ckpt = checkpoint # --- Restore from checkpoint if available --- ( self.last_timestamp_processed, self.state, self.current_plan, self.last_close_plan, self.memory_str, loaded_logs, ) = self.ckpt.load() # In-memory logs we keep appending to this run def _seed(df: pd.DataFrame) -> List[Dict[str, Any]]: return cast(List[Dict[str, Any]], df.to_dict(orient="records") if not df.empty else []) self.trade_log = _seed(loaded_logs["trade"]) self.stats_log = _seed(loaded_logs["stats"]) self.expert_log = _seed(loaded_logs["expert"]) self.summary_log = _seed(loaded_logs["summary"]) # Rolling context across ticks self.last_summary_bn: Optional[SummaryBankNifty] = None self.last_sentiment: Optional[str] = None self.morning_summary_full = None # morning Summary (banknifty/nifty prep) self.last_slice_start: Optional[datetime] = None # anchor for intraday sim slices # ------------------------------------------------------------------ # Utilities for saving, market data extraction, and forced exits # ------------------------------------------------------------------ def _flush_to_excels(self): """Write human-friendly Excel snapshots at the very end of run().""" to_excel_safely(pd.DataFrame(self.stats_log), self.out_dir / "stats_log.xlsx") to_excel_safely(pd.DataFrame(self.trade_log), self.out_dir / "trade_log.xlsx") to_excel_safely(pd.DataFrame(self.expert_log), self.out_dir / "expert_log.xlsx") to_excel_safely(pd.DataFrame(self.summary_log), self.out_dir / "summary_log.xlsx") def _save_checkpoint_now(self, ts: datetime): """Persist all critical state + logs after processing timestamp ts.""" self.ckpt.save( last_ts=ts, state=self.state, current_plan=self.current_plan, last_close_plan=self.last_close_plan, memory_str=self.memory_str, trade_log=self.trade_log, stats_log=self.stats_log, expert_log=self.expert_log, summary_log=self.summary_log, ) self.last_timestamp_processed = ts def _sentiment_for(self, day: datetime): df = self.bundle.df_sentiment row = df[df["predicted_for"].dt.date == day.date()] if row.empty: return ("neutral", "No sentiment row found") return ( row.iloc[0]["proposed_sentiment"], row.iloc[0].get("reasoning", ""), ) def _expert_text(self, day: datetime) -> str: df = self.bundle.df_transcript # try to detect a column like "Prediction_for_date" date_cols = [c for c in df.columns if c.lower().startswith("prediction_for")] dt_col = date_cols[0] if date_cols else "Prediction_for_date" row = df[df[dt_col].dt.date == day.date()] if row.empty: return "No expert analysis is available; use technicals." return row.iloc[0]["Transcript"] def _day_ohlc(self, df: pd.DataFrame, dt_col: str, day: datetime): 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 {"open": o, "high": h, "low": l, "close": c} def _nifty_prev(self, day: datetime): ohlc = self._day_ohlc(self.bundle.df_nifty_daily, "datetime", day) row = self.bundle.df_nifty_daily[ self.bundle.df_nifty_daily["datetime"].dt.date == day.date() ].iloc[0] return { "ohlc": ohlc, "ind": { "RSI": round(float(row["RSI"]), 2), "MACD_Line": round(float(row["MACD_Line"]), 2), "MACD_Signal": round(float(row["Signal_Line"]), 2), }, } def _bn_prev(self, ts_prev: datetime): ohlc = self._day_ohlc(self.bundle.df_bn_hourly, "datetime", ts_prev) row = self.bundle.df_bn_hourly[ self.bundle.df_bn_hourly["datetime"] == ts_prev ].iloc[0] return { "ohlc": ohlc, "ind": { "RSI": round(float(row["RSI"]), 2), "MACD_Line": round(float(row["MACD_Line"]), 2), "MACD_Signal": round(float(row["Signal_Line"]), 2), }, } def _prev_hour_ts(self, ts: datetime) -> Optional[datetime]: """ Return the last hourly timestamp strictly before `ts` from df_bn_hourly. Used to avoid lookahead when we need 'previous bar' context. """ df = self.bundle.df_bn_hourly col = df["datetime"] prev_candidates = col[col < ts] if prev_candidates.empty: return None return prev_candidates.max() def _force_flatten_position(self, ts: datetime, reason: Literal["target", "stoploss", "Exited at market price","market close"]): """ Exit any open position at the close of timestamp ts. This logs realized stats, updates memory_str, and resets self.state. """ # grab that hour's close as "market exit" close_px = float( self.bundle.df_bn_1m[ self.bundle.df_bn_1m["datetime"] == ts ]["close"].values[0] ) pnl_pct_val = None if self.state.entered and self.state.entry_price is not None: raw = (close_px - self.state.entry_price) / self.state.entry_price if self.state.side == "short": raw = -raw pnl_pct_val = round(raw * 100.0, 4) exited_state = PositionState( entered=True, entry_time=self.state.entry_time, entry_price=self.state.entry_price, side=self.state.side, exited=True, exit_time=ts, exit_price=close_px, exit_reason=reason, pnl_pct=pnl_pct_val, open_position=False, unrealized_pct=None, ) # log exit stats snapshot self.stats_log.append({**exited_state.model_dump(), "datetime": ts}) # update "memory_str" to feed LLM next turn if exited_state.side is not None: self.memory_str = ( "{" f"\"side\": \"{exited_state.side}\", " f"\"entry_price\": {exited_state.entry_price}, " f"\"exit_price\": {exited_state.exit_price}, " f"\"pnl_pct\": {exited_state.pnl_pct}, " f"\"exit_reason\": \"{exited_state.exit_reason}\"" "}" ) else: self.memory_str = "No trade completed" # reset to flat self.state = PositionState() # ------------------------------------------------------------------ # Main replay / inference loop with resume + carry-forward # ------------------------------------------------------------------ def run(self, start_ts: datetime, end_ts: datetime): # Build the list of timestamps to iterate hourly_ts = self.bundle.df_bn_hourly["datetime"] timeline = ( hourly_ts[(hourly_ts >= start_ts) & (hourly_ts <= end_ts)] .sort_values() .tolist() ) if len(timeline) < 2: raise ValueError("Not enough hourly timestamps in range") # Skip timestamps we've already processed (resume support) if self.last_timestamp_processed is not None: timeline = [t for t in timeline if t > self.last_timestamp_processed] # Initialize slice anchor for intraday sim if first time if self.last_slice_start is None: if self.last_timestamp_processed is not None: self.last_slice_start = self.last_timestamp_processed elif timeline: self.last_slice_start = timeline[0] post_must_flatten=False side_change=False for i, ts in enumerate(timeline): self.log.info(f"[Engine] Tick {i}: {ts}") print(ts) # ------------------------------------------------------ # Define "previous bar" for this tick (no lookahead) # ------------------------------------------------------ if i > 0: # previous bar within this run prev_ts = timeline[i - 1] elif self.last_timestamp_processed is not None: # first bar after a resume: use last processed bar prev_ts = self.last_timestamp_processed else: # cold start: pull previous bar from the full dataset prev_ts = self._prev_hour_ts(ts) # ---------------------------------------------------------- # 09:15 block (morning prep and first plan of the session) # ---------------------------------------------------------- if ts.time().hour == 9 and ts.time().minute == 15: if prev_ts is None: raise ValueError("No previous timestamp available for 09:15 logic") bn_prev = self._bn_prev(prev_ts) nf_prev = self._nifty_prev(prev_ts) sentiment, sent_reason = self._sentiment_for(ts) expert_text = self._expert_text(ts) # news = summaries_between( # self.bundle.df_news, "datetime_ist", ts - timedelta(hours=17,minutes=45), ts # ) # 1) Morning summary from LLM user_morning = USER_MORNING.format( nifty_ohlc=nf_prev["ohlc"], nifty_ind=nf_prev["ind"], bn_ohlc=bn_prev["ohlc"], bn_ind=bn_prev["ind"], sentiment=sentiment, sentiment_reason=sent_reason, expert=expert_text, # news=news ) morning_summary = self.llm.morning_summary(user_morning) self.expert_log.append( {**morning_summary.model_dump(), "predicted_for": ts.date()} ) # 2) Build the morning trade decision prompt # priority: # (a) last_close_plan from previous session # (b) current_plan we carried through resume # (c) default "No trade" if self.last_close_plan is not None: opening_trade_context = self.last_close_plan.model_dump() elif self.current_plan is not None: opening_trade_context = self.current_plan.model_dump() else: opening_trade_context = { "status": "No trade", "brief_reason": "init", "type": "none", "entry_at": 0, "target": 0, "stoploss": 0, } user_decide = USER_DECIDE_TRADE.format( major_concern=morning_summary.major_concern_banknifty, sentiment=sentiment, strategy=morning_summary.trade_strategy_banknifty, reason=morning_summary.trade_reasoning_banknifty, bn_ohlc=bn_prev["ohlc"], bn_ind=bn_prev["ind"], trade=opening_trade_context, position=self.state.to_compact(ts), memory=self.memory_str, ) first_plan = self.llm.trade_plan(user_decide) self.current_plan = first_plan post_must_flatten = False side_change = False if self.state.open_position and self.current_plan is not None: if self.current_plan.status == "No trade": post_must_flatten = True elif ( self.current_plan.status == "Trade" and self.current_plan.type != self.state.side ): post_must_flatten = True side_change=True if post_must_flatten: self._force_flatten_position(ts, reason="Exited at market price") self.last_slice_start = ts if side_change: post_must_flatten=False # Commit plan+context self.current_plan = first_plan self.trade_log.append({**first_plan.model_dump(), "datetime": ts}) self.last_sentiment = sentiment self.morning_summary_full = morning_summary self.last_slice_start = ts self._save_checkpoint_now(ts) # ---------------------------------------------------------- # 10:15 block (first intraday decision after open) # ---------------------------------------------------------- elif ts.time().hour == 10 and ts.time().minute == 15: # STEP 1: simulate last slice (last_slice_start -> ts) if self.last_slice_start and self.current_plan and post_must_flatten==False: intraday = slice_intraday(self.bundle.df_bn_1m, self.last_slice_start, ts) if not intraday.empty: new_state = simulate_trade_from_signal( df=intraday, trade=self.current_plan, dt_col="datetime", state=self.state, lookback_minutes=60, ) if self.state.model_dump() != new_state.model_dump(): # We log the transition self.stats_log.append({**new_state.model_dump(), "datetime": ts}) # If the new_state is exited (trade is fully closed), finalize it if new_state.exited and not new_state.open_position: # update memory_str once if new_state.side is not None: self.memory_str = ( "{" f"\"side\": \"{new_state.side}\", " f"\"entry_price\": {new_state.entry_price}, " f"\"exit_price\": {new_state.exit_price}, " f"\"pnl_pct\": {new_state.pnl_pct}, " f"\"exit_reason\": \"{new_state.exit_reason}\"" "}" ) else: self.memory_str = "No trade completed" # reset engine state to flat so we don't keep re-logging this closed trade self.state = PositionState() # after closing, next slice should start from here self.last_slice_start = ts else: # still in position (or haven't entered yet) -> keep tracking self.state = new_state self.last_slice_start = ts # STEP 2: ask LLM for updated decision at 10:15 news_last_hour = summaries_between( self.bundle.df_news, "datetime_ist", ts - timedelta(hours=1), ts ) hourly_dict = hourly_ohlc_dict(self.bundle.df_bn_hourly, "datetime", ts) if prev_ts is None: raise ValueError("No previous timestamp available for after 11:15 logic") prev_ts_for_ind = prev_ts bn_now = self._bn_prev(prev_ts_for_ind) user_update = USER_INTRAHOUR_UPDATE.format( news=news_last_hour, hourly_ohlc=hourly_dict, bn_ind=bn_now["ind"], trade=self.current_plan.model_dump() if self.current_plan else {}, position=self.state.to_compact(ts), hours_since_open=hour_passed(ts), major_concern=self.morning_summary_full.major_concern_banknifty if self.morning_summary_full else "", sentiment=self.last_sentiment if self.last_sentiment else "", strategy=self.morning_summary_full.trade_strategy_banknifty if self.morning_summary_full else "", reason=self.morning_summary_full.trade_reasoning_banknifty if self.morning_summary_full else "", memory=self.memory_str, ) decision: DecisionOutput = self.llm.trade_decision_output(user_update) new_plan = decision.trade self.last_summary_bn = decision.summary_banknifty # STEP 3: enforce the NEW decision right away post_must_flatten = False side_change=False if self.state.open_position: if new_plan.status == "No trade": post_must_flatten = True elif new_plan.status == "Trade" and new_plan.type != self.state.side: post_must_flatten = True side_change=True if post_must_flatten: self._force_flatten_position(ts, reason="Exited at market price") self.last_slice_start = ts if side_change: post_must_flatten=False # STEP 4: accept/record plan + summary self.current_plan = new_plan self.trade_log.append({**new_plan.model_dump(), "datetime": ts}) self.summary_log.append( {**decision.summary_banknifty.model_dump(), "datetime": ts} ) self._save_checkpoint_now(ts) # ---------------------------------------------------------- # Intraday updates for 11:15 .. 15:15 # ---------------------------------------------------------- else: # STEP 1: simulate previous slice with current plan if self.last_slice_start and self.current_plan and post_must_flatten==False: intraday = slice_intraday(self.bundle.df_bn_1m, self.last_slice_start, ts) if not intraday.empty: new_state = simulate_trade_from_signal( df=intraday, trade=self.current_plan, dt_col="datetime", state=self.state, lookback_minutes=60, ) if self.state.model_dump() != new_state.model_dump(): # We log the transition self.stats_log.append({**new_state.model_dump(), "datetime": ts}) # If the new_state is exited (trade is fully closed), finalize it if new_state.exited and not new_state.open_position: # update memory_str once if new_state.side is not None: self.memory_str = ( "{" f"\"side\": \"{new_state.side}\", " f"\"entry_price\": {new_state.entry_price}, " f"\"exit_price\": {new_state.exit_price}, " f"\"pnl_pct\": {new_state.pnl_pct}, " f"\"exit_reason\": \"{new_state.exit_reason}\"" "}" ) else: self.memory_str = "No trade completed" # reset engine state to flat so we don't keep re-logging this closed trade self.state = PositionState() # after closing, next slice should start from here self.last_slice_start = ts else: # still in position (or haven't entered yet) -> keep tracking self.state = new_state self.last_slice_start = ts # STEP 2: query LLM for updated decision news_last_hour = summaries_between( self.bundle.df_news, "datetime_ist", ts - timedelta(hours=1), ts ) hourly_dict = hourly_ohlc_dict(self.bundle.df_bn_hourly, "datetime", ts) if prev_ts is None: raise ValueError("No previous timestamp available for after 11:15 logic") prev_ts_for_ind = prev_ts bn_now = self._bn_prev(prev_ts_for_ind) user_update2 = USER_INTRAHOUR_UPDATE_2.format( news=news_last_hour, news_summary=self.last_summary_bn.news_summary if self.last_summary_bn else "", hourly_ohlc=hourly_dict, bn_ind=bn_now["ind"], trade=self.current_plan.model_dump() if self.current_plan else {}, position=self.state.to_compact(ts), hours_since_open=hour_passed(ts), major_concern=self.last_summary_bn.major_concern if self.last_summary_bn else "", sentiment=self.last_summary_bn.sentiment if self.last_summary_bn else "", strategy=self.last_summary_bn.trade_strategy if self.last_summary_bn else "", reason=self.last_summary_bn.reasoning if self.last_summary_bn else "", memory=self.memory_str, ) decision: DecisionOutput = self.llm.trade_decision_output(user_update2) new_plan = decision.trade self.last_summary_bn = decision.summary_banknifty # STEP 3: enforce the NEW decision post_must_flatten = False side_change=False if self.state.open_position: if new_plan.status == "No trade": post_must_flatten = True elif new_plan.status == "Trade" and new_plan.type != self.state.side: post_must_flatten = True side_change=True if post_must_flatten: self._force_flatten_position(ts, reason="Exited at market price") self.last_slice_start = ts if side_change: post_must_flatten=False # STEP 4: record plan + summary self.current_plan = new_plan self.trade_log.append({**new_plan.model_dump(), "datetime": ts}) self.summary_log.append( {**decision.summary_banknifty.model_dump(), "datetime": ts} ) self._save_checkpoint_now(ts) #################### #15-15 block if (ts.time().hour == 15 and ts.time().minute == 15): print(ts+timedelta(minutes=14)) # STEP 1: simulate previous slice with current plan if self.last_slice_start and self.current_plan and post_must_flatten == False: intraday = slice_intraday(self.bundle.df_bn_1m, self.last_slice_start,(ts+timedelta(minutes=14))) if not intraday.empty: new_state = simulate_trade_from_signal( df=intraday, trade=self.current_plan, dt_col="datetime", state=self.state, lookback_minutes=14, ) if self.state.model_dump() != new_state.model_dump(): # We log the transition self.stats_log.append({**new_state.model_dump(), "datetime": ts+timedelta(minutes=14)}) # If the new_state is exited (trade is fully closed), finalize it if new_state.exited and not new_state.open_position: # update memory_str once if new_state.side is not None: self.memory_str = ( "{" f"\"side\": \"{new_state.side}\", " f"\"entry_price\": {new_state.entry_price}, " f"\"exit_price\": {new_state.exit_price}, " f"\"pnl_pct\": {new_state.pnl_pct}, " f"\"exit_reason\": \"{new_state.exit_reason}\"" "}" ) else: self.memory_str = "No trade completed" # reset engine state to flat so we don't keep re-logging this closed trade self.state = PositionState() # after closing, next slice should start from here self.last_slice_start = (ts+timedelta(minutes=14)) else: # still in position (or haven't entered yet) -> keep tracking self.state = new_state self.last_slice_start = (ts+timedelta(minutes=14)) #decision of carry forward or not at 15-30 news_last_15m = summaries_between( self.bundle.df_news, "datetime_ist", ts, ts + timedelta(minutes=14)) hourly_dict = hourly_ohlc_dict(self.bundle.df_bn_hourly, "datetime", ts + timedelta(minutes=15)) prev_ts_for_ind = ts bn_prev_for_ind = self._bn_prev(prev_ts_for_ind) user_close = USER_CLOSING.format( news=news_last_15m, news_summary=self.last_summary_bn.news_summary if self.last_summary_bn else "", hourly_ohlc=hourly_dict, bn_ind=bn_prev_for_ind["ind"], trade=self.current_plan.model_dump() if self.current_plan else {}, position=self.state.to_compact(ts), major_concern=self.last_summary_bn.major_concern if self.last_summary_bn else "", sentiment=self.last_summary_bn.sentiment if self.last_summary_bn else "", strategy=self.last_summary_bn.trade_strategy if self.last_summary_bn else "", reason=self.last_summary_bn.reasoning if self.last_summary_bn else "", memory=self.memory_str, ) close_plan = self.llm.trade_plan(user_close) last_1_min=ts+timedelta(minutes=14) intraday_data = slice_intraday(self.bundle.df_bn_1m, last_1_min, (ts+timedelta(minutes=15))) # Get the data for last minute post_must_flatten = False side_change=False if self.state.open_position: if close_plan.status == "No trade": post_must_flatten = True elif close_plan.status == "Trade" and close_plan.type != self.state.side: post_must_flatten = True side_change=True if post_must_flatten: self._force_flatten_position((ts+timedelta(minutes=14)), reason="market close") self.last_slice_start = ts if side_change: post_must_flatten=False if not intraday_data.empty and post_must_flatten == False: # Simulate the trade for the last 1 minutes new_state = simulate_trade_from_signal( df=intraday_data, trade=close_plan, dt_col="datetime", state=self.state, lookback_minutes=1 ) # Check if the state has actually changed if self.state.model_dump() != new_state.model_dump(): # Log the transition self.stats_log.append({**new_state.model_dump(), "datetime": ts+timedelta(minutes=15)}) # If the new state is exited (trade is fully closed), finalize it if new_state.exited and not new_state.open_position: # Update memory_str once the trade is closed if new_state.side is not None: self.memory_str = ( "{" f"\"side\": \"{new_state.side}\", " f"\"entry_price\": {new_state.entry_price}, " f"\"exit_price\": {new_state.exit_price}, " f"\"pnl_pct\": {new_state.pnl_pct}, " f"\"exit_reason\": \"{new_state.exit_reason}\"" "}" ) else: self.memory_str = "No trade completed" # Reset engine state to flat so we don't keep re-logging this closed trade self.state = PositionState() # After closing, next slice should start from here self.last_slice_start = (ts+timedelta(minutes=15)) else: # Still in position (or haven't entered yet) -> keep tracking self.state = new_state # Record the closing plan for next day at 09:15 self.current_plan = close_plan self.last_close_plan = close_plan self.trade_log.append({**close_plan.model_dump(), "datetime": ts+timedelta(minutes=14)}) # self._save_checkpoint_now(ts+timedelta(minutes=14)) # If we did NOT flatten, self.state still shows that position is open, so we carry overnight. # We'll resume tomorrow with that. # ---------------------------------------------------------- # Save checkpoint after every timestamp # ---------------------------------------------------------- # After loop completes, dump friendly Excel snapshots self._flush_to_excels()