+
    (7j4m              	       2   R t ^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RI	t	^ RI
t
^ RIt^ RIHtHt ^ RIt^ RIt]
P$                  P'                  ]P$                  P)                  ]P$                  P+                  ]P$                  P-                  ]4      R4      4      4       ^ RIt^ RIHtHtHtHtHtHt ^ RI H!t! ^ RI"H#t#H$t$ ^<t%Rt&Rt'R	t(R
t)Rt*Rs+R t,R t-R t.R t/R t0R t1R t2R t3R t4RR lt5R t6R t7R t8RR lt9RR lt:R t;R t<]=R8X  d
   ]<! 4        R# R# ) u  
Two-phase trainer for the MLP activation-score strategy (strategy_mlp_scores).

Phase 1 — supervised pretrain (PyTorch):
    Target: y_t = tanh( scale * (k-bar forward log return / k) / rolling_vol_t )
    where rolling_vol is past-only (shifted) so there is no lookahead leakage.
    Temporal split: train on bars up to the last WFO fold's IS end, early-stop
    on the last fold's OOS span. (Full per-epoch expanding-window CV across all
    folds was deliberately simplified away — Phase 2 does the real fold-averaged
    model selection on the actual backtest metric.)

Phase 2 — CMA-ES fine-tune (cma):
    Parameter vector = flattened MLP weights + [entry, exit, exit_conf, trail]
    thresholds. Fitness = -(mean per-fold OOS Calmar across config.WFO_FOLDS,
    invalid folds scoring 0, >= WFO_MIN_VALID_FOLDS valid folds required)
    + lambda * mean squared deviation from the pretrained weights (L2 anchor).
    `--fold-objective robust` keeps the same WFO-only training boundary but
    subtracts penalties for high fold drawdown, zero P&L/DD, low fold trade
    coverage, negative folds, and threshold fragility.
    Per-fold Calmar matches the existing WFO rescore convention in
    auto_optimize_loop.py (composite_score's 1000% P&L gate is meaningless on
    ~1-year folds, so Calmar is the per-fold metric).

Usage:
    python3 tools/train_mlp.py --data data/COINBASE_BTCUSD-6H.csv         [--hidden 16 8] [--target-k 10] [--phase1-epochs 300]         [--es-generations 300] [--es-popsize 32] [--es-sigma 0.05] [--l2 1e-3]         [--fold-objective mean|robust] [--es-workers 0]         [--seed 42] [--smoke] [--skip-phase2] [--out PATH]

Output: strategies/params/mlp/mlp_weights_{ASSET}_{TF}.json
N)datetimetimezone..)ACTIVATION_NAMEFEATURE_COLS_score_to_signalscalculate_metricsmlp_forwardsave_mlp_artifact)_prepare_features)DEFAULT_WORKER_FRACTIONresolve_worker_countg       @      Y@g      I@皙?      ?c                     \         P                  ! R \        P                  P	                  V 4      4      pV'       g   \        RV  24      hVP                  ^4      VP                  ^4      3# )z ([A-Z0-9_!]+)-([0-9]+[HDW])\.csvz&Cannot derive ASSET/TF from filename: )rematchospathbasename
ValueErrorgroup)	data_pathms   & :/Users/jameslopez/projects/TradingBot25/tools/train_mlp.pyderive_asset_tfr   I   sS    
4bgg6F6Fy6QRAA)MNN771:qwwqz!!    c                    \         P                  ! V 4      pVP                  P                  P	                  4       P                  P                  4       Vn        \         P                  ! VR ,          RR7      P                  P                  R4      VR &   VR ,          \        P                  8  VR ,          \        P                  8*  ,          pVP                  V,          P                  RR7      # )timeT)utcNdrop)pdread_csvcolumnsstrlowerstripto_datetimedttz_localizeconfigTRAIN_START	TRAIN_ENDlocreset_index)r   dfmasks   &  r   	load_datar3   P   s    	Y	B%%'++113BJ6
588DDTJBvJvJ&,,,Fv?O?O1OPD66$<###..r   c                   \         P                  ! V R,          P                  P                  \         P                  4      4      p\
        P                  ! \         P                  ! W"^ ,          R7      4      pVP                  \        4      P                  4       P                  ^4      P                  p\         P                  ! \        V 4      \         P                  4      pW!R VRV)  ,
          V,          VRV) % \         P                  ! \         V,          VR,           ,          4      p\         P"                  ! V4      ( pWpR,          \$        P&                  8  P                  ,          pWg3# )zJtanh-squashed vol-normalised k-bar forward log return. Returns (y, valid).close)prependNư>r   )nplogvaluesastypefloat64r#   Seriesdiffrolling
VOL_WINDOWstdshiftfulllennantanhTARGET_SCALEisnanr,   SCORE_START)r1   k	log_closeret1volfwdyvalids   &&      r   build_targetrQ   X   s    r'{))00<=I99RWWY!=>D
,,z
"
&
&
(
.
.q
1
8
8C
''#b'266
"C"	#A2.!3C!H
s"cDj12AXXa[LE	jF...666E8Or   c
                 	  a aa!a" ^ RI o"S"P                  P                  4       '       d   RM-S"P                  P                  P                  4       '       d   RMRo!S"P                  V4       \        P                  P                  V4       S P                  ^,          .\        V4      ,           ^.,           p
. p. p\        \        V
4      ^,
          4       Fe  pS"P                  P                  W,          W^,           ,          4      pWS"P                  P                  4       .,          pVP!                  V4       Kg  	  S"P                  P"                  ! V!  P%                  S!4      pW#V8  P&                  ,          W88*  P&                  ,          pW#V8  P&                  ,          pV	! RS! RV
 RVP)                  4        RVP)                  4        24       V V!V"V3R	 lpV! V4      w  ppV! V4      w  ppS"P*                  P-                  VP/                  4       R
RR7      pS"P                  P1                  4       p\        P2                  R^^ 3w  pppp\        V4       EF  pVP5                  4        VP7                  4        V! V! V4      V4      pVP9                  4        VP;                  4        VP=                  4       pVP?                  4        S"PA                  4       ;_uu_ 4        \        V4      '       d   \C        V! V! V4      V4      4      MTp RRR4       X VR,
          8  d   T ^ ppV Uu. uF  pVPD                  PG                  4       PI                  4       PK                  4       PM                  4       PO                  4       VPP                  PG                  4       PI                  4       PK                  4       PM                  4       PO                  4       3NK  	  ppM"V^,          pVV8  d   V	! RV RVR R24        M)V^2,          ^ 8X  g   EK  V	! RV RVR RV R 24       EK  	  VRS!RV
RX^,           RVR\S        VP)                  4       4      R\S        VP)                  4       4      /3#   + '       g   i     ELg; iu upi )    Ncudampscpuzphase1: device=z arch=z train_bars=z
 val_bars=c                    < SP                  SV ,          SP                  SR 7      SP                  SV ,          SP                  SR 7      P                  ^4      3# ))dtypedevice)tensorfloat32	unsqueeze)mask_arrXrY   torchrO   s   &r   tenspretrain.<locals>.tens   sO    Qx[fMQx[fMWWXYZ\ 	\r   g{Gz?g-C6?)lrweight_decayr7   zphase1: early stop at epoch z (best val MSE z.5f)zphase1: epoch z train=z val=rY   arch
epochs_runbest_val_mse
train_barsval_bars)*r_   rT   is_availablebackendsrU   manual_seedr8   randomseedshapelistrangerD   nnLinearTanhappend
Sequentialtor:   sumoptimAdam
parametersMSELossinftrain	zero_gradbackwardstepitemevalno_gradfloatweightdetachrV   doublenumpycopybiasint)#r^   rO   rP   timeshiddenepochsrn   	val_startval_endr9   re   layers_tmodulesilinmodelval_mask
train_maskr`   XtrytrXvayvaoptloss_fnbest_val
best_statepatience
since_bestepochloss
train_lossval_lossrY   r_   s#   ff&&&&&&&&                       @@r   pretrainr   j   s   

//11f!NN..;;==5  
dIINN4GGAJ<$v,&!,DHG3t9q=!hhoodgtE{3)) " HH),,V4E*222e6F5N5NNH)+333J/&v\*..:J9K LLLN#	% &\ \ JHCH~HC
++

5++-$T

JChh G13r11D.Hj(JvuSz3'
YY[


]]__:=c((uWU3Z56
H ho%#+QjH &./%-c ::,,.224;;=CCEJJL88??,00299;AACHHJL%-  /J !OJX%25'RUVWXY2:?.wz#.>eHS>RS+ . &&$eai&$c*..*:&;"C$79 9 9 __/s   ',Q11B-R1Rc                     \         P                  ! V  UUu. uF9  w  r\         P                  ! VP                  4       VP                  4       .4      NK;  	  upp4      # u uppi N)r8   concatenateravel)layersWbs   &  r   flatten_layersr      s?    >>fUfda2>>1779aggi*@AfUVVUs   ?A
c                     . ^ r2\        \        V4      ^,
          4       Fk  pW^,           ,          W,          reWW5V,          ,            P                  WV4      qsWV,          ,          pWW5,            qV,          pVP                  Wx34       Km  	  V# )rS   )rq   rD   reshaperu   )	thetare   r   r   lin_outn_inr   r   s	   &&       r   unflatten_layersr      s{    AACIM"6lDHtA$%--e:<MAAIU
qf	 #
 Mr   c                 f   VR 8X  d    \        \        P                  ! V 4      4      # VR8X  d    \        \        P                  ! V 4      4      # VR8X  dR   R\        \        P                  ! V 4      4      ,          R\        \        P                  ! V 4      4      ,          ,           # \	        RV 24      h)meanminmean_mingffffff?333333?zUnknown fold objective: )r   r8   r   r   r   )calmars	objectives   &&r   aggregate_fold_scorer      s    FRWWW%&&ERVVG_%%JU2777+,,sU266'?5K/KKK
/	{;
<<r   c                    \         P                  ! VR ,          \         P                  R7      p\        V4      ^ 8X  d   ^ # \         P                  ! V \         P                  R7      p \         P                  ! \         P
                  ! V R,          VR,          ,
          4      ^R7      p\        \         P                  ! W28  4      4      # ):N   NrX   )axis)NNNN)Nr   )r8   asarrayr<   rD   r   absr   rx   )scores
thresholdsmargindists   &&& r   threshold_fragility_countr      sz    JrN"**=J
:!ZZbjj1F66"&&:g+>>?aHDrvvdm$%%r   c                    \        V R 4      p\        V^,           \        \        P                  ! VR,          4      4      4      p\        ^\        V4      4      pRpRp	Rp
RpV F  p\        VP                  R^ 4      4      p\        \        VP                  RR4      4      4      p\        VP                  RR4      4      p\        VP                  RR4      4      pV\        RV\        ,
          4      \        ,          ,          pVR8:  d
   V	R,          p	V
\        RWm,
          4      V,          ,          p
V\        R\        RV) 4      4      ,          pK  	  W,          pW,          p	W,          p
W,          p\        W#\        4      p\        W#\        4      pRV,          \        RVR	,          4      ,           pR
VRV	RV
RVRVRVRVRV/pRV,          RV	,          ,           RV
,          ,           RV,          ,           V,           pVV,
          V3# )r   g      ?        Total TradesMax Drawdown %P&L/DD RatioCalmar Ratior   r   g     @@drawdown_penaltypnl_dd_penaltytrade_penaltynegative_fold_penaltyfragility_penaltyfragile_0_05fragile_1_0trade_targetg?g      ?r         $)r   maxr   r8   ceilrD   getr   r   ROBUST_DRAWDOWN_TARGETr   r   ROBUST_FRAGILITY_TIGHT_MARGINROBUST_FRAGILITY_WIDE_MARGIN)r   fold_metricsr   r   min_fold_tradesbaser   n_foldsr   r   r   neg_fold_penaltymetricstradesdrawdownpnl_ddcalmarfragile_tightfragile_wider   	penaltiespenaltys   &&&&&                 r   robust_objective_scorer      s   4D*C#8M0N,OPL!S&'GNMW[[34uW[[)93?@Aw{{>378w{{>59:CX0F%FGJ```S=c!NS,"78<GGCSvg%677   NM-fB_`M,VA]^L-S,:N1OO 	,.!1.|	I 	

	

	 !
!	" 		  '>9$$r   c	                    R V RR.,          P                  4       RV R,          P                  4       RV R,          P                  P                  \        P                  4      RV R,          P                  P                  \        P                  4      RVR,          RVR	\        V4      R
\        P                  ! V\        P                  R7      R\        V4      RVRVRVRV/# )base_dfr   r5   r   	close_arrhigh_arrhighstoch_peak_arrr^   re   theta0_wr   foldsr   min_valid_foldsl2fold_objective)r   	   )r   r:   r;   r8   r<   rp   r   )	r1   r^   re   r   r   r   r   r   r   s	   &&&&&&&&&r   make_fitness_contextr      s     	2vw'(--/F"R[''..rzz:BvJ%%,,RZZ8!D'QT
BJJxrzz:e??b. r   c                 Z   \         P                  ! V \         P                  R 7      p VR,          p\        V4      p\	        V RV VR,          4      p\         P
                  ! WR \        ,          . R#O. R$O4      p\        VR,          V4      pVR,          P                  4       pWgR&   VR,          VR	&   R
V^ ,          RV^,          RV^,          RRRRR\        RV^,          4      /p\        VVVR,          VR,          VR,          4      p. . ^ rp	VR,          pVR,          pVR,           F  w  rpVP                  W8  VV8*  ,          ,          p\        V4      ^
8  d-   V
P                  R^ RR%RRRR/4       V	P                  R4       Ka  \        VVR7      pV
P                  V4       VR,          R%8:  g   VR,          V8  d   V	P                  R4       K  V	P                  VR,          4       V^,          pK  	  RV/pVR,          pVR8X  d4   \        V	V
VVV4      w  ppVP                  V4       \!        V	R4      VR &   MWR!,          8  d   RpM\!        V	V4      pVR",          \#        \         P$                  ! V RV V,
          ^,          4      4      ,          pV) V,           WV3# )&r   r   Nre   r   r^   r   activation_scorer   r   !i_long_entry_activation_threshold i_long_exit_activation_threshold-i_long_exit_activation_confirmation_thresholdi_use_long_exit_confirmationr   i_use_long_entry_confirmationFi_trailing_stop_thresholdr   r   r   r   r   r   r   r   r   )
min_tradesvalid_foldsr   robustr   base_fold_scorer   r   )      r  r  r   )      @r	  r	  g      >@r   )r8   r   r<   rD   r   clipTHRESHOLD_SCALEr	   r   r   r   r/   ru   r   r   updater   r   r   )r   contextr   n_wr   r   r   dparamsr   r   rP   r   r   _	oos_startoos_endslr   diagnosticsr   scorer   anchors   &&                      r   evaluate_thetar    s   JJuBJJ/Ez"H
h-CeDSk76?;Fdo%%#J v.F	!A"
#AfI+Z]*JqM7A&'#Sjm%<F 		 !
	A $&r15GGE/0O!(!1!1gUUE&5G+;<=r7R<NE!/6F!M NNN3#B?CG$>"e+w~/F/XNN3NN7>23QJE "2 !%(K-.N!1
y 	9%)=gz)R%&	*+	+$Wn=T]U277E$3K(,Bq+H#IJJF8fg;>>r   c                 
    V s R # r   )_FITNESS_CONTEXT)r  s   &r   init_fitness_workerr  Y  s    r   c                 "    \        V \        4      # r   )r  r  )r   s   &r   evaluate_theta_workerr  ^  s    %!122r   c	                 R   a	a
 \        WW#WEWgV4	      o	V	V
3R  lo
S	S
n        / S
n        S
# )c                 8   < \        V S4      w  rr4VSn        WV3# r   )r  last_diagnostics)r   fitr   r   r  r  fitnesss   &    r   r"  make_fitness.<locals>.fitnessi  s'    0>ug0N-j#. Z''r   )r   r  r   )r1   r^   re   r   r   r   r   r   r   r  r"  s   &&&&&&&&&@@r   make_fitnessr$  b  s4    "
tuG
(
 GO!GNr   c                   a aaaaaaa ^ RI pVP                  WRVRVRR/4      o\        ^\        S4      4      oR\        P
                  RVRRRRR	/ R
S/oVV3R loVVVVV3R lp	S^8X  dO   S! R4       V 3R lp
\        S4       F/  pV	! W4       SP                  4       '       g   K#  S! RV 24        S# 	  S# \        S RR4      pVf   \        R4      hS! RS R24       \        P                  ! R4      p \        P                  P                  SV\        V3R7      ;_uu_ 4       o\        S4       F3  pV	! VV3R l4       SP                  4       '       g   K(  S! RV 24        M	  RRR4       S#   + '       g   i     S# ; i  \         \"        3 d)   pS! RT R24       \%        S YTSTS^R7      u Rp?# Rp?ii ; i)rS   Npopsizern   verboser!  r   r   thrr  workersc                    < Vw  r4rVVP                  V4       VSR ,          8  d<   R VR\        P                  ! V 4      P                  4       RVRVR\	        V4      RS/oR# R# )r!  r   r   r(  r  r)  N)ru   r8   r   r   dict)	solutionresultfitsfr   r(  r  bestr)  s	   &&&    r   observe_solution!run_cma.<locals>.observe_solution|  sd    '-$CAtE{?qH-2247stK07D r   c                   < S
P                  4        Uu. uF)  p\        P                  ! V\        P                  R 7      NK+  	  ppV! V4      p. p\	        W44       F  w  rgS! WgV4       K  	  S
P                  W54       V ^
,          ^ 8X  g   V S^,
          8X  dJ   S! RT  RS RS	R,          R RS	R,          ;'       g    .  Uu. uF  p\        V^4      NK  	  up 24       R# R# u upi u upi )	r   zphase2: gen /z best_fitness=r!  .4f fold_calmars=r   N)askr8   r   r<   ziptellround)gen	evaluators	solutionsresultsr.  r,  r-  cr0  esgenerationsr9   r1  s   &&       r   run_generationrun_cma.<locals>.run_generation  s    >@ffhGhRZZ4h	GI& #I 7HXt4 !8
	 8q=C;?2,se1[MUC?P Q 7;I7L7L"7L N7Lq!7L NOQ R 3 H !Os   /C$C)z1phase2: evaluating CMA-ES population sequentiallyc                    < . pV  F6  pS! V4      w  r4pVP                  W4V\        \        SR / 4      4      34       K8  	  V# )r   )ru   r+  getattr)r>  outr,  r/  r   r(  r"  s   &     r   sequential_evaluator%run_cma.<locals>.sequential_evaluator  sP    C%")("3C

A 2Db!IJL M & Jr   z phase2: CMA-ES converged at gen r  z*Parallel CMA-ES requires a fitness contextz*phase2: evaluating CMA-ES population with z worker processesspawn)max_workers
mp_contextinitializerinitargsc                 B   < \        SP                  \        V 4      4      # r   )rp   mapr  )r>  pools   &r   <lambda>run_cma.<locals>.<lambda>  s    d488DY[d;e6fr   z!phase2: worker pool unavailable (z(); falling back to sequential evaluation)r)  i)cmaCMAEvolutionStrategyr   r   r8   r}   rq   stoprF  r   mpget_context
concurrentfuturesProcessPoolExecutorr  OSErrorPermissionErrorrun_cma)r"  theta0sigma0r&  rB  rn   r9   r)  rT  rC  rH  r;  r  rL  excr0  rA  r1  rQ  s   f&&&f&ff       @@@@r   r^  r^  s  s   		!	!&#,gvtYPR"S
UB!S\"G2667FItUD2y'3D	R 	R !|?@	 %C35wwyy6se<= &
 gy$/GEFF
4WI=NOP(J\33!+Z	 4 
 

 [)s$fg7799:3%@A	 *
 K
 
 K _% \/u4\]^wdCYZ[[\sB   ;0F +/E8E8.F 8F		F 	F GG :G Gc                D   ^ RI Hp VP                  ;'       g
    RV RV R2pV! RV 24       \        P                  ! V4      pVP
                  ^ ,          P                  4       pV! R4       V! V P                  4       3/ VB p	V	R,          P                  p
V
P                  \        P                  4      p\        P                  ! \        V
4      \        P                  R7      p^ p\        \        V
4      4       F2  pW,          ^ 8  d!   \        VR	,          R
4      W&   V^,          pK0  ^ pK4  	  WR&   WR&   \!        VP#                  4       4      p\%        VP'                  4       4      pV! RV R\        V 4       RVR RV^d,          R R2	4       \(        RR.,           # )a  Compute in_long_position + bars_held_norm from the current winner policy.

One-cycle circularity (documented in roadmap): the position state used for
training comes from the OLD model's decisions, not the new model.  This is
acceptable for the first retrain; a second retrain with the new policy's
state would converge.

Mutates df in-place, adding columns 'in_long_position' and 'bars_held_norm'.
Returns the extended feature_cols list.
)generate_signalsz8results/winners/optimization_winner_strategy_mlp_scores_r  z.csvz'approach-b: loading winner params from zNapproach-b: running generate_signals with old policy to get position state ...positionr   r   r   in_long_positionbars_held_normu+   approach-b: position features injected — r4  z& bars in-position, max bars_held_norm=z.3fz (=.0fz bars))strategies.strategy_mlp_scoresrc  approach_b_paramsr#   r$   ilocto_dictr   r:   r;   r8   r<   zerosrD   rq   r   r   rx   r   r   r   )r1   assettfargsr9   _gen_signalsparams_path	params_dfr  signalsrd  in_long	bars_heldbars_inr   n_in_posmax_helds   &&&&&            r   _inject_position_featuresry    s    P 	 	W 	WEeWAbTQUV  
1+?@K(I^^A&&(FXY2779//Gz"))Hoobjj)GXbjj9IG3x=!;?w4ILqLGG " %$7;;=!HY]]_%H
5hZqR	 J&s^3x|C.@	H I -/?@@@r   c                     \         P                  ! R R7      p V P                  RRR7       V P                  R\        R^^.R7       V P                  R\        ^
R	7       V P                  R
\        RR	7       V P                  R\        RR	7       V P                  R\        ^ R	7       V P                  R\        RR	7       V P                  R\        RR	7       V P                  R. RORRR7       V P                  R\        ^ RR7       V P                  R\        \
        RR7       V P                  R\        ^*R	7       V P                  RRRR 7       V P                  R!RR"7       V P                  R#R$R%7       V P                  R&R'R%7       V P                  R(R)R%7       V P                  R*RR+R 7       V P                  R,R-R%7       V P                  R.. ROR2R3R7       V P                  4       p\        P                  ! 4       pR4 pVP                  '       d+   VP                  '       d   VP                  VP                  rTM\        VP                  4      w  rE\        VP                  4      pVP                  '       Ed   VP                  R54      P                  RR67      p^^.Vn        \#        VP$                  ^4      Vn        \#        VP&                  ^4      Vn        \#        VP(                  ^4      Vn        VR7,          P*                  \        \-        V4      R8,          4      ,          pR9\/        VP1                  4       4      \/        VR7,          P*                  R,          P1                  4       4      3.p^^rTpMT\2        P4                  p\2        P6                  p	\2        P8                  p
\:        P<                  ! VR,          ^,          4      p\?        VP@                  VP(                  VPB                  4      Vn         VR7,          P*                  R,          pV! R:V R;V R<\-        V4       R=VR7,          P*                  ^ ,          P1                  4        R>VR7,          P*                  R,          P1                  4        R?VP                    24       VPD                  '       d   \G        WdWQV4      pM\H        p\K        Wm4      p\M        WaPN                  4      w  ppR/^R0RR1^ /pVPP                  R28w  d   VVPP                  ,          pR@VPR                  9   d   VR@,          PT                  V8H  p\        VPW                  4       4      pVV,          p\        VPW                  4       4      \Y        ^V4      ,          ^d,          pV! RAVPP                   RBV RC\        VPW                  4       4       RDVRE RF2	4       MV! RGVPP                   RH24       \[        WVVR7,          VP                   VP$                  VP\                  WV4
      w  ppVRI,          pRJ/ VCRKVPN                  RL\^        RM\`        RN\/        V4      \/        V4      ./CROVP                  RP\b        Pd                  ! \g        VP                  RQ4      Pi                  4       4      Pk                  4       RR\/        VR7,          P*                  ^ ,          P1                  4       4      \/        VR7,          P*                  R,          P1                  4       4      .RSVP\                  RTVPP                  RU\l        Pn                  ! \p        Pr                  4      Pu                  RVRW7      /p\w        VV4      p\x        Pz                  ! \x        P|                  ! V^<4      \x        P|                  ! V^K4      \x        P|                  ! V^4      RX.4      pV! RYVP#                  4       RZ R[VPY                  4       RZ R\V^ ,          RZ R]V^,          RZ R^V^,          RZ 2
4       VP~                  '       Eg   \        V4      p\x        P                  ! VV\        ,          .4      p\        WnVVVWVP                  VP                  4	      pV! V4      w  pp p!T! R_VR` RaV  U"u. uF  p"\        V"^4      NK  	  up" 24       \        VVVP                  VP(                  VP&                  VP\                  W1P@                  4      p#\-        V4      p$\        V#Rb,          R9V$ V4      pV#Rc,          pRdVP(                  ReVP                  RfVP&                  RgVP                  RhV#P                  RiVP@                  4      RjVP                  RkV#Rl,          RmV#Rn,          Ro\	        \x        P                  ! V#Rn,          4      4      Rp\	        \x        P"                  ! V#Rn,          4      4      /
VRq&   VP                  R8X  d   V#P                  Rr/ 4      VRq,          Rs&   Rt\	        V^ ,          4      Ru\	        V^,          4      Rv\	        V^,          4      Rw\	        V^,          4      RxRyRzR{/VR|&   VP                  ;'       g*    \        P                  P                  R}R~RRV RV R24      p%\        V%VWEVVR7       V! RV% R\        P                  ! 4       V,
          RE R24       V! RVR|,           24       R9# u up"i )zTwo-phase MLP trainer)descriptionz--dataT)requiredz--hidden+)typenargsdefaultz
--target-k)r~  r  z--phase1-epochsi,  z--es-generationsz--es-popsizez
--es-sigmar   z--l2gMbP?z--fold-objectiver   r  zPhase-2 fold aggregation: mean matches legacy behavior; min emphasizes worst fold; mean_min blends 70%% mean / 30%% min; robust subtracts drawdown, P&L/DD, trade-count, negative-fold, and threshold-fragility penalties.)choicesr  helpz--es-workerszWorker processes for parallel CMA-ES population evaluation. Use 0 for auto, currently 50%% of logical CPUs capped by popsize; use 1 for sequential evaluation.)r~  r  r  z--worker-fractionz.Logical CPU fraction used when --es-workers=0.z--seedz--smoke
store_truez/Tiny run on recent bars for plumbing validation)actionr  z--skip-phase2)r  z--outzArtifact path override)r  z--assetzHAsset override (e.g. COINBASE_BTCUSD) when filename format doesn't matchz--tfz?Timeframe override (e.g. 4H) when filename format doesn't matchz--approach-bzProbe: inject in_long_position + bars_held_norm (cols 50-51) computed from the current winner artifact's position state (one-cycle circularity per roadmap). Output artifact will have 52 features.z--approach-b-paramszMWinner CSV to derive position state from (default: auto-detect from asset/tf)z--regimebullbearsidewaysallzFilter Phase-1 supervised training to MVRV regime bars only (requires mvrv_regime column). Phase-2 CMA-ES always uses all IS bars.c                 T    \        R \        P                  ! R4       RV  2RR7       R# )[z%H:%M:%Sz] T)flushN)printr   strftime)msgs   &r   r9   main.<locals>.log!  s#    $--
+,Bse4DAr   i   r!   r   g      ?Nzasset=z tf=z bars=z window=r   z hidden=mvrv_regimezregime=z: Phase-1 training bars u    → z (rg  z%)zWARNING: --regime=z0 requested but mvrv_regime not in data; ignoringre   phase1target_k
vol_windowtarget_scaleval_span	data_filedata_sha256rbtrain_windowrn   regime_filtercreatedseconds)timespecr   zphase2: score range [z.1fz, z], seed thresholds entry=z exit=z conf=z"phase2: pretrain baseline fitness=r5  r6  r   r(  
es_popsizees_sigmaes_generations	l2_anchor
es_workersr)  r   best_fitnessr!  fold_calmarsr   fold_mean_calmarfold_min_calmarphase2r  robust_diagnosticsr   r   r   r  r  r   r  Frecommended_thresholds
strategiesr  mlpmlp_weights_r  z.json)rm  	timeframetrainingfeature_colszartifact written: z  (zs total)zrecommended thresholds: )r   r   r   r  )r  r  r  r  )QargparseArgumentParseradd_argumentr   r   r   
parse_argsr   rm  rn  r   datar3   smoketailr0   r   r   phase1_epochsr  r  rj  rD   r&   dater,   	WFO_FOLDSWFO_MIN_OOS_TRADESWFO_MIN_VALID_FOLDSr#   	Timestampr   r  worker_fraction
approach_bry  r   r   rQ   r  regimer%   r:   rx   r   r   rn   r@   rG   hashlibsha256openread	hexdigestr   nowr   r    	isoformatr	   r8   array
percentileskip_phase2r   r   r  r$  r   r   r:  r^  r  r   r   r   rG  r   r   joinr
   )&pro  t0r9   rm  rn  r1   t75r   r   r   r   r   r  r^   rO   rP   _REGIME_INT
regime_intregime_maskbeforepctr   p1_metare   training_metascores0r   r   r_  r"  f0calmars0r  r@  r0  r  rG  s&                                         r   mainr    sD	   ,CDANN8dN+NN:CsRGNDNN<c2N6NN$3N<NN%CN=NN>RN8NN<eTN:NN6tN4NN%/T!=  > NN>Q;  < NN&U<SH  JNN8#rN2NN9\I  KNN?<N8NN7!9N:NN9#mNnNN6#dNeNN>,O  P NN(g  iNN:'JTYa  b <<>D	BB zzzdgggJJr#DII.		499	BzzzWWS\%%4%0!f !3!3R8!$"5"5q9dooq1jooc#b'D.12CHHJRZ__R-@-E-E-G)HIJ+,a	   33 44LLr1.	*4??DOOTMaMabDOjoob!G&tB4vc"gYhf:??1""$
%R6
(;(@(@(B'C8DKK=	Z [ 0BcJ#"+AB.HAu 1fb*a8K{{e -
BJJ&]+22j@K%FK'Eeiik"SF^3c9C'$++&>vheCPUPYPYP[L\K]]_`cdg_hhjkl$T[[M1abc qUBvJ#11499iRUWOFG6?D 	 ?W ?j$--^\IG=? 	TYYw~~d499d&;&@&@&BCMMORZ__Q/4467RZ__R=P=U=U=W9XY		8<<-777K
M !V$G
gr"
gr"
gr"	 J 
c2"W[[]34G H!!+As 36*Q-9L M1c"	$ %
 !&):+G HIrdHe.#224 "&/Ha0C 92:;(QU1a[(;<> 	?wt**DIIsOOM(m!$w-"5t<%[
$//:t}}d11;$((9doo>d11DKDObggd9o&> ?uRVVDO%<=	#
h (*<@HH]TV<WM(#$89 	,U:a=-A*E*Q-,@7z!}9M#U:a=%9&'/M*+ (( E Ebggll<5%1%"U#CECc6,<I
SETYY[2%5c$:(CD
"=1I#J"KLMC <s   8k__main__)r   )   )>__doc__r  concurrent.futuresrY  r  jsonmultiprocessingrW  r   r   sysr   r   r   r   r8   pandasr#   r   ru   abspathr  dirname__file__r,   rh  r   r   r   r   r	   r
   %strategies.strategy_activation_scoresr   tools.worker_utilsr   r   r@   rG   r  r   r   r   r  r   r3   rQ   r   r   r   r   r   r   r   r  r  r  r$  r^  ry  r  __name__ r   r   <module>r     s  @      	 	 
  '   RWW__X-F MN O   D L
  $ "  "/$<9FW=&/%d&C?L
3"I`-AhgNT zF r   