Skip to content

About

A Python package to model financial returns as Levy processes.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

21 Commits

Folders and files

Repository files navigation

PyLevyProcess

Simulate Lévy processes and diffusions on regular or irregular time grids. In a Lévy process starting at zero, increments over disjoint intervals are independent and their distributions depend only on the interval lengths. The process is stochastically continuous and has a version with right-continuous paths and left limits. Brownian motion has continuous paths, whereas Poisson and other jump processes can change abruptly.

Geometric Brownian motion models log-price increments as Gaussian. Stable and other jump models offer alternatives when studying heavy-tailed returns or discontinuous movements. For observed returns, serial-correlation diagnostics can help detect departures from an independent-increment model. Independence is a stronger condition than zero autocorrelation.

Installation

python -m pip install git+https://github.com/datstat-consulting/PyLevyProcess.git

From a checkout, run python -m pip install .. The simulators require Python 3.10 or later, NumPy, and SciPy. Install python -m pip install '.[price-model]' from a checkout to use the optional price-model workflow.

Stable increments and price paths

import numpy as np
from PyLevyProcess import GeometricStableProcess, StableLevyProcess

times = np.linspace(0, 1, 253)
stable = StableLevyProcess(alpha=1.7, beta=0.2, scale=0.03, drift=0.02)
paths = stable.simulate(times, paths=500, random_state=42)
increments = np.diff(paths, axis=1)

price_model = GeometricStableProcess(1.7, beta=0.2, scale=0.03, drift=0.02)
prices = price_model.simulate(times, initial=100, paths=500, random_state=42)
lower, median, upper = np.quantile(prices, [0.05, 0.5, 0.95], axis=0)

Pass a strictly increasing time grid beginning at zero. Each row of the output is one path, with the initial value in column zero. Supply an integer seed or a NumPy random generator through random_state. Stable increments use the S1 parameterization, including the skew-dependent location correction at alpha=1 for uneven time steps.

Geometric models exponentiate their simulated log paths. Depending on the stable parameters, the resulting levels can have infinite expectation. Quantiles summarize the simulated levels without requiring a finite mean. An out-of-range geometric simulation raises an exception.

Process selection

Model Class
Gaussian increments with drift BrownianMotion
Stable increments StableLevyProcess
Counts and nondecreasing gamma increments PoissonProcess, GammaProcess
Normally marked jumps and jump diffusion CompoundPoissonProcess, MertonJumpDiffusion
Variance gamma increments VarianceGammaProcess
Mean-reverting Gaussian diffusion OrnsteinUhlenbeck
Exponentiated log paths GeometricLevyProcess, GeometricStableProcess, GeometricBrownianMotion

The simulators draw increments or transitions directly on the supplied grid. For example, PoissonProcess(rate=3).simulate([0, 0.25, 0.75, 1], paths=10, random_state=42) generates independent count increments over intervals of different lengths. Ornstein–Uhlenbeck uses its conditional Gaussian transition, since future levels depend on the current level.

Preparing historical price data

For cryptocurrency data, CCXT can retrieve public candle histories. This helper uses daily candles and an exclusive end date. Choose a venue that lists both markets, or supply historical CSV exports with the same columns. Install CCXT separately with python -m pip install ccxt.

import pandas as pd

def fetch_daily_close(exchange, symbol, start, stop):
    first = exchange.parse8601(start)
    stop_ms = exchange.parse8601(stop)
    day_ms = 86_400_000
    cursor = first
    closes = {}
    while cursor < stop_ms:
        candles = exchange.fetch_ohlcv(symbol, "1d", since=cursor, limit=100)
        if not candles:
            break
        closes.update(
            (row[0], row[4]) for row in candles
            if first <= row[0] and row[0] + day_ms <= stop_ms
        )
        next_cursor = max(row[0] for row in candles) + day_ms
        if next_cursor <= cursor:
            raise RuntimeError(f"{symbol} candle timestamps stopped advancing")
        cursor = next_cursor

    return pd.Series(
        list(closes.values()),
        index=pd.to_datetime(list(closes), unit="ms", utc=True),
        name=symbol,
        dtype=float,
    ).sort_index()

With a configured exchange and its unified market symbols, combine the closing prices by timestamp. The dates below preserve the window used in the original example. Historical coverage varies by venue.

def fetch_prices(exchange, symbols, start, stop):
    columns = [fetch_daily_close(exchange, symbol, start, stop) for symbol in symbols]
    return pd.concat(columns, axis=1).rename_axis("timestamp").sort_index()

# Run with a CCXT exchange that provides these markets and dates.
# prices = fetch_prices(
#     exchange, ["ETH/USD", "BIFI/USD"],
#     "2022-01-01T00:00:00Z", "2023-04-20T00:00:00Z",
# )
# prices.to_csv("IlliquidAssetData.csv")

To extend a saved file, read it with pd.read_csv(..., index_col=0, parse_dates=True) and fetch the next interval. Combine by date with new.combine_first(existing).sort_index() before writing the CSV. Check for missing sessions before using an equal-step return model. Dropping isolated missing dates can turn adjacent rows into returns spanning more than one day. CCXT candlestick documentation

Historical liquid and illiquid prices

StochasticPriceModel provides the earlier price-analysis interface. Use one positive, timestamp-sorted closing price per observation. To study an illiquid asset alongside a liquid reference asset, align both price series on a common sampling grid before passing them to the model. For example, an exchange export could contain an Ethereum column and a Beefy Finance column.

import pandas as pd
from PyLevyProcess import StochasticPriceModel

closes = (
    pd.read_csv("IlliquidAssetData.csv", index_col=0, parse_dates=True)
    .sort_index()[["ETH/USD", "BIFI/USD"]]
    .dropna()
)
liquid = closes["ETH/USD"]
illiquid = closes["BIFI/USD"]

eth_model = StochasticPriceModel(liquid_data=liquid)
eth_model.liquidModel(horizon=30)
eth_model.plotEstimates()
bands = (eth_model.lower_confidence, eth_model.median_confidence, eth_model.upper_confidence)

paired_model = StochasticPriceModel(liquid_data=liquid, illiquid_data=illiquid)
paired_model.illiquidModel(horizon=30)
paired_model.plotEstimates(assetType="illiquid")

The experimental workflow fits the empirical characteristic function of the log returns and samples stable parameters using Hamiltonian Monte Carlo. fit_ecf_stable exposes the fitting step and generateEstimateFigure provides a Plotly view. For a holdout study, pass only the training prices to the constructor and compare the simulated quantiles with later observations. The legacy backtesting=True path still anchors simulation at the last supplied price.

paired_model.assetCorrelation reports the sample correlation between the two log-return series. The simulation itself uses the fitted illiquid return law. The first entry of each price band is the starting price, so compare only subsequent entries with held-out observations.

References

  • Ang, A., Papanikolaou, D., & Westerfield, M. M. (2014). Portfolio choice with illiquid assets. Management Science, 60(11), 2737–2761.
  • Nolan, J. P. (2003). Modeling financial data with stable distributions. In Handbook of Heavy Tailed Distributions in Finance (pp. 105–130). North-Holland.

About

A Python package to model financial returns as Levy processes.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages