Last updated: 2023-03-16.
tf_quant_finance.models.GeometricBrownianMotion#
Geometric Brownian Motion.
Inherits From: ItoProcess
tf_quant_finance.models.GeometricBrownianMotion(
mean, volatility, dtype=None, name=None
)
Represents the 1-dimensional Ito process:
dX(t) = means(t) * X(t) * dt + volatilities(t) * X(t) * dW(t),
where W(t) is a 1D Brownian motion, mean(t) and volatility(t) are either
constant Tensors or piecewise constant functions of time.
Supports batching which enables modelling multiple univariate geometric
brownian motions (GBMs) efficiently. No guarantee is made about the
relationships between the batched univariate GMBs. To control the correlation
between multiple GBMs use MultivariateGeometricBrownianMotion.
Example#
import tensorflow as tf
import tf_quant_finance as tff
process = tff.models.GeometricBrownianMotion(0.05, 1.0, dtype=tf.float64)
times = [0.1, 0.2, 1.0]
# Use SOBOL sequence to draw trajectories
samples_sobol = process.sample_paths(
times=times,
initial_state=1.5,
random_type=tff.math.random.RandomType.SOBOL,
num_samples=100000)
# You can also supply the random normal draws directly to the sampler
normal_draws = tf.random.stateless_normal(
[100000, 3, 1], seed=[4, 2], dtype=tf.float64)
samples_custom = process.sample_paths(
times=times,
initial_state=1.5,
normal_draws=normal_draws)
Args:#
mean: A realTensorbroadcastable tobatch_shape + [1]or an instance of left-continuousPiecewiseConstantFuncwithbatch_shape + [1]dimensions. Herebatch_shaperepresents a batch of independent GBMs. Corresponds to the mean drift of the Ito process.volatility: A realTensorbroadcastable tobatch_shape + [1]or an instance of left-continuousPiecewiseConstantFuncof the samedtypeandbatch_shapeas set bymean. Corresponds to the volatility of the process and should be positive.dtype: The default dtype to use when converting values toTensors. Default value:Nonewhich means that default dtypes inferred frommeanis used.name: Python string. The name to give to the ops created by this class. Default value:Nonewhich maps to the default name ‘geometric_brownian_motion’.
Methods#
dim
dim()
The dimension of the process.
drift_fn
drift_fn()
Python callable calculating instantaneous drift.
drift_is_constant
drift_is_constant()
Returns True if the drift of the process is a constant.
dtype
dtype()
The data type of process realizations.
fd_solver_backward
fd_solver_backward(
start_time, end_time, coord_grid, values_grid, discounting=None,
one_step_fn=None, boundary_conditions=None, start_step_count=0, num_steps=None,
time_step=None, values_transform_fn=None, dtype=None, name=None, **kwargs
)
Returns a solver for Feynman-Kac PDE associated to the process.
This method applies a finite difference method to solve the final value problem as it appears in the Feynman-Kac formula associated to this Ito process. The Feynman-Kac PDE is closely related to the backward Kolomogorov equation associated to the stochastic process and allows for the inclusion of a discounting function.
For more details of the Feynman-Kac theorem see [1]. The PDE solved by this method is:
dV(t)/dt + mean(t, x) dV_i/dx
+ (1/2) volatility^2(t, x) d^2V_i/dx^2 - r(t, x) V = 0
This method evolves a spatially discretized solution of the above PDE from
time t0 to time t1 < t0 (i.e. backwards in time).
The solution V(t,x) is assumed to be discretized on a grid.
This method allows batching of solutions. In this context, batching means
the ability to represent and evolve multiple independent functions V
(e.g. V1, V2 …) simultaneously corresponding to mean_1, mean_2 ... and
volatility_1, volatility_2 .....
The evolution of the solution from t0 to t1 is often done by
discretizing the differential equation to a difference equation along
the spatial and temporal axes. The temporal discretization is given by a
(sequence of) time steps [dt_1, dt_2, … dt_k] such that the sum of the
time steps is equal to the total time step t0 - t1. If a uniform time
step is used, it may equivalently be specified by stating the number of
steps (n_steps) to take. This method provides both options via the
time_step and num_steps parameters. However, not all methods need
discretization along time direction (e.g. method of lines) so this argument
may not be applicable to some implementations.
The workhorse of this method is the one_step_fn. For the commonly used
methods, see functions in math.pde.steppers module.
The mapping between the arguments of this method and the above equation are described in the Args section below.
For a simple instructive example of implementation of this method, see
models.GenericItoProcess.fd_solver_backward.
Args:#
start_time: Real positive scalarTensor. The start time of the grid. Corresponds to timet0above.end_time: Real scalarTensorsmaller than thestart_timeand greater than zero. The time to step back to. Corresponds to timet1above.coord_grid: List ofnrank 1 realTensors.nis the dimension of the domain. The i-thTensorhas shape,[d_i]whered_iis the size of the grid along axisi. The coordinates of the grid points. Corresponds to the spatial gridGabove.values_grid: RealTensorcontaining the function values at timestart_timewhich have to be stepped back to timeend_time. The shape of theTensormust broadcast with[K, d_1, d_2, ..., d_n]. The first axis of sizeKis the values batch dimension and allows multiple functions (with potentially different boundary/final conditions) to be stepped back simultaneously.discounting: Callable corresponding tor(t,x)above. If not supplied, zero discounting is assumed.one_step_fn: The transition kernel. A callable that consumes the following arguments by keyword:‘time’: Current time
‘next_time’: The next time to step to. For the backwards in time evolution, this time will be smaller than the current time.
‘coord_grid’: The coordinate grid.
‘values_grid’: The values grid.
‘boundary_conditions’: The boundary conditions.
‘quadratic_coeff’: A callable returning the quadratic coefficients of the PDE (i.e.
(1/2)D_{ij}(t, x)above). The callable accepts the time and coordinate grid as keyword arguments and returns aTensorwith shape that broadcasts with[dim, dim].‘linear_coeff’: A callable returning the linear coefficients of the PDE (i.e.
mean_i(t, x)above). Accepts time and coordinate grid as keyword arguments and returns aTensorwith shape that broadcasts with[dim].‘constant_coeff’: A callable returning the coefficient of the linear homogeneous term (i.e.
r(t,x)above). Same spec as above. Theone_step_fncallable returns a 2-tuple containing the next coordinate grid, next values grid.
boundary_conditions: A list of sizedimcontaining boundary conditions. The i’th element of the list is a 2-tuple containing the lower and upper boundary condition for the boundary along the i`th axis.start_step_count: Scalar integerTensor. Initial value for the number of time steps performed. Default value: 0 (i.e. no previous steps performed).num_steps: Positive int scalarTensor. The number of time steps to take when moving fromstart_timetoend_time. Either this argument or thetime_stepargument must be supplied (but not both). If num steps isk>=1, uniform time steps of size(t0 - t1)/kare taken to evolve the solution fromt0tot1. Corresponds to then_stepsparameter above.time_step: The time step to take. Either this argument or thenum_stepsargument must be supplied (but not both). The type of this argument may be one of the following (in order of generality): (a) None in which casenum_stepsmust be supplied. (b) A positive real scalarTensor. The maximum time step to take. If the value of this argument isdt, then the total number of steps taken is N = (t0 - t1) / dt rounded up to the nearest integer. The first N-1 steps are of size dt and the last step is of sizet0 - t1 - (N-1) * dt. (c) A callable accepting the current time and returning the size of the step to take. The input and the output are real scalarTensors.values_transform_fn: An optional callable applied to transform the solution values at each time step. The callable is invoked after the time step has been performed. The callable should accept the time of the grid, the coordinate grid and the values grid and should return the values grid. All input arguments to be passed by keyword.dtype: The dtype to use.name: The name to give to the ops. Default value: None which meanssolve_backwardis used.**kwargs: Additional keyword args: (1) pde_solver_fn: Function to solve the PDE that accepts all the above arguments by name and returns the same tuple object as required below. Defaults totff.math.pde.fd_solvers.solve_backward.
Returns:#
A tuple object containing at least the following attributes:
final_values_grid: A Tensor of same shape and dtype as values_grid.
Contains the final state of the values grid at time end_time.
final_coord_grid: A list of Tensors of the same specification as
the input coord_grid. Final state of the coordinate grid at time
end_time.
step_count: The total step count (i.e. the sum of the start_step_count
and the number of steps performed in this call.).
final_time: The final time at which the evolution stopped. This value
is given by max(min(end_time, start_time), 0).
fd_solver_forward
fd_solver_forward(
start_time, end_time, coord_grid, values_grid, one_step_fn=None,
boundary_conditions=None, start_step_count=0, num_steps=None, time_step=None,
values_transform_fn=None, dtype=None, name=None, **kwargs
)
Returns a solver for the Fokker Plank equation of this process.
The Fokker Plank equation (also known as the Kolmogorov Forward equation) associated to this Ito process is given by:
dV/dt + d(mean_i(t, x) V) / dx
- (1/2) d^2(volatility^2(t, x) V) / dx^2 = = 0
with the initial value condition $\(V(0, x) = u(x)\)$.
This method evolves a spatially discretized solution of the above PDE from
time t0 to time t1 < t0 (i.e. backwards in time).
The solution V(t,x) is assumed to be discretized on a grid.
This method allows batching of solutions. In this context, batching means
the ability to represent and evolve multiple independent functions V
(e.g. V1, V2 …) simultaneously corresponding to mean_1, mean_2 ... and
volatility_1, volatility_2 .....
The evolution of the solution from t0 to t1 is often done by
discretizing the differential equation to a difference equation along
the spatial and temporal axes. The temporal discretization is given by a
(sequence of) time steps [dt_1, dt_2, … dt_k] such that the sum of the
time steps is equal to the total time step t0 - t1. If a uniform time
step is used, it may equivalently be specified by stating the number of
steps (n_steps) to take. This method provides both options via the
time_step and num_steps parameters. However, not all methods need
discretization along time direction (e.g. method of lines) so this argument
may not be applicable to some implementations.
The workhorse of this method is the one_step_fn. For the commonly used
methods, see functions in math.pde.steppers module.
The mapping between the arguments of this method and the above equation are described in the Args section below.
For a simple instructive example of implementation of this method, see
models.GenericItoProcess.fd_solver_forward.
Args:#
start_time: Real positive scalarTensor. The start time of the grid. Corresponds to timet0above.end_time: Real scalarTensorsmaller than thestart_timeand greater than zero. The time to step back to. Corresponds to timet1above.coord_grid: List ofnrank 1 realTensors.nis the dimension of the domain. The i-thTensorhas shape,[d_i]whered_iis the size of the grid along axisi. The coordinates of the grid points. Corresponds to the spatial gridGabove.values_grid: RealTensorcontaining the function values at timestart_timewhich have to be stepped back to timeend_time. The shape of theTensormust broadcast with[K, d_1, d_2, ..., d_n]. The first axis of sizeKis the values batch dimension and allows multiple functions (with potentially different boundary/final conditions) to be stepped back simultaneously.one_step_fn: The transition kernel. A callable that consumes the following arguments by keyword:‘time’: Current time
‘next_time’: The next time to step to. For the backwards in time evolution, this time will be smaller than the current time.
‘coord_grid’: The coordinate grid.
‘values_grid’: The values grid.
‘quadratic_coeff’: A callable returning the quadratic coefficients of the PDE (i.e.
(1/2)D_{ij}(t, x)above). The callable accepts the time and coordinate grid as keyword arguments and returns aTensorwith shape that broadcasts with[dim, dim].‘linear_coeff’: A callable returning the linear coefficients of the PDE (i.e.
mean_i(t, x)above). Accepts time and coordinate grid as keyword arguments and returns aTensorwith shape that broadcasts with[dim].‘constant_coeff’: A callable returning the coefficient of the linear homogeneous term (i.e.
r(t,x)above). Same spec as above. Theone_step_fncallable returns a 2-tuple containing the next coordinate grid, next values grid.
boundary_conditions: A list of sizedimcontaining boundary conditions. The i’th element of the list is a 2-tuple containing the lower and upper boundary condition for the boundary along the i`th axis.start_step_count: Scalar integerTensor. Initial value for the number of time steps performed. Default value: 0 (i.e. no previous steps performed).num_steps: Positive int scalarTensor. The number of time steps to take when moving fromstart_timetoend_time. Either this argument or thetime_stepargument must be supplied (but not both). If num steps isk>=1, uniform time steps of size(t0 - t1)/kare taken to evolve the solution fromt0tot1. Corresponds to then_stepsparameter above.time_step: The time step to take. Either this argument or thenum_stepsargument must be supplied (but not both). The type of this argument may be one of the following (in order of generality): (a) None in which casenum_stepsmust be supplied. (b) A positive real scalarTensor. The maximum time step to take. If the value of this argument isdt, then the total number of steps taken is N = (t1 - t0) / dt rounded up to the nearest integer. The first N-1 steps are of size dt and the last step is of sizet1 - t0 - (N-1) * dt. (c) A callable accepting the current time and returning the size of the step to take. The input and the output are real scalarTensors.values_transform_fn: An optional callable applied to transform the solution values at each time step. The callable is invoked after the time step has been performed. The callable should accept the time of the grid, the coordinate grid and the values grid and should return the values grid. All input arguments to be passed by keyword.dtype: The dtype to use.name: The name to give to the ops. Default value: None which meanssolve_forwardis used.**kwargs: Additional keyword args: (1) pde_solver_fn: Function to solve the PDE that accepts all the above arguments by name and returns the same tuple object as required below. Defaults totff.math.pde.fd_solvers.solve_forward.
Returns:#
A tuple object containing at least the following attributes:
final_values_grid: A Tensor of same shape and dtype as values_grid.
Contains the final state of the values grid at time end_time.
final_coord_grid: A list of Tensors of the same specification as
the input coord_grid. Final state of the coordinate grid at time
end_time.
step_count: The total step count (i.e. the sum of the start_step_count
and the number of steps performed in this call.).
final_time: The final time at which the evolution stopped. This value
is given by max(min(end_time, start_time), 0).
name
name()
The name to give to ops created by this class.
sample_paths
sample_paths(
times, initial_state=None, num_samples=1, random_type=None, seed=None, skip=0,
normal_draws=None, name=None
)
Returns a sample of paths from the process.
If mean and volatility were specified with batch dimensions the sample
paths will be generated for all batch dimensions for the specified times
using a single set of random draws.
Args:#
times: ATensorof positive real values of a shape[T, k], whereTis either empty or a shape which is broadcastable tobatch_shape(as defined by the shape ofmeanorvolatilitywhich were set when this instance of GeometricBrownianMotion was initialised) andkis the number of time points. The times at which the path points are to be evaluated.initial_state: ATensorof the samedtypeastimesand of shape broadcastable to[batch_shape, num_samples]. Represents the initial state of the Ito process. Default value:Nonewhich maps to a initial state of ones.num_samples: Positive scalarint. The number of paths to draw.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 an Python integer. ForSTATELESSandSTATELESS_ANTITHETICmust be supplied as an integerTensorof shape[2]. Default value:Nonewhich means no seed is set.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.normal_draws: ATensorof shape[num_samples, num_time_points, 1]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.num_time_pointsshould be equal totf.shape(times)[0]. Default value:Nonewhich means that the draws are generated by the algorithm.name: Str. The name to give this op. Default value:sample_paths.
Returns:#
A Tensors of shape [batch_shape, num_samples, k, 1] where k is the
the number of time points.
Raises:#
ValueError: Ifnormal_drawsis supplied and does not have shape broadcastable to[num_samples, num_time_points, 1].
volatility_fn
volatility_fn()
Python callable calculating the instantaneous volatility.
volatility_is_constant
volatility_is_constant()
Returns True is the volatility of the process is a constant.