Skip to content

Astralchemist/Expert-Advisor-v0.5.1

Repository files navigation

📊 Power Laws Expert Advisor - Research Suite

Version Python Status License

⚠️ 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.


📁 Project Structure

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

📋 Table of Contents


Overview

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

Modules

1. 🎯 Power Law Criticality (powerlaw_criticality.py)

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


2. 📈 Power Law Extremes (powerlaw_extremes.py)

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


3. 🎰 St. Petersburg Research (st_petersburg_research.py)

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


Installation

Requirements

pip install numpy pandas scipy matplotlib

Python Version

  • Python 3.8+ recommended

Dependencies

Package Version Purpose
numpy ≥1.20 Numerical computation
pandas ≥1.3 Data manipulation
scipy ≥1.7 Statistical functions
matplotlib ≥3.4 Visualization

Usage

Run Individual Modules

# 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.py

Check Version

python version.py
# Output: Power Laws Research Suite v0.5.1

Example Output

---------------------------------------------------------
   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...

🏷️ Version History

See CHANGELOG.md for full version history.

Current: v0.5.1 (2026-01-08)

Added:

  • Comprehensive documentation for all modules
  • SECURITY.md vulnerability audit
  • Reorganized project into module subfolders
  • Version tracking infrastructure

🔴 Security Vulnerabilities & Required Fixes

HIGH SEVERITY

1. Hardcoded Random Seeds (Reproducibility Risk)

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)))

2. Division by Zero Vulnerabilities

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)

3. Unbounded Memory Allocation

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_results

MEDIUM SEVERITY

4. Floating Point Overflow Risk

Location: 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)

5. Unvalidated User Inputs

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"

6. File Path Hardcoding

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'))

LOW SEVERITY

7. Silent NaN Propagation

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.UNKNOWN

8. Missing Dependency Version Pins

Issue: 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

9. No Logging Rotation

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)

10. Potential Index Out of Bounds

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 None

Mathematical Background

Hill Estimator

The Hill Estimator calculates the tail index α from order statistics:

$$\hat{\alpha}_{Hill} = \frac{1}{\frac{1}{k} \sum_{i=1}^{k} \log\left(\frac{X_{(i)}}{X_{(k+1)}}\right)}$$

Where $X_{(i)}$ is the i-th largest observation.

Hurst Exponent (R/S Analysis)

$$E\left[\frac{R(n)}{S(n)}\right] \sim n^H$$

Where R is the range of cumulative deviations and S is standard deviation.

St. Petersburg Expected Value

$$E[X] = \sum_{k=1}^{\infty} \frac{1}{2^k} \cdot 2^k = \sum_{k=1}^{\infty} 1 = \infty$$


Disclaimer

⚠️ THIS SOFTWARE IS FOR EDUCATIONAL AND RESEARCH PURPOSES ONLY

  • Not financial advice
  • Not suitable for live trading
  • No warranty of any kind
  • Authors are not liable for any losses

License

MIT License - See LICENSE file for details.


Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Submit a pull request with tests

Last Updated: January 2026

Packages

 
 
 

Contributors

Languages