Levy stochastic jump path using tensors instead of numpy

I have this function to generate a Levy stochastic jump path implemented by numpy.

#generate the merton jump

def merton_jump_paths_numpy( T, r, sigma,  lam, m, v, steps, Npaths):
    dt = T/steps
    poi_rv = np.multiply(np.random.poisson( lam*dt, size=size),
                     np.random.normal(m,v, size=size)).cumsum(axis=0)
    geo = np.cumsum(((r -  sigma**2/2 -lam*(m  + v**2*0.5))*dt +\
                          sigma*np.sqrt(dt) * \
                          np.random.normal(size=size)), axis=0)

    return np.exp(geo+poi_rv)

I have a torch.nn network to calibrate r,sigma, lam, m, and v variables. So they are tensor paramaters with requires_grad=True.
For this reason, I need help to rewrite this function using tensors instead of numpy.
I have tried some code like this:

import torch

def merton_jump_paths_tensors( T, r, sigma,  lam, m, v, steps, Npaths):
   lam = torch.tensor(lam) 
   m = torch.tensor(m) 
   v = torch.tensor(v)  
   r = torch.tensor(r) 
   sigma = torch.tensor(sigma)
   size = torch.tensor(size)
   dt = T/steps
   dt_tensor = torch.tensor(dt)
   poi_rv = torch.poisson(lam * dt_tensor, size=size)
   normal_rv = torch.normal(m, v, size=size)
   poi_rv = poi_rv * normal_rv
   poi_rv = torch.cumsum(poi_rv, dim=0)
   drift_term = r - sigma **2 / 2.0 - lam * (m + v**2 / 2.0) * dt_tensor
   diffusion_term = sigma * torch.sqrt(dt_tensor) * torch.normal(size=size)  
   geo = torch.cumsum(drift_term + diffusion_term, dim=0)
   return np.exp(geo+poi_rv)

But not worked.
any one can help please?

Recreating new tensors will detach them and the original parameters won’t be trained. Use the parameters directly to create the computation graph properly.

1 Like