Skip to main content

A fractal econometrics package for python, built with JAX.

Project description

fractrics

PyPI - Version PyPI - Python Version


Table of Contents

Installation

pip install fractrics

Quick example

The main tool in fractrics is the MSM class, an implementation of the univariate Markov Switching Multifractal Model. The logaritmic difference between observations is modeled as the noise-adjusted square root of the product of a chosen number of latent volatility components, each following the dynamics of discrete first order markov chains, whose transition depends on geometrically-spaced Poisson arrivals, and an unconditional term, effectively being the unconditional volatility.

Such structure effectively captures the behaviour of time series with fat tails, hyperbolic correlation decay, and multifractal moments, such as the returns of many financial assets.

The implementation is made in JAX, thus leveraging JIT compilation while keeping the simple syntax of python.

To use the model, we start by simulating data from a MSM process. In this package, we adopt a functional style, where methods are free functions (under the MSM namespace), while relevant information about the model (data, hyperparameters, parameters, ...) are kept in a metadata object, which is the primary input for most of the functions of the package.

To make a simulation, we need to initialize hyperparameters and parameters of the model in the metadata. It requires the following hyperparameters:

  • n_latent: how many volatility components, integer.
  • marg_prob_mass: the probability mass of the marginal distribution of the latent states, needs to sum to 1.

By assumption, all the parameters need to be positive, and have further individual constrains:

  • marg_value: One of the values of the support of the marginal probability mass defined in the parameters. The marginal probability mass needs to have unity and positive support. In the symmetric binomial case, this can be enforced by specifying one value $m_0$, and having the second value be $2 - m_0$, which is the case that this implementation focuses on. More general marginal distributions could be considered, but then the computations of standard errors may become more challenging, because the unity and positivity constraints impose dependencies on the Hessian matrix, thus making hypothesis tests impossible.

  • unconditional_term: the unconditional distribution of the model, a positive double.

  • arrival_gdistance: the geometric distance between the Poisson arrivals of each latent volatility component, a positive double.

  • hf_arrival: the highest poisson arrival probability (i.e. the proability of state switch of the highest frequency component).

import jax.numpy as jnp
from fractrics import MSM

model = MSM.metadata(data=None,
    parameters= {
    'unconditional_term': 1.0,
    'arrival_gdistance': 3.0,
    'hf_arrival': 0.98,
    'marginal_value': 1.5 
    },
    
    num_latent= 5)

The MSM.simulation method takes a msm_metadata object as input to choose the parameters.

Follows an example with the parameters of the fitted model above. It returns a tuple containing the simulated logarithmic change (e.g. 1 step return in a financial setting) and corresponding implied volatility.

import matplotlib.pyplot as plt
ret, vol = MSM.simulation(n_simulations = 1000, model_info = model, seed=123)
plt.plot(ret)
plt.show()

png

To fit the model to the data, start with an initial guess. The MSM.fit() method then optimizes the parameters using a custom implementation of the Nelder-Mead method, and the constrains are enforced with an internal re-mappig.

Note that the model is only defined for positive time series (as it was created to model prices of financial assets), so we reconstruct the price from ret.

from dataclasses import replace
x = jnp.exp(jnp.cumsum(ret))
model = replace(model, data=x)
msm_result = MSM.fit(model, max_iter=1000)

msm_result is also msm_metadata that contains relevant information about the model. This construct reduces the verbosity of the API, as it can be passed as the only input required to operate with the following methods.

It contains:

  • filtered: a dictionary containing the current distribution of the latent components, the list of distribution list at each time step, inferred using the forward algorithm, the transition tensor of the model (in factor form), and the vector of latent states (which can be populated using the MSM.filter() method.)
  • parameters: a dictionary containing the model parameters.
  • standard_errors: a dictionary containing the model standard errors
  • robust_standard_errors: a dictionary containing the Eicker–Huber–White standard errors
  • num_latent: the number of latent volatility components.
  • optimization_info: information about the optimization process
  • name: the internal name of the model (defaults to "MSM")
  • data: the input data
  • data_log_change: the logarithmic change between each data point and its next observation (e.g. the log. return if the original data is a series of financial prices).

Most of this information can be printed using the summary() function.

from fractrics.utilities import summary
summary(msm_result)
                    parameters standard_errors robust_standard_errors
unconditional_term   1.4911367      0.11745711             0.13154256
arrival_gdistance      6.67688             nan              4.2458887
hf_arrival          0.02006583     0.017231423            0.019555239
marginal_value       1.6799235      0.02701448            0.028021006
negative_log_likelihood    -1467.5436
n_iteration                       161
is_converged                     True
dtype: object

Finally, a 200 period forecast. The method returns the (noise-free) expected state at each forecast horizon, along with selected confidence intervals.

filtered = MSM.filter(msm_result)
expect, c1, c2 = MSM.forecast(horizon=200, model_info=filtered, quantiles=(0.05, 0.95))
from fractrics.utilities import plot_forecast
plot_forecast(expect, c1, c2)

png

Clearly, including noise in the forecast can have value in practical applications (such as scenario analysis), so we can instead bootstrap paths using the fitted model.

from fractrics.utilities import plot_simulation_batch
return_f, _ = MSM.boostrap_forecast(filtered, num_simulation=4000, horizon=200)
plot_simulation_batch(return_f)

png

MSM documentation

Refer to:

Project Structure

.
├── notebooks                     # [example jupyter notebooks]
└── src/fractrics                 # [main code repository]
    ├── _components/              # abstract classes and methods for time series
    ├── MSM.py                    # Markov Switching Multifractal Implementation
    ├── utilities.py              # contains summary and plot functions
    ├── nelder_mead.py            # Nelder-Mead solver implementation
    ├── unscent_KF.py             # Unscent Kalman Filter implementation
    └── diagnostics.py            # Statistics to test performances of models

Planned updates

  • components/_HMM/base.py:
    • implementing viterbi and backwards algorithms
    • generalize components of the forward algorithms that apply to other hidden markov models
  • MSM:
    • create plot functions.
      • visualize states
      • visualize learning path
    • implement model selection metrics
    • Allow for creating simulations without initializing the model with a time series.
  • diagnostics.py: adding other common metrics.
  • re-implementing the functions in _components/_pending_refactor:

References

  • Calvet, L.E. and Fisher, A.J. (2004). How to Forecast Long-Run Volatility: Regime Switching and the Estimation of Multifractal Processes. Journal of Financial Econometrics, 2(1).

  • Calvet, L.E. and Fisher, A.J. (2008). Multifractal Volatility. Theory, Forecasting, and Pricing. Academic Press.

  • Calvet, L.E., Fisher, A.J. and Thompson, S.B. (2004). Volatility Comovement: A Multifrequency Approach. SSRN Electronic Journal. doi:https://doi.org/10.2139/ssrn.582541.

  • Ghahramani, Z. and Jordan, M.I. (1997). Factorial Hidden Markov Models. Machine Learning, 29(2/3), pp.245–273. doi:https://doi.org/10.1023/a:1007425814087.

  • Lux, T. (2008). The Markov-Switching Multifractal Model of Asset Returns. Journal of Business & Economic Statistics, 26(2), pp.194–210. doi:https://doi.org/10.1198/073500107000000403.

  • Lux, T. (2020). Inference for Nonlinear State Space Models: A Comparison of Different Methods applied to Markov-Switching Multifractal Models. Econometrics and Statistics. doi:https://doi.org/10.1016/j.ecosta.2020.03.001.

  • Lux, T., Morales-Arias, L. and Sattarhoff, C. (2011). A Markov-switching multifractal approach to forecasting realized volatility. [online] Kiel Working Papers. Available at: https://ideas.repec.org/p/zbw/ifwkwp/1737.html [Accessed 30 May 2025].

  • Murphy, K.P. (2012). Machine learning : a probabilistic perspective. Cambridge (Ma): Mit Press.

  • Rypdal, M. and Løvsletten, O. (2011). Multifractal modeling of short-term interest rates. arXiv (Cornell University).

License

fractrics is distributed under the terms of the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fractrics-0.3.0.tar.gz (776.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fractrics-0.3.0-py3-none-any.whl (31.8 kB view details)

Uploaded Python 3

File details

Details for the file fractrics-0.3.0.tar.gz.

File metadata

  • Download URL: fractrics-0.3.0.tar.gz
  • Upload date:
  • Size: 776.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for fractrics-0.3.0.tar.gz
Algorithm Hash digest
SHA256 b7db229dd25d3858cb5d72697ce2fe5c2f2998bf42b442dfd53e12de2879650f
MD5 40c78f8d10eb66f96cee90699130932b
BLAKE2b-256 15af7c833f846a813beebe5f2c7a4f2cafcf7579032fc3d57f5aeb5f13a76f06

See more details on using hashes here.

File details

Details for the file fractrics-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: fractrics-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 31.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for fractrics-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f5e9f5757bfe5b69f35752f048f7dc77f5069abaa372237d9da7fb94d6261b27
MD5 4e693d489e901847d2f201d0b2a32363
BLAKE2b-256 1b41bb6bd8fbfc6e5543949502f1dd0834be9c75e8dbaf96e4eafafa81701c06

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page