o
    ìv¡j¡#  ã                   @   s  d Z ddlmZmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZmZ ddlmZ ddlmZ eG dd„ dƒƒZ			d!dede de de!de!de"de#de"de de de"defdd „Z$dS )"aq	  
prediction_pipeline.py

Live wiring for the full engine chain -- stream_features -> trend_engine ->
structure_engine -> compression_engine -> regime_engine -> setup_engine ->
prediction_engine -> entry_score.py -- plus, additively (Phase 5,
2026-09-08), relative_strength_engine + winner_score.py + state_transitions.py
for ranking/state visibility. Live counterpart to
simulate_prediction_pipeline.py's offline replay.

evaluate_entry_pipeline() is monitor.py's alternative to
entry_engine.evaluate_entry(), selected via config.json's
entry.decision_engine == "prediction_pipeline". It returns an
EntryDecision-shaped result (should_enter, confirmation_score, reasons_for,
reasons_against) PLUS additive fields (winner_score, market_state,
next_state_probabilities, score_trend) that a caller can ignore entirely
without anything breaking -- see PipelineDecision's field defaults.

THE ENTRY GATE ITSELF IS UNCHANGED (2026-09-08 design decision, Option A):
should_enter is still driven ONLY by entry_score.compute_entry_score()'s
action == ACTION_READY, exactly as before. winner_score/market_state/
next_state are purely additive -- for ranking, logging, and the
state-machine output shape the project asked for -- and never override
should_enter.

CALLER-HELD STATE: same contract as every engine in this pipeline. monitor.py
keeps one dict per symbol (Monitor._pipeline_state[symbol]) across poll
cycles and passes it in as `state`; this function mutates it in place
(prior_features/prior_prediction/confirmation_state/regime_state/
score_history). A fresh {} for a symbol is a cold start, same as before.

WHAT'S NEW AND OPTIONAL (all fail-soft -- omitting any of these reproduces
the pre-Phase-5 behavior for that piece, never crashes):
  - premarket_result: this symbol's own scorer.score_premarket_candidate()
      dict (pm_high/pm_low/total_score). Seeds structure_engine's day-1
      resistance/support reference and winner_score's premarket_setup
      component. THIS closes a real gap found auditing 2026-09-08's live
      session: without it, structure_score sat at 0 and last_swing_high/
      low were both None for the first several minutes of every session.
  - spy_bars / qqq_bars / peer_bars: enables relative_strength_engine and
      the market-regime read. Omit entirely to skip both -- winner_score
      degrades to a neutral default for those two components, nothing
      else changes.
é    )Ú	dataclassÚfield)ÚdatetimeÚtimezone)Úcompute_features)Úclassify_trend)Úanalyze_structure)Úanalyze_compression)Úclassify_regime)Úevaluate_setups)Úcompute_prediction)Úcompute_entry_scoreÚACTION_READY)Úcompute_relative_strengthÚclassify_market_regime)Úcompute_winner_score)Úestimate_next_statec                   @   sŒ   e Zd ZU eed< eed< eed< eed�Z	eed< eed�Z
eed< dZeed< eed�Zeed	< dZeed
< dZeed< dZeed< dS )ÚPipelineDecisionÚsymbolÚshould_enterÚconfirmation_score)Údefault_factoryÚreasons_forÚreasons_againstNÚmarket_stateÚnext_state_probabilitiesÚwinner_scoreÚwinner_score_trendÚwinner_score_velocity)Ú__name__Ú
__module__Ú__qualname__ÚstrÚ__annotations__ÚboolÚfloatr   Úlistr   r   r   Údictr   r   r   r   © r(   r(   ú2/var/www/screener/premarket/prediction_pipeline.pyr   >   s   
 r   é   Nr   ÚbarsÚbars_subÚavg_vol_baselineÚsession_elapsed_minutesÚstateÚsub_bucket_secondsÚpremarket_resultÚspy_barsÚqqq_barsÚ	peer_barsÚreturnc                 C   s0  |pt  tj¡}| dd¡ | dd¡ | di ¡ | di ¡ | dg ¡ |	r-|	 d¡nd}|	r6|	 d¡nd}t| |||||d ||d	�}t|ƒ}t| |||d
�}t	| |||d�}t
| ||||||d |d d d�}t||||ƒ}t| ||||||d d�}t| |||||||d |d�	}d\}}|
r¥|r¥t| ||
||d�}t|
|ƒ}t| |||||||||	||d d�}|jsÌ|d ||j|jfg dd… |d< t|j||d�}||d< ||d< |j|d< |jtk}t| ||j|rð|jng |rõg n|j|j|j|j�s|jnd|j�s
|jnd|j�s|jd�
S dd�
S )a[  
    bars / bars_sub / quote: same shapes stream.StreamManager already
        hands entry_engine.evaluate_entry() plus get_bars_sub().
    avg_vol_baseline: same "expected normal volume" baseline
        entry_engine/intraday_health already use.
    session_elapsed_minutes: market_time.minutes_since_open() -- drives
        regime_engine's OPENING_VOLATILITY window check.
    state: caller-held per-symbol dict, see module docstring.
    premarket_result / spy_bars / qqq_bars / peer_bars: see module
        docstring's "WHAT'S NEW AND OPTIONAL" section -- all optional,
        all fail-soft.
    Úprior_featuresNÚprior_predictionÚconfirmation_stateÚregime_stateÚscore_historyÚpm_highÚpm_low)r-   Úpriorr0   Úas_of)Úpremarket_highÚpremarket_low)ÚfeaturesÚ	structureéÿÿÿÿÚt)r.   Úcompressionr/   Úbar_t)ÚregimeÚsetupsr=   )rG   rH   r8   r>   )NN)r4   )Úrelative_strengthrE   rH   Úmarket_regimer1   Únowr:   iöÿÿÿ)Ú
predictionrE   )
r   r   r   r   r   r   r   r   r   r   )r   rK   r   ÚutcÚ
setdefaultÚgetr   r   r   r	   r
   r   r   r   r   r   r   Úinsufficient_datar   Úvelocity_per_minr   rG   ÚconfirmationÚactionr   r   Úentry_scoreÚreasonsÚprobabilitiesÚscore_trend)r   r+   r,   Úquoter-   r.   r/   r0   r>   r1   r2   r3   r4   r?   r@   rA   ÚtrendrB   rE   rG   rH   rL   Úentry_readingrI   rJ   Úwinner_readingÚ
transitionr   r(   r(   r)   Úevaluate_entry_pipelineM   sx   þ

ýÿþ

üÿÿ

ùùr]   )r*   NNNNN)%Ú__doc__Údataclassesr   r   r   r   Ústream_featuresr   Útrend_enginer   Ústructure_enginer   Úcompression_enginer	   Úregime_enginer
   Úsetup_enginer   Úprediction_enginer   rT   r   r   Úrelative_strength_enginer   r   r   r   Ústate_transitionsr   r   r"   r&   r%   r'   Úintr]   r(   r(   r(   r)   Ú<module>   sL    -üÿÿþþýýüüü