Last updated: 2023-03-16.
tf_quant_finance.models.euler_sampling.sample#
Returns a sample paths from the process using Euler method.
tf_quant_finance.models.euler_sampling.sample(
dim, drift_fn, volatility_fn, times, time_step=None, num_time_steps=None,
num_samples=1, initial_state=None, random_type=None, seed=None,
swap_memory=True, skip=0, precompute_normal_draws=True, times_grid=None,
normal_draws=None, watch_params=None, validate_args=False, tolerance=None,
dtype=None, name=None
)
For an Ito process,
dX = a(t, X_t) dt + b(t, X_t) dW_t
X(t=0) = x0
with given drift a and volatility b functions Euler method generates a
sequence {X_n} as
X_{n+1} = X_n + a(t_n, X_n) dt + b(t_n, X_n) (N(0, t_{n+1}) - N(0, t_n)),
X_0 = x0
where dt = t_{n+1} - t_n and N is a sample from the Normal distribution.
See [1] for details.
Example#
Sampling from 2-dimensional Ito process of the form:
dX_1 = mu_1 * sqrt(t) dt + s11 * dW_1 + s12 * dW_2
dX_2 = mu_2 * sqrt(t) dt + s21 * dW_1 + s22 * dW_2
import tensorflow as tf
import tf_quant_finance as tff
import numpy as np
mu = np.array([0.2, 0.7])
s = np.array([[0.3, 0.1], [0.1, 0.3]])
num_samples = 10000
dim = 2
dtype = tf.float64
# Define drift and volatility functions
def drift_fn(t, x):
return mu * tf.sqrt(t) * tf.ones([num_samples, dim], dtype=dtype)
def vol_fn(t, x):
return s * tf.ones([num_samples, dim, dim], dtype=dtype)
# Set starting location
x0 = np.array([0.1, -1.1])
# Sample `num_samples` paths at specified `times` using Euler scheme.
times = [0.1, 1.0, 2.0]
paths = tff.models.euler_sampling.sample(
dim=dim,
drift_fn=drift_fn,
volatility_fn=vol_fn,
times=times,
num_samples=num_samples,
initial_state=x0,
time_step=0.01,
seed=42,
dtype=dtype)
# Expected: paths.shape = [10000, 3, 2]
References#
[1]: Wikipedia. Euler-Maruyama method: https://en.wikipedia.org/wiki/Euler-Maruyama_method
Args:#
dim: Python int greater than or equal to 1. The dimension of the Ito Process.drift_fn: A Python callable to compute the drift of the process. The callable should accept two realTensorarguments of the same dtype. The first argument is the scalar time t, the second argument is the value of Ito process X - tensor of shapebatch_shape + [num_samples, dim].batch_shapeis the shape of the independent stochastic processes being modelled and is inferred from the initial statex0. The result is value of drift a(t, X). The return value of the callable is a realTensorof the same dtype as the input arguments and of shapebatch_shape + [num_samples, dim].volatility_fn: A Python callable to compute the volatility of the process. The callable should accept two realTensorarguments of the same dtype and shapetimes_shape. The first argument is the scalar time t, the second argument is the value of Ito process X - tensor of shapebatch_shape + [num_samples, dim]. The result is value of drift b(t, X). The return value of the callable is a realTensorof the same dtype as the input arguments and of shapebatch_shape + [num_samples, dim, dim].times: Rank 1Tensorof increasing positive real values. The times at which the path points are to be evaluated.time_step: An optional scalar realTensor- maximal distance between points in grid in Euler schema. Either this ornum_time_stepsshould be supplied. Default value:None.num_time_steps: An optional Scalar integerTensor- a total number of time steps performed by the algorithm. The maximal distance betwen points in grid is bounded bytimes[-1] / (num_time_steps - times.shape[0]). Either this ortime_stepshould be supplied. Default value:None.num_samples: Positive scalarint. The number of paths to draw. Default value: 1.initial_state:Tensorof shape broadcastable withbatch_shape + [num_samples, dim]. The initial state of the process.batch_shaperepresents the shape of the independent batches of the stochastic process. Note thatbatch_shapeis inferred from theinitial_stateand hence when sampling is requested for a batch of stochastic processes, the shape ofinitial_stateshould be at leastbatch_shape + [1, 1]. Default value: None which maps to a zero initial state.random_type: Enum value ofRandomType. The type of (quasi)-random number generator to use to generate the paths. Default value: None which maps to the standard pseudo-random numbers.seed: Seed for the random number generator. The seed is only relevant ifrandom_typeis one of[STATELESS, PSEUDO, HALTON_RANDOMIZED, PSEUDO_ANTITHETIC, STATELESS_ANTITHETIC]. ForPSEUDO,PSEUDO_ANTITHETICandHALTON_RANDOMIZEDthe seed should be a Python integer. ForSTATELESSandSTATELESS_ANTITHETICmust be supplied as an integerTensorof shape[2]. Default value:Nonewhich means no seed is set.swap_memory: A Python bool. Whether GPU-CPU memory swap is enabled for this op. See an equivalent flag intf.while_loopdocumentation for more details. Useful when computing a gradient of the op sincetf.while_loopis used to propagate stochastic process in time. Default value: True.skip:int320-dTensor. The number of initial points of the Sobol or Halton sequence to skip. Used only whenrandom_typeis ‘SOBOL’, ‘HALTON’, or ‘HALTON_RANDOMIZED’, otherwise ignored. Default value:0.precompute_normal_draws: Python bool. Indicates whether the noise incrementsN(0, t_{n+1}) - N(0, t_n)are precomputed. ForHALTONandSOBOLrandom types the increments are always precomputed. While the resulting graph consumes more memory, the performance gains might be significant. Default value:True.times_grid: An optional rank 1Tensorrepresenting time discretization grid. Iftimesare not on the grid, then the nearest points from the grid are used. When supplied,num_time_stepsandtime_stepare ignored. Default value:None, which means that times grid is computed usingtime_stepandnum_time_steps.normal_draws: ATensorof shape broadcastable withbatch_shape + [num_samples, num_time_points, dim]and the samedtypeastimes. Represents random normal draws to compute incrementsN(0, t_{n+1}) - N(0, t_n). When supplied,num_samplesargument is ignored and the first dimensions ofnormal_drawsis used instead. Default value:Nonewhich means that the draws are generated by the algorithm. By default normal_draws for each model in the batch are independent.watch_params: An optional list of zero-dimensionalTensors of the samedtypeasinitial_state. If provided, specifiesTensors with respect to which the differentiation of the sampling function will happen. A more efficient algorithm is used whenwatch_paramsare specified. Note the the function becomes differentiable onlhy wrt to theseTensors and theinitial_state. The gradient wrt any otherTensoris set to be zero.validate_args: Pythonbool. WhenTrueperforms multiple checks:That
timesare increasing with the minimum increments of the specified tolerance.If
normal_drawsare supplied, checks thatnormal_draws.shape[1]is equal tonum_time_stepsthat is either supplied as an argument or computed fromtime_step. WhenFalseinvalid dimension may silently render incorrect outputs. Default value:False.
tolerance: A non-negative scalarTensorspecifying the minimum tolerance for discernible times on the time grid. Times that are closer than the tolerance are perceived to be the same. Default value:Nonewhich maps to1-e6if the for single precisiondtypeand1e-10for double precisiondtype.dtype:tf.Dtype. If supplied the dtype for the input and outputTensors. Default value: None which means that the dtype implied bytimesis used.name: Python string. The name to give this op. Default value:Nonewhich maps toeuler_sample.
Returns:#
A real Tensor of shape batch_shape_process + [num_samples, k, n] where k
is the size of the times, n is the dimension of the process.
Raises:#
ValueError: (a) Whentimes_gridis not supplied, and neithernum_time_stepsnortime_stepare supplied or if both are supplied. (b) Ifnormal_drawsis supplied anddimis mismatched.tf.errors.InvalidArgumentError: Ifnormal_drawsis supplied andnum_time_stepsis mismatched.