Skip to content

chirindaopensource/universal_dynamics_financial_bubbles_isolated_markets

Repository files navigation

README.md

Universal Dynamics of Financial Bubbles in Isolated Markets: Evidence from the Iranian Stock Market

License: MIT Python Version arXiv Journal Year Discipline Data Sources Data Sources Core Method Analysis Validation Robustness Code style: black Type Checking: mypy NumPy Pandas SciPy Matplotlib Statsmodels Jupyter

Repository: https://github.com/chirindaopensource/universal_dynamics_financial_bubbles_isolated_markets

Owner: 2025 Craig Chirinda (Open Source Projects)

This repository contains an independent, professional-grade Python implementation of the research methodology from the 2025 paper entitled "Universal Dynamics of Financial Bubbles in Isolated Markets: Evidence from the Iranian Stock Market" by:

  • Ali Hosseinzadeh (Shahid Beheshti University, Tehran)

The project provides a complete, end-to-end computational framework for replicating the paper's findings. It delivers a modular, auditable, and extensible pipeline that executes the entire research workflow: from the ingestion and cleansing of irregular financial time series data to the rigorous calibration of the Log-Periodic Power Law Singularity (LPPLS) model, bubble inception detection via Lagrange regularization, and non-parametric spectral validation of log-periodicity.

Table of Contents

Introduction

This project provides a Python implementation of the analytical framework presented in Hosseinzadeh (2025). The core of this repository is the iPython Notebook universal_dynamics_financial_bubbles_isolated_markets_draft.ipynb, which contains a comprehensive suite of functions to replicate the paper's findings. The pipeline is designed to be a generalizable "Universal Diagnostic Engine" for detecting systemic risk and critical transitions in financial markets, with a specific focus on validating the universality of bubble dynamics in isolated economies like Iran.

The paper addresses the question of whether endogenous market mechanisms—such as herding and positive feedback—drive financial instability even in the absence of global capital flows. This codebase operationalizes the paper's framework, allowing users to:

  • Rigorously validate and manage the entire experimental configuration via a single config.yaml file.
  • Cleanse and normalize financial time series data, handling irregular trading calendars (e.g., Persian trading week) and market halts.
  • Calibrate the LPPLS model using the robust Filimonov-Sornette (2013) variable projection method.
  • Detect the most probable bubble start date ($t_1$) using a Lagrange-regularized error metric scan.
  • Validate the presence of log-periodic oscillations using Lomb-Scargle periodograms and $(H,q)$-derivative diagnostics.
  • Assess statistical significance via Monte Carlo surrogate data testing (AR(1), fGn, Lévy-stable).

Theoretical Background

The implemented methods combine techniques from Econophysics, Complex Systems Theory, and Statistical Signal Processing.

1. The LPPLS Model: The core model describes the log-price $\ln p(t)$ as a power law decorated with log-periodic oscillations, capturing the super-exponential growth and herding behavior preceding a crash: $$ \ln p(t) = A + B(t_c - t)^\beta + C(t_c - t)^\beta \cos(\omega \ln(t_c - t) + \phi) $$ where $t_c$ is the critical time (singularity), $\beta$ is the power-law exponent ($0 < \beta < 1$), and $\omega$ is the angular log-frequency.

2. Calibration Strategy (Filimonov-Sornette): To ensure numerical stability, the nonlinear optimization is reduced to a 3-parameter search over $(t_c, \beta, \omega)$ by slaving the linear parameters $(A, B, C_1, C_2)$ via Ordinary Least Squares (OLS): $$ \ln p(t) = A + B f(t) + C_1 g(t) + C_2 h(t) $$ where $f(t) = (t_c - t)^\beta$, $g(t) = f(t) \cos(\omega \ln(t_c - t))$, and $h(t) = f(t) \sin(\omega \ln(t_c - t))$.

3. Bubble Inception Detection: The start date of the bubble ($t_1$) is identified by minimizing a Lagrange-regularized error metric that balances model fit against window length stability: $$ \chi^2_{\lambda}(t_1) = \chi^2_{np}(t_1) - \lambda L(t_1) $$ where $\chi^2_{np}$ is the normalized sum of squared residuals and $L$ is the window length.

4. Non-Parametric Validation: The presence of log-periodicity is independently verified by analyzing the detrended residuals $r(t)$ in log-time coordinates $x = \ln(t_c - t)$ using the Lomb-Scargle periodogram, which handles unevenly sampled data: $$ P(\omega) = \frac{1}{2} \left{ \frac{[\sum r_i \cos \omega(x_i - \tau)]^2}{\sum \cos^2 \omega(x_i - \tau)} + \frac{[\sum r_i \sin \omega(x_i - \tau)]^2}{\sum \sin^2 \omega(x_i - \tau)} \right} $$

Below is a diagram which summarizes the proposed approach:

Universal Diagnostic Engine Process Summary

Features

The provided iPython Notebook (universal_dynamics_financial_bubbles_isolated_markets_draft.ipynb) implements the full research pipeline, including:

  • Modular, Multi-Task Architecture: The pipeline is decomposed into 25 distinct, modular tasks, each with its own orchestrator function.
  • Configuration-Driven Design: All study parameters (grid bounds, regularization settings, surrogate protocols) are managed in an external config.yaml file.
  • Rigorous Data Validation: A multi-stage validation process checks schema integrity, temporal monotonicity, and price positivity.
  • Event-Time Normalization: Implements a robust mapping from calendar dates to integer event-time indices to handle market closures without imputation.
  • Advanced Diagnostics: Includes $(H,q)$-derivative analysis and characteristic time scale ($\tau$) computation.
  • Reproducible Artifacts: Generates structured dictionaries and serializable outputs for every intermediate result, ensuring full auditability.

Methodology Implemented

The core analytical steps directly implement the methodology from the paper:

  1. Validation & Cleansing (Tasks 1-6): Ingests raw TEDPIX data, validates schemas, enforces integrity constraints, and cleanses the time series for analysis.
  2. Episode Definition (Tasks 7-9): Resolves anchor dates ($t_2$) to trading days, generates candidate window grids, and maps data to event-time coordinates.
  3. LPPLS Calibration (Tasks 10-15): Specifies the canonical and linearized models, implements the grid search engine, solves the slaved OLS problem, and reproduces the reporting fits (Plots 1-4).
  4. Inception Detection (Tasks 16-18): Computes the inception error curves, estimates the regularization parameter $\lambda$, and selects the optimal bubble start date.
  5. Robustness & Diagnostics (Tasks 20-24): Performs $t_2$-shifting robustness analysis, computes Lomb-Scargle periodograms, executes surrogate significance tests, and calculates diagnostic metrics.
  6. Reporting (Task 25): Generates the final publication-ready plots and tables.

Core Components (Notebook Structure)

The universal_dynamics_financial_bubbles_isolated_markets_draft.ipynb notebook is structured as a logical pipeline with modular orchestrator functions for each of the 25 major tasks. All functions are self-contained, fully documented with type hints and docstrings, and designed for professional-grade execution.

Key Callable: run_universal_diagnostic_engine

The project is designed around a single, top-level user-facing interface function:

  • run_universal_diagnostic_engine: This master orchestrator function runs the entire automated research pipeline from end-to-end. A single call to this function reproduces the entire computational portion of the project, managing data flow between the calibration, inception detection, and diagnostic modules.

Prerequisites

  • Python 3.9+
  • Core dependencies: pandas, numpy, scipy, statsmodels, matplotlib, pyyaml.

Installation

  1. Clone the repository:

    git clone https://github.com/chirindaopensource/universal_dynamics_financial_bubbles_isolated_markets.git
    cd universal_dynamics_financial_bubbles_isolated_markets
  2. Create and activate a virtual environment (recommended):

    python -m venv venv
    source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
  3. Install Python dependencies:

    pip install pandas numpy scipy statsmodels matplotlib pyyaml

Input Data Structure

The pipeline requires a primary DataFrame and optional supplementary data:

  1. df_tedpix_raw: The primary index data with columns: Date_Gregorian, Date_SH, Open, High, Low, Close, Adj_Close, Volume, Value_IRR.
  2. Optional DataFrames: df_constituents_raw, df_sectoral_stats_raw, df_market_cap_raw, df_fx_rates_raw, df_trading_calendar_raw for contextual analysis.

Usage

The universal_dynamics_financial_bubbles_isolated_markets_draft.ipynb notebook provides a complete, step-by-step guide. The primary workflow is to execute the final cell of the notebook, which demonstrates how to use the top-level run_universal_diagnostic_engine orchestrator:

# Final cell of the notebook

# This block serves as the main entry point for the entire project.
if __name__ == '__main__':
    # 1. Load the master configuration from the YAML file.
    import yaml
    with open('config.yaml', 'r') as f:
        raw_config = yaml.safe_load(f)
    
    # 2. Load raw datasets (Example using synthetic generator provided in the notebook)
    # In production, load from CSV/Parquet: pd.read_csv(...)
    df_tedpix_raw, optional_dfs = generate_synthetic_tse_data()
    
    # 3. Define Run Mode
    run_mode = {
        "fit_reporting": True,
        "scan_inception": True,
        "run_robustness": True,
        "run_diagnostics": True
    }

    # 4. Execute the entire replication study.
    results = run_universal_diagnostic_engine(
        raw_config=raw_config,
        df_tedpix_raw=df_tedpix_raw,
        optional_dfs=optional_dfs,
        run_mode=run_mode
    )
    
    # 5. Access results
    print(f"Optimal Start Date (2020): {results['pipeline_results'].inception_results['bubble_2020'].optimal_t1}")

Output Structure

The pipeline returns a master dictionary containing all analytical artifacts:

  • pipeline_results: A PipelineResults object containing:
    • manifest: Audit record.
    • df_cleansed: The processed dataset.
    • reporting_fits: Parameter tables for Plots 1-4.
    • inception_results: Optimal start dates and parameters.
    • lomb_results, surrogate_results, hq_results: Diagnostic outputs.
  • artifacts: A StudyArtifacts object containing:
    • fit_plots: Matplotlib figures of LPPLS fits.
    • inception_plots: Error curve visualizations.
    • lomb_plots: Periodogram figures.
    • tau_summary: Characteristic time scale table.

Project Structure

universal_dynamics_financial_bubbles_isolated_markets/
│
├── universal_dynamics_financial_bubbles_isolated_markets_draft.ipynb  # Main implementation notebook
├── config.yaml                                                        # Master configuration file
├── requirements.txt                                                   # Python package dependencies
│
├── LICENSE                                                            # MIT Project License File
└── README.md                                                          # This file

Customization

The pipeline is highly customizable via the config.yaml file. Users can modify study parameters such as:

  • Grid Search Bounds: tc_search, beta_search, omega_search.
  • Regularization: k_definition, lambda_estimation.
  • Diagnostics: lomb_scargle frequency grid, h_q_derivative parameters.
  • Validation: monte_carlo_config (number of surrogates, null models).

Contributing

Contributions are welcome. Please fork the repository, create a feature branch, and submit a pull request with a clear description of your changes. Adherence to PEP 8, type hinting, and comprehensive docstrings is required.

Recommended Extensions

Future extensions could include:

  • Deep LPPLS: Integrating neural network-based calibration methods for enhanced parameter estimation.
  • Real-Time Monitoring: Adapting the pipeline for streaming data to provide live bubble indicators.
  • Cross-Market Analysis: Applying the "Universal Diagnostic Engine" to other isolated or emerging markets (e.g., Venezuela, Zimbabwe).

License

This project is licensed under the MIT License. See the LICENSE file for details.

Citation

If you use this code or the methodology in your research, please cite the original paper:

@article{hosseinzadeh2025universal,
  title={Universal Dynamics of Financial Bubbles in Isolated Markets: Evidence from the Iranian Stock Market},
  author={Hosseinzadeh, Ali},
  journal={arXiv preprint arXiv:2512.12054},
  year={2025}
}

For the implementation itself, you may cite this repository:

Chirinda, C. (2025). Universal Diagnostic Engine for Systemic Risk: An Open Source Implementation.
GitHub repository: https://github.com/chirindaopensource/universal_dynamics_financial_bubbles_isolated_markets

Acknowledgments

  • Credit to Ali Hosseinzadeh for the foundational research that forms the entire basis for this computational replication.
  • This project is built upon the exceptional tools provided by the open-source community. Sincere thanks to the developers of the scientific Python ecosystem, including Pandas, NumPy, SciPy, Statsmodels, and Matplotlib.

--

This README was generated based on the structure and content of the universal_dynamics_financial_bubbles_isolated_markets_draft.ipynb notebook and follows best practices for research software documentation.

About

End-to-End Python implementation of LPPLS (Log-Periodic Power Law Singularity) framework for detecting financial bubbles and critical transitions. Features Filimonov-Sornette calibration, Lagrange regularization, Lomb-Scargle spectral validation, and Monte Carlo significance testing. Complete computational replication of Hosseinzadeh (2025).

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors