Skip to main content

🛡️ ShieldRegime: Physics-Inspired Financial Market Anomaly Detection

License: MIT Python Version Style Open In Colab

ShieldRegime is an open-source Python library designed to identify market manipulation and suspicious trading activities (such as Pump-and-Dump schemes and Wash Trading) using price kinematics—an innovative, physics-inspired approach to financial time-series analysis.

By modeling price as a physical particle and volume as the underlying force moving it, ShieldRegime computes real-time derivatives (velocity, acceleration, kinetic friction) to flag manipulative trends before they impact market integrity.

[!TIP] Try it in your browser right now! Click the Open In Colab badge above to launch a fully interactive cloud demo running on real-world GameStop ($GME$) retail-driven mania data.


⚡ Key Features

  • 📈 Price Kinematics: Smoothed velocity (1st derivative) and acceleration (2nd derivative) rolling Z-score computations to identify momentum-thrust anomalies.
  • 📊 Volume-Price Profiling: Advanced indicators (volume_price_divergence, wash_trade_index) to catch high-volume, narrow-range wash sales.
  • 🚨 Multi-Stage Detectors: High-fidelity detection models (PumpDumpDetector) mapping base, pump, and dump stages.
  • 🎨 Stunning Visualization: Interactive, presentation-ready Plotly charts highlighting anomaly regions, trigger bounds, and drawdowns.

🚀 Installation

1. Via PyPI (Recommended)

You can install the stable release of ShieldRegime directly from PyPI:

pip install shield-regime

2. From Source (For Development)

If you want to contribute, run the tests, or build from source:

# Clone the official repository
git clone https://github.com/VL-mwb/shield-regime.git
cd shield-regime

# Install in editable mode with development dependencies
pip install -e ".[dev]"

📖 Quick Start & Visualization

The following example downloads historical data for GameStop (GME) during the 2021 short-squeeze anomaly, runs the PumpDumpDetector, and visualizes the results with Plotly.

import shield_regime as sr
import yfinance as yf

# 1. Download historical market data
df = yf.download("GME", start="2020-09-01", end="2021-04-30")

# Rename columns to match requirements
df_clean = df.copy()
df_clean.index = pd.to_datetime(df.index)
df_clean.columns = [col.lower() for col in df_clean.columns]

# 2. Initialize the detector with custom thresholds
detector = sr.PumpDumpDetector(
    velocity_z_threshold=2.0,      # Trigger on +2.0σ price velocity
    volume_spike_threshold=3.0,    # Require volume > 3x recent average
    dump_drop_threshold=-25.0,     # Flag if price crashes > 25% from peak
    lookback=40,                   # 40-day rolling baseline
)

# 3. Scan the asset
alerts = detector.scan(df_clean, ticker="GME")

for alert in alerts:
    print(f"\n🚨 [DETECTED] {alert}")
    print(f"Details: {alert.details}")
    print(f"Metrics: {alert.metrics}")

# 4. Generate beautiful interactive Plotly chart
fig = sr.plot_alerts(df_clean, alerts, ticker="GME", lookback=40)
if fig:
    # In Jupyter, this displays directly. Or save to HTML:
    fig.write_html("gme_analysis.html")
    print("\n📊 Saved interactive analysis to 'gme_analysis.html'")

🧪 Mathematical Foundation

Price Velocity ($V$)

The rate of change of price over time, smoothed via Exponential Moving Average (EMA) to filter out high-frequency noise:

$$V_t = \text{EMA}(\Delta P_t, \lambda)$$

Price Acceleration ($A$)

The second derivative of price, capturing sudden trend thrusts and aggressive manipulation entries:

$$A_t = \text{EMA}(V_t - V_{t-1}, \lambda)$$

Wash Trade Index ($WTI$)

Under self-dealing conditions, volume explodes while the intraday price range remains narrow. We flag this anomaly using:

$$WTI_t = \frac{\text{Volume Spike Ratio}}{\text{Normalized Intraday Range} + \epsilon}$$


🛠️ Running Unit Tests

We maintain 100% test coverage for all kinematic formulas, detectors, and visualization routines. Run tests with:

pytest tests/ -v

🤖 Autonomous AI Agent Integration & Cloud API

ShieldRegime's mathematical engine is designed to be fully compatible with Model Context Protocol (MCP) and modern Agentic AI frameworks (Claude, ChatGPT, AutoGen).

[!NOTE] Looking for Zero-Config AI Agent Integration?
If you want your AI agents to query ShieldRegime directly without managing local data pipelines, stock scrapers, or Python environments, check out our official Capafy Managed Agent Skill.

The Capafy version provides:

  • Pre-calibrated parameters fine-tuned for TWSE (Taiwan Stock Exchange) and US equity market microstructures.
  • Live market data feeds integrated automatically.
  • Plug-and-play MCP / API endpoints for instant integration into AI trading assistants.

🗺️ Roadmap & Future Work

ShieldRegime is actively developed to provide regulatory-grade market surveillance.

  • Phase 1: Core Price Kinematics — Smoothed velocity & acceleration derivatives.
  • Phase 2: Pump-and-Dump Detection — Dynamic peak-tracking state machines.
  • Phase 3: Wash Trading & Crypto Scans — Volume-price profiling (wash_trade_index) and crypto speculative scans.
  • Phase 4 (Future HFT Expansion): High-Frequency Spoofing & Layering Detector — Modeling book pressure imbalances (requires L2/L3 order book tick feeds).

📄 License

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

Metadata

Release files for shield-regime 0.1.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for shield-regime 0.1.4
File Size Uploaded
shield_regime-0.1.4.tar.gz 39.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for shield-regime 0.1.4
File Interpreter ABI Platform
shield_regime-0.1.4-py3-none-any.whl Python 3 none any Details

Total release size: 58.3 kB

Release files / shield_regime-0.1.4.tar.gz

Download URL shield_regime-0.1.4.tar.gz
Size 39.2 kB
Tags Source
SHA-256 checksum
How to use checksums
0edad3e83e9ef48f19c7496d9dbdd8a10bc07fcdbb1e8529988e70937fdd3b51
BLAKE2b-256 checksum
How to use checksums
ce3731f6786910ed8a5d6a586206298b8557a91d93ad1d3fd4f7052e4783d775
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Release files / shield_regime-0.1.4-py3-none-any.whl

Download URL shield_regime-0.1.4-py3-none-any.whl
Size 19.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5c0d0b17b4fd30eddc76b847bc3ec177ab50d10666247c046eb6153a63f3f12b
BLAKE2b-256 checksum
How to use checksums
60af08ae440b691fe2068429b287b1857a536d59fc54e9f21012f5249c000074
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Release history Release notifications | RSS feed

0.1.5

2 release files

This release

0.1.4 This release

2 release files

0.1.3

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page