Rough volatility and deep calibration
Implement rough Bergomi, which reproduces short-maturity skew but has no fast pricing formula, and calibrate it using a GPU-trained surrogate neural network on simulated surfaces. Calibration moves from hours to milliseconds and its fit is compared with Heston on the project's real snapshots.
After this lesson you can
- Simulate rough Bergomi with a scheme for fractional Brownian processes and validate its moments.
- Generate a training set of implied surfaces over a parameter grid.
- Train a network mapping parameters to surfaces with error on the order of Monte Carlo error.
- Calibrate by gradient through the network and compare its fit with Heston on real data.
Before you start
- P03Heston calibrationVariance reduction in pricingSSVI surface
- 28Fractional Brownian motion and Hurst exponent
- 15Epochs and shuffling
- 11Distance metrics and feature scaling
- 13Early stopping as regularization
- 00Canonical training and evaluation loopTraining memory budget
- 29Neural surrogates for UQ and inversionBayesian inverse problem
- 09Reverse-mode automatic differentiation
How much volatility changes up close
If the standard deviation of a signal’s increments scales as , reducing the horizon tenfold reduces its size by . A small retains more variation at short scales. In Volatility is rough, Gatheral, Jaisson, and Rosenbaum estimated log-volatility from high-frequency data and described an exponent on the order of 0.1 in their sample. This is an empirical conclusion about those data and estimators, not a universal constant or a measurement made in this laboratory.
Fractional Brownian motion satisfies . When fitting a line to log-moment against log-scale, the second-moment slope is , while that of the absolute moment of order is . Scale choice, microstructure noise, and realized-volatility estimation matter: a neat line alone does not establish a model.
In correlated rough families under regularity assumptions, short-maturity ATM skew can scale as . This is an asymptotic claim about a class of models, not an exact law for every maturity. Regular Heston with fixed parameters has different short-term dynamics; comparing only one expiry does not identify .
Rough Bergomi and a hybrid scheme
The rough volatility of rough Bergomi uses a Gaussian Volterra process, not the stationary-increment fBm in the figure:
Then and for a flat initial curve. Under the risk-neutral measure take , with and zero rates. links spot and variance changes; makes the kernel singular at the recent endpoint. The memory of means the state is not summarized by as in Heston.
Discretizing the kernel at its singular point gives a poor approximation. The hybrid scheme of Bennedsen, Lunde, and Pakkanen carefully handles intervals near the singularity. Here we use a one-exact-interval version: at each step we jointly simulate and that interval’s singular integral with their exact covariance; for earlier intervals we project the kernel onto constant increments. The discretized process variance is calculated explicitly and used in exponential compensation to preserve on the grid. The scheme still has time error and should be compared as the grid is refined.
The most costly feature is memory: Cholesky factorization of an matrix costs order and stores order entries. On small grids it is a useful reference; on large grids methods exploiting convolution structure or hybrid schemes are preferable. The next control calculates fBm increment covariance, which must not be confused with the Volterra process used to price options.
import numpy as np
def fbm_cholesky(n,H,T,paths=1,seed=0):
if n<1 or not 0<H<1 or T<=0 or paths<1: raise ValueError('Parámetros inválidos')
i=np.arange(n); lag=np.abs(i[:,None]-i[None,:]); dt=T/n
cov=.5*dt**(2*H)*((lag+1)**(2*H)+np.abs(lag-1)**(2*H)-2*lag**(2*H))
L=np.linalg.cholesky(cov); z=np.random.default_rng(seed).standard_normal((paths,n)); [email protected]
return np.column_stack([np.zeros(paths),np.cumsum(increments,axis=1)])
paths=fbm_cholesky(8,.1,1,paths=20000,seed=7); dx=np.diff(paths,axis=1)
emp=np.cov(dx,rowvar=False); dt=1/8; variance=dt**.2; adjacent=.5*dt**.2*(2**.2-2)
print('varianza empírica',emp[0,0],'teórica',variance,'covarianza adyacente empírica',emp[0,1],'teórica',adjacent)For , adjacent fBm increments have negative covariance. By contrast, is a Volterra process starting at zero and its increments are not stationary: using the fBm matrix as if it were the exact covariance of would change the model.
A network as a direct map
Deep calibration with a surrogate network learns the map from model parameters to prices or IVs. Parameters are then fitted to a given surface by propagating derivatives through the network. Horvath, Muguruza, and Tomas study this approach for volatility models: simulation cost is paid during generation and training; inference does not eliminate model or network error.
There are three distinct errors: Monte Carlo noise in labels, simulator time approximation, and network generalization. Validation and test parameters are held out of fitting, and test points are repriced with another seed and more paths. If calibration approaches a boundary of the training domain, an optimum at that boundary does not prove the true parameter lies there. Expanding the domain and generating new labels is more defensible than uncontrolled extrapolation.
Laboratory: the distribution before the network
We work with , , , and . The domain is an experimental choice, not a claim about market ranges. The surface has five maturities from 0.0625 to 1 year and three log-moneyness values . We use 32 steps and out-of-the-money options to avoid subtracting a large intrinsic value. CUDA accelerates the laboratory; this run used an RTX 3060, not the GPU indicated by a generic budget.
For each parameter we simulate increments of the Brownian motion driving . We analytically integrate the price’s independent Brownian motion conditional on that path: if and , conditional forward is and its remaining log variance is . The conditional Black price is variance reduction by conditioning, not an approximation to the independent distribution. We pair normals with their negatives and calculate standard error over pair averages.
import math
import numpy as np
import torch
from scipy.special import ndtr
TIMES=np.array([.0625,.125,.25,.5,1.]); KS=np.array([-.1,0.,.1]); INDICES=(2,4,8,16,32)
LOW=np.array([.03,.08,.5,-.9]); HIGH=np.array([.09,.35,1.5,-.3])
device='cuda' if torch.cuda.is_available() else 'cpu'
def black_otm(vol,T,k):
s=vol*np.sqrt(T); K=np.exp(k); d1=-k/s+s/2; d2=d1-s
return np.where(k>=0,ndtr(d1)-K*ndtr(d2),K*ndtr(-d2)-ndtr(-d1))
def invert(prices):
T=np.repeat(TIMES,len(KS)); k=np.tile(KS,len(TIMES)); lo=np.full_like(prices,.005); hi=np.full_like(prices,3.)
if np.any(prices<=black_otm(lo,T,k)) or np.any(prices>=black_otm(hi,T,k)):
raise ValueError('Precio fuera del intervalo de inversión')
for _ in range(48):
mid=(lo+hi)/2; below=black_otm(mid,T,k)<prices
lo=np.where(below,mid,lo); hi=np.where(below,hi,mid)
return (lo+hi)/2
def simulate(params,paths=4096,steps=32,seed=7,device=device,return_moments=False):
if paths%2 or steps<16 or steps%16: raise ValueError('Se requieren pares y pasos múltiplos de 16')
p=torch.as_tensor(params,dtype=torch.float32,device=device); B=p.shape[0]; P=paths//2; dt=1/steps
xi,H,eta,rho=[p[:,j,None,None] for j in range(4)]
gen=torch.Generator(device=device).manual_seed(seed)
dW=torch.randn((B,steps,P),device=device,generator=gen)*math.sqrt(dt)
extra=torch.randn((B,steps,P),device=device,generator=gen)
dW=torch.cat((dW,-dW),dim=2); extra=torch.cat((extra,-extra),dim=2)
idx=torch.arange(steps,device=device); lag=idx[:,None]-idx[None,:]; L=lag.clamp_min(1).to(torch.float32)[None,:,:]
exponent=H+.5; weights=dt**(H-.5)*((L+1)**exponent-L**exponent)/exponent
weights=torch.where((lag>0)[None,:,:],weights,torch.zeros_like(weights))
coeff=dt**(H-.5)/(H+.5); diag_var=dt**(2*H)/(2*H)
extra_sd=torch.sqrt((diag_var-coeff*coeff*dt).clamp_min(0))
Y=torch.sqrt(2*H)*(torch.bmm(weights,dW)+coeff*dW+extra_sd*extra)
varY=2*H*(weights.square().sum(dim=2,keepdim=True)*dt+diag_var)
Yprev=torch.cat((torch.zeros_like(Y[:,:1]),Y[:,:-1]),dim=1)
Vprev=torch.cat((torch.zeros_like(varY[:,:1]),varY[:,:-1]),dim=1)
variance=xi*torch.exp(eta*Yprev-.5*eta*eta*Vprev)
sumvar=torch.cumsum(variance*dt,dim=1); corr=torch.cumsum(torch.sqrt(variance)*dW,dim=1)
prices=[]; errors=[]
for step,T in zip((TIMES*steps).astype(int),TIMES):
vv=sumvar[:,step-1,:]; cc=corr[:,step-1,:]
Fc=torch.exp(rho[:,0,:]*cc-.5*rho[:,0,:]**2*vv); s=torch.sqrt((1-rho[:,0,:]**2)*vv)
for k in KS:
K=math.exp(k); d1=(torch.log(Fc/K)+.5*s*s)/s; d2=d1-s
Phi=lambda x:.5*(1+torch.erf(x/math.sqrt(2)))
call=Fc*Phi(d1)-K*Phi(d2); payoff=call if k>=0 else call-Fc+K
paired=(payoff[:,:P]+payoff[:,P:])/2
prices.append(paired.mean(dim=1)); errors.append(paired.std(dim=1,unbiased=True)/math.sqrt(P))
price=torch.stack(prices,dim=1).cpu().numpy(); price_se=torch.stack(errors,dim=1).cpu().numpy(); vol=invert(price)
T=np.repeat(TIMES,len(KS)); k=np.tile(KS,len(TIMES)); d1=-k/(vol*np.sqrt(T))+vol*np.sqrt(T)/2
vega=np.exp(-d1*d1/2)/np.sqrt(2*np.pi)*np.sqrt(T); iv_se=price_se/vega
if return_moments:
terminal=xi[:,0,:]*torch.exp(eta[:,0,:]*Y[:,-1,:]-.5*eta[:,0,:]**2*varY[:,-1,:])
return vol,iv_se,{'media Y':Y[:,-1,:].mean().item(),'var Y':Y[:,-1,:].var(unbiased=True).item(),
'var exacta del esquema':varY[:,-1,:].mean().item(),'media v':terminal.mean().item()}
return vol,iv_se
vol,se,moments=simulate(np.array([[.04,.1,1.,-.7]]),paths=8192,return_moments=True)
print('momentos',moments,'IV',vol,'SE IV',se)npm run lab and open the connection link.In a run with 8192 paths, empirical variance of was 0.9904 against the discrete approximation’s exact variance 0.9993, and mean was 0.03964 against 0.04. This is a moment check with sampling noise, not proof of surface convergence as time is refined.
An additional check reprices the same parameter on three grids. Simulations use different seeds, so the standard error of a difference is obtained by adding estimator variances. The comparison does not identify the continuous limit or guarantee uniform convergence across the domain.
ref=[]; ref_se=[]
for n,seed in [(32,810),(64,811),(128,812)]:
with torch.no_grad(): v,e=simulate(np.array([[.04,.1,1.,-.7]]),paths=32768,steps=n,seed=seed,device=device)
ref.append(v[0]); ref_se.append(e[0])
for i in (0,1):
gap=ref[i]-ref[2]; err=np.sqrt(ref_se[i]**2+ref_se[2]**2)
print('pasos', [32,64][i], 'frente a 128: máximo |ΔIV|',np.max(np.abs(gap)),
'ΔIV ATM 1 año',gap[13],'SE de diferencia',err[13])npm run lab and open the connection link.In the reference run, maximum against 128 steps was 0.01892 with 32 steps and 0.00759 with 64. By contrast, the one-year ATM difference was 0.000230 with SE 0.000640 for 32 steps and -0.000114 with SE 0.000630 for 64. Some nodes are much more sensitive; a network accurately reproducing the 32-step grid does not correct that discretization bias.
Generate labels and train
The set uses 2560 parameters uniformly distributed in the domain: 2048 for training, 256 for validation, and 256 for testing. Each surface is estimated with 4096 paths in antithetic pairs. Test seeds and parameters differ from training. An additional seed and 16,384 paths reprice 64 test points to separate network error from label noise. The same 32-step time grid is used in both valuations, so that comparison does not measure time bias.
import time
rng=np.random.default_rng(42); count=2560; batch=8
params=LOW+(HIGH-LOW)*rng.random((count,4)); labels=[]; label_se=[]; start=time.perf_counter()
for i in range(0,count,batch):
with torch.no_grad(): vols,errors=simulate(params[i:i+batch],paths=4096,seed=1000+i,device=device)
labels.append(vols); label_se.append(errors)
if i%256==0: print('superficies',i+len(vols),'de',count)
labels=np.vstack(labels); label_se=np.vstack(label_se)
print('forma',labels.shape,'dispositivo',torch.cuda.get_device_name() if device=='cuda' else 'CPU',
'segundos',time.perf_counter()-start)npm run lab and open the connection link.The MLP receives four parameters normalized to and returns 15 IVs. Each output is normalized using only the training-set mean and standard deviation. Validation selects the best state and triggers early stopping; the test set does not enter that decision. Displayed losses are MSE in normalized units, so they should not be interpreted directly as volatility points.
torch.set_num_threads(1)
train=slice(0,2048); valid=slice(2048,2304); test=slice(2304,2560)
mu=labels[train].mean(axis=0); sd=np.maximum(labels[train].std(axis=0),1e-5)
X=(params-LOW)/(HIGH-LOW)*2-1; Z=(labels-mu)/sd
xt=torch.tensor(X,dtype=torch.float32,device=device); yt=torch.tensor(Z,dtype=torch.float32,device=device)
torch.manual_seed(23)
net=torch.nn.Sequential(torch.nn.Linear(4,64),torch.nn.SiLU(),torch.nn.Linear(64,64),torch.nn.SiLU(),
torch.nn.Linear(64,64),torch.nn.SiLU(),torch.nn.Linear(64,15)).to(device)
optimizer=torch.optim.Adam(net.parameters(),lr=.001); best=float('inf'); best_state=None; best_epoch=0; history=[]
for epoch in range(1,801):
net.train(); order=torch.randperm(2048,device=device)
for ids in order.split(128):
loss=(net(xt[ids])-yt[ids]).square().mean(); optimizer.zero_grad(); loss.backward(); optimizer.step()
net.eval()
with torch.no_grad():
train_loss=(net(xt[train])-yt[train]).square().mean().item()
val_loss=(net(xt[valid])-yt[valid]).square().mean().item()
history.append((epoch,train_loss,val_loss))
if val_loss<best-1e-6:
best=val_loss; best_epoch=epoch; best_state={k:v.detach().cpu().clone() for k,v in net.state_dict().items()}
if epoch-best_epoch>=80: break
net.load_state_dict(best_state); net.eval()
with torch.no_grad(): pred=net(xt[test]).cpu().numpy()*sd+mu
print('mejor época',best_epoch,'épocas ejecutadas',epoch,'RMSE IV frente a etiquetas',np.sqrt(np.mean((pred-labels[test])**2)),
'mediana SE IV de etiquetas',np.median(label_se[test]))npm run lab and open the connection link.cases=params[test][:64]; fresh=[]; fresh_se=[]
for i in range(0,len(cases),8):
with torch.no_grad(): value,error=simulate(cases[i:i+8],paths=16384,seed=50000+i,device=device)
fresh.append(value); fresh_se.append(error)
fresh=np.vstack(fresh); fresh_se=np.vstack(fresh_se)
print('RMSE red contra MC independiente',np.sqrt(np.mean((pred[:64]-fresh)**2)))
print('RMSE etiqueta contra MC independiente',np.sqrt(np.mean((labels[test][:64]-fresh)**2)))
print('error MC combinado cuadrático',np.sqrt(np.mean(label_se[test][:64]**2+fresh_se**2)))npm run lab and open the connection link.In this run, best validation was at epoch 268 and stopping occurred at 348. RMSE against held-out labels was 0.001924 IV, with median label SE 0.001349. Against 64 independent surfaces it was 0.000988; between the original label and second estimate it was 0.001814, compared with a root-sum-square combined MC error of 0.002133. Network error is on the scale of experimental noise, not necessarily below the time error just observed.
Comparison with a second simulation is more informative than evaluating only against labels that generated the set. Still, both share discretization and model family. A convergence study must regenerate prices with more steps and also control inversion bias in the wings.
Calibrate to the historical sample
The sample from the first lesson comes from HistoricalData.net. The cell downloads the daily member again and checks its SHA256. It selects European SPXW with PM settlement on September 15, 2022, and estimates forward and discount by parity at strikes 3600 to 4200. The file lacks quote times: the comparison is exploratory and does not show that bands were simultaneous. It filters to maturities and log-moneyness within the network grid; interpolation is not observation of the surface between nodes.
import io, urllib.request, zipfile, hashlib
import pandas as pd
from scipy.optimize import brentq, least_squares
class RemoteZip(io.RawIOBase):
def __init__(self,url):
self.url=url; self.pos=0
with urllib.request.urlopen(urllib.request.Request(url,method='HEAD'),timeout=30) as r: self.n=int(r.headers['Content-Length'])
def seekable(self): return True
def readable(self): return True
def tell(self): return self.pos
def seek(self,off,whence=0):
self.pos=off if whence==0 else self.pos+off if whence==1 else self.n+off
return self.pos
def read(self,n=-1):
if n<0: n=self.n-self.pos
if not n: return b''
end=min(self.n-1,self.pos+n-1)
with urllib.request.urlopen(urllib.request.Request(self.url,headers={'Range':f'bytes={self.pos}-{end}'}),timeout=60) as r:
if r.status!=206: raise RuntimeError('El servidor no admite rangos')
data=r.read()
self.pos+=len(data); return data
url='https://historicaldata.net/file/options_sample_2022H2.zip'
with zipfile.ZipFile(RemoteZip(url)) as z: data=z.read('day_by_date/2022-09-15_options.csv')
assert hashlib.sha256(data).hexdigest()=='054acc61106b15a21a2b166e975a506fb0559b9a8d7ec896817ab5e6eb8c208a'
raw=pd.read_csv(io.BytesIO(data)); d=raw[(raw.underlying=='SPXW')&(raw['style']=='E')&(raw.settlement_time=='PM')].copy()
d=d[(d.bid>=0)&(d.ask>d.bid)&(d.volume>=1)&(d.open_interest>=10)]
def black(F,K,T,D,v,call):
s=v*np.sqrt(T); z=np.log(F/K)/s+s/2
return D*((F*ndtr(z)-K*ndtr(z-s)) if call else (K*ndtr(-z+s)-F*ndtr(-z)))
rows=[]
for expiry in ['2022-09-30','2022-10-14','2022-10-28','2022-11-18','2022-12-16']:
group=d[d.expiration==expiry].copy()
if group.duplicated(['strike','type']).any(): raise ValueError('Contratos duplicados')
pairs=group.pivot(index='strike',columns='type',values=['bid','ask']).dropna()
mid=(pairs['bid']+pairs['ask'])/2; mask=(pairs.index>=3600)&(pairs.index<=4200)
strike=pairs.index.to_numpy()[mask]; y=(mid['call']-mid['put']).to_numpy()[mask]
a,slope=np.linalg.lstsq(np.c_[np.ones(len(strike)),strike],y,rcond=None)[0]; D=-slope; F=a/D
if D<=0 or F<=0: raise ValueError('Paridad inválida')
T=(pd.Timestamp(expiry)-pd.Timestamp('2022-09-15')).days/365
for row in group.itertuples():
if not 3600<=row.strike<=4200: continue
call=row.type=='call'
if call!=(row.strike>=F): continue
def iv(price):
lo=black(F,row.strike,T,D,.0001,call); hi=black(F,row.strike,T,D,4.,call)
if not lo<price<hi: return np.nan
return brentq(lambda v:black(F,row.strike,T,D,v,call)-price,.0001,4.)
vol=iv((row.bid+row.ask)/2); vlo=iv(row.bid); vhi=iv(row.ask)
if np.isfinite(vol) and np.isfinite(vlo) and np.isfinite(vhi) and vhi>vlo:
rows.append((expiry,T,np.log(row.strike/F),vol,(vhi-vlo)/2))
real=pd.DataFrame(rows,columns=['expiry','T','k','iv','halfspread'])
real=real[(real['T']>=TIMES[0])&(real['T']<=TIMES[-1])&(real.k>=KS[0])&(real.k<=KS[-1])].copy()
print('observaciones',len(real),'vencimientos',real.expiry.unique().tolist(),'mediana semispread IV',real.halfspread.median(),
'horas de cotización disponibles',int(d.quote_time.notna().sum()))npm run lab and open the connection link.The network returns IV at 15 nodes. We interpolate bilinearly in maturity and log-moneyness only within that grid. Optimizer parameter constraints match the training domain. Optimization time is measured once the network is loaded and warmed up, excluding dataset generation and training. The solution is then simulated with an independent seed and more paths to detect whether the optimizer has exploited network errors.
net=net.to('cpu'); net.eval(); mu_t=torch.tensor(mu,dtype=torch.float32); sd_t=torch.tensor(sd,dtype=torch.float32)
low_t=torch.tensor(LOW,dtype=torch.float32); high_t=torch.tensor(HIGH,dtype=torch.float32)
W=np.zeros((len(real),15))
for i,row in enumerate(real.itertuples()):
j=np.clip(np.searchsorted(TIMES,row.T)-1,0,len(TIMES)-2); q=np.clip(np.searchsorted(KS,row.k)-1,0,len(KS)-2)
t=(row.T-TIMES[j])/(TIMES[j+1]-TIMES[j]); k=(row.k-KS[q])/(KS[q+1]-KS[q])
for ti,tw in ((j,1-t),(j+1,t)):
for ki,kw in ((q,1-k),(q+1,k)): W[i,ti*3+ki]=tw*kw
Wt=torch.tensor(W,dtype=torch.float32); target=real.iv.to_numpy(); target_t=torch.tensor(target,dtype=torch.float32)
def surrogate_t(param): return net(2*(param-low_t)/(high_t-low_t)-1)*sd_t+mu_t
def residual_t(param): return Wt@surrogate_t(param)-target_t
def residual(param):
with torch.no_grad(): return residual_t(torch.tensor(param,dtype=torch.float32)).numpy().astype(float)
def jacobian(param):
v=torch.tensor(param,dtype=torch.float32,requires_grad=True)
return torch.autograd.functional.jacobian(residual_t,v,vectorize=True,strategy='forward-mode').detach().numpy().astype(float)
initial=(LOW+HIGH)/2; residual(initial); jacobian(initial); start=time.perf_counter()
fit=least_squares(residual,initial,jac=jacobian,bounds=(LOW+1e-6,HIGH-1e-6),max_nfev=100,
ftol=1e-9,xtol=1e-9,gtol=1e-9)
print('parámetros rough',fit.x,'RMSE IV red',np.sqrt(np.mean(fit.fun**2)),
'segundos optimización',time.perf_counter()-start,'éxito',fit.success)
with torch.no_grad(): check,check_se=simulate(fit.x[None,:],paths=65536,seed=8777,device=device)
pred_mc=W@check[0]; pred_net=W@surrogate_t(torch.tensor(fit.x,dtype=torch.float32)).detach().numpy()
print('RMSE IV de MC independiente frente a datos',np.sqrt(np.mean((pred_mc-target)**2)),
'RMSE red frente a MC',np.sqrt(np.mean((pred_net-pred_mc)**2)),'mediana SE IV MC',np.median(check_se))npm run lab and open the connection link.The run selected 268 observations at four maturities. Network fitting gave , , , and , with IV RMSE 0.008220; and were practically at the allowed limits. Once the network was loaded and warmed up, optimization took 0.261 s on this machine, excluding simulation and training. Independent repricing gave RMSE 0.007640 against data and 0.000948 between network and MC, with median MC IV SE per node 0.000639. This diagnoses this grid; with the optimizer at the boundary, it is not reliable parameter identification or a satisfactory fit.
We compare with Heston using the same observations and unweighted IV RMSE. COS prices the call as put plus parity, with 512 terms and fixed truncation for log-return. Initial parameters and bounds are printed in the code; a local minimum does not prove the best possible fit was found. Both models use a flat initial variance curve and are not calibrated to synchronized quotes.
def heston_cf(u,T,p):
v0,theta,kappa,xi,rho=p; u=np.asarray(u,complex); beta=kappa-rho*xi*1j*u
d=np.sqrt(beta*beta+xi*xi*(u*u+1j*u)); g=(beta-d)/(beta+d); e=np.exp(-d*T)
C=kappa*theta/xi**2*((beta-d)*T-2*np.log((1-g*e)/(1-g)))
D=(beta-d)/xi**2*(1-e)/(1-g*e)
return np.exp(C+D*v0)
def heston_cos(K,T,p,N=512,L=3.):
K=np.atleast_1d(np.asarray(K,float)); a=-L; b=L; u=np.arange(N)*np.pi/(b-a)
def chi(c,d):
return (np.exp(d)*(np.cos(u*(d-a))+u*np.sin(u*(d-a)))-np.exp(c)*(np.cos(u*(c-a))+u*np.sin(u*(c-a))))/(1+u*u)
def psi(c,d):
out=np.empty_like(u); out[0]=d-c; out[1:]=(np.sin(u[1:]*(d-a))-np.sin(u[1:]*(c-a)))/u[1:]; return out
H=2/(b-a)*(psi(a,0)-chi(a,0)); H[0]*=.5
phase=np.outer(np.log(1/K),u); coef=heston_cf(u,T,p)*np.exp(-1j*a*u)*H
return K*(np.cos(phase)@coef.real-np.sin(phase)@coef.imag)+1-K
def heston_resid(p):
out=np.empty(len(real))
for T in sorted(real['T'].unique()):
ids=np.flatnonzero(real['T'].to_numpy()==T); strikes=np.exp(real.k.to_numpy()[ids]); values=heston_cos(strikes,T,p)
for j,K,c in zip(ids,strikes,values):
lo=black(1,K,T,1,.0001,True); hi=black(1,K,T,1,4.,True)
out[j]=1. if not lo<c<hi else brentq(lambda v:black(1,K,T,1,v,True)-c,.0001,4.)-target[j]
return out
hfit=least_squares(heston_resid,[.06,.06,1.,.5,-.6],bounds=([.01,.01,.1,.05,-.98],[.2,.2,5.,1.5,.98]),max_nfev=100)
print('Heston (v0, theta, kappa, xi, rho)',hfit.x,'RMSE IV',np.sqrt(np.mean(hfit.fun**2)),
'precios sin inversión',np.sum(hfit.fun==1.),'éxito',hfit.success)npm run lab and open the connection link.Heston produced , , , , and , with IV RMSE 0.001221 and no uninvertible prices at the solution. In this experiment Heston’s fit error is lower, but the comparison does not establish general superiority: rough uses bounded parameters, a flat initial curve, interpolation, and the 32-step discretization that showed sensitivity at some nodes; quote simultaneity is also unknown. Median IV half-spread of these observations is 0.000564, below both RMSEs, and distance from market must be read with those qualifications.
Exercises
def fbm_cholesky(n,H,T,paths=1,seed=0):
raise NotImplementedError()Ideas to remember
Roughness, Monte Carlo error, discretization, and generalization are distinct questions. Out-of-sample tests and independent repricing of the calibrated solution are part of the model, not decoration.