import math import logging import time import numpy as np from scipy import stats from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware logging.basicConfig(level=logging.INFO) logger = logging.getLogger("s7-monte-carlo") app = FastAPI(title="Monte Carlo s7") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # Constants NUM_PATHS = 600 NUM_STEPS = 24 GARCH_OMEGA = 2e-6 GARCH_ALPHA = 0.08 GARCH_BETA = 0.90 @app.post("/simulate") async def simulate(payload: dict): """ Run Monte Carlo simulation with GARCH variance dynamics. Samples innovations from a fitted Student's t-distribution. Enhanced with quantiles, target probabilities, and confidence intervals. """ start_time = time.time() try: last_close = payload.get("lastClose") current_vol = payload.get("currentVol") vol_spike = payload.get("volSpikeActive", False) t_df = payload.get("tDistDf", 3.0) t_loc = payload.get("tDistLoc", 0.0) t_scale = payload.get("tDistScale", 1.0) # Validate inputs if last_close is None or current_vol is None: raise HTTPException(status_code=400, detail="Missing lastClose or currentVol") if last_close <= 0: raise HTTPException(status_code=400, detail="lastClose must be positive") if current_vol < 0: raise HTTPException(status_code=400, detail="currentVol must be non-negative") # Use a tiny default vol if zero if current_vol < 1e-8: current_vol = 0.001 # Convert to float last_close = float(last_close) current_vol = float(current_vol) t_df = float(t_df) t_loc = float(t_loc) t_scale = float(t_scale) # Sanity bounds on t-distribution params t_df = max(2.1, min(t_df, 30.0)) t_scale = max(0.1, min(t_scale, 5.0)) t_loc = max(-2.0, min(t_loc, 2.0)) # Create t-distribution sampler t_sampler = stats.t(df=t_df, loc=t_loc, scale=t_scale) logger.info(f"MC: lastClose={last_close}, currentVol={current_vol}, " f"t(df={t_df}, loc={t_loc}, scale={t_scale}), volSpike={vol_spike}") # ── Run Monte Carlo ── paths = [] init_var = current_vol ** 2 failed_paths = 0 for p in range(NUM_PATHS): try: price = last_close var_t = max(init_var, 1e-12) for step in range(NUM_STEPS): # Sample innovation from t-distribution innovation = float(t_sampler.rvs(1)[0]) # Guard against extreme values innovation = max(-8.0, min(8.0, innovation)) # Current step volatility step_vol = math.sqrt(var_t) # Amplify vol if spike detected (first 6 steps) if vol_spike and step < 6: step_vol *= 1.2 # Price update ret = innovation * step_vol # Guard: clamp return to prevent explosion ret = max(-2.0, min(2.0, ret)) price *= math.exp(ret) price = max(price, 1e-6) # floor # Update GARCH variance var_t = GARCH_OMEGA + GARCH_ALPHA * (ret ** 2) + GARCH_BETA * var_t var_t = max(var_t, 1e-12) # Clamp variance var_t = min(var_t, 0.1) if math.isfinite(price) and price > 0: paths.append(price) else: paths.append(last_close) # fallback failed_paths += 1 except Exception: paths.append(last_close) failed_paths += 1 if len(paths) == 0: raise HTTPException(status_code=500, detail="All Monte Carlo paths failed") if failed_paths > NUM_PATHS * 0.3: logger.warning(f"MC: {failed_paths}/{NUM_PATHS} paths had issues") # ── Sort and compute statistics ── sorted_paths = sorted(paths) n = len(sorted_paths) pred_mean = sum(sorted_paths) / n # ── ENHANCED QUANTILES (instead of just 15/50/85) ── idx_95 = min(int(n * 0.95), n - 1) idx_85 = min(int(n * 0.85), n - 1) idx_75 = min(int(n * 0.75), n - 1) idx_50 = min(int(n * 0.50), n - 1) idx_25 = max(int(n * 0.25), 0) idx_15 = max(int(n * 0.15), 0) idx_05 = max(int(n * 0.05), 0) bull_case_95 = sorted_paths[idx_95] # 95th percentile (very bullish) bull_case_85 = sorted_paths[idx_85] # 85th percentile (bullish) bull_case_75 = sorted_paths[idx_75] # 75th percentile (mildly bullish) median_case = sorted_paths[idx_50] # 50th percentile (median) bear_case_25 = sorted_paths[idx_25] # 25th percentile (mildly bearish) bear_case_15 = sorted_paths[idx_15] # 15th percentile (bearish) bear_case_05 = sorted_paths[idx_05] # 5th percentile (very bearish) # Spread (coefficient of variation) if n > 1: variance = sum((p - pred_mean) ** 2 for p in sorted_paths) / n path_std = math.sqrt(max(variance, 1e-12)) else: path_std = 0.0 spread = path_std / last_close # Break-even probability above = sum(1 for p in sorted_paths if p > last_close) prob_above = round(above / n, 3) prob_below = round(1 - prob_above, 3) # ── NEW: TARGET PROBABILITIES (moves of ±1%, ±2%, ±5%) ── target_up_1pct = sum(1 for p in sorted_paths if p > last_close * 1.01) / n target_down_1pct = sum(1 for p in sorted_paths if p < last_close * 0.99) / n target_up_2pct = sum(1 for p in sorted_paths if p > last_close * 1.02) / n target_down_2pct = sum(1 for p in sorted_paths if p < last_close * 0.98) / n target_up_5pct = sum(1 for p in sorted_paths if p > last_close * 1.05) / n target_down_5pct = sum(1 for p in sorted_paths if p < last_close * 0.95) / n # ── NEW: CONFIDENCE INTERVALS ── # 80% confidence interval (between 10th and 90th percentile) idx_90 = min(int(n * 0.90), n - 1) idx_10 = max(int(n * 0.10), 0) confidence_interval_80 = [sorted_paths[idx_10], sorted_paths[idx_90]] # 90% confidence interval (between 5th and 95th percentile) confidence_interval_90 = [sorted_paths[idx_05], sorted_paths[idx_95]] # ── NEW: DISTRIBUTION SKEWNESS ── # Positive skew = more upside potential, Negative skew = more downside risk if n > 2 and path_std > 0: skewness = sum(((p - pred_mean) / path_std) ** 3 for p in sorted_paths) / n else: skewness = 0.0 # Upside potential ratio (how much bigger is upside vs downside) upside_potential = (bull_case_85 - last_close) / max(last_close - bear_case_15, 1e-6) # ── NEW: VOLATILITY-ADJUSTED METRICS ── # Expected move based on current volatility expected_move_1step = current_vol * math.sqrt(1/24) # daily vol to step vol expected_move_range = [last_close * (1 - expected_move_1step * 2), last_close * (1 + expected_move_1step * 2)] elapsed = time.time() - start_time logger.info(f"MC done in {elapsed:.1f}s: mean={pred_mean:.2f}, " f"95%ile={bull_case_95:.2f}, 5%ile={bear_case_05:.2f}, " f"skew={skewness:.2f}, up1%={target_up_1pct:.2f}") return { # Original fields (backward compatible) "predMean": round(pred_mean, 2), "bullCase": round(bull_case_85, 2), "medianCase": round(median_case, 2), "bearCase": round(bear_case_15, 2), "spread": round(spread, 6), "probabilityAbove": prob_above, "probabilityBelow": prob_below, # NEW: Full quantiles "quantile_95": round(bull_case_95, 2), "quantile_85": round(bull_case_85, 2), "quantile_75": round(bull_case_75, 2), "quantile_50": round(median_case, 2), "quantile_25": round(bear_case_25, 2), "quantile_15": round(bear_case_15, 2), "quantile_05": round(bear_case_05, 2), # NEW: Confidence intervals "confidence_interval_80": [round(confidence_interval_80[0], 2), round(confidence_interval_80[1], 2)], "confidence_interval_90": [round(confidence_interval_90[0], 2), round(confidence_interval_90[1], 2)], # NEW: Target probabilities "prob_up_1pct": round(target_up_1pct, 3), "prob_down_1pct": round(target_down_1pct, 3), "prob_up_2pct": round(target_up_2pct, 3), "prob_down_2pct": round(target_down_2pct, 3), "prob_up_5pct": round(target_up_5pct, 3), "prob_down_5pct": round(target_down_5pct, 3), # NEW: Distribution characteristics "skewness": round(skewness, 3), "upside_potential_ratio": round(upside_potential, 2), "expected_move_range": [round(expected_move_range[0], 2), round(expected_move_range[1], 2)], # Metadata "num_paths": n, "failed_paths": failed_paths } except HTTPException: raise except Exception as e: logger.exception("Monte Carlo failed") raise HTTPException(status_code=500, detail=f"MC error: {str(e)}") @app.get("/health") async def health(): return {"status": "ok", "service": "s7-monte-carlo"}