⚠️ RESEARCH ONLY — NOT SUITABLE FOR LIVE TRADING
A collection of Python research tools for exploring power law distributions, extreme value theory, and market criticality detection.
Expert-Advisor-v0.5.1/
├── 📂 powerlaw_criticality/
│ ├── powerlaw_criticality.py # Market criticality detector
│ └── README.md # Module documentation
├── 📂 powerlaw_extremes/
│ ├── powerlaw_extremes.py # EVT & Hurst analysis
│ └── README.md # Module documentation
├── 📂 st_petersburg/
│ ├── st_petersburg_research.py # St. Petersburg simulation
│ └── README.md # Module documentation
├── README.md # This file
├── SECURITY.md # Vulnerability audit
├── CHANGELOG.md # Version history
├── VERSION # Current version (0.5.1)
├── version.py # Python version module
└── requirements.txt # Dependencies
- Overview
- Project Structure
- Modules
- Installation
- Usage
- Version History
- Security Vulnerabilities & Required Fixes
- Mathematical Background
- Disclaimer
This research suite implements statistical analysis frameworks for studying:
| Module | Location | Focus Area | Key Algorithm |
|---|---|---|---|
| Criticality | powerlaw_criticality/ |
Market regime detection | Hill Estimator + State Machine |
| Extremes | powerlaw_extremes/ |
Extreme event analysis | EVT, Hurst Exponent, Hawkes Process |
| St. Petersburg | st_petersburg/ |
Infinite variance games | Monte Carlo Wealth Simulation |
Purpose: Detects market "criticality states" where the distribution of returns becomes fat-tailed (power law), indicating potential phase transitions.
Key Features:
- Hill Estimator for tail index (α) calculation
- Volatility compression detection via Bollinger Band percentile
- Directional Tick Bias as order flow proxy
- Deterministic regime state machine
Market States:
| State | Condition | Interpretation |
|---|---|---|
NORMAL |
α > 3.0 | Thin tails, stable market |
COMPRESSED |
Low BB width percentile | Consolidation, possible breakout |
UNSTABLE |
2.5 < α < 3.0 or high imbalance | Transition zone |
CRITICAL |
α < 2.5 | Fat tails, fragile market |
CHAOTIC |
α < 2.0 | Infinite variance territory |
Output: powerlaw_criticality_results.png
Purpose: Applies Extreme Value Theory (EVT) and long-memory analysis to understand tail risk and event clustering.
Key Features:
- Hurst Exponent (R/S Analysis): Detects persistence/mean-reversion
- H = 0.5: Random walk
- H > 0.5: Trending/persistent
- H < 0.5: Mean-reverting
- Hill Estimator with Bootstrap: Confidence intervals for α estimation
- Hawkes Process Proxy: Measures "cascade probability" (event clustering)
Output: powerlaw_extremes_results.png
Purpose: Monte Carlo exploration of the St. Petersburg Paradox — a game with infinite expected value but finite practical utility.
Game Rules:
- Flip a fair coin until Tails appears
- Payoff = 2^k where k = number of Heads
- Expected Value = ∞ (mathematically)
Research Insights:
- Demonstrates ergodicity breaking (time-average ≠ ensemble-average)
- Tests various betting strategies under infinite variance
- Validates Kelly Criterion logic for ruin probability
Output: st_petersburg_results.png
pip install numpy pandas scipy matplotlib- Python 3.8+ recommended
| Package | Version | Purpose |
|---|---|---|
numpy |
≥1.20 | Numerical computation |
pandas |
≥1.3 | Data manipulation |
scipy |
≥1.7 | Statistical functions |
matplotlib |
≥3.4 | Visualization |
# Criticality Analysis
python powerlaw_criticality/powerlaw_criticality.py
# EVT & Hurst Research
python powerlaw_extremes/powerlaw_extremes.py
# St. Petersburg Simulation
python st_petersburg/st_petersburg_research.pypython version.py
# Output: Power Laws Research Suite v0.5.1---------------------------------------------------------
POWER LAW CRITICALITY DETECTOR (RESEARCH PROTOTYPE)
---------------------------------------------------------
2026-01-08 20:00:00 [INFO] Initializing Power Law Criticality Research...
2026-01-08 20:00:00 [INFO] Generating synthetic data (N=5000)...
2026-01-08 20:00:01 [INFO] Starting Rolling Analysis...
2026-01-08 20:00:05 [INFO] Analysis Complete. Generating Report...
See CHANGELOG.md for full version history.
Added:
- Comprehensive documentation for all modules
- SECURITY.md vulnerability audit
- Reorganized project into module subfolders
- Version tracking infrastructure
Location: All three files
Issue: Fixed seeds (RANDOM_SEED = 42, 99, 123) make analysis non-random and results predictable.
# VULNERABLE
RANDOM_SEED = 42
np.random.seed(RANDOM_SEED)
# FIX: Make seed configurable or use secure randomness for production
import secrets
RANDOM_SEED = int(os.environ.get('RANDOM_SEED', secrets.randbelow(2**32)))Location: powerlaw_criticality.py:211, powerlaw_extremes.py:130-132
Issue: Potential division by zero in imbalance calculation and R/S analysis.
# VULNERABLE (powerlaw_criticality.py)
imbalance = (buy_vol_s - sell_vol_s) / total_vol.replace(0, 1)
# FIX: Use proper guarding with np.errstate
with np.errstate(divide='ignore', invalid='ignore'):
imbalance = np.where(total_vol > 0, (buy_vol_s - sell_vol_s) / total_vol, 0)Location: powerlaw_criticality.py:256, powerlaw_extremes.py:249
Issue: Results lists grow without bound; could cause OOM with large datasets.
# VULNERABLE
results = [] # Unbounded list growth
# FIX: Pre-allocate or use streaming/chunked processing
max_results = len(df) - start_idx
results = [None] * max_resultsLocation: st_petersburg_research.py:88
Issue: np.power(2.0, heads) can overflow for large heads values.
# VULNERABLE
payoffs = np.power(2.0, heads) # 2^1000 = overflow
# FIX: Cap maximum heads or use log-space computation
MAX_HEADS = 50 # 2^50 ≈ 1 quadrillion
heads = np.minimum(heads, MAX_HEADS)
payoffs = np.power(2.0, heads)Location: All configuration blocks
Issue: No validation on configuration constants; negative lookbacks or zero thresholds crash silently.
# FIX: Add validation
def validate_config():
assert LOOKBACK_ALPHA > MIN_TAIL_SIZE, "LOOKBACK_ALPHA must exceed MIN_TAIL_SIZE"
assert 0 < TAIL_PERCENTILE < 1, "TAIL_PERCENTILE must be in (0,1)"
assert ALPHA_CHAOTIC < ALPHA_CRITICAL < ALPHA_STABLE, "Alpha thresholds must be ordered"Location: All plt.savefig() calls
Issue: Hardcoded output paths prevent multi-run analysis and may fail on read-only systems.
# VULNERABLE
plt.savefig('powerlaw_criticality_results.png')
# FIX: Use configurable output directory
import os
OUTPUT_DIR = os.environ.get('OUTPUT_DIR', '.')
plt.savefig(os.path.join(OUTPUT_DIR, 'powerlaw_criticality_results.png'))Location: powerlaw_criticality.py:219-220
Issue: When Hill estimator returns NaN, regime defaults to NORMAL which may mask data quality issues.
# VULNERABLE
if np.isnan(alpha):
return MarketState.NORMAL # Silent default
# FIX: Add explicit UNKNOWN state or log warning
if np.isnan(alpha):
logger.warning(f"Insufficient data for Alpha calculation at bar {timestamp}")
return MarketState.UNKNOWNIssue: No requirements.txt or version pins could lead to compatibility issues.
FIX: Create requirements.txt:
numpy>=1.20,<2.0
pandas>=1.3,<3.0
scipy>=1.7,<2.0
matplotlib>=3.4,<4.0
Location: All logging configuration
Issue: StreamHandler only; no file logging or rotation for debugging.
# FIX: Add rotating file handler
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler(
'research.log', maxBytes=5*1024*1024, backupCount=3
)
logging.getLogger().addHandler(file_handler)Location: st_petersburg_research.py:137
Issue: np.argmax(path==0) returns 0 for all-zeros or when 0 appears first, which is ambiguous.
# VULNERABLE
ruin_step = np.argmax(path==0) if 0 in path else 'None'
# FIX: Handle the edge case explicitly
zero_indices = np.where(path == 0)[0]
ruin_step = zero_indices[0] if len(zero_indices) > 0 else NoneThe Hill Estimator calculates the tail index α from order statistics:
Where
Where R is the range of cumulative deviations and S is standard deviation.
- Not financial advice
- Not suitable for live trading
- No warranty of any kind
- Authors are not liable for any losses
MIT License - See LICENSE file for details.
- Fork the repository
- Create a feature branch
- Submit a pull request with tests
Last Updated: January 2026