
    8i                         d Z ddlZddlmZmZmZ dedefdZddee   dedefd	Z	dd
ee   dedefdZ
	 	 	 ddededededededefdZdededeeef   fdZdedefdZy)u  
PolyEdge — Fair Value Model for Binary Options

Prices a "Will BTC be above $X in T minutes?" binary option using:
1. Log-normal model (Black-Scholes-style) for base fair value
2. Realized volatility (EWMA) for vol estimate
3. Momentum adjustment for short-term drift
4. Mean-reversion overlay for extreme prices

Fair Value = Φ((ln(S/K) + μT) / (σ√T))
Where:
  S = current BTC price
  K = strike price
  σ = annualized realized volatility
  μ = drift (momentum-adjusted)
  T = time to expiry in years
  Φ = standard normal CDF
    N)ListOptionalTuplexreturnc                     d}d}d}d}d}d}d}| dk  rd	}t        |       } d
d
|| z  z   z  }d
||z  |z   |z  |z   |z  |z   |z  |z   |z  t        j                  |  | z  dz        z  z
  }	dd
||	z  z   z  S )z:Approximate standard normal CDF using Abramowitz & Stegun.g~Z O?gi<15ҿgWU?g9LW@g-UB?g{=@?   r         ?       @      ?)absmathexp)
r   a1a2a3a4a5psigntys
             7/var/www/html/crpytotradingbot/polymarket/fair_value.pynorm_cdfr      s    
B	B
B	B
B
AD1uFsQU{A26B;!#r)Q.3q82=BTXXqbSTfWZlE[[[A#q.!!    returns	ewma_spanc                     t        |       dk  ryd|dz   z  }| d   dz  }| dd D ]  }||dz  z  d|z
  |z  z   } d}t        j                  ||z        }t        |d      S )	a  
    Calculate realized volatility using EWMA of squared returns.
    Returns annualized vol (assuming 5-min bars, 252 trading days).
    
    Args:
        returns: List of log returns
        ewma_span: EWMA span for smoothing
    
    Returns:
        Annualized volatility
       r   r   r	   r   N頚 g?)lenr   sqrtmax)r   r   alphaewma_varrbars_per_year
annual_vols          r   realized_volr*   ,   s     7|a 9q=!EqzQHQR[ =AF#q5yH&<<=
 M8m34Jz4  r   priceslookbackc                     t        |       |dz   k  ry| | d }t        j                  |d   |d   z        }d}||z  }||z  }|S )z
    Estimate short-term drift from recent price momentum.
    
    Args:
        prices: Recent close prices
        lookback: Number of bars for momentum calc
    
    Returns:
        Annualized drift estimate
    r	           Nr
   r   r!   )r"   r   log)r+   r,   recenttotal_returnr(   per_bar_returnannual_drifts          r   momentum_driftr4   J   sa     6{X\!XIJF88F2J23L M!H,N!M1Lr   current_pricestrikevoltime_to_expiry_mindriftmomentum_weightc                    | dk  s
|dk  s|dk  ry|dz  }||z  }|t        j                  |      z  }|dk  r	| |kD  rdS dS t        j                  | |z        |d|dz  z  z
  |z  z   |z  }	t        |	      }
t	        dt        d	|
            S )
uK  
    Calculate fair value of a binary option "BTC above strike at expiry".
    
    Uses log-normal model:
    FV = Φ((ln(S/K) + (μ - σ²/2)T) / (σ√T))
    
    With momentum-adjusted drift:
    μ_adj = drift * momentum_weight
    
    Args:
        current_price: Current BTC price
        strike: Strike price of the binary
        vol: Annualized volatility
        time_to_expiry_min: Minutes until resolution
        drift: Annualized momentum drift
        momentum_weight: Weight for momentum (0 = ignore, 1 = full)
    
    Returns:
        Fair value between 0 and 1
    r   r   i  g|=r   r.   r    g{Gz?gGz?)r   r#   r/   r   r$   min)r5   r6   r7   r8   r9   r:   Tmusigma_sqrt_td2
fair_values              r   calc_fair_valuerB   d   s    8 Vq[C1H 	m,A 
	 B 1%Le#f,s5#5
((=6)
*b3a<.?1-D
D	TB"J tSz*++r   rA   market_pricec                 D    | |z
  }|dkD  rd|fS |dk  rdt        |      fS y)aP  
    Calculate trading edge: difference between fair value and market price.
    
    Returns:
        (direction, edge_magnitude)
        direction: "buy_yes" if FV > market (YES is cheap)
                   "buy_no"  if FV < market (NO is cheap / YES is expensive)
        edge: absolute mispricing (always positive if tradeable)
    r   buy_yesbuy_no)noner.   )r   )rA   rC   edges      r   	calc_edgerI      s8     $Dax$	T""r   c                 8    | dkD  r| dz
  dz  S | dk  rd| z
  dz  S y)a,  
    Adjust edge for mean-reversion at extremes.
    
    When market price is very high (>0.85) or very low (<0.15),
    there's a statistical tendency to revert. This adds a small
    edge bonus for fading extreme prices.
    
    Returns:
        Additional edge (positive = fade the extreme)
    g333333?r   g333333?r.    )rC   s    r   mean_reversion_adjustmentrL      s7     dt#s**		|#s**r   )   )   )g      @r.   g333333?)__doc__r   typingr   r   r   floatr   intr*   r4   rB   strrI   rL   rK   r   r   <module>rT      s   &  ( (" "% "(!$u+ !# !u !<4; # e < !$ 1,1,1, 
1, 	1,
 1, 1, 1,h% u sEz9J (E e r   