Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,10 @@
|
|
| 1 |
import math
|
| 2 |
-
import random
|
| 3 |
import logging
|
| 4 |
import time
|
| 5 |
import numpy as np
|
|
|
|
| 6 |
from fastapi import FastAPI, HTTPException
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
-
from typing import List
|
| 9 |
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
| 11 |
logger = logging.getLogger("s7-monte-carlo")
|
|
@@ -27,46 +26,21 @@ GARCH_ALPHA = 0.08
|
|
| 27 |
GARCH_BETA = 0.90
|
| 28 |
|
| 29 |
|
| 30 |
-
def gaussian_rand():
|
| 31 |
-
"""Box-Muller standard normal."""
|
| 32 |
-
u1 = random.random()
|
| 33 |
-
u2 = random.random()
|
| 34 |
-
while u1 == 0:
|
| 35 |
-
u1 = random.random()
|
| 36 |
-
return math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2)
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def kde_sample(samples: List[float], bandwidth: float) -> float:
|
| 40 |
-
"""Sample from KDE built on samples using Gaussian kernel."""
|
| 41 |
-
n = len(samples)
|
| 42 |
-
if n == 0:
|
| 43 |
-
return gaussian_rand()
|
| 44 |
-
|
| 45 |
-
# Pick a random base point
|
| 46 |
-
base = samples[random.randint(0, n - 1)]
|
| 47 |
-
# Add Gaussian noise scaled by bandwidth
|
| 48 |
-
sample_val = base + bandwidth * gaussian_rand()
|
| 49 |
-
|
| 50 |
-
# Guard against extreme values
|
| 51 |
-
if not math.isfinite(sample_val) or abs(sample_val) > 10:
|
| 52 |
-
return gaussian_rand()
|
| 53 |
-
|
| 54 |
-
return sample_val
|
| 55 |
-
|
| 56 |
-
|
| 57 |
@app.post("/simulate")
|
| 58 |
async def simulate(payload: dict):
|
| 59 |
"""
|
| 60 |
Run Monte Carlo simulation with GARCH variance dynamics.
|
|
|
|
| 61 |
"""
|
| 62 |
start_time = time.time()
|
| 63 |
|
| 64 |
try:
|
| 65 |
-
last_close
|
| 66 |
-
current_vol
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
| 70 |
|
| 71 |
# Validate inputs
|
| 72 |
if last_close is None or current_vol is None:
|
|
@@ -75,8 +49,6 @@ async def simulate(payload: dict):
|
|
| 75 |
raise HTTPException(status_code=400, detail="lastClose must be positive")
|
| 76 |
if current_vol < 0:
|
| 77 |
raise HTTPException(status_code=400, detail="currentVol must be non-negative")
|
| 78 |
-
if len(normalized_returns) < 10:
|
| 79 |
-
raise HTTPException(status_code=400, detail="Need at least 10 normalized returns")
|
| 80 |
|
| 81 |
# Use a tiny default vol if zero
|
| 82 |
if current_vol < 1e-8:
|
|
@@ -85,11 +57,20 @@ async def simulate(payload: dict):
|
|
| 85 |
# Convert to float
|
| 86 |
last_close = float(last_close)
|
| 87 |
current_vol = float(current_vol)
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
logger.info(f"MC: lastClose={last_close}, currentVol={current_vol}, "
|
| 91 |
-
f"
|
| 92 |
-
f"volSpike={vol_spike_active}")
|
| 93 |
|
| 94 |
# ββ Run Monte Carlo ββ
|
| 95 |
paths = []
|
|
@@ -102,14 +83,17 @@ async def simulate(payload: dict):
|
|
| 102 |
var_t = max(init_var, 1e-12)
|
| 103 |
|
| 104 |
for step in range(NUM_STEPS):
|
| 105 |
-
# Sample innovation from
|
| 106 |
-
innovation =
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
# Current step volatility
|
| 109 |
step_vol = math.sqrt(var_t)
|
| 110 |
|
| 111 |
# Amplify vol if spike detected (first 6 steps)
|
| 112 |
-
if
|
| 113 |
step_vol *= 1.2
|
| 114 |
|
| 115 |
# Price update
|
|
|
|
| 1 |
import math
|
|
|
|
| 2 |
import logging
|
| 3 |
import time
|
| 4 |
import numpy as np
|
| 5 |
+
from scipy import stats
|
| 6 |
from fastapi import FastAPI, HTTPException
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 8 |
|
| 9 |
logging.basicConfig(level=logging.INFO)
|
| 10 |
logger = logging.getLogger("s7-monte-carlo")
|
|
|
|
| 26 |
GARCH_BETA = 0.90
|
| 27 |
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
@app.post("/simulate")
|
| 30 |
async def simulate(payload: dict):
|
| 31 |
"""
|
| 32 |
Run Monte Carlo simulation with GARCH variance dynamics.
|
| 33 |
+
Samples innovations from a fitted Student's t-distribution.
|
| 34 |
"""
|
| 35 |
start_time = time.time()
|
| 36 |
|
| 37 |
try:
|
| 38 |
+
last_close = payload.get("lastClose")
|
| 39 |
+
current_vol = payload.get("currentVol")
|
| 40 |
+
vol_spike = payload.get("volSpikeActive", False)
|
| 41 |
+
t_df = payload.get("tDistDf", 3.0)
|
| 42 |
+
t_loc = payload.get("tDistLoc", 0.0)
|
| 43 |
+
t_scale = payload.get("tDistScale", 1.0)
|
| 44 |
|
| 45 |
# Validate inputs
|
| 46 |
if last_close is None or current_vol is None:
|
|
|
|
| 49 |
raise HTTPException(status_code=400, detail="lastClose must be positive")
|
| 50 |
if current_vol < 0:
|
| 51 |
raise HTTPException(status_code=400, detail="currentVol must be non-negative")
|
|
|
|
|
|
|
| 52 |
|
| 53 |
# Use a tiny default vol if zero
|
| 54 |
if current_vol < 1e-8:
|
|
|
|
| 57 |
# Convert to float
|
| 58 |
last_close = float(last_close)
|
| 59 |
current_vol = float(current_vol)
|
| 60 |
+
t_df = float(t_df)
|
| 61 |
+
t_loc = float(t_loc)
|
| 62 |
+
t_scale = float(t_scale)
|
| 63 |
+
|
| 64 |
+
# Sanity bounds on t-distribution params
|
| 65 |
+
t_df = max(2.1, min(t_df, 30.0))
|
| 66 |
+
t_scale = max(0.1, min(t_scale, 5.0))
|
| 67 |
+
t_loc = max(-2.0, min(t_loc, 2.0))
|
| 68 |
+
|
| 69 |
+
# Create t-distribution sampler
|
| 70 |
+
t_sampler = stats.t(df=t_df, loc=t_loc, scale=t_scale)
|
| 71 |
|
| 72 |
logger.info(f"MC: lastClose={last_close}, currentVol={current_vol}, "
|
| 73 |
+
f"t(df={t_df}, loc={t_loc}, scale={t_scale}), volSpike={vol_spike}")
|
|
|
|
| 74 |
|
| 75 |
# ββ Run Monte Carlo ββ
|
| 76 |
paths = []
|
|
|
|
| 83 |
var_t = max(init_var, 1e-12)
|
| 84 |
|
| 85 |
for step in range(NUM_STEPS):
|
| 86 |
+
# Sample innovation from t-distribution
|
| 87 |
+
innovation = float(t_sampler.rvs(1)[0])
|
| 88 |
+
|
| 89 |
+
# Guard against extreme values
|
| 90 |
+
innovation = max(-8.0, min(8.0, innovation))
|
| 91 |
|
| 92 |
# Current step volatility
|
| 93 |
step_vol = math.sqrt(var_t)
|
| 94 |
|
| 95 |
# Amplify vol if spike detected (first 6 steps)
|
| 96 |
+
if vol_spike and step < 6:
|
| 97 |
step_vol *= 1.2
|
| 98 |
|
| 99 |
# Price update
|