Module contents
Lesson 30 of 30Research 120 min

Frontier II: deep hedging, rough volatility and synthetic markets

Explore deep hedging with transaction costs, rough volatility and neural calibration, and synthetic market generators, with emphasis on independent validation and model risk.

After this lesson you can

  • Formulate deep hedging as convex risk minimization and train with transaction costs on GPU.
  • Compare the learned policy with delta and Leland hedging and interpret differences.
  • Simulate rough volatility with a hybrid scheme and explain the short-maturity skew power law.
  • Train a neural surrogate for model pricing and calibration.
  • Train and evaluate a synthetic financial-series generator and explain validation risks.

Before you start

Three tools, three sets of assumptions

A learned hedge, rough-volatility model and market generator can broaden the set of experiments. Each depends on its training distribution, discretization and objective. A network does not automatically turn a simulator into reality or eliminate model risk.

Deep hedging from Buehler and coauthors learns a policy adapted to available information that minimizes a risk measure of the hedging outcome. For a short derivative with payoff HH, trading gains G(δ)G(\delta) and costs C(δ)C(\delta), one formulation is inf⁡δρ(−H+G(δ)−C(δ))\inf_\delta\rho(-H+G(\delta)-C(\delta)), where ρ\rho is a wealth risk measure. A network can receive price, time and previous position; the latter matters because trading has a cost.

For loss LL, 95% ES measures upper-tail mean under a continuous convention. In a finite sample one must choose how to handle ties and observations at the quantile; the lab uses the mean of the largest losses. Minimizing that tail is not equivalent to minimizing variance, expected loss or mean hedging cost. A policy can improve one metric and worsen another, so both should be shown.

If cost depends on position change, a rule that always jumps to the costless delta may trade too much. Some formulations produce no-trading regions, but not every trained network learns a band and not every cost rule produces the same region. The displayed policy depends on inventory and the simulated process; decisions in rare or out-of-training states need specific tests.

If ρ(X+c)=ρ(X)−c\rho(X+c)=\rho(X)-c, the selling indifference price is the difference between optimal risk with and without the obligation. Without frictions, if an admissible strategy exactly replicates HH at initial cost pp, subtracting its replicating portfolio transforms one position into the other and translation invariance gives price pp. This assumes exact replication and the same opportunity set; it does not automatically extend to incomplete markets.

InteractiveA learned policy

Blue is the policy trained on Heston paths and exported from the lab. Orange is the Black–Scholes delta with simulated volatility as a proxy. The original maturity is 0.25 years. The chart shows a slice of the policy at the selected inputs.

Stock price: 80 to 120Position: 0 to 1

The saved weights correspond to one seed, architecture, distribution, and cost level. The position control evaluates the same network at a different inventory.

0.50
0.20
0.50
Network at price 1000.533
BS delta at price 1000.514
Network order0.033
A slice of the lab-trained network and approximate delta.

Fractional Brownian motion BHB^H is centered Gaussian with covariance 12(t2H+s2H−∣t−s∣2H)\frac12(t^{2H}+s^{2H}-|t-s|^{2H}). Its increments have variance proportional to ∣t−s∣2H|t-s|^{2H} and the process is self-similar with exponent HH. If H<1/2H<1/2, its paths are rougher than ordinary Brownian paths; path roughness should not be confused with long-run persistence.

A common estimate computes structure function m(q,ℓ)=media⁡∣Xt+ℓ−Xt∣qm(q,\ell)=\operatorname{media}|X_{t+\ell}-X_t|^q and fits the slope of log⁡m\log m against log⁡ℓ\log\ell. For ideal fBM the expected exponent is qHqH; with q=2q=2 divide slope by two. Lag choice and microstructure noise can bias it, and a short path does not perfectly identify the exponent.

Rough volatility describes models where log volatility has low regularity. Gatheral, Jaisson and Rosenbaum document estimates around 0.1 in their realized-volatility data. This is specific evidence, not a universal constant. In certain models and under short-maturity assumptions, ATM skew scales as TH−1/2T^{H-1/2}; the constant and validity range depend on model and parameterization.

InteractiveRoughness and structure

The example simulates fBM with the exact covariance of 128 increments using Cholesky factorization. The lower line shows the second-order structure function at lags 1, 2, 4, 8, and 16. Half the log–log slope estimates H.

fBM: ±1.82log structureLags on a log scale: 1 to 16

The skew factor applies the hypothetical T^(H−1/2) law from four weeks to one. The estimated H depends on lags, the sample, and measurement noise.

0.10
H estimated on this path0.08
Skew factor from 4 weeks to 11.74
A finite fractional path does not identify H perfectly.

The rBergomi Volterra process uses singular kernel (t−s)H−1/2(t-s)^{H-1/2}. The hybrid scheme of Bennedsen, Lunde and Pakkanen treats the segment nearest the singularity specially and approximates the rest. A simple discretization can alter roughness and price; time refinement and Monte Carlo error must be studied.

Neural calibration trains a surrogate for the mapping from parameters to prices or implied volatilities, then optimizes parameters against a surface. Speed does not eliminate approximation error, Monte Carlo uncertainty or lack of identification. Independent evaluation against the simulator is needed, along with control of extrapolation outside the trained region.

If different parameters produce nearly identical surfaces on observed strikes and maturities, the inverse problem can have a broad valley. A low-error network can return an acceptable surface with parameters different from those planted. Testing should compare both surface error and parameters and repeat valuation with new seeds; timing only the optimizer hides surrogate construction cost.

Market generators produce paths according to a learned distribution or explicit model. Quant GANs uses temporal convolutions to capture dependence; reproducing a histogram does not guarantee reproducing volatility clustering, tails, cross-dependence or strategy behavior.

Agent-based market simulation represents participants and market messages. ABIDES implements an event simulator with agents, exchange and configurable latencies. Results depend on rules and calibration: an agent appearing profitable in that world is not validated in another.

Synthetic-data validation requires separating fit, validation and real test data by time. If the generator saw the test period, it can transmit future information even when generated paths are new. It can also omit extreme episodes or memorize segments; marginal metrics, temporal dependence, discriminators and comparable backtests examine different aspects.

A discriminator unable to separate two sets in a small sample does not prove their distributions equal: it may have low capacity or few observations. Conversely, a powerful discriminator can detect differences irrelevant to an application. Validation should explain which decisions generated data support, preserve independent temporal sets and check whether a strategy changes behavior under consistent costs and constraints.

InteractiveGuess the origin

One window comes from AAPL in LOBSTER on June 21, 2012, and the other comes from the selected generator. Both show cumulative returns over 64 observations, scaled to compare shapes. AAPL was sampled every 50 messages and normalized by that day's standard deviation.

AB64 steps, cumulative scale ±13.5

The GAN was trained on synthetic GARCH. The displayed AUC comes from classifying GARCH versus GAN on held-out windows. The three pairs are examples to inspect visually.

0
AAPL windowHidden
GARCH vs. GAN AUC0.836
Compare windows derived from AAPL with a synthetic benchmark.

Local lab: Heston hedging

The simulated market has a stock and a sold European call with strike 100 and maturity 0.25 years. We use Heston with Euler and variance projection to zero, zero rate and proportional cost of 10 basis points per trade. The policy observes simulated variance, an idealized information assumption. Simulation runs on GPU when available; the actual device is reported. Training, validation and test paths differ.

The network receives relative log price, instantaneous volatility, remaining time and previous position; it returns a position between 0 and 1. It minimizes the mean of each batch’s largest 5% of losses, an empirical ES estimate. Risk obtained for the call without premium approximates indifference price within this family of stock policies. Under this driftless generator and nonnegative costs, a flat portfolio has zero risk without the obligation and no adapted stock-only strategy has negative expected loss; ES dominates expected loss. The trained network is not guaranteed to reach the global minimum, and this conclusion excludes the approximately quoted option used in another benchmark.

[ ]Train and compare hedgesLocal GPU
import os,json,time,copy
import numpy as np, torch
torch.set_num_threads(2); device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Dispositivo:',device,torch.cuda.get_device_name(0) if device.type=='cuda' else 'CPU')
K=100.; T=.25; steps=20; dt=T/steps; cost=.001; alpha=.95
def heston(n,seed):
    gen=torch.Generator(device=device).manual_seed(seed)
    spot=torch.full((n,),100.,device=device); var=torch.full((n,),.04,device=device)
    S=[spot]; V=[var]
    for _ in range(steps):
        a=torch.randn(n,device=device,generator=gen); b=torch.randn(n,device=device,generator=gen)
        root=var.clamp_min(0).sqrt()
        spot=spot*torch.exp(-.5*root**2*dt+root*np.sqrt(dt)*a)
        var=(var+2*(.04-var.clamp_min(0))*dt+.4*root*np.sqrt(dt)*(-.7*a+np.sqrt(1-.7**2)*b)).clamp_min(0)
        S.append(spot); V.append(var)
    return torch.stack(S,1),torch.stack(V,1)
class Policy(torch.nn.Module):
    def __init__(self):
        super().__init__(); self.net=torch.nn.Sequential(torch.nn.Linear(4,24),torch.nn.ReLU(),
                                                         torch.nn.Linear(24,24),torch.nn.ReLU(),torch.nn.Linear(24,1),torch.nn.Sigmoid())
    def forward(self,S,V,t,q):
        tau=torch.full_like(q,(steps-t)/steps)
        return self.net(torch.stack([torch.log(S/K),V.clamp_min(0).sqrt(),tau,q],1)).squeeze(1)
def es(loss):
    k=max(1,int(np.ceil((1-alpha)*len(loss))))
    return torch.topk(loss,k).values.mean()
def precio_delta_vega(S,vol,tau,strike):
    tau=max(tau,1e-8); vol=vol.clamp_min(.001); rt=np.sqrt(tau)
    d1=(torch.log(S/strike)+.5*vol**2*tau)/(vol*rt); d2=d1-vol*rt
    cdf=lambda x:.5*(1+torch.erf(x/np.sqrt(2)))
    precio=S*cdf(d1)-strike*cdf(d2)
    delta=cdf(d1); vega=S*torch.exp(-.5*d1*d1)/np.sqrt(2*np.pi)*rt
    return precio,delta,vega
def perdida(S,V,modo,policy=None):
    n=len(S); q=torch.zeros(n,device=device); q2=torch.zeros(n,device=device)
    ganancia=torch.zeros(n,device=device); gastos=torch.zeros(n,device=device)
    for t in range(steps):
        tau=(steps-t)*dt; vol=V[:,t].sqrt().clamp_min(.001)
        c2=torch.zeros_like(q); cnext=c2
        if modo=='red': nuevo=policy(S[:,t],V[:,t],t,q); nuevo2=torch.zeros_like(q)
        elif modo=='plana': nuevo=torch.zeros_like(q); nuevo2=torch.zeros_like(q)
        else:
            _,delta,vega=precio_delta_vega(S[:,t],vol,tau,K)
            if modo=='delta': nuevo=delta; nuevo2=torch.zeros_like(q)
            elif modo=='leland':
                vol_L=torch.sqrt(vol**2+cost*vol*np.sqrt(2/(np.pi*dt)))
                nuevo=precio_delta_vega(S[:,t],vol_L,tau,K)[1]; nuevo2=torch.zeros_like(q)
            elif modo=='delta-vega':
                c2,d2,v2=precio_delta_vega(S[:,t],vol,tau,110.)
                cnext=precio_delta_vega(S[:,t+1],V[:,t+1].sqrt(),(steps-t-1)*dt,110.)[0] if t<steps-1 else (S[:,t+1]-110).clamp_min(0)
                nuevo2=(vega/v2.clamp_min(.01)).clamp(0,2); nuevo=delta-nuevo2*d2
            else: raise ValueError('Modo desconocido')
        gastos=gastos+cost*(torch.abs(nuevo-q)*S[:,t]+torch.abs(nuevo2-q2)*c2)
        ganancia=ganancia+nuevo*(S[:,t+1]-S[:,t])+nuevo2*(cnext-c2)
        q,q2=nuevo,nuevo2
    gastos=gastos+cost*torch.abs(q)*S[:,-1]
    return (S[:,-1]-K).clamp_min(0)-ganancia+gastos
torch.manual_seed(283001); train=heston(4096,283002); valid=heston(1024,283003); prueba=heston(4096,283004)
policy=Policy().to(device); opt=torch.optim.Adam(policy.parameters(),lr=.003); best=float('inf'); estado=None
comienzo=time.perf_counter()
for paso in range(160):
    idx=torch.randint(len(train[0]),(512,),device=device)
    opt.zero_grad(); loss=es(perdida(train[0][idx],train[1][idx],'red',policy)); loss.backward(); opt.step()
    if paso%20==19:
        with torch.no_grad(): medida=float(es(perdida(*valid,'red',policy)))
        if medida<best: best=medida; estado=copy.deepcopy(policy.state_dict())
policy.load_state_dict(estado); policy.eval()
if device.type=='cuda': torch.cuda.synchronize()
with torch.no_grad():
    for modo in ('plana','delta','leland','delta-vega','red'):
        loss=perdida(*prueba,modo,policy)
        print(modo,'| ES pérdida 95 %:',float(es(loss)),'| pérdida media:',float(loss.mean()))
    ejemplo=policy(torch.tensor([100.],device=device),torch.tensor([.04],device=device),10,torch.tensor([.5],device=device))
    print('Posición de la red con S=100, σ=.2, vida restante=.5 e inventario=.5:',float(ejemplo[0]))
print('ES validación elegida:',best,'| segundos entrenamiento y evaluación:',time.perf_counter()-comienzo)
ruta=os.environ.get('DEEP_HEDGE_EXPORT')
if ruta:
    pesos={k:v.detach().cpu().tolist() for k,v in policy.state_dict().items()}
    with open(ruta,'w',encoding='utf8') as salida: json.dump({'seed':283001,'cost':cost,'weights':pesos},salida)
    print('Pesos exportados:',ruta)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The comparison uses the same test paths. Black-Scholes delta uses instantaneous volatility as a proxy and is not exact Heston delta. Leland adjusts volatility for costs in this discrete scheme; it is not a no-trading band. Delta-vega hedging adds a strike-110 call valued with Black-Scholes and instantaneous volatility, caps its position at two units and liquidates stock at the end; that quote is an approximation, not a consistent Heston options market. The network trades only the stock. Cost is charged on traded value and stock is liquidated at maturity.

In one NVIDIA RTX 3060 run, test loss ES was approximately 17.35 without hedging, 6.75 with delta, 6.73 with Leland, 6.63 with approximate delta-vega and 7.24 with the network. The network does not beat those benchmarks in this run; its ES estimates trained-policy risk, not proof of a global minimum or a market price.

Local lab: rBergomi and neural calibration

The Volterra process Yt=2H∫0t(t−s)H−1/2dWsY_t=\sqrt{2H}\int_0^t(t-s)^{H-1/2}dW_s is discretized. In each recent interval the singular integral is simulated exactly alongside the correlated Brownian increment; for earlier intervals the kernel is replaced by its interval mean. This one-segment hybrid variant is approximate and uses a direct sum, not FFT convolution. Its cost grows quadratically with step count.

Instantaneous variance is vt=ξ0exp⁡(ηYt−η2Var⁡(Yt)/2)v_t=\xi_0\exp(\eta Y_t-\eta^2\operatorname{Var}(Y_t)/2) and the stock uses a Brownian motion correlated with WW. The correction uses variance of the discretized process to preserve initial mean in that discretization. We train a network on synthetic Monte Carlo surfaces and compare calibration parameters with the simulator. Prices use zero rate, three maturities and three strikes; implied volatilities use bisection and noisy prices are clipped to no-arbitrage bounds before inversion.

[ ]Hybrid surfaces and calibration networkLocal GPU
import numpy as np,torch,time
from scipy.optimize import least_squares
from scipy.special import ndtr
torch.set_num_threads(2); dev=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
steps=32; maturity=.25; dt=maturity/steps; strikes=np.array([.97,1.,1.03]); tenors=np.array([.0625,.125,.25])
def superficies(parametros,npaths,seed):
    pars=torch.as_tensor(parametros,dtype=torch.float32,device=dev); B=len(pars)
    gen=torch.Generator(device=dev).manual_seed(seed)
    H=pars[:,0,None]; eta=pars[:,1,None]; rho=pars[:,2,None]
    dw=torch.randn((B,npaths,steps),device=dev,generator=gen)*np.sqrt(dt)
    dz=torch.randn((B,npaths,steps),device=dev,generator=gen)*np.sqrt(dt)
    zi=torch.randn((B,npaths,steps),device=dev,generator=gen)
    cov=dt**(H+.5)/(H+.5); var_i=dt**(2*H)/(2*H); c=cov/dt
    singular=c[:,:,None]*dw+torch.sqrt((var_i-c*c*dt).clamp_min(0))[:,:,None]*zi
    spot=torch.ones((B,npaths),device=dev); prices=[]
    for t in range(steps):
        if t==0: Y=torch.zeros_like(spot); varY=torch.zeros_like(H)
        else:
            integr=singular[:,:,t-1]; varY=2*H*var_i
            if t>1:
                ks=torch.arange(2,t+1,device=dev,dtype=torch.float32)[None,:]
                weights=((ks*dt)**(H+.5)-((ks-1)*dt)**(H+.5))/((H+.5)*dt)
                integr=integr+torch.sum(torch.flip(dw[:,:,:t-1],dims=[2])*weights[:,None,:],dim=2)
                varY=varY+2*H*dt*torch.sum(weights**2,dim=1,keepdim=True)
            Y=torch.sqrt(2*H)*integr
        v=.04*torch.exp(eta*Y-.5*eta**2*varY)
        dspot=rho*dw[:,:,t]+torch.sqrt(1-rho**2)*dz[:,:,t]
        spot=spot*torch.exp(-.5*v*dt+torch.sqrt(v)*dspot)
        if t+1 in (8,16,32):
            prices.append(torch.stack([(spot-float(k)).clamp_min(0).mean(dim=1) for k in strikes],dim=1))
    return torch.stack(prices,dim=1).detach().cpu().numpy()
def bs_call(vol,k,t):
    s=max(vol,1e-8)*np.sqrt(t); d1=(np.log(1/k)+.5*s*s)/s
    return ndtr(d1)-k*ndtr(d1-s)
def implied(prices):
    out=np.empty_like(prices)
    for i in range(len(prices)):
        for t,tau in enumerate(tenors):
            for j,k in enumerate(strikes):
                p=np.clip(prices[i,t,j],max(1-k,0)+1e-10,1-1e-10); lo,hi=1e-5,3.
                for _ in range(35):
                    mid=(lo+hi)/2
                    if bs_call(mid,k,tau)<p: lo=mid
                    else: hi=mid
                out[i,t,j]=(lo+hi)/2
    return out.reshape(len(prices),-1)
rng=np.random.default_rng(283010); B=160
params=np.column_stack([rng.uniform(.08,.35,B),rng.uniform(.5,2.,B),rng.uniform(-.9,-.2,B)])
started=time.perf_counter(); target=implied(superficies(params,512,283011))
scale=np.array([.35,2.,1.]); X=torch.tensor(params/scale,dtype=torch.float32,device=dev)
Y=torch.tensor(target,dtype=torch.float32,device=dev); torch.manual_seed(283012)
net=torch.nn.Sequential(torch.nn.Linear(3,32),torch.nn.Tanh(),torch.nn.Linear(32,32),torch.nn.Tanh(),torch.nn.Linear(32,9)).to(dev)
opt=torch.optim.Adam(net.parameters(),lr=.003); best=np.inf; best_state=None; espera=0
import copy
for epoch in range(500):
    opt.zero_grad(); loss=((net(X[:120])-Y[:120])**2).mean(); loss.backward(); opt.step()
    with torch.no_grad(): val=float(((net(X[120:140])-Y[120:140])**2).mean())
    if val<best-1e-8: best=val; best_state=copy.deepcopy(net.state_dict()); espera=0
    else: espera+=1
    if espera>=30: break
net.load_state_dict(best_state); net.eval()
with torch.no_grad(): test_rmse=float(torch.sqrt(torch.mean((net(X[140:])-Y[140:])**2)))
verdad=np.array([.17,1.1,-.7]); mercado=implied(superficies(verdad[None,:],8192,283013))[0]
def residual(p):
    with torch.no_grad(): return net(torch.tensor((p/scale)[None,:],dtype=torch.float32,device=dev)).cpu().numpy()[0]-mercado
start=time.perf_counter()
fit=least_squares(residual,[.2,1.,-.5],bounds=([.08,.5,-.9],[.35,2.,-.2]),diff_step=1e-3)
tiempo=time.perf_counter()-start
check=implied(superficies(fit.x[None,:],8192,283014))[0]
with torch.no_grad():
    hs,_=heston(8192,283015); hs=hs/100.
    precios_h=np.array([[float((hs[:,idx]-float(k)).clamp_min(0).mean()) for k in strikes] for idx in (8,16,32)])[None,:,:]
ivs_h=implied(precios_h).reshape(3,3); ivs_r=mercado.reshape(3,3)
skew_h=(ivs_h[:,2]-ivs_h[:,0])/(strikes[2]-strikes[0])
skew_r=(ivs_r[:,2]-ivs_r[:,0])/(strikes[2]-strikes[0])
print('Dispositivo:',dev,'| RMSE volatilidad test:',test_rmse,'| época final:',epoch)
print('Parámetros verdad:',verdad,'| calibrados:',fit.x,'| RMSE red:',np.sqrt(np.mean(fit.fun**2)))
print('RMSE simulador independiente:',np.sqrt(np.mean((check-mercado)**2)),'| calibración segundos:',tiempo,
      '| total segundos:',time.perf_counter()-started)
print('Skew diferencias finitas rBergomi/Heston por vencimiento:',skew_r,skew_h)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Calibration accuracy depends on noise in both Monte Carlo surfaces and surrogate capacity. A small network fit error does not imply unique recovery of the three parameters. This reduced budget does not reproduce industrial-study accuracy or timing; calibration time excludes surrogate generation and training cost.

In one RTX 3060 run, surrogate RMSE on test surfaces was approximately 0.0118 volatility points. Given planted parameters (0,17, 1,1, −0,7)(0,17,\ 1,1,\ -0,7), calibration returned approximately (0,103, 1,007, −0,684)(0,103,\ 1,007,\ -0,684): it recovered a similar surface but not exact parameters. RMSE against an independent simulation was 0.00274 and optimization took about 0.35 seconds, excluding generation and training. Monte Carlo uncertainty and imperfect surrogate fit limit that comparison.

The code also compares finite-difference skew between strikes 0.97 and 1.03 with another set of Heston paths. In one run the three rBergomi values were approximately −0.363, −0.363 and −0.303, versus −0.264, −0.284 and −0.304 for Heston. Both approximations have discretization and Monte Carlo noise; three maturities do not prove an asymptotic law or establish a universal comparison.

Local lab: generator and real benchmark

We train a small temporal GAN with causal convolutions on windows of a known synthetic GARCH. This teaching version is inspired by Quant GAN, without its architecture or risk-neutral measure construction. We evaluate separate GARCH windows, generated windows and an independent real sample: the public LOBSTER AAPL sample, level 1, June 21, 2012. It is one day of order-book events, not a daily index or population of days.

We sample midpoint every 50 messages, calculate log returns and split into consecutive windows of 64 returns. Time between observations is not constant. The ZIP is read from the LOBSTER_ZIP variable’s path if present; otherwise it is downloaded from LOBSTER. Data are not redistributed here. The generator is not fitted to AAPL and comparison with that sample is out of distribution, not general market validation.

[ ]Temporal GAN and LOBSTER sampleLocal GPU
import os,io,zipfile,urllib.request,hashlib
import numpy as np,torch
from scipy.stats import skew,kurtosis
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
torch.set_num_threads(2); dev=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.manual_seed(283020); rng=np.random.default_rng(283020); length=64
def garch(n,seed):
    rgen=np.random.default_rng(seed); out=np.empty((n,length)); h=np.ones(n)
    for t in range(length):
        r=np.sqrt(h)*rgen.normal(size=n); out[:,t]=r
        h=.05+.12*r*r+.83*h
    return out
train=garch(3000,283021); referencia=garch(1000,283022)
class Causal(torch.nn.Module):
    def __init__(self,cin,cout,dilation=1):
        super().__init__(); self.pad=2*dilation; self.conv=torch.nn.Conv1d(cin,cout,3,dilation=dilation)
    def forward(self,x): return self.conv(torch.nn.functional.pad(x,(self.pad,0)))
G=torch.nn.Sequential(Causal(4,24,1),torch.nn.LeakyReLU(.2),Causal(24,24,2),torch.nn.LeakyReLU(.2),Causal(24,1,4)).to(dev)
D=torch.nn.Sequential(Causal(1,24,1),torch.nn.LeakyReLU(.2),Causal(24,24,2),torch.nn.LeakyReLU(.2),
                      torch.nn.AdaptiveAvgPool1d(1),torch.nn.Flatten(),torch.nn.Linear(24,1)).to(dev)
og=torch.optim.Adam(G.parameters(),lr=.0003,betas=(.5,.9)); od=torch.optim.Adam(D.parameters(),lr=.0003,betas=(.5,.9))
bce=torch.nn.BCEWithLogitsLoss(); datos=torch.tensor(train[:,None,:],dtype=torch.float32,device=dev)
for paso in range(600):
    idx=torch.randint(len(datos),(64,),device=dev); real=datos[idx]
    ruido=torch.randn((64,4,length),device=dev); falso=G(ruido)
    od.zero_grad(); lossD=bce(D(real),torch.ones((64,1),device=dev))+bce(D(falso.detach()),torch.zeros((64,1),device=dev))
    lossD.backward(); od.step()
    og.zero_grad(); lossG=bce(D(G(torch.randn((64,4,length),device=dev))),torch.ones((64,1),device=dev))
    lossG.backward(); og.step()
with torch.no_grad(): generadas=G(torch.randn((1000,4,length),device=dev)).squeeze(1).cpu().numpy()
def caracteristicas(x):
    x=np.asarray(x); centred=x-x.mean(axis=1,keepdims=True); sd=np.maximum(x.std(axis=1),1e-9)
    def acf(v): return np.sum((v[:,:-1]-v[:,:-1].mean(axis=1,keepdims=True))*(v[:,1:]-v[:,1:].mean(axis=1,keepdims=True)),axis=1)/np.maximum(np.sum((v-v.mean(axis=1,keepdims=True))**2,axis=1),1e-12)
    return np.column_stack([x.mean(axis=1),sd,np.mean((centred/sd[:,None])**3,axis=1),
                            np.mean((centred/sd[:,None])**4,axis=1),acf(x),acf(x*x)])
def metricas(x):
    c=caracteristicas(x)
    return {'media':float(np.mean(x)),'sd':float(np.std(x)),
            'asimetría':float(skew(x.ravel())),'curtosis':float(kurtosis(x.ravel(),fisher=False)),
            'acf retornos':float(np.mean(c[:,4])),'acf cuadrados':float(np.mean(c[:,5]))}
source=os.environ.get('LOBSTER_ZIP')
if source:
    raw=open(source,'rb').read()
else:
    url='https://php.lobsterdata.com/info/sample/LOBSTER_SampleFile_AAPL_2012-06-21_1.zip'
    raw=urllib.request.urlopen(url,timeout=45).read()
archive=zipfile.ZipFile(io.BytesIO(raw))
name=next(n for n in archive.namelist() if 'orderbook_1.csv' in n)
libro=np.loadtxt(io.BytesIO(archive.read(name)),delimiter=',')
valid=(libro[:,1]>0)&(libro[:,3]>0)&(libro[:,0]>libro[:,2])
mid=(libro[valid,0]+libro[valid,2])/20000
ret=np.diff(np.log(mid[::50])); nwin=len(ret)//length
real=ret[:nwin*length].reshape(nwin,length); escala_real=np.std(real)
if nwin<4 or escala_real<=0: raise ValueError('Muestra real insuficiente')
real_std=real/escala_real
X=np.vstack([caracteristicas(referencia),caracteristicas(generadas)])
labels=np.r_[np.zeros(len(referencia)),np.ones(len(generadas))]
idx=np.r_[np.arange(500),np.arange(1000,1500)]
testidx=np.r_[np.arange(500,1000),np.arange(1500,2000)]
clasificador=LogisticRegression(max_iter=1000).fit(X[idx],labels[idx])
auc=roc_auc_score(labels[testidx],clasificador.predict_proba(X[testidx])[:,1])
def momentum(x,escala):
    pos=np.sign(x[:,:-1]); cambio=np.abs(np.diff(np.column_stack([np.zeros(len(x)),pos]),axis=1))
    return (pos*x[:,1:]*escala-.00005*cambio).ravel()
gan_pnl=momentum(generadas,.001); garch_pnl=momentum(referencia,.001); real_pnl=momentum(real_std,escala_real)
print('ZIP SHA256:',hashlib.sha256(raw).hexdigest(),'| archivo:',name,'| filas válidas:',int(valid.sum()),'| ventanas reales:',nwin)
print('GARCH:',metricas(referencia),'| GAN:',metricas(generadas),'| AAPL normalizada descriptivamente:',metricas(real_std))
print('AUC discriminador GARCH/GAN:',auc,'| score medio AAPL:',float(clasificador.predict_proba(caracteristicas(real_std))[:,1].mean()))
print('Momentum neto medio por paso GARCH/GAN/AAPL:',float(garch_pnl.mean()),float(gan_pnl.mean()),float(real_pnl.mean()))
ruta=os.environ.get('GAN_EXPORT')
if ruta:
    muestra={'source_sha256':hashlib.sha256(raw).hexdigest(),'real':real_std[:3].tolist(),
             'gan':generadas[:3].tolist(),'garch':referencia[:3].tolist(),
             'auc':float(auc),'score_real':float(clasificador.predict_proba(caracteristicas(real_std))[:,1].mean())}
    import json
    with open(ruta,'w',encoding='utf8') as salida: json.dump(muestra,salida)
    print('Muestras derivadas exportadas:',ruta)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Normalization of the real sample uses its full-day standard deviation only to compare descriptive shapes; the GAN did not see that day. The discriminator is trained for GARCH versus GAN, so its AAPL score is not an authenticity probability. The backtest uses the prior return’s sign, idealized midpoint execution and a fixed cost of 0.5 basis points per unit of position change; message sampling and a single day prevent annualization or generalization. GAN return scale is fixed at 0.001 per step for illustrative comparison, not estimated using the real test.

In the reported run, the LOBSTER ZIP had SHA-256 b50994786f2996ae3c349d6b11a07b412c981a417a17ece44f068f9e12e45058 and yielded 37 real windows. The GARCH-versus-GAN discriminator achieved AUC 0.836 on its test windows: it still distinguishes both generators. Mean net momentum per step was approximately −0.000049 in GARCH, −0.000173 in GAN and −0.0000375 in AAPL. All three are negative in this test, though magnitude changes; neither a sign change nor executability of those returns has been demonstrated.

Exercises

NumericChanging maturity
If |skew| is proportional to T^(H−1/2), H=0.1 and a month has four weeks, by what factor does it change from one month to one week?
QuizExact replication
If a derivative is exactly replicated for p without costs, what does translation invariance of a risk measure imply?
QuizTraining distribution
Why can a policy trained only on Heston paths fail?
QuizThe generator saw the test
A generator is fitted on data from 2000 to 2020 and then used to validate a strategy meant to be evaluated before 2020. What is the problem?
CodeEstimate H
Implement estimar_hurst(x,lags): for each integer lag calculate the mean of (x[t+lag]−x[t])²; fit log of that mean against log(lag) by least squares with intercept and return half the slope. If any mean is zero, raise ValueError.
def estimar_hurst(x,lags):
  raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
A policy, simulator and generator are valid only under the conditions checked; independent testing and model risk remain essential.

Compare policies on the same paths, quantify surrogate error against the simulator and evaluate both dependence and economic outcomes. A synthetic example or a single real day does not replace market validation.