flynn.gg

Christopher Flynn

Machine Learning
Systems Architect,
PhD Mathematician

Home
Projects
Open Source
Blog
Résumé

GitHub
LinkedIn

Blog


Stochastic Python package

2018-01-04 Feed

Last year I released my first open source project, fbm, a python package for generating realizations of fractional Brownian motion. The package contains a port of some MATLAB code I wrote for my PhD to run Monte Carlo simulations which used fractional Brownian motion as the process to model stochastic volatility.

I’ve seen a few other packages that did similar things, but with other stochastic processes. Most of the projects that I found were either abandoned and/or poorly designed. I thought that a nice next project would be to extend the functionality of fbm to a larger collection of stochastic processes.

GeometricBrownianMotion

Over the winter holidays I put together the initial iteration of the stochastic package for generating exact realizations of different discrete-time, continuous-time, and noise processes (including fractional Brownian motion, of course). Also included are several diffusion processes which are commonly found in physics and financial modeling. Generation of the diffusion processes is approximate using the Euler–Maruyama method.

stochastic is available on pypi and can be installed using pip. The package depends on the numpy and scipy packages for calculations and random number generation.

pip install stochastic

As of the initial release (0.1.0) these are the currently supported processes and how to access their classes from the stochastic package structure:

For example, to create a realization of a fractional Brownian motion with Hurst parameter 0.7, we would execute the following code:

from stochastic.continuous import FractionalBrownianMotion


fbm = FractionalBrownianMotion(t=1, hurst=0.7)
sample = fbm.sample(n=2**12)

Most of these processes expose a similar interface to generate samples. The classes are instantiated with process-specific parameters and an end time t. Almost every process has a sample() method which takes parameter n to determine the number of increments to generate. Some processes have a sample_at() method which accepts a monotonic sequence of times at which to generate the realization. Most processes also have a times() method which accepts a parameter n for generating the timesteps associated with a method invocation to sample(n) on the same instance. This is very useful for plotting.

import matplotlib.pyplot as plt
from stochastic.continuous import FractionalBrownianMotion


fbm = FractionalBrownianMotion(t=1, hurst=0.7)
s = fbm.sample(32)
times = fbm.times(32)

plt.plot(times, s)
plt.show()

Check the documentation for more information and a gallery of examples using matplotlib.

Further reading

Stochastic

Stochastic processes

Python

Python Package Index

Back to the posts.