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.
- Introduction
- Theoretical Background
- Features
- Methodology Implemented
- Core Components (Notebook Structure)
- Key Callable:
run_universal_diagnostic_engine - Prerequisites
- Installation
- Input Data Structure
- Usage
- Output Structure
- Project Structure
- Customization
- Contributing
- Recommended Extensions
- License
- Citation
- Acknowledgments
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.yamlfile. - 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).
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
2. Calibration Strategy (Filimonov-Sornette):
To ensure numerical stability, the nonlinear optimization is reduced to a 3-parameter search over
3. Bubble Inception Detection:
The start date of the bubble (
4. Non-Parametric Validation:
The presence of log-periodicity is independently verified by analyzing the detrended residuals
Below is a diagram which summarizes the proposed approach:
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.yamlfile. - 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.
The core analytical steps directly implement the methodology from the paper:
- Validation & Cleansing (Tasks 1-6): Ingests raw TEDPIX data, validates schemas, enforces integrity constraints, and cleanses the time series for analysis.
-
Episode Definition (Tasks 7-9): Resolves anchor dates (
$t_2$ ) to trading days, generates candidate window grids, and maps data to event-time coordinates. - 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).
-
Inception Detection (Tasks 16-18): Computes the inception error curves, estimates the regularization parameter
$\lambda$ , and selects the optimal bubble start date. -
Robustness & Diagnostics (Tasks 20-24): Performs
$t_2$ -shifting robustness analysis, computes Lomb-Scargle periodograms, executes surrogate significance tests, and calculates diagnostic metrics. - Reporting (Task 25): Generates the final publication-ready plots and tables.
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.
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.
- Python 3.9+
- Core dependencies:
pandas,numpy,scipy,statsmodels,matplotlib,pyyaml.
-
Clone the repository:
git clone https://github.com/chirindaopensource/universal_dynamics_financial_bubbles_isolated_markets.git cd universal_dynamics_financial_bubbles_isolated_markets -
Create and activate a virtual environment (recommended):
python -m venv venv source venv/bin/activate # On Windows, use `venv\Scripts\activate`
-
Install Python dependencies:
pip install pandas numpy scipy statsmodels matplotlib pyyaml
The pipeline requires a primary DataFrame and optional supplementary data:
df_tedpix_raw: The primary index data with columns:Date_Gregorian,Date_SH,Open,High,Low,Close,Adj_Close,Volume,Value_IRR.- Optional DataFrames:
df_constituents_raw,df_sectoral_stats_raw,df_market_cap_raw,df_fx_rates_raw,df_trading_calendar_rawfor contextual analysis.
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}")The pipeline returns a master dictionary containing all analytical artifacts:
pipeline_results: APipelineResultsobject 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: AStudyArtifactsobject containing:fit_plots: Matplotlib figures of LPPLS fits.inception_plots: Error curve visualizations.lomb_plots: Periodogram figures.tau_summary: Characteristic time scale table.
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
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_scarglefrequency grid,h_q_derivativeparameters. - Validation:
monte_carlo_config(number of surrogates, null models).
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.
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).
This project is licensed under the MIT License. See the LICENSE file for details.
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
- 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.
