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 default baseline thresholds
# (Note: For pre-calibrated live TWSE/US market parameters, use the Capafy Agent Skill)
detector = sr.PumpDumpDetector(lookback=40)

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

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.5
File Size Uploaded
shield_regime-0.1.5.tar.gz 39.1 kB Details

Built distribution (wheel)

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

Total release size: 58.1 kB

Release files / shield_regime-0.1.5.tar.gz

Download URL shield_regime-0.1.5.tar.gz
Size 39.1 kB
Tags Source
SHA-256 checksum
How to use checksums
e3c8dab71405f5af34ed89d620dc6693522200d62a8ff66ce2c1217ba3f1194f
BLAKE2b-256 checksum
How to use checksums
73f81739a8ecdc4923c43eb60f78c08ec43a36a03ba5810f2ce2e76a0ed28997
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.5-py3-none-any.whl

Download URL shield_regime-0.1.5-py3-none-any.whl
Size 19.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
04c4687f0b84f404fe7fa93f59cdbccbbfe7232bc511c46c2c3cf7e1e82c3f83
BLAKE2b-256 checksum
How to use checksums
c63d8971b395e8e0bcc76500c4e75f12ef65b9ab782072facab7982ab9029a7b
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

This release

0.1.5 This release

2 release files

0.1.4

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