# Tag Archives: Brownian Motion # Projection of Brownian motion with drift video

Projection of Brownian motion with drift video

From the fine folks at ARPM who have their workshop in NYC

Join my FREE newsletter to see how I will apply their techniques to automated trading

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat! # Help Brownian Motion in C++?

Help Brownian Motion in C++?

I got this through my Facebook Messenger:

hi bryan…i have a code in C++ for Brownian bridge ..can you please clear my some doubts?
i cannot help you on Brownian motion code as i am not expert in that space yet. I will post in my Facebook page to see if anyone can help
//
// ======================================================================================
// Copyright © 2002-2008 Peter Jäckel. Distributed with “Monte Carlo methods in finance”
//
// Permission to use, copy, modify, and distribute this software is freely granted,
// provided that this notice is preserved.
// ======================================================================================
//

#include “BrownianBridge.h”
#include <cmath>

BrownianBridge::BrownianBridge( unsigned long numberOfSteps_ ) :
numberOfSteps(numberOfSteps_),
leftIndex(numberOfSteps), rightIndex(numberOfSteps), bridgeIndex(numberOfSteps),
leftWeight(numberOfSteps), rightWeight(numberOfSteps), sigma(numberOfSteps)
{
assert(numberOfSteps); // There must be at least one step.
std::vector <unsigned long> map(numberOfSteps);
// map is used to indicate which points are already constructed. If map[i] is zero, path point i
// is yet unconstructed. map[i]-1 is the index of the variate that constructs the path point # i.
unsigned long i,j,k,l;
map[numberOfSteps-1] = 1; // The first point in the construction is the global step.
bridgeIndex = numberOfSteps-1; // The global step is constructed from the first variate.
sigma = sqrt(numberOfSteps); // The variance of the global step is numberOfSteps*1.0.
leftWeight = rightWeight = 0.; // The global step to the last point in time is special.
for (j=0,i=1;i<numberOfSteps;++i){
while (map[j]) ++j; // Find the next unpopulated entry in the map.
k=j;
while ((!map[k])) ++k; // Find the next populated entry in the map from there.
l=j+((k-1-j)>>1); // l-1 is now the index of the point to be constructed next.
map[l]=i;
bridgeIndex[i] = l; // The i-th Gaussian variate will be used to set point l-1.
leftIndex[i] = j;
rightIndex[i] = k;
leftWeight[i] = (k-l)/(k+1.-j);
rightWeight[i] = (l+1.-j)/(k+1.-j);
sigma[i] = sqrt(((l+1.-j)*(k-l))/(k+1.-j));
j=k+1;
if (j>=numberOfSteps) j=0; // Wrap around.
}
}

void BrownianBridge::buildPath( std::vector <double> &path, const std::vector <double> &gaussianVariates ){
assert( gaussianVariates.size() == numberOfSteps && path.size() == numberOfSteps );
unsigned long i,j,k,l;
path[numberOfSteps-1] = sigma*gaussianVariates; // The global step.
for (i=1;i<numberOfSteps;i++){
j = leftIndex[i];
k = rightIndex[i];
l = bridgeIndex[i];
if (j) path[l] = leftWeight[i]*path[j-1] + rightWeight[i]*path[k] + sigma[i]*gaussianVariates[i];
else path[l] = rightWeight[i]*path[k] + sigma[i]*gaussianVariates[i];
}
}

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat! # Girsanov Theorem in R and Simple Brownian motion source code identified with Matlab

Girsanov Theorem in R and Simple Brownian motion source code identified with Matlab

These are required for this DB FX strategy.

Girsanov R example: (the only one I could find)

http://commons.wikimedia.org/wiki/File:Girsanov.png

Simple Brownian Motion with Matlab:

http://ddeville.me/static/media/research/univpm_thesis.pdf

function Brownian_Motion(mu,sigma)
T = 1;
N = 5000;
h = T/N; t = (0:h:T);
X(1) = 0;
for i=1:N
X(i+1) = X(i) + mu*h + sigma*sqrt(h)*randn;
end
plot(t,X)

Both do work

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat! # Debugging can help you reverse enginer research paper algos from scratch: Demo video in Matlab and C++ with Brownian Motion Simulation

Debugging can help you reverse enginer research paper algos from scratch: Demo video in Matlab and C++ with Brownian Motion Simulation

Get the code versions here:

http://people.sc.fsu.edu/~jburkardt/m_src/brownian_motion_simulation/brownian_motion_simulation.html

http://people.sc.fsu.edu/~jburkardt/cpp_src/brownian_motion_simulation/brownian_motion_simulation.html

This is really benefitial when you are starting to learn a trading algorithm from scratch

Join my FREE newsletter to learn other useful debugging tips

Matlab demo

Note: I tried to use the C++ version but I don’t got time to monkey around with this within Visual Studio. I just hope this one video gives you the idea you need to know.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat! # Here are some code samples of Levy Process and Brownian Motion in in R Matlab C and C++

Here are some code samples of Levy Process and Brownian Motion in in R Matlab C and C++

As I dig further into this DB FX strategy to better understand these processses, I figured I would list some useful coding examples. I cannot work off theory alone as I need to see working examples in action.

Levy Process:

In C:

https://github.com/mlandis/creepy-jerk

On L ́evy Processes for Option Pricin with lots of Matlab functions: http://ddeville.me/static/media/research/univpm_thesis.pdf

Monte Carlo Simulation in C++/Matlab: http://www.math.lsa.umich.edu/~mityab/Monte-Carlo/

General easy to understand Powerpoint: Pure Jump Lévy Processes and Self-decomposability in Financia
Modelling  http://calvino.polito.it/~probstat/PRIN/Onalan.pdf

Exponential of Lévy processes as a stock price – Arbitrage opportunities, completeness and derivatives valuation (some Matlab)

http://edoc.hu-berlin.de/master/tisserand-marc-2006-07-25/PDF/tisserand.pdf

Complete BROWNIAN_MOTION_SIMULATION Simulation of Brownian Motion in M Dimensions in Matlab C C++ and Fortan

http://people.sc.fsu.edu/~jburkardt/m_src/brownian_motion_simulation/brownian_motion_simulation.html

In simple R with Brownian Motion: http://probaperception.blogspot.ca/2012/10/generate-stock-option-prices-how-to.html

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

# How to create Brownian Motion Model and GBM in Matlab

Here are some popular ways to create BMs within Matlab. From the help system:

Creating Brownian Motion (BM) Models

The Brownian Motion (BM) model derives directly from the linear drift (SDELD) class:

Example: BM Models. Create a univariate Brownian motion (BM) object to represent the model:

obj = bm(0, 0.3) % (A = Mu, Sigma)
obj =
Class BM: Brownian Motion
—————————————-
Dimensions: State = 1, Brownian = 1
—————————————-
StartTime: 0
StartState: 0
Correlation: 1
Drift: drift rate function F(t,X(t))
Diffusion: diffusion rate function G(t,X(t))
Simulation: simulation method/function simByEuler
Mu: 0
Sigma: 0.3

BM objects display the parameter A as the more familiar Mu.

The BM class also provides an overloaded Euler simulation method that improves run time performance in certain common situations. This specialized method is invoked automatically only if all of the following conditions are met:

*

The expected drift, or trend, rate Mu is a column vector.
*

The volatility rate, Sigma, is a matrix.
*

*

If specified, the random noise process Z is a three-dimensional array.
*

If Z is unspecified, the assumed Gaussian correlation structure is a double matrix.

Creating Geometric Brownian Motion (GBM) Models

The Geometric Brownian Motion (GBM) model derives directly from the CEV model:

Compared to CEV, GBM constrains all elements of the alpha exponent vector to one such that D is now a diagonal matrix with the state vector X along the main diagonal.

The GBM class also provides two simulation methods that can be used by separable models:

*

An overloaded Euler simulation method that improves run time performance in certain common situations. This specialized method is invoked automatically only if all of the following conditions are true:
o

The expected rate of return (Return) is a diagonal matrix.
o

The volatility rate (Sigma) is a matrix.
o

o

If specified, the random noise process Z is a three-dimensional array.
o

If Z is unspecified, the assumed Gaussian correlation structure is a double matrix.

*

An approximate analytic solution (simBySolution) obtained by applying an Euler approach to the transformed (using Ito’s formula) logarithmic process. In general, this is not the exact solution to this GBM model, as the probability distributions of the simulated and true state vectors are identical only for piecewise constant parameters. If the model parameters are piecewise constant over each observation period, the state vector Xt is log-normally distributed and the simulated process is exact for the observation times at which Xt is sampled.

Example: Univariate GBM Models. Create a univariate GBM object to represent the model:

obj = gbm(0.25, 0.3) % (B = Return, Sigma)
obj =
Class GBM: Generalized Geometric Brownian Motion
————————————————
Dimensions: State = 1, Brownian = 1
————————————————
StartTime: 0
StartState: 1
Correlation: 1
Drift: drift rate function F(t,X(t))
Diffusion: diffusion rate function G(t,X(t))
Simulation: simulation method/function simByEuler
Return: 0.25
Sigma: 0.3

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

# Creating Matlab SDE models objects like Brownian Motion (BM), Cox-Ingersoll-Ross (CIR), Hull-White/Vasicek (HWV), and Heston

Creating Matlab SDE models objects like Brownian Motion (BM), Cox-Ingersoll-Ross (CIR), Hull-White/Vasicek (HWV), and Heston

This is an important discussion from Matlab’s Eonometric’s Toolbox help system->User guide-> Stochastic differential equation->SDE objects

Introduction

Most models and utilities available with Monte Carlo Simulation of SDEs are represented as MATLAB objects. Therefore, this documentation often uses the terms model and object interchangeably.

However, although all models are represented as objects, not all objects represent models. In particular, drift and diffusion objects are used in model specification, but neither of these types of objects in and of themselves makes up a complete model. In most cases, you do not need to create drift and diffusion objects directly, so you do not need to differentiate between objects and models. It is important, however, to understand the distinction between these terms.

In many of the following examples, most model parameters are evaluated or invoked like any MATLAB function. Although it is helpful to examine and access model parameters as you would data structures, think of these parameters as functions that perform actions.

For more information about MATLAB objects, see Using Objects to Write Data to a File in the MATLAB documentation.

Creating SDE Objects

*

Constructing Objects
*

Displaying Objects
*

Assigning and Referencing Object Parameters
*

Constructing and Evaluating Models
*

Specifying SDE Simulation Parameters

Constructing Objects

You use constructors to create SDE objects.

*

Modeling with SDE Objects
*

Example: Simulating Equity Prices
*

Example: Simulating Interest Rates

Displaying Objects

*

Objects display like traditional MATLAB data structures.
*

Displayed object parameters appear as nouns that begin with capital letters. In contrast, parameters such as simulate and interpolate appear as verbs that begin with lowercase letters, which indicate tasks to perform.

Assigning and Referencing Object Parameters

*

Objects support referencing similar to data structures. For example, statements like the following are generally valid:

A = obj.A

*

Objects support complete parameter assignment similar to data structures. For example, statements like the following are generally valid:

obj.A = 3

*

Objects do not support partial parameter assignment as data structures do. Therefore, statements like the following are generally invalid:

obj.A(i,j) = 0.3

Constructing and Evaluating Models

*

You can construct objects of any model class only if enough information is available to determine unambiguously the dimensionality of the model. Because various class constructors offer unique input interfaces, some models require additional information to resolve model dimensionality.
*

You need only enter required input parameters in placeholder format, where a given input argument is associated with a specific position in an argument list. You can enter optional inputs in any order as parameter name-value pairs, where the name of a given parameter appears in single quotation marks and precedes its corresponding value.
*

Association of dynamic (time-variable) behavior with function evaluation, where time and state (t,Xt) are passed to a common, published interface, is pervasive throughout the SDE class system. You can use this function evaluation approach to model or construct powerful analytics. For a simple example, see Example: Univariate GBM Models.

Specifying SDE Simulation Parameters

The SDE engine allows the simulation of generalized multivariate stochastic processes, and provides a flexible and powerful simulation architecture. The framework also provides you with utilities and model classes that offer a variety of parametric specifications and interfaces. The architecture is fully multidimensional in both the state vector and the Brownian motion, and offers both linear and mean-reverting drift-rate specifications.

You can specify most parameters as MATLAB arrays or as functions accessible by a common interface, that support general dynamic/nonlinear relationships common in SDE simulation. Specifically, you can simulate correlated paths of any number of state variables driven by a vector-valued Brownian motion of arbitrary dimensionality. This simulation approximates the underlying multivariate continuous-time process using a vector-valued stochastic difference equation.

Consider the following general stochastic differential equation:
(10-1)

where:

*

X is an NVARS-by-1 state vector of process variables (for example, short rates or equity prices) to simulate.
*

W is an NBROWNS-by-1 Brownian motion vector.
*

F is an NVARS-by-1 vector-valued drift-rate function.
*

G is an NVARS-by-NBROWNS matrix-valued diffusion-rate function.

The drift and diffusion rates, F and G, respectively, are general functions of a real-valued scalar sample time t and state vector Xt. Also, static (non-time-variable) coefficients are simply a special case of the more general dynamic (time-variable) situation, just as a function can be a trivial constant; for example, f(t,Xt) = 4. The SDE in Equation 10-1 is useful in implementing derived classes that impose additional structure on the drift and diffusion-rate functions.

Specifying Drift and Diffusion Parameters. For example, an SDE with a linear drift rate has the form:
(10-2)

where A is an NVARS-by-1 vector-valued function and B is an NVARS-by-NVARS matrix-valued function.

As an alternative, consider a drift-rate specification expressed in mean-reverting form:
(10-3)

where S is an NVARS-by-NVARS matrix-valued function of mean reversion speeds (that is, rates of mean reversion), and L is an NVARS-by-1 vector-valued function of mean reversion levels (that is, long run average level).

Similarly, consider the following diffusion-rate specification:
(10-4)

where D is an NVARS-by-NVARS diagonal matrix-valued function. Each diagonal element of D is the corresponding element of the state vector raised to the corresponding element of an exponent Alpha, which is also an NVARS-by-1 vector-valued function. V is an NVARS-by-NBROWNS matrix-valued function of instantaneous volatility rates. Each row of V corresponds to a particular state variable, and each column corresponds to a particular Brownian source of uncertainty. V associates the exposure of state variables with sources of risk.

The parametric specifications for the drift and diffusion-rate functions associate parametric restrictions with familiar models derived from the general SDE class, and provide coverage for many popular models.

As discussed in the following sections, the class system and hierarchy of the SDE engine use industry-standard terminology to provide simplified interfaces for many models by placing user-transparent restrictions on drift and diffusion specifications. This design allows you to mix and match existing models, and customize drift or diffusion-rate functions.

For example, the following models are special cases of the general SDE model.

SDE Models
Model Name Specification
Brownian Motion (BM)

Geometric Brownian Motion (GBM)

Constant Elasticity of Variance (CEV)

Cox-Ingersoll-Ross (CIR)

Hull-White/Vasicek (HWV)

Heston

Specifying User-defined Functions as Model Parameters. Several examples in this documentation emphasize the evaluation of object parameters as functions accessible by a common interface. In fact, you can evaluate object parameters by passing to them time and state, regardless of whether the underlying user-specified parameter is a function. However, it is helpful to compare the behavior of object parameters that are specified as functions to that of user-specified noise and end-of-period processing functions.

Model parameters that are specified as functions are evaluated in the same way as user-specified random number (noise) generation functions. (For more information, see Evaluating Different Types of Functions.) Model parameters that are specified as functions are inputs to remove object constructors. User-specified noise and processing functions are optional inputs to simulation methods.

Because class constructors offer unique interfaces, and simulation methods of any given model have different implementation details, models often call parameter functions for validation purposes a different number of times, or in a different order, during object creation, simulation, and interpolation.

Therefore, although parameter functions, user-specified noise generation functions, and end-of-period processing functions all share the same interface and are validated at the same initial time and state (obj.StartTime and obj.StartState), parameter functions are not guaranteed to be invoked only once before simulation as noise generation and end-of-period processing functions are. In fact, parameter functions might not even be invoked the same number of times during a given Monte Carlo simulation process.

In most applications in which you specify parameters as functions, they are simple, deterministic functions of time and/or state. There is no need to count periods, count trials, or otherwise accumulate information or synchronize time.

However, if parameter functions require more sophisticated bookkeeping, the correct way to determine when a simulation has begun (or equivalently, to determine when model validation is complete) is to determine when the input time and/or state differs from the initial time and state (obj.StartTime and obj.StartState, respectively). Because the input time is a known scalar, detecting a change from the initial time is likely the best choice in most situations. This is a general mechanism that you can apply to any type of user-defined function.
Evaluating Different Types of Functions.

It is useful to compare the evaluation rules of user-specified noise generation functions to those of end-of-period processing functions. These functions have the following in common:

*

They both share the same general interface, returning a column vector of appropriate length when evaluated at the current time and state:

*

Before simulation, the simulation method itself calls each function once to validate the size of the output at the initial time and state, obj.StartTime and obj.StartState, respectively.
*

During simulation, the simulation method calls each function the same number of times: NPERIODS * NSTEPS.

However, there is an important distinction regarding the timing between these two types of functions. It is most clearly drawn directly from the generic SDE model:

This equation is expressed in continuous time, but the simulation methods approximate the model in discrete time as:

where ?t > 0 is a small (and not necessarily equal) period or time increment into the future. This equation is often referred to as an Euler approximation. All functions on the right-hand side are evaluated at the current time and state (t, Xt).

In other words, over the next small time increment, the simulation evolves the state vector based only on information available at the current time and state. In this sense, you can think of the noise function as a beginning-of-period function, or as a function evaluated from the left. This is also true for any user-supplied drift or diffusion function.

In contrast, user-specified end-of-period processing functions are applied only at the end of each simulation period or time increment. For more information about processing functions, see Pricing Equity Options.

Therefore, all simulation methods evaluate noise generation functions as:

for t = t0, t0 + ?t, t0 + 2?t, …, T – ?t.

Yet simulation methods evaluate end-of-period processing functions as:

for t = t0 + ?t, t0 + 2?t, …, T.

where t0 and T are the initial time (taken from the object) and the terminal time (derived from inputs to the simulation method), respectively. These evaluations occur on all sample paths. Therefore, during simulation, noise functions are never evaluated at the final (terminal) time, and end-of-period processing functions are never evaluated at the initial (starting) time.