
    ':iu#                        d dl Zd dlZd dlZd dlZd dlmZ dbdZ	dcdZ
 ed        ej                  ddd	      Zed
   j                         j                  j!                         Zej%                         Z ed ee       d        eded   d       ej+                         Zeez  Z ed        ed        ed        e	edd      Z ed        eded   d        eded            eded            eded   ez  d        eded   ez  d         ed!ed"   d#        ed$        e
ede%      ez  Z ej2                  d&d&d'(      \  ZZed)   Z eed*         D ]2  \  ZZeD  cg c]  } | d"   	 c} Z ejC                  e d+d,edz    -       4 ejE                  d.       ejG                  d/       ejI                  d0       ejK                  d1       ejM                          ed2   Z eed*         D ]2  \  ZZeD  cg c]  } | d3   	 c} Z'ejC                  e'd+d,edz    -       4 ejQ                  ed   d4d5d6ed    7       ejG                  d8       ejI                  d0       ejK                  d9       ejM                          ed:   Z ejR                   ee            Z* ejR                   ee       ee      dz         Z+ejC                  e*ed;d<d=       ejC                  e+ed>d?d&=       ejY                  e+ed@z  edAz  dBd4C       ej[                   ee      dz
  dDdEdFG       ejG                  dH       ejI                  dI       ejK                  dJ       ejM                          edK   Zej]                  dL       dMed   ddNZ/ej_                  dOd@e/ej`                  ddPdQ e1dRdSdTU      V        ejd                           ejf                           ed        edW        ed        edIdXdYdZd[dYd\d]        ed^       d_D ]#  Z4e4 ee      k  s ee4dXd`ee4dz
     da       %  ed       yc c} w c c} w )d    N(   c           	         | d   }d }t        j                  t        |      d      }d}t        d      }g }	t        |      D ]z  }
t        j                  d      t        j                  |      z  dz  }|j                         j                         }t         j                  j                  |g|	      }g }t        d
      D ]  }|j                           |||      \  }}|j                          |j                          t        j                         5  |j                  d       ddd       |j!                  ||j#                         |j#                         |j#                         d       |j#                         |k  s|j#                         }|j#                         } |	j!                  |       |dk  s{ n |t        j$                  |      sd}t        t'        |            }|dz  d|z  z   }t        t)        j                  t+        |d                  }t+        ||z
  dz  d      }t+        ||z   dz  d      }||||||	dS # 1 sw Y   (xY w)uU  
    BTC forecasting via gradient descent on the price gap.
    
    Key Insight:
    - Treat BTC price P as having a "hidden factorization" structure
    - Find the "gap" d between price and market equilibrium
    - The loss L(d) = sin²(π·s) where s = √(d² + 4P)
    - Gradient descent collapses d to find the true price manifold
    c                     t        j                  | dz  d|z  z         }t        j                  t         j                  |z        dz  }||fS )u   
        d = gap between price and equilibrium
        P_val = current BTC price
        s = √(d² + 4P) is the "market invariant" that should be integer-like
           g      @)torchsqrtsinpi)dP_valslosss       btc_factorization.pyloss_fnz*cct_btc_gradient_forecast.<locals>.loss_fn   sE     JJq!tcEk)* yyA&!+Qw    F)requires_gradNinf   
   )lri  g        )min)stepr   r   r   g|=r      g       @)d_starr   base_factorsentiment_factorr   trajectories)r   tensorfloatrangerandnnpr	   detachrequires_grad_optimAdam	zero_gradbackwardr   no_gradclamp_appenditemisfiniteroundmathmax)prices
days_aheadr   num_restartsPr   P_tbest_d	best_lossall_trajectoriesrestartr   	optimizer
trajectoryr   r   r   r   s_sqbase	sentiments                        r   cct_btc_gradient_forecastr@      s    	r
A
 ,,uQxu
5CFeI& KKNRWWQZ'",HHJ%%'KK$$aSR$0	
#J 	"D!aoGD!MMONN "S!" VVX		VVX	  yy{Y& IIK	%	"( 	
+u=B ~R[[05=!F19q1uDdiiD#'(A F
c!3'DQZ3&,I %( ?" "s   IIc                    g }| j                         }t        |      D ]  }|d   }t        |dd      }t        t	        |d         d      }|t        ddt
        j                  j                         z  z   d      z  }|j                  |       t        j                  ||      }t        d	|dz    d
||z  dd||z  dd|d   |z  dd|d    
        t        j                  |      S )z
    CCT-ODE Multi-Step Forecast:
    Each future day is predicted by gradient descent on the current state.
    This creates a "chain of collapses" - each day collapses independently.
    r   r      r3   r4   r   g-q=g{Gz?gư>zDay z: P=.2fu    → Predicted=z | Base Factor=z, Gap d=r   )copyr!   r@   r1   r    r#   randomr"   r,   printarray)	r2   r3   price_scale	forecastscurrent_pricesdayr5   resultpredicted_prices	            r   predict_multi_steprO   f   s    I[[]NZ  b2 +>aVWX eF=$9:EB 	3q4"))//*;#;;TBB)>?CSUG4K4OOVaDabeCf g#M2[@EXfU]N^M_a 	b#b( 88Ir   zDownloading BTC data...zBTC-USD6mo1d)periodintervalClosezLoaded z days of BTC datazCurrent price: $r   z,.2fz=
============================================================zCCT-GRADIENT BTC FORECASTz<============================================================r   r   rC   z
CCT Analysis of Current Price:z  Current Price P: $z  Optimal Gap d*: r   z  Market Invariant s: r   z  Base Factor (Fundamental): $r   z  Sentiment Factor: r   rD   z  Loss (Collapsed): r   z.2ez
Generating 40-day forecast...)r3   rI   r   )   r   )figsize)r   r   r   gffffff?zRestart )alphalabellogz&CCT Gradient Descent: Loss ConvergenceStepu   Loss (sin²))r   r   r   redz--z	Final d*=)ycolor	linestylerX   z'CCT Gradient Descent: Gap d ConvergencezGap d)r   r   zb-
Historical)rX   	linewidthzr-zCCT Forecastg?g?g?)rW   r]   gray:Today)xr]   r^   rX   z)BTC-USD: Historical + 40-Day CCT ForecastDayzPrice (USD))r   r   offu   
CCT-GRADIENT STRUCTURE
═══════════════════════════════════════════

BTC Price P = Base Factor × Sentiment Factor

Current Price: $uF  

┌─────────────────────────────────────────────┐
│  Loss: L(d) = sin²(π·s)                     │
│  where s = √(d² + 4P)                       │
│                                             │
│  Gradient: ∂L/∂d = π·sin(2πs)·d/s           │
│                                             │
│  Converges when s → integer (stable state)  │
└─────────────────────────────────────────────┘

Analogy to Factorization:
• Factorization: c = p × q, find gap d = q - p
• BTC: P = B × S, find gap d = S - B

Both use: s² = d² + 4c  (or 4P)

The "integer constraint" forces collapse
to the true factor structure.
g?top	monospacer/   wheatg      ?)boxstyle	facecolorrW   )	transformfontsizeverticalalignment
fontfamilybboxz"40-Day BTC Forecast (CCT-Gradient)z<6 Forecastz<20zBase Factorz<15z<------------------------------------------------------------)r      r      r   z $z>15,.2f)r   g?rs   )r   g      ?)5numpyr#   yfinanceyfr   r0   matplotlib.pyplotpyplotpltr@   rO   rG   downloadbtcdropnavaluesflattencloserE   	close_rawlenr1   close_scalerM   forecastsubplotsfigaxesax	enumerateitrajlossesplot
set_yscale	set_title
set_xlabel
set_ylabellegenddsaxhlinearange	days_histdays_fcfill_betweenaxvlineaxistext	transAxesdicttight_layoutshowr   )ts   0r   <module>r      s       TnF   bkk)ED9G$$,,.JJL	 E
|,- . 2t,- . iik  
 m  ! " f 
#5QR	H ( * Yr]401 2 6(+,- . vc{m, - &}(=(KT&RS T V$67+EcJK L VF^C01 2 ' )eL{Z
 CLLAx0	T 
$Z/0 7GAt!%&Aai&FGGF#x!u%5G67 e  5 6 f  n  		 
$Z/0 3GAt	Q!C&	BGGBc8AaC5!1G23 

VHUdIfU]N^M_B`
 a 6 7 f  g  		 
$ZBIIc%j!	
"))CJE
R
0 	9d,! D 4~ C CCs% P 

S^AVs'
 J 8 9 e  m  		 
$Z  2t$ %4 S$",,K7gSA  C     

 m  * + f r
!Js#1]3$78 9 f	 2ACM2b!A#w/012 fa ' 
 s   >QQ"